From 76cb9c2a39d477a64824a985ade40507e3bbade1 Mon Sep 17 00:00:00 2001 From: Adam Mathes Date: Fri, 13 Feb 2026 21:34:48 -0800 Subject: feat(vanilla): add testing infrastructure and tests (NK-wjnczv) --- vanilla/node_modules/.bin/esbuild | 1 + vanilla/node_modules/.bin/nanoid | 1 + vanilla/node_modules/.bin/parser | 1 + vanilla/node_modules/.bin/rollup | 1 + vanilla/node_modules/.bin/semver | 1 + vanilla/node_modules/.bin/tldts | 1 + vanilla/node_modules/.bin/vite | 1 + vanilla/node_modules/.bin/vitest | 1 + vanilla/node_modules/.bin/why-is-node-running | 1 + vanilla/node_modules/.package-lock.json | 1414 + .../results.json | 1 + vanilla/node_modules/@acemir/cssom/LICENSE.txt | 20 + vanilla/node_modules/@acemir/cssom/README.mdown | 64 + vanilla/node_modules/@acemir/cssom/build/CSSOM.js | 6611 ++++ .../@acemir/cssom/lib/CSSConditionRule.js | 32 + .../@acemir/cssom/lib/CSSContainerRule.js | 70 + .../@acemir/cssom/lib/CSSCounterStyleRule.js | 57 + .../@acemir/cssom/lib/CSSDocumentRule.js | 48 + .../@acemir/cssom/lib/CSSFontFaceRule.js | 62 + .../@acemir/cssom/lib/CSSGroupingRule.js | 165 + .../node_modules/@acemir/cssom/lib/CSSHostRule.js | 54 + .../@acemir/cssom/lib/CSSImportRule.js | 267 + .../@acemir/cssom/lib/CSSKeyframeRule.js | 63 + .../@acemir/cssom/lib/CSSKeyframesRule.js | 247 + .../@acemir/cssom/lib/CSSLayerBlockRule.js | 49 + .../@acemir/cssom/lib/CSSLayerStatementRule.js | 36 + .../node_modules/@acemir/cssom/lib/CSSMediaRule.js | 74 + .../@acemir/cssom/lib/CSSNamespaceRule.js | 103 + .../@acemir/cssom/lib/CSSNestedDeclarations.js | 56 + vanilla/node_modules/@acemir/cssom/lib/CSSOM.js | 58 + .../node_modules/@acemir/cssom/lib/CSSPageRule.js | 125 + .../@acemir/cssom/lib/CSSPropertyRule.js | 122 + vanilla/node_modules/@acemir/cssom/lib/CSSRule.js | 92 + .../node_modules/@acemir/cssom/lib/CSSRuleList.js | 26 + .../node_modules/@acemir/cssom/lib/CSSScopeRule.js | 61 + .../@acemir/cssom/lib/CSSStartingStyleRule.js | 52 + .../@acemir/cssom/lib/CSSStyleDeclaration.js | 164 + .../node_modules/@acemir/cssom/lib/CSSStyleRule.js | 109 + .../@acemir/cssom/lib/CSSStyleSheet.js | 371 + .../@acemir/cssom/lib/CSSSupportsRule.js | 48 + vanilla/node_modules/@acemir/cssom/lib/CSSValue.js | 43 + .../@acemir/cssom/lib/CSSValueExpression.js | 346 + .../node_modules/@acemir/cssom/lib/MatcherList.js | 62 + .../node_modules/@acemir/cssom/lib/MediaList.js | 78 + .../node_modules/@acemir/cssom/lib/StyleSheet.js | 62 + vanilla/node_modules/@acemir/cssom/lib/clone.js | 105 + .../@acemir/cssom/lib/cssstyleTryCatchBlock.js | 5 + .../node_modules/@acemir/cssom/lib/errorUtils.js | 119 + vanilla/node_modules/@acemir/cssom/lib/index.js | 42 + vanilla/node_modules/@acemir/cssom/lib/parse.js | 3332 ++ .../@acemir/cssom/lib/regexPatterns.js | 162 + vanilla/node_modules/@acemir/cssom/package.json | 32 + vanilla/node_modules/@asamuzakjp/css-color/LICENSE | 21 + .../node_modules/@asamuzakjp/css-color/README.md | 316 + .../css-color/dist/browser/css-color.min.js | 1 + .../css-color/dist/browser/css-color.min.js.map | 1 + .../@asamuzakjp/css-color/dist/cjs/index.cjs | 5764 +++ .../@asamuzakjp/css-color/dist/cjs/index.cjs.map | 1 + .../@asamuzakjp/css-color/dist/cjs/index.d.cts | 110 + .../@asamuzakjp/css-color/dist/esm/index.d.ts | 18 + .../@asamuzakjp/css-color/dist/esm/index.js | 22 + .../@asamuzakjp/css-color/dist/esm/index.js.map | 1 + .../@asamuzakjp/css-color/dist/esm/js/cache.d.ts | 44 + .../@asamuzakjp/css-color/dist/esm/js/cache.js | 72 + .../@asamuzakjp/css-color/dist/esm/js/cache.js.map | 1 + .../@asamuzakjp/css-color/dist/esm/js/color.d.ts | 537 + .../@asamuzakjp/css-color/dist/esm/js/color.js | 2833 ++ .../@asamuzakjp/css-color/dist/esm/js/color.js.map | 1 + .../@asamuzakjp/css-color/dist/esm/js/common.d.ts | 21 + .../@asamuzakjp/css-color/dist/esm/js/common.js | 7 + .../css-color/dist/esm/js/common.js.map | 1 + .../css-color/dist/esm/js/constant.d.ts | 43 + .../@asamuzakjp/css-color/dist/esm/js/constant.js | 101 + .../css-color/dist/esm/js/constant.js.map | 1 + .../@asamuzakjp/css-color/dist/esm/js/convert.d.ts | 99 + .../@asamuzakjp/css-color/dist/esm/js/convert.js | 361 + .../css-color/dist/esm/js/convert.js.map | 1 + .../css-color/dist/esm/js/css-calc.d.ts | 89 + .../@asamuzakjp/css-color/dist/esm/js/css-calc.js | 826 + .../css-color/dist/esm/js/css-calc.js.map | 1 + .../css-color/dist/esm/js/css-gradient.d.ts | 79 + .../css-color/dist/esm/js/css-gradient.js | 261 + .../css-color/dist/esm/js/css-gradient.js.map | 1 + .../@asamuzakjp/css-color/dist/esm/js/css-var.d.ts | 31 + .../@asamuzakjp/css-color/dist/esm/js/css-var.js | 195 + .../css-color/dist/esm/js/css-var.js.map | 1 + .../css-color/dist/esm/js/relative-color.d.ts | 29 + .../css-color/dist/esm/js/relative-color.js | 535 + .../css-color/dist/esm/js/relative-color.js.map | 1 + .../@asamuzakjp/css-color/dist/esm/js/resolve.d.ts | 52 + .../@asamuzakjp/css-color/dist/esm/js/resolve.js | 350 + .../css-color/dist/esm/js/resolve.js.map | 1 + .../@asamuzakjp/css-color/dist/esm/js/typedef.d.ts | 80 + .../@asamuzakjp/css-color/dist/esm/js/util.d.ts | 53 + .../@asamuzakjp/css-color/dist/esm/js/util.js | 359 + .../@asamuzakjp/css-color/dist/esm/js/util.js.map | 1 + .../@asamuzakjp/css-color/package.json | 82 + .../@asamuzakjp/css-color/src/index.ts | 30 + .../@asamuzakjp/css-color/src/js/cache.ts | 114 + .../@asamuzakjp/css-color/src/js/color.ts | 3511 ++ .../@asamuzakjp/css-color/src/js/common.ts | 31 + .../@asamuzakjp/css-color/src/js/constant.ts | 68 + .../@asamuzakjp/css-color/src/js/convert.ts | 469 + .../@asamuzakjp/css-color/src/js/css-calc.ts | 955 + .../@asamuzakjp/css-color/src/js/css-gradient.ts | 384 + .../@asamuzakjp/css-color/src/js/css-var.ts | 250 + .../@asamuzakjp/css-color/src/js/relative-color.ts | 635 + .../@asamuzakjp/css-color/src/js/resolve.ts | 443 + .../@asamuzakjp/css-color/src/js/typedef.ts | 88 + .../@asamuzakjp/css-color/src/js/util.ts | 443 + .../node_modules/@asamuzakjp/dom-selector/LICENSE | 21 + .../@asamuzakjp/dom-selector/README.md | 324 + .../@asamuzakjp/dom-selector/dist/cjs/index.cjs | 4622 +++ .../dom-selector/dist/cjs/index.cjs.map | 1 + .../@asamuzakjp/dom-selector/dist/cjs/index.d.cts | 16 + .../@asamuzakjp/dom-selector/package.json | 81 + .../@asamuzakjp/dom-selector/src/index.js | 353 + .../@asamuzakjp/dom-selector/src/js/constant.js | 129 + .../@asamuzakjp/dom-selector/src/js/finder.js | 3122 ++ .../@asamuzakjp/dom-selector/src/js/matcher.js | 587 + .../@asamuzakjp/dom-selector/src/js/parser.js | 431 + .../@asamuzakjp/dom-selector/src/js/utility.js | 1107 + .../@asamuzakjp/dom-selector/types/index.d.ts | 14 + .../dom-selector/types/js/constant.d.ts | 77 + .../@asamuzakjp/dom-selector/types/js/finder.d.ts | 63 + .../@asamuzakjp/dom-selector/types/js/matcher.d.ts | 16 + .../@asamuzakjp/dom-selector/types/js/parser.d.ts | 14 + .../@asamuzakjp/dom-selector/types/js/utility.d.ts | 30 + vanilla/node_modules/@asamuzakjp/nwsapi/LICENSE | 22 + vanilla/node_modules/@asamuzakjp/nwsapi/README.md | 132 + .../node_modules/@asamuzakjp/nwsapi/package.json | 43 + .../node_modules/@asamuzakjp/nwsapi/src/nwsapi.js | 1855 + .../@babel/helper-string-parser/LICENSE | 22 + .../@babel/helper-string-parser/README.md | 19 + .../@babel/helper-string-parser/lib/index.js | 295 + .../@babel/helper-string-parser/lib/index.js.map | 1 + .../@babel/helper-string-parser/package.json | 31 + .../@babel/helper-validator-identifier/LICENSE | 22 + .../@babel/helper-validator-identifier/README.md | 19 + .../helper-validator-identifier/lib/identifier.js | 70 + .../lib/identifier.js.map | 1 + .../helper-validator-identifier/lib/index.js | 57 + .../helper-validator-identifier/lib/index.js.map | 1 + .../helper-validator-identifier/lib/keyword.js | 35 + .../helper-validator-identifier/lib/keyword.js.map | 1 + .../helper-validator-identifier/package.json | 31 + vanilla/node_modules/@babel/parser/CHANGELOG.md | 1073 + vanilla/node_modules/@babel/parser/LICENSE | 19 + vanilla/node_modules/@babel/parser/README.md | 19 + .../node_modules/@babel/parser/bin/babel-parser.js | 15 + vanilla/node_modules/@babel/parser/lib/index.js | 14582 ++++++++ .../node_modules/@babel/parser/lib/index.js.map | 1 + vanilla/node_modules/@babel/parser/package.json | 50 + .../@babel/parser/typings/babel-parser.d.ts | 262 + vanilla/node_modules/@babel/types/LICENSE | 22 + vanilla/node_modules/@babel/types/README.md | 19 + .../@babel/types/lib/asserts/assertNode.js | 16 + .../@babel/types/lib/asserts/assertNode.js.map | 1 + .../@babel/types/lib/asserts/generated/index.js | 1251 + .../types/lib/asserts/generated/index.js.map | 1 + .../@babel/types/lib/ast-types/generated/index.js | 3 + .../types/lib/ast-types/generated/index.js.map | 1 + .../types/lib/builders/flow/createFlowUnionType.js | 18 + .../lib/builders/flow/createFlowUnionType.js.map | 1 + .../flow/createTypeAnnotationBasedOnTypeof.js | 31 + .../flow/createTypeAnnotationBasedOnTypeof.js.map | 1 + .../@babel/types/lib/builders/generated/index.js | 29 + .../types/lib/builders/generated/index.js.map | 1 + .../types/lib/builders/generated/lowercase.js | 2902 ++ .../types/lib/builders/generated/lowercase.js.map | 1 + .../types/lib/builders/generated/uppercase.js | 272 + .../types/lib/builders/generated/uppercase.js.map | 1 + .../@babel/types/lib/builders/productions.js | 12 + .../@babel/types/lib/builders/productions.js.map | 1 + .../types/lib/builders/react/buildChildren.js | 24 + .../types/lib/builders/react/buildChildren.js.map | 1 + .../lib/builders/typescript/createTSUnionType.js | 22 + .../builders/typescript/createTSUnionType.js.map | 1 + .../@babel/types/lib/builders/validateNode.js | 21 + .../@babel/types/lib/builders/validateNode.js.map | 1 + .../node_modules/@babel/types/lib/clone/clone.js | 12 + .../@babel/types/lib/clone/clone.js.map | 1 + .../@babel/types/lib/clone/cloneDeep.js | 12 + .../@babel/types/lib/clone/cloneDeep.js.map | 1 + .../@babel/types/lib/clone/cloneDeepWithoutLoc.js | 12 + .../types/lib/clone/cloneDeepWithoutLoc.js.map | 1 + .../@babel/types/lib/clone/cloneNode.js | 107 + .../@babel/types/lib/clone/cloneNode.js.map | 1 + .../@babel/types/lib/clone/cloneWithoutLoc.js | 12 + .../@babel/types/lib/clone/cloneWithoutLoc.js.map | 1 + .../@babel/types/lib/comments/addComment.js | 15 + .../@babel/types/lib/comments/addComment.js.map | 1 + .../@babel/types/lib/comments/addComments.js | 22 + .../@babel/types/lib/comments/addComments.js.map | 1 + .../types/lib/comments/inheritInnerComments.js | 12 + .../types/lib/comments/inheritInnerComments.js.map | 1 + .../types/lib/comments/inheritLeadingComments.js | 12 + .../lib/comments/inheritLeadingComments.js.map | 1 + .../types/lib/comments/inheritTrailingComments.js | 12 + .../lib/comments/inheritTrailingComments.js.map | 1 + .../@babel/types/lib/comments/inheritsComments.js | 17 + .../types/lib/comments/inheritsComments.js.map | 1 + .../@babel/types/lib/comments/removeComments.js | 15 + .../types/lib/comments/removeComments.js.map | 1 + .../@babel/types/lib/constants/generated/index.js | 60 + .../types/lib/constants/generated/index.js.map | 1 + .../@babel/types/lib/constants/index.js | 31 + .../@babel/types/lib/constants/index.js.map | 1 + .../@babel/types/lib/converters/ensureBlock.js | 14 + .../@babel/types/lib/converters/ensureBlock.js.map | 1 + .../lib/converters/gatherSequenceExpressions.js | 65 + .../converters/gatherSequenceExpressions.js.map | 1 + .../lib/converters/toBindingIdentifierName.js | 14 + .../lib/converters/toBindingIdentifierName.js.map | 1 + .../@babel/types/lib/converters/toBlock.js | 29 + .../@babel/types/lib/converters/toBlock.js.map | 1 + .../@babel/types/lib/converters/toComputedKey.js | 14 + .../types/lib/converters/toComputedKey.js.map | 1 + .../@babel/types/lib/converters/toExpression.js | 28 + .../types/lib/converters/toExpression.js.map | 1 + .../@babel/types/lib/converters/toIdentifier.js | 25 + .../types/lib/converters/toIdentifier.js.map | 1 + .../@babel/types/lib/converters/toKeyAlias.js | 38 + .../@babel/types/lib/converters/toKeyAlias.js.map | 1 + .../types/lib/converters/toSequenceExpression.js | 19 + .../lib/converters/toSequenceExpression.js.map | 1 + .../@babel/types/lib/converters/toStatement.js | 39 + .../@babel/types/lib/converters/toStatement.js.map | 1 + .../@babel/types/lib/converters/valueToNode.js | 89 + .../@babel/types/lib/converters/valueToNode.js.map | 1 + .../@babel/types/lib/definitions/core.js | 1725 + .../@babel/types/lib/definitions/core.js.map | 1 + .../types/lib/definitions/deprecated-aliases.js | 11 + .../lib/definitions/deprecated-aliases.js.map | 1 + .../@babel/types/lib/definitions/experimental.js | 124 + .../types/lib/definitions/experimental.js.map | 1 + .../@babel/types/lib/definitions/flow.js | 495 + .../@babel/types/lib/definitions/flow.js.map | 1 + .../@babel/types/lib/definitions/index.js | 106 + .../@babel/types/lib/definitions/index.js.map | 1 + .../@babel/types/lib/definitions/jsx.js | 157 + .../@babel/types/lib/definitions/jsx.js.map | 1 + .../@babel/types/lib/definitions/misc.js | 31 + .../@babel/types/lib/definitions/misc.js.map | 1 + .../@babel/types/lib/definitions/placeholders.js | 27 + .../types/lib/definitions/placeholders.js.map | 1 + .../@babel/types/lib/definitions/typescript.js | 528 + .../@babel/types/lib/definitions/typescript.js.map | 1 + .../@babel/types/lib/definitions/utils.js | 296 + .../@babel/types/lib/definitions/utils.js.map | 1 + .../@babel/types/lib/index-legacy.d.ts | 2797 ++ vanilla/node_modules/@babel/types/lib/index.d.ts | 3617 ++ vanilla/node_modules/@babel/types/lib/index.js | 582 + .../node_modules/@babel/types/lib/index.js.flow | 2650 ++ vanilla/node_modules/@babel/types/lib/index.js.map | 1 + .../lib/modifications/appendToMemberExpression.js | 15 + .../modifications/appendToMemberExpression.js.map | 1 + .../lib/modifications/flow/removeTypeDuplicates.js | 65 + .../modifications/flow/removeTypeDuplicates.js.map | 1 + .../@babel/types/lib/modifications/inherits.js | 28 + .../@babel/types/lib/modifications/inherits.js.map | 1 + .../lib/modifications/prependToMemberExpression.js | 17 + .../modifications/prependToMemberExpression.js.map | 1 + .../types/lib/modifications/removeProperties.js | 24 + .../lib/modifications/removeProperties.js.map | 1 + .../lib/modifications/removePropertiesDeep.js | 14 + .../lib/modifications/removePropertiesDeep.js.map | 1 + .../typescript/removeTypeDuplicates.js | 66 + .../typescript/removeTypeDuplicates.js.map | 1 + .../lib/retrievers/getAssignmentIdentifiers.js | 48 + .../lib/retrievers/getAssignmentIdentifiers.js.map | 1 + .../types/lib/retrievers/getBindingIdentifiers.js | 102 + .../lib/retrievers/getBindingIdentifiers.js.map | 1 + .../@babel/types/lib/retrievers/getFunctionName.js | 63 + .../types/lib/retrievers/getFunctionName.js.map | 1 + .../lib/retrievers/getOuterBindingIdentifiers.js | 13 + .../retrievers/getOuterBindingIdentifiers.js.map | 1 + .../@babel/types/lib/traverse/traverse.js | 50 + .../@babel/types/lib/traverse/traverse.js.map | 1 + .../@babel/types/lib/traverse/traverseFast.js | 40 + .../@babel/types/lib/traverse/traverseFast.js.map | 1 + .../@babel/types/lib/utils/deprecationWarning.js | 44 + .../types/lib/utils/deprecationWarning.js.map | 1 + .../node_modules/@babel/types/lib/utils/inherit.js | 13 + .../@babel/types/lib/utils/inherit.js.map | 1 + .../lib/utils/react/cleanJSXElementLiteralChild.js | 40 + .../utils/react/cleanJSXElementLiteralChild.js.map | 1 + .../@babel/types/lib/utils/shallowEqual.js | 17 + .../@babel/types/lib/utils/shallowEqual.js.map | 1 + .../lib/validators/buildMatchMemberExpression.js | 13 + .../validators/buildMatchMemberExpression.js.map | 1 + .../@babel/types/lib/validators/generated/index.js | 2797 ++ .../types/lib/validators/generated/index.js.map | 1 + .../node_modules/@babel/types/lib/validators/is.js | 27 + .../@babel/types/lib/validators/is.js.map | 1 + .../@babel/types/lib/validators/isBinding.js | 27 + .../@babel/types/lib/validators/isBinding.js.map | 1 + .../@babel/types/lib/validators/isBlockScoped.js | 13 + .../types/lib/validators/isBlockScoped.js.map | 1 + .../@babel/types/lib/validators/isImmutable.js | 21 + .../@babel/types/lib/validators/isImmutable.js.map | 1 + .../@babel/types/lib/validators/isLet.js | 13 + .../@babel/types/lib/validators/isLet.js.map | 1 + .../@babel/types/lib/validators/isNode.js | 12 + .../@babel/types/lib/validators/isNode.js.map | 1 + .../types/lib/validators/isNodesEquivalent.js | 57 + .../types/lib/validators/isNodesEquivalent.js.map | 1 + .../types/lib/validators/isPlaceholderType.js | 15 + .../types/lib/validators/isPlaceholderType.js.map | 1 + .../@babel/types/lib/validators/isReferenced.js | 96 + .../types/lib/validators/isReferenced.js.map | 1 + .../@babel/types/lib/validators/isScope.js | 18 + .../@babel/types/lib/validators/isScope.js.map | 1 + .../types/lib/validators/isSpecifierDefault.js | 14 + .../types/lib/validators/isSpecifierDefault.js.map | 1 + .../@babel/types/lib/validators/isType.js | 17 + .../@babel/types/lib/validators/isType.js.map | 1 + .../types/lib/validators/isValidES3Identifier.js | 13 + .../lib/validators/isValidES3Identifier.js.map | 1 + .../types/lib/validators/isValidIdentifier.js | 18 + .../types/lib/validators/isValidIdentifier.js.map | 1 + .../@babel/types/lib/validators/isVar.js | 15 + .../@babel/types/lib/validators/isVar.js.map | 1 + .../@babel/types/lib/validators/matchesPattern.js | 44 + .../types/lib/validators/matchesPattern.js.map | 1 + .../types/lib/validators/react/isCompatTag.js | 11 + .../types/lib/validators/react/isCompatTag.js.map | 1 + .../types/lib/validators/react/isReactComponent.js | 11 + .../lib/validators/react/isReactComponent.js.map | 1 + .../@babel/types/lib/validators/validate.js | 42 + .../@babel/types/lib/validators/validate.js.map | 1 + vanilla/node_modules/@babel/types/package.json | 39 + vanilla/node_modules/@bcoe/v8-coverage/LICENSE.md | 21 + vanilla/node_modules/@bcoe/v8-coverage/LICENSE.txt | 14 + vanilla/node_modules/@bcoe/v8-coverage/README.md | 11 + .../node_modules/@bcoe/v8-coverage/package.json | 29 + .../@bcoe/v8-coverage/src/lib/ascii.js | 145 + .../@bcoe/v8-coverage/src/lib/clone.js | 75 + .../@bcoe/v8-coverage/src/lib/compare.js | 44 + .../@bcoe/v8-coverage/src/lib/index.js | 41 + .../@bcoe/v8-coverage/src/lib/merge.js | 353 + .../@bcoe/v8-coverage/src/lib/normalize.js | 96 + .../@bcoe/v8-coverage/src/lib/range-tree.js | 157 + .../@csstools/color-helpers/CHANGELOG.md | 16 + .../@csstools/color-helpers/LICENSE.md | 18 + .../node_modules/@csstools/color-helpers/README.md | 32 + .../@csstools/color-helpers/dist/index.d.ts | 429 + .../@csstools/color-helpers/dist/index.mjs | 263 + .../@csstools/color-helpers/package.json | 55 + .../node_modules/@csstools/css-calc/CHANGELOG.md | 9 + vanilla/node_modules/@csstools/css-calc/LICENSE.md | 20 + vanilla/node_modules/@csstools/css-calc/README.md | 132 + .../@csstools/css-calc/dist/index.d.ts | 101 + .../node_modules/@csstools/css-calc/dist/index.mjs | 1 + .../node_modules/@csstools/css-calc/package.json | 59 + .../@csstools/css-color-parser/CHANGELOG.md | 9 + .../@csstools/css-color-parser/LICENSE.md | 20 + .../@csstools/css-color-parser/README.md | 37 + .../@csstools/css-color-parser/dist/index.d.ts | 168 + .../@csstools/css-color-parser/dist/index.mjs | 1 + .../@csstools/css-color-parser/package.json | 64 + .../@csstools/css-parser-algorithms/CHANGELOG.md | 11 + .../@csstools/css-parser-algorithms/LICENSE.md | 20 + .../@csstools/css-parser-algorithms/README.md | 119 + .../css-parser-algorithms/dist/index.d.ts | 604 + .../@csstools/css-parser-algorithms/dist/index.mjs | 1 + .../@csstools/css-parser-algorithms/package.json | 58 + .../css-syntax-patches-for-csstree/CHANGELOG.md | 9 + .../css-syntax-patches-for-csstree/LICENSE.md | 18 + .../css-syntax-patches-for-csstree/README.md | 43 + .../css-syntax-patches-for-csstree/dist/index.d.ts | 5 + .../css-syntax-patches-for-csstree/dist/index.json | 913 + .../css-syntax-patches-for-csstree/package.json | 48 + .../@csstools/css-tokenizer/CHANGELOG.md | 10 + .../@csstools/css-tokenizer/LICENSE.md | 20 + .../node_modules/@csstools/css-tokenizer/README.md | 111 + .../@csstools/css-tokenizer/dist/index.d.ts | 593 + .../@csstools/css-tokenizer/dist/index.mjs | 1 + .../@csstools/css-tokenizer/package.json | 55 + .../node_modules/@esbuild/linux-arm64/README.md | 3 + .../node_modules/@esbuild/linux-arm64/bin/esbuild | Bin 0 -> 10158264 bytes .../node_modules/@esbuild/linux-arm64/package.json | 20 + vanilla/node_modules/@exodus/bytes/LICENSE | 21 + vanilla/node_modules/@exodus/bytes/README.md | 925 + vanilla/node_modules/@exodus/bytes/array.d.ts | 62 + vanilla/node_modules/@exodus/bytes/array.js | 17 + vanilla/node_modules/@exodus/bytes/assert.js | 26 + vanilla/node_modules/@exodus/bytes/base32.d.ts | 83 + vanilla/node_modules/@exodus/bytes/base32.js | 39 + vanilla/node_modules/@exodus/bytes/base58.d.ts | 62 + vanilla/node_modules/@exodus/bytes/base58.js | 220 + .../node_modules/@exodus/bytes/base58check.d.ts | 131 + vanilla/node_modules/@exodus/bytes/base58check.js | 18 + .../node_modules/@exodus/bytes/base58check.node.js | 14 + vanilla/node_modules/@exodus/bytes/base64.d.ts | 96 + vanilla/node_modules/@exodus/bytes/base64.js | 178 + vanilla/node_modules/@exodus/bytes/bech32.d.ts | 76 + vanilla/node_modules/@exodus/bytes/bech32.js | 257 + vanilla/node_modules/@exodus/bytes/bigint.d.ts | 48 + vanilla/node_modules/@exodus/bytes/bigint.js | 14 + .../@exodus/bytes/encoding-browser.browser.js | 55 + .../@exodus/bytes/encoding-browser.d.ts | 24 + .../node_modules/@exodus/bytes/encoding-browser.js | 1 + .../@exodus/bytes/encoding-browser.native.js | 1 + .../node_modules/@exodus/bytes/encoding-lite.d.ts | 62 + .../node_modules/@exodus/bytes/encoding-lite.js | 10 + vanilla/node_modules/@exodus/bytes/encoding.d.ts | 140 + vanilla/node_modules/@exodus/bytes/encoding.js | 16 + .../node_modules/@exodus/bytes/fallback/_utils.js | 20 + .../node_modules/@exodus/bytes/fallback/base32.js | 233 + .../@exodus/bytes/fallback/base58check.js | 53 + .../node_modules/@exodus/bytes/fallback/base64.js | 191 + .../@exodus/bytes/fallback/encoding.api.js | 38 + .../@exodus/bytes/fallback/encoding.js | 359 + .../@exodus/bytes/fallback/encoding.labels.js | 50 + .../@exodus/bytes/fallback/encoding.util.js | 64 + vanilla/node_modules/@exodus/bytes/fallback/hex.js | 126 + .../node_modules/@exodus/bytes/fallback/latin1.js | 151 + .../bytes/fallback/multi-byte.encodings.cjs | 1 + .../bytes/fallback/multi-byte.encodings.json | 546 + .../@exodus/bytes/fallback/multi-byte.js | 962 + .../@exodus/bytes/fallback/multi-byte.table.js | 118 + .../node_modules/@exodus/bytes/fallback/percent.js | 31 + .../@exodus/bytes/fallback/platform.browser.js | 31 + .../@exodus/bytes/fallback/platform.js | 2 + .../@exodus/bytes/fallback/platform.native.js | 122 + .../bytes/fallback/single-byte.encodings.js | 73 + .../@exodus/bytes/fallback/single-byte.js | 110 + .../node_modules/@exodus/bytes/fallback/utf16.js | 266 + .../@exodus/bytes/fallback/utf8.auto.browser.js | 2 + .../@exodus/bytes/fallback/utf8.auto.js | 1 + .../@exodus/bytes/fallback/utf8.auto.native.js | 1 + .../node_modules/@exodus/bytes/fallback/utf8.js | 270 + vanilla/node_modules/@exodus/bytes/hex.d.ts | 35 + vanilla/node_modules/@exodus/bytes/hex.js | 17 + vanilla/node_modules/@exodus/bytes/hex.node.js | 28 + vanilla/node_modules/@exodus/bytes/index.d.ts | 43 + vanilla/node_modules/@exodus/bytes/index.js | 5 + vanilla/node_modules/@exodus/bytes/multi-byte.d.ts | 64 + vanilla/node_modules/@exodus/bytes/multi-byte.js | 19 + .../node_modules/@exodus/bytes/multi-byte.node.js | 29 + vanilla/node_modules/@exodus/bytes/package.json | 298 + .../node_modules/@exodus/bytes/single-byte.d.ts | 159 + vanilla/node_modules/@exodus/bytes/single-byte.js | 135 + .../node_modules/@exodus/bytes/single-byte.node.js | 120 + .../node_modules/@exodus/bytes/utf16.browser.js | 8 + vanilla/node_modules/@exodus/bytes/utf16.d.ts | 92 + vanilla/node_modules/@exodus/bytes/utf16.js | 1 + vanilla/node_modules/@exodus/bytes/utf16.native.js | 22 + vanilla/node_modules/@exodus/bytes/utf16.node.js | 70 + vanilla/node_modules/@exodus/bytes/utf8.d.ts | 96 + vanilla/node_modules/@exodus/bytes/utf8.js | 66 + vanilla/node_modules/@exodus/bytes/utf8.node.js | 67 + vanilla/node_modules/@exodus/bytes/whatwg.d.ts | 48 + vanilla/node_modules/@exodus/bytes/whatwg.js | 80 + vanilla/node_modules/@exodus/bytes/wif.d.ts | 76 + vanilla/node_modules/@exodus/bytes/wif.js | 41 + .../node_modules/@jridgewell/resolve-uri/LICENSE | 19 + .../node_modules/@jridgewell/resolve-uri/README.md | 40 + .../@jridgewell/resolve-uri/dist/resolve-uri.mjs | 232 + .../resolve-uri/dist/resolve-uri.mjs.map | 1 + .../resolve-uri/dist/resolve-uri.umd.js | 240 + .../resolve-uri/dist/resolve-uri.umd.js.map | 1 + .../resolve-uri/dist/types/resolve-uri.d.ts | 4 + .../@jridgewell/resolve-uri/package.json | 69 + .../@jridgewell/sourcemap-codec/LICENSE | 19 + .../@jridgewell/sourcemap-codec/README.md | 264 + .../sourcemap-codec/dist/sourcemap-codec.mjs | 423 + .../sourcemap-codec/dist/sourcemap-codec.mjs.map | 6 + .../sourcemap-codec/dist/sourcemap-codec.umd.js | 464 + .../dist/sourcemap-codec.umd.js.map | 6 + .../@jridgewell/sourcemap-codec/package.json | 63 + .../@jridgewell/sourcemap-codec/src/scopes.ts | 345 + .../sourcemap-codec/src/sourcemap-codec.ts | 111 + .../@jridgewell/sourcemap-codec/src/strings.ts | 65 + .../@jridgewell/sourcemap-codec/src/vlq.ts | 55 + .../@jridgewell/sourcemap-codec/types/scopes.d.cts | 50 + .../sourcemap-codec/types/scopes.d.cts.map | 1 + .../@jridgewell/sourcemap-codec/types/scopes.d.mts | 50 + .../sourcemap-codec/types/scopes.d.mts.map | 1 + .../sourcemap-codec/types/sourcemap-codec.d.cts | 9 + .../types/sourcemap-codec.d.cts.map | 1 + .../sourcemap-codec/types/sourcemap-codec.d.mts | 9 + .../types/sourcemap-codec.d.mts.map | 1 + .../sourcemap-codec/types/strings.d.cts | 16 + .../sourcemap-codec/types/strings.d.cts.map | 1 + .../sourcemap-codec/types/strings.d.mts | 16 + .../sourcemap-codec/types/strings.d.mts.map | 1 + .../@jridgewell/sourcemap-codec/types/vlq.d.cts | 7 + .../sourcemap-codec/types/vlq.d.cts.map | 1 + .../@jridgewell/sourcemap-codec/types/vlq.d.mts | 7 + .../sourcemap-codec/types/vlq.d.mts.map | 1 + .../node_modules/@jridgewell/trace-mapping/LICENSE | 19 + .../@jridgewell/trace-mapping/README.md | 348 + .../trace-mapping/dist/trace-mapping.mjs | 493 + .../trace-mapping/dist/trace-mapping.mjs.map | 6 + .../trace-mapping/dist/trace-mapping.umd.js | 559 + .../trace-mapping/dist/trace-mapping.umd.js.map | 6 + .../@jridgewell/trace-mapping/package.json | 67 + .../@jridgewell/trace-mapping/src/binary-search.ts | 115 + .../@jridgewell/trace-mapping/src/by-source.ts | 41 + .../@jridgewell/trace-mapping/src/flatten-map.ts | 192 + .../@jridgewell/trace-mapping/src/resolve.ts | 16 + .../@jridgewell/trace-mapping/src/sort.ts | 45 + .../trace-mapping/src/sourcemap-segment.ts | 23 + .../trace-mapping/src/strip-filename.ts | 8 + .../@jridgewell/trace-mapping/src/trace-mapping.ts | 502 + .../@jridgewell/trace-mapping/src/types.ts | 114 + .../trace-mapping/types/binary-search.d.cts | 33 + .../trace-mapping/types/binary-search.d.cts.map | 1 + .../trace-mapping/types/binary-search.d.mts | 33 + .../trace-mapping/types/binary-search.d.mts.map | 1 + .../trace-mapping/types/by-source.d.cts | 4 + .../trace-mapping/types/by-source.d.cts.map | 1 + .../trace-mapping/types/by-source.d.mts | 4 + .../trace-mapping/types/by-source.d.mts.map | 1 + .../trace-mapping/types/flatten-map.d.cts | 9 + .../trace-mapping/types/flatten-map.d.cts.map | 1 + .../trace-mapping/types/flatten-map.d.mts | 9 + .../trace-mapping/types/flatten-map.d.mts.map | 1 + .../@jridgewell/trace-mapping/types/resolve.d.cts | 4 + .../trace-mapping/types/resolve.d.cts.map | 1 + .../@jridgewell/trace-mapping/types/resolve.d.mts | 4 + .../trace-mapping/types/resolve.d.mts.map | 1 + .../@jridgewell/trace-mapping/types/sort.d.cts | 4 + .../@jridgewell/trace-mapping/types/sort.d.cts.map | 1 + .../@jridgewell/trace-mapping/types/sort.d.mts | 4 + .../@jridgewell/trace-mapping/types/sort.d.mts.map | 1 + .../trace-mapping/types/sourcemap-segment.d.cts | 17 + .../types/sourcemap-segment.d.cts.map | 1 + .../trace-mapping/types/sourcemap-segment.d.mts | 17 + .../types/sourcemap-segment.d.mts.map | 1 + .../trace-mapping/types/strip-filename.d.cts | 5 + .../trace-mapping/types/strip-filename.d.cts.map | 1 + .../trace-mapping/types/strip-filename.d.mts | 5 + .../trace-mapping/types/strip-filename.d.mts.map | 1 + .../trace-mapping/types/trace-mapping.d.cts | 80 + .../trace-mapping/types/trace-mapping.d.cts.map | 1 + .../trace-mapping/types/trace-mapping.d.mts | 80 + .../trace-mapping/types/trace-mapping.d.mts.map | 1 + .../@jridgewell/trace-mapping/types/types.d.cts | 107 + .../trace-mapping/types/types.d.cts.map | 1 + .../@jridgewell/trace-mapping/types/types.d.mts | 107 + .../trace-mapping/types/types.d.mts.map | 1 + .../@rollup/rollup-linux-arm64-gnu/README.md | 3 + .../@rollup/rollup-linux-arm64-gnu/package.json | 25 + .../rollup.linux-arm64-gnu.node | Bin 0 -> 1805000 bytes .../@rollup/rollup-linux-arm64-musl/README.md | 3 + .../@rollup/rollup-linux-arm64-musl/package.json | 25 + .../rollup.linux-arm64-musl.node | Bin 0 -> 1846304 bytes vanilla/node_modules/@standard-schema/spec/LICENSE | 21 + .../node_modules/@standard-schema/spec/README.md | 198 + .../@standard-schema/spec/dist/index.cjs | 18 + .../@standard-schema/spec/dist/index.d.cts | 119 + .../@standard-schema/spec/dist/index.d.ts | 119 + .../@standard-schema/spec/dist/index.js | 0 .../@standard-schema/spec/package.json | 52 + vanilla/node_modules/@types/chai/LICENSE | 21 + vanilla/node_modules/@types/chai/README.md | 15 + vanilla/node_modules/@types/chai/index.d.ts | 2145 ++ vanilla/node_modules/@types/chai/package.json | 75 + .../node_modules/@types/chai/register-should.d.ts | 7 + vanilla/node_modules/@types/deep-eql/LICENSE | 21 + vanilla/node_modules/@types/deep-eql/README.md | 57 + vanilla/node_modules/@types/deep-eql/index.d.ts | 38 + vanilla/node_modules/@types/deep-eql/package.json | 25 + vanilla/node_modules/@types/estree/LICENSE | 21 + vanilla/node_modules/@types/estree/README.md | 15 + vanilla/node_modules/@types/estree/flow.d.ts | 167 + vanilla/node_modules/@types/estree/index.d.ts | 694 + vanilla/node_modules/@types/estree/package.json | 27 + vanilla/node_modules/@vitest/coverage-v8/LICENSE | 21 + .../@vitest/coverage-v8/dist/browser.d.ts | 5 + .../@vitest/coverage-v8/dist/browser.js | 58 + .../@vitest/coverage-v8/dist/index.d.ts | 5 + .../node_modules/@vitest/coverage-v8/dist/index.js | 61 + .../coverage-v8/dist/load-provider-CdgAx3rL.js | 11 + .../coverage-v8/dist/pathe.M-eThtNZ-BTaAGrLg.js | 104 + .../@vitest/coverage-v8/dist/provider.d.ts | 25 + .../@vitest/coverage-v8/dist/provider.js | 296 + .../node_modules/@vitest/coverage-v8/package.json | 76 + vanilla/node_modules/@vitest/expect/LICENSE | 21 + vanilla/node_modules/@vitest/expect/README.md | 21 + .../node_modules/@vitest/expect/dist/index.d.ts | 806 + vanilla/node_modules/@vitest/expect/dist/index.js | 1875 + vanilla/node_modules/@vitest/expect/package.json | 46 + vanilla/node_modules/@vitest/mocker/LICENSE | 21 + vanilla/node_modules/@vitest/mocker/README.md | 5 + .../@vitest/mocker/dist/auto-register.d.ts | 2 + .../@vitest/mocker/dist/auto-register.js | 9 + .../node_modules/@vitest/mocker/dist/automock.d.ts | 12 + .../node_modules/@vitest/mocker/dist/automock.js | 3 + .../node_modules/@vitest/mocker/dist/browser.d.ts | 53 + .../node_modules/@vitest/mocker/dist/browser.js | 91 + .../@vitest/mocker/dist/chunk-automock.js | 354 + .../mocker/dist/chunk-interceptor-native.js | 15 + .../@vitest/mocker/dist/chunk-mocker.js | 521 + .../@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js | 174 + .../@vitest/mocker/dist/chunk-registry.js | 185 + .../@vitest/mocker/dist/chunk-utils.js | 16 + .../@vitest/mocker/dist/index.d-C-sLYZi-.d.ts | 25 + .../node_modules/@vitest/mocker/dist/index.d.ts | 2 + vanilla/node_modules/@vitest/mocker/dist/index.js | 185 + .../@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts | 81 + vanilla/node_modules/@vitest/mocker/dist/node.d.ts | 800 + vanilla/node_modules/@vitest/mocker/dist/node.js | 967 + .../node_modules/@vitest/mocker/dist/redirect.d.ts | 3 + .../node_modules/@vitest/mocker/dist/redirect.js | 79 + .../node_modules/@vitest/mocker/dist/register.d.ts | 9 + .../node_modules/@vitest/mocker/dist/register.js | 41 + .../@vitest/mocker/dist/types.d-B8CCKmHt.d.ts | 107 + vanilla/node_modules/@vitest/mocker/package.json | 86 + vanilla/node_modules/@vitest/pretty-format/LICENSE | 21 + .../@vitest/pretty-format/dist/index.d.ts | 124 + .../@vitest/pretty-format/dist/index.js | 1022 + .../@vitest/pretty-format/package.json | 44 + vanilla/node_modules/@vitest/runner/LICENSE | 21 + vanilla/node_modules/@vitest/runner/README.md | 5 + .../@vitest/runner/dist/chunk-tasks.js | 340 + .../node_modules/@vitest/runner/dist/index.d.ts | 180 + vanilla/node_modules/@vitest/runner/dist/index.js | 2114 ++ .../@vitest/runner/dist/tasks.d-C7UxawJ9.d.ts | 834 + .../node_modules/@vitest/runner/dist/types.d.ts | 183 + vanilla/node_modules/@vitest/runner/dist/types.js | 1 + .../node_modules/@vitest/runner/dist/utils.d.ts | 45 + vanilla/node_modules/@vitest/runner/dist/utils.js | 5 + vanilla/node_modules/@vitest/runner/package.json | 48 + vanilla/node_modules/@vitest/runner/types.d.ts | 1 + vanilla/node_modules/@vitest/runner/utils.d.ts | 1 + vanilla/node_modules/@vitest/snapshot/LICENSE | 21 + vanilla/node_modules/@vitest/snapshot/README.md | 84 + .../snapshot/dist/environment.d-DHdQ1Csl.d.ts | 22 + .../@vitest/snapshot/dist/environment.d.ts | 16 + .../@vitest/snapshot/dist/environment.js | 40 + .../node_modules/@vitest/snapshot/dist/index.d.ts | 130 + .../node_modules/@vitest/snapshot/dist/index.js | 1437 + .../@vitest/snapshot/dist/manager.d.ts | 18 + .../node_modules/@vitest/snapshot/dist/manager.js | 73 + .../snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts | 61 + .../node_modules/@vitest/snapshot/environment.d.ts | 1 + vanilla/node_modules/@vitest/snapshot/manager.d.ts | 1 + vanilla/node_modules/@vitest/snapshot/package.json | 54 + vanilla/node_modules/@vitest/spy/LICENSE | 21 + vanilla/node_modules/@vitest/spy/README.md | 3 + vanilla/node_modules/@vitest/spy/dist/index.d.ts | 384 + vanilla/node_modules/@vitest/spy/dist/index.js | 433 + vanilla/node_modules/@vitest/spy/package.json | 35 + vanilla/node_modules/@vitest/utils/LICENSE | 21 + vanilla/node_modules/@vitest/utils/diff.d.ts | 1 + .../@vitest/utils/dist/chunk-_commonjsHelpers.js | 5 + .../@vitest/utils/dist/chunk-pathe.M-eThtNZ.js | 156 + .../node_modules/@vitest/utils/dist/constants.d.ts | 21 + .../node_modules/@vitest/utils/dist/constants.js | 49 + vanilla/node_modules/@vitest/utils/dist/diff.d.ts | 93 + vanilla/node_modules/@vitest/utils/dist/diff.js | 2199 ++ .../node_modules/@vitest/utils/dist/display.d.ts | 29 + vanilla/node_modules/@vitest/utils/dist/display.js | 742 + vanilla/node_modules/@vitest/utils/dist/error.d.ts | 7 + vanilla/node_modules/@vitest/utils/dist/error.js | 42 + .../node_modules/@vitest/utils/dist/helpers.d.ts | 73 + vanilla/node_modules/@vitest/utils/dist/helpers.js | 295 + .../node_modules/@vitest/utils/dist/highlight.d.ts | 9 + .../node_modules/@vitest/utils/dist/highlight.js | 538 + vanilla/node_modules/@vitest/utils/dist/index.d.ts | 5 + vanilla/node_modules/@vitest/utils/dist/index.js | 1 + .../node_modules/@vitest/utils/dist/offset.d.ts | 5 + vanilla/node_modules/@vitest/utils/dist/offset.js | 32 + .../node_modules/@vitest/utils/dist/resolver.d.ts | 7 + .../node_modules/@vitest/utils/dist/resolver.js | 71 + .../node_modules/@vitest/utils/dist/serialize.d.ts | 3 + .../node_modules/@vitest/utils/dist/serialize.js | 118 + .../@vitest/utils/dist/source-map.d.ts | 55 + .../node_modules/@vitest/utils/dist/source-map.js | 478 + .../node_modules/@vitest/utils/dist/timers.d.ts | 33 + vanilla/node_modules/@vitest/utils/dist/timers.js | 49 + .../@vitest/utils/dist/types.d-BCElaP-c.d.ts | 53 + vanilla/node_modules/@vitest/utils/dist/types.d.ts | 34 + vanilla/node_modules/@vitest/utils/dist/types.js | 1 + vanilla/node_modules/@vitest/utils/error.d.ts | 1 + vanilla/node_modules/@vitest/utils/helpers.d.ts | 1 + vanilla/node_modules/@vitest/utils/package.json | 98 + vanilla/node_modules/agent-base/LICENSE | 22 + vanilla/node_modules/agent-base/README.md | 69 + vanilla/node_modules/agent-base/dist/helpers.d.ts | 15 + .../node_modules/agent-base/dist/helpers.d.ts.map | 1 + vanilla/node_modules/agent-base/dist/helpers.js | 66 + .../node_modules/agent-base/dist/helpers.js.map | 1 + vanilla/node_modules/agent-base/dist/index.d.ts | 41 + .../node_modules/agent-base/dist/index.d.ts.map | 1 + vanilla/node_modules/agent-base/dist/index.js | 178 + vanilla/node_modules/agent-base/dist/index.js.map | 1 + vanilla/node_modules/agent-base/package.json | 46 + vanilla/node_modules/assertion-error/LICENSE | 21 + vanilla/node_modules/assertion-error/README.md | 68 + vanilla/node_modules/assertion-error/index.d.ts | 27 + vanilla/node_modules/assertion-error/index.js | 60 + vanilla/node_modules/assertion-error/package.json | 32 + vanilla/node_modules/ast-v8-to-istanbul/LICENSE | 21 + vanilla/node_modules/ast-v8-to-istanbul/README.md | 278 + .../ast-v8-to-istanbul/dist/index.d.mts | 568 + .../node_modules/ast-v8-to-istanbul/dist/index.mjs | 848 + .../node_modules/ast-v8-to-istanbul/package.json | 71 + vanilla/node_modules/bidi-js/LICENSE.txt | 22 + vanilla/node_modules/bidi-js/README.md | 133 + vanilla/node_modules/bidi-js/dist/bidi.js | 1010 + vanilla/node_modules/bidi-js/dist/bidi.min.js | 1 + vanilla/node_modules/bidi-js/dist/bidi.min.mjs | 1 + vanilla/node_modules/bidi-js/dist/bidi.mjs | 1002 + vanilla/node_modules/bidi-js/package.json | 39 + vanilla/node_modules/bidi-js/src/brackets.js | 30 + vanilla/node_modules/bidi-js/src/charTypes.js | 66 + .../bidi-js/src/data/bidiBrackets.data.js | 5 + .../bidi-js/src/data/bidiCharTypes.data.js | 25 + .../bidi-js/src/data/bidiMirroring.data.js | 2 + .../node_modules/bidi-js/src/embeddingLevels.js | 690 + vanilla/node_modules/bidi-js/src/index.js | 5 + vanilla/node_modules/bidi-js/src/mirroring.js | 48 + vanilla/node_modules/bidi-js/src/reordering.js | 99 + .../bidi-js/src/util/parseCharacterMap.js | 30 + vanilla/node_modules/chai/LICENSE | 21 + vanilla/node_modules/chai/README.md | 162 + vanilla/node_modules/chai/index.js | 4172 +++ vanilla/node_modules/chai/package.json | 71 + vanilla/node_modules/chai/register-assert.js | 3 + vanilla/node_modules/chai/register-expect.js | 3 + vanilla/node_modules/chai/register-should.js | 3 + vanilla/node_modules/css-tree/LICENSE | 19 + vanilla/node_modules/css-tree/README.md | 192 + .../node_modules/css-tree/cjs/convertor/create.cjs | 32 + .../node_modules/css-tree/cjs/convertor/index.cjs | 8 + vanilla/node_modules/css-tree/cjs/data-patch.cjs | 7 + vanilla/node_modules/css-tree/cjs/data.cjs | 120 + .../css-tree/cjs/definition-syntax/SyntaxError.cjs | 16 + .../css-tree/cjs/definition-syntax/generate.cjs | 139 + .../css-tree/cjs/definition-syntax/index.cjs | 13 + .../css-tree/cjs/definition-syntax/parse.cjs | 556 + .../css-tree/cjs/definition-syntax/scanner.cjs | 113 + .../css-tree/cjs/definition-syntax/tokenizer.cjs | 59 + .../css-tree/cjs/definition-syntax/walk.cjs | 57 + .../node_modules/css-tree/cjs/generator/create.cjs | 102 + .../node_modules/css-tree/cjs/generator/index.cjs | 8 + .../css-tree/cjs/generator/sourceMap.cjs | 96 + .../css-tree/cjs/generator/token-before.cjs | 170 + vanilla/node_modules/css-tree/cjs/index.cjs | 65 + vanilla/node_modules/css-tree/cjs/lexer/Lexer.cjs | 517 + vanilla/node_modules/css-tree/cjs/lexer/error.cjs | 128 + .../css-tree/cjs/lexer/generic-an-plus-b.cjs | 235 + .../css-tree/cjs/lexer/generic-const.cjs | 12 + .../css-tree/cjs/lexer/generic-urange.cjs | 149 + .../node_modules/css-tree/cjs/lexer/generic.cjs | 589 + vanilla/node_modules/css-tree/cjs/lexer/index.cjs | 7 + .../css-tree/cjs/lexer/match-graph.cjs | 530 + vanilla/node_modules/css-tree/cjs/lexer/match.cjs | 632 + .../css-tree/cjs/lexer/prepare-tokens.cjs | 54 + vanilla/node_modules/css-tree/cjs/lexer/search.cjs | 65 + .../node_modules/css-tree/cjs/lexer/structure.cjs | 173 + vanilla/node_modules/css-tree/cjs/lexer/trace.cjs | 73 + vanilla/node_modules/css-tree/cjs/lexer/units.cjs | 38 + .../css-tree/cjs/parser/SyntaxError.cjs | 74 + .../node_modules/css-tree/cjs/parser/create.cjs | 340 + vanilla/node_modules/css-tree/cjs/parser/index.cjs | 8 + .../css-tree/cjs/parser/parse-selector.cjs | 8 + .../node_modules/css-tree/cjs/parser/sequence.cjs | 47 + .../css-tree/cjs/syntax/atrule/container.cjs | 32 + .../css-tree/cjs/syntax/atrule/font-face.cjs | 12 + .../css-tree/cjs/syntax/atrule/import.cjs | 101 + .../css-tree/cjs/syntax/atrule/index.cjs | 27 + .../css-tree/cjs/syntax/atrule/layer.cjs | 16 + .../css-tree/cjs/syntax/atrule/media.cjs | 16 + .../css-tree/cjs/syntax/atrule/nest.cjs | 16 + .../css-tree/cjs/syntax/atrule/page.cjs | 16 + .../css-tree/cjs/syntax/atrule/scope.cjs | 16 + .../css-tree/cjs/syntax/atrule/starting-style.cjs | 12 + .../css-tree/cjs/syntax/atrule/supports.cjs | 16 + .../css-tree/cjs/syntax/config/generator.cjs | 9 + .../css-tree/cjs/syntax/config/lexer.cjs | 14 + .../css-tree/cjs/syntax/config/mix.cjs | 127 + .../css-tree/cjs/syntax/config/parser-selector.cjs | 19 + .../css-tree/cjs/syntax/config/parser.cjs | 49 + .../css-tree/cjs/syntax/config/walker.cjs | 9 + .../node_modules/css-tree/cjs/syntax/create.cjs | 58 + .../css-tree/cjs/syntax/function/expression.cjs | 11 + .../css-tree/cjs/syntax/function/var.cjs | 43 + vanilla/node_modules/css-tree/cjs/syntax/index.cjs | 14 + .../css-tree/cjs/syntax/node/AnPlusB.cjs | 293 + .../css-tree/cjs/syntax/node/Atrule.cjs | 103 + .../css-tree/cjs/syntax/node/AtrulePrelude.cjs | 52 + .../css-tree/cjs/syntax/node/AttributeSelector.cjs | 148 + .../css-tree/cjs/syntax/node/Block.cjs | 96 + .../css-tree/cjs/syntax/node/Brackets.cjs | 38 + .../node_modules/css-tree/cjs/syntax/node/CDC.cjs | 26 + .../node_modules/css-tree/cjs/syntax/node/CDO.cjs | 26 + .../css-tree/cjs/syntax/node/ClassSelector.cjs | 31 + .../css-tree/cjs/syntax/node/Combinator.cjs | 61 + .../css-tree/cjs/syntax/node/Comment.cjs | 40 + .../css-tree/cjs/syntax/node/Condition.cjs | 120 + .../css-tree/cjs/syntax/node/Declaration.cjs | 166 + .../css-tree/cjs/syntax/node/DeclarationList.cjs | 62 + .../css-tree/cjs/syntax/node/Dimension.cjs | 30 + .../css-tree/cjs/syntax/node/Feature.cjs | 101 + .../css-tree/cjs/syntax/node/FeatureFunction.cjs | 67 + .../css-tree/cjs/syntax/node/FeatureRange.cjs | 133 + .../css-tree/cjs/syntax/node/Function.cjs | 45 + .../css-tree/cjs/syntax/node/GeneralEnclosed.cjs | 68 + .../node_modules/css-tree/cjs/syntax/node/Hash.cjs | 30 + .../css-tree/cjs/syntax/node/IdSelector.cjs | 33 + .../css-tree/cjs/syntax/node/Identifier.cjs | 25 + .../css-tree/cjs/syntax/node/Layer.cjs | 35 + .../css-tree/cjs/syntax/node/LayerList.cjs | 43 + .../css-tree/cjs/syntax/node/LayerName.cjs | 34 + .../css-tree/cjs/syntax/node/LayerNameList.cjs | 42 + .../css-tree/cjs/syntax/node/MediaCondition.cjs | 70 + .../css-tree/cjs/syntax/node/MediaFeature.cjs | 76 + .../css-tree/cjs/syntax/node/MediaFeatureRange.cjs | 11 + .../css-tree/cjs/syntax/node/MediaQuery.cjs | 100 + .../css-tree/cjs/syntax/node/MediaQueryList.cjs | 41 + .../css-tree/cjs/syntax/node/NestingSelector.cjs | 29 + .../node_modules/css-tree/cjs/syntax/node/Nth.cjs | 54 + .../css-tree/cjs/syntax/node/Number.cjs | 25 + .../css-tree/cjs/syntax/node/Operator.cjs | 28 + .../css-tree/cjs/syntax/node/Parentheses.cjs | 38 + .../css-tree/cjs/syntax/node/Percentage.cjs | 25 + .../cjs/syntax/node/PseudoClassSelector.cjs | 67 + .../cjs/syntax/node/PseudoElementSelector.cjs | 69 + .../css-tree/cjs/syntax/node/Ratio.cjs | 71 + .../node_modules/css-tree/cjs/syntax/node/Raw.cjs | 48 + .../node_modules/css-tree/cjs/syntax/node/Rule.cjs | 58 + .../css-tree/cjs/syntax/node/Scope.cjs | 69 + .../css-tree/cjs/syntax/node/Selector.cjs | 38 + .../css-tree/cjs/syntax/node/SelectorList.cjs | 43 + .../css-tree/cjs/syntax/node/String.cjs | 26 + .../css-tree/cjs/syntax/node/StyleSheet.cjs | 83 + .../cjs/syntax/node/SupportsDeclaration.cjs | 38 + .../css-tree/cjs/syntax/node/SupportsFeature.cjs | 69 + .../css-tree/cjs/syntax/node/TypeSelector.cjs | 59 + .../css-tree/cjs/syntax/node/UnicodeRange.cjs | 158 + .../node_modules/css-tree/cjs/syntax/node/Url.cjs | 54 + .../css-tree/cjs/syntax/node/Value.cjs | 26 + .../css-tree/cjs/syntax/node/WhiteSpace.cjs | 34 + .../cjs/syntax/node/common/feature-range.cjs | 112 + .../css-tree/cjs/syntax/node/common/feature.cjs | 76 + .../css-tree/cjs/syntax/node/index-generate.cjs | 103 + .../cjs/syntax/node/index-parse-selector.cjs | 39 + .../css-tree/cjs/syntax/node/index-parse.cjs | 103 + .../css-tree/cjs/syntax/node/index.cjs | 103 + .../css-tree/cjs/syntax/pseudo/index.cjs | 60 + .../css-tree/cjs/syntax/pseudo/lang.cjs | 37 + .../css-tree/cjs/syntax/scope/atrulePrelude.cjs | 9 + .../css-tree/cjs/syntax/scope/default.cjs | 76 + .../css-tree/cjs/syntax/scope/index.cjs | 11 + .../css-tree/cjs/syntax/scope/selector.cjs | 88 + .../css-tree/cjs/syntax/scope/value.cjs | 29 + .../css-tree/cjs/tokenizer/OffsetToLocation.cjs | 91 + .../css-tree/cjs/tokenizer/TokenStream.cjs | 308 + .../css-tree/cjs/tokenizer/adopt-buffer.cjs | 13 + .../cjs/tokenizer/char-code-definitions.cjs | 236 + .../node_modules/css-tree/cjs/tokenizer/index.cjs | 554 + .../node_modules/css-tree/cjs/tokenizer/names.cjs | 32 + .../node_modules/css-tree/cjs/tokenizer/types.cjs | 57 + .../node_modules/css-tree/cjs/tokenizer/utils.cjs | 261 + vanilla/node_modules/css-tree/cjs/utils/List.cjs | 473 + vanilla/node_modules/css-tree/cjs/utils/clone.cjs | 25 + .../css-tree/cjs/utils/create-custom-error.cjs | 18 + vanilla/node_modules/css-tree/cjs/utils/ident.cjs | 102 + vanilla/node_modules/css-tree/cjs/utils/index.cjs | 20 + vanilla/node_modules/css-tree/cjs/utils/names.cjs | 113 + vanilla/node_modules/css-tree/cjs/utils/string.cjs | 99 + vanilla/node_modules/css-tree/cjs/utils/url.cjs | 108 + vanilla/node_modules/css-tree/cjs/version.cjs | 5 + .../node_modules/css-tree/cjs/walker/create.cjs | 291 + vanilla/node_modules/css-tree/cjs/walker/index.cjs | 8 + vanilla/node_modules/css-tree/data/patch.json | 982 + vanilla/node_modules/css-tree/dist/csstree.esm.js | 12 + vanilla/node_modules/css-tree/dist/csstree.js | 12 + vanilla/node_modules/css-tree/dist/data.cjs | 1308 + vanilla/node_modules/css-tree/dist/data.js | 1308 + vanilla/node_modules/css-tree/dist/version.cjs | 1 + vanilla/node_modules/css-tree/dist/version.js | 1 + .../node_modules/css-tree/lib/convertor/create.js | 28 + .../node_modules/css-tree/lib/convertor/index.js | 4 + vanilla/node_modules/css-tree/lib/data-patch.js | 6 + vanilla/node_modules/css-tree/lib/data.js | 118 + .../css-tree/lib/definition-syntax/SyntaxError.js | 12 + .../css-tree/lib/definition-syntax/generate.js | 135 + .../css-tree/lib/definition-syntax/index.js | 4 + .../css-tree/lib/definition-syntax/parse.js | 552 + .../css-tree/lib/definition-syntax/scanner.js | 109 + .../css-tree/lib/definition-syntax/walk.js | 53 + .../node_modules/css-tree/lib/generator/create.js | 97 + .../node_modules/css-tree/lib/generator/index.js | 4 + .../css-tree/lib/generator/sourceMap.js | 92 + .../css-tree/lib/generator/token-before.js | 182 + vanilla/node_modules/css-tree/lib/index.js | 30 + vanilla/node_modules/css-tree/lib/lexer/Lexer.js | 511 + vanilla/node_modules/css-tree/lib/lexer/error.js | 123 + .../css-tree/lib/lexer/generic-an-plus-b.js | 238 + .../css-tree/lib/lexer/generic-const.js | 8 + .../css-tree/lib/lexer/generic-urange.js | 151 + vanilla/node_modules/css-tree/lib/lexer/generic.js | 622 + vanilla/node_modules/css-tree/lib/lexer/index.js | 1 + .../node_modules/css-tree/lib/lexer/match-graph.js | 527 + vanilla/node_modules/css-tree/lib/lexer/match.js | 630 + .../css-tree/lib/lexer/prepare-tokens.js | 50 + vanilla/node_modules/css-tree/lib/lexer/search.js | 61 + .../node_modules/css-tree/lib/lexer/structure.js | 169 + vanilla/node_modules/css-tree/lib/lexer/trace.js | 66 + vanilla/node_modules/css-tree/lib/lexer/units.js | 27 + .../css-tree/lib/parser/SyntaxError.js | 70 + vanilla/node_modules/css-tree/lib/parser/create.js | 350 + vanilla/node_modules/css-tree/lib/parser/index.js | 4 + .../css-tree/lib/parser/parse-selector.js | 4 + .../node_modules/css-tree/lib/parser/sequence.js | 43 + .../css-tree/lib/syntax/atrule/container.js | 28 + .../css-tree/lib/syntax/atrule/font-face.js | 8 + .../css-tree/lib/syntax/atrule/import.js | 104 + .../css-tree/lib/syntax/atrule/index.js | 23 + .../css-tree/lib/syntax/atrule/layer.js | 12 + .../css-tree/lib/syntax/atrule/media.js | 12 + .../css-tree/lib/syntax/atrule/nest.js | 12 + .../css-tree/lib/syntax/atrule/page.js | 12 + .../css-tree/lib/syntax/atrule/scope.js | 12 + .../css-tree/lib/syntax/atrule/starting-style.js | 8 + .../css-tree/lib/syntax/atrule/supports.js | 12 + .../css-tree/lib/syntax/config/generator.js | 5 + .../css-tree/lib/syntax/config/lexer.js | 10 + .../node_modules/css-tree/lib/syntax/config/mix.js | 123 + .../css-tree/lib/syntax/config/parser-selector.js | 15 + .../css-tree/lib/syntax/config/parser.js | 45 + .../css-tree/lib/syntax/config/walker.js | 5 + vanilla/node_modules/css-tree/lib/syntax/create.js | 55 + .../css-tree/lib/syntax/function/expression.js | 7 + .../css-tree/lib/syntax/function/var.js | 39 + vanilla/node_modules/css-tree/lib/syntax/index.js | 10 + .../css-tree/lib/syntax/node/AnPlusB.js | 292 + .../css-tree/lib/syntax/node/Atrule.js | 100 + .../css-tree/lib/syntax/node/AtrulePrelude.js | 47 + .../css-tree/lib/syntax/node/AttributeSelector.js | 147 + .../node_modules/css-tree/lib/syntax/node/Block.js | 95 + .../css-tree/lib/syntax/node/Brackets.js | 35 + .../node_modules/css-tree/lib/syntax/node/CDC.js | 19 + .../node_modules/css-tree/lib/syntax/node/CDO.js | 19 + .../css-tree/lib/syntax/node/ClassSelector.js | 24 + .../css-tree/lib/syntax/node/Combinator.js | 54 + .../css-tree/lib/syntax/node/Comment.js | 33 + .../css-tree/lib/syntax/node/Condition.js | 123 + .../css-tree/lib/syntax/node/Declaration.js | 165 + .../css-tree/lib/syntax/node/DeclarationList.js | 62 + .../css-tree/lib/syntax/node/Dimension.js | 23 + .../css-tree/lib/syntax/node/Feature.js | 103 + .../css-tree/lib/syntax/node/FeatureFunction.js | 63 + .../css-tree/lib/syntax/node/FeatureRange.js | 133 + .../css-tree/lib/syntax/node/Function.js | 41 + .../css-tree/lib/syntax/node/GeneralEnclosed.js | 66 + .../node_modules/css-tree/lib/syntax/node/Hash.js | 23 + .../css-tree/lib/syntax/node/IdSelector.js | 26 + .../css-tree/lib/syntax/node/Identifier.js | 18 + .../node_modules/css-tree/lib/syntax/node/Layer.js | 28 + .../css-tree/lib/syntax/node/LayerList.js | 36 + .../css-tree/lib/syntax/node/MediaQuery.js | 102 + .../css-tree/lib/syntax/node/MediaQueryList.js | 34 + .../css-tree/lib/syntax/node/NestingSelector.js | 22 + .../node_modules/css-tree/lib/syntax/node/Nth.js | 47 + .../css-tree/lib/syntax/node/Number.js | 18 + .../css-tree/lib/syntax/node/Operator.js | 21 + .../css-tree/lib/syntax/node/Parentheses.js | 34 + .../css-tree/lib/syntax/node/Percentage.js | 18 + .../lib/syntax/node/PseudoClassSelector.js | 65 + .../lib/syntax/node/PseudoElementSelector.js | 66 + .../node_modules/css-tree/lib/syntax/node/Ratio.js | 68 + .../node_modules/css-tree/lib/syntax/node/Raw.js | 41 + .../node_modules/css-tree/lib/syntax/node/Rule.js | 51 + .../node_modules/css-tree/lib/syntax/node/Scope.js | 66 + .../css-tree/lib/syntax/node/Selector.js | 31 + .../css-tree/lib/syntax/node/SelectorList.js | 35 + .../css-tree/lib/syntax/node/String.js | 19 + .../css-tree/lib/syntax/node/StyleSheet.js | 82 + .../lib/syntax/node/SupportsDeclaration.js | 34 + .../css-tree/lib/syntax/node/TypeSelector.js | 52 + .../css-tree/lib/syntax/node/UnicodeRange.js | 156 + .../node_modules/css-tree/lib/syntax/node/Url.js | 52 + .../node_modules/css-tree/lib/syntax/node/Value.js | 19 + .../css-tree/lib/syntax/node/WhiteSpace.js | 27 + .../css-tree/lib/syntax/node/index-generate.js | 49 + .../lib/syntax/node/index-parse-selector.js | 17 + .../css-tree/lib/syntax/node/index-parse.js | 49 + .../node_modules/css-tree/lib/syntax/node/index.js | 49 + .../css-tree/lib/syntax/pseudo/index.js | 56 + .../css-tree/lib/syntax/pseudo/lang.js | 33 + .../css-tree/lib/syntax/scope/atrulePrelude.js | 5 + .../css-tree/lib/syntax/scope/default.js | 85 + .../css-tree/lib/syntax/scope/index.js | 3 + .../css-tree/lib/syntax/scope/selector.js | 94 + .../css-tree/lib/syntax/scope/value.js | 25 + .../css-tree/lib/tokenizer/OffsetToLocation.js | 87 + .../css-tree/lib/tokenizer/TokenStream.js | 316 + .../css-tree/lib/tokenizer/adopt-buffer.js | 9 + .../lib/tokenizer/char-code-definitions.js | 212 + .../node_modules/css-tree/lib/tokenizer/index.js | 513 + .../node_modules/css-tree/lib/tokenizer/names.js | 28 + .../node_modules/css-tree/lib/tokenizer/types.js | 28 + .../node_modules/css-tree/lib/tokenizer/utils.js | 254 + vanilla/node_modules/css-tree/lib/utils/List.js | 469 + vanilla/node_modules/css-tree/lib/utils/clone.js | 21 + .../css-tree/lib/utils/create-custom-error.js | 14 + vanilla/node_modules/css-tree/lib/utils/ident.js | 101 + vanilla/node_modules/css-tree/lib/utils/index.js | 6 + vanilla/node_modules/css-tree/lib/utils/names.js | 106 + vanilla/node_modules/css-tree/lib/utils/string.js | 99 + vanilla/node_modules/css-tree/lib/utils/url.js | 108 + vanilla/node_modules/css-tree/lib/version.js | 5 + vanilla/node_modules/css-tree/lib/walker/create.js | 287 + vanilla/node_modules/css-tree/lib/walker/index.js | 4 + vanilla/node_modules/css-tree/package.json | 125 + vanilla/node_modules/cssstyle/LICENSE | 20 + vanilla/node_modules/cssstyle/README.md | 11 + .../cssstyle/lib/CSSStyleDeclaration.js | 649 + .../cssstyle/lib/generated/allProperties.js | 653 + .../lib/generated/implementedProperties.js | 1466 + .../cssstyle/lib/generated/properties.js | 6637 ++++ .../cssstyle/lib/generated/propertyDefinitions.js | 13033 +++++++ vanilla/node_modules/cssstyle/lib/normalize.js | 1574 + vanilla/node_modules/cssstyle/lib/parsers.js | 871 + .../cssstyle/lib/properties/background.js | 406 + .../lib/properties/backgroundAttachment.js | 61 + .../cssstyle/lib/properties/backgroundClip.js | 61 + .../cssstyle/lib/properties/backgroundColor.js | 50 + .../cssstyle/lib/properties/backgroundImage.js | 63 + .../cssstyle/lib/properties/backgroundOrigin.js | 61 + .../cssstyle/lib/properties/backgroundPosition.js | 204 + .../cssstyle/lib/properties/backgroundRepeat.js | 93 + .../cssstyle/lib/properties/backgroundSize.js | 126 + .../node_modules/cssstyle/lib/properties/border.js | 107 + .../cssstyle/lib/properties/borderBottom.js | 100 + .../cssstyle/lib/properties/borderBottomColor.js | 54 + .../cssstyle/lib/properties/borderBottomStyle.js | 54 + .../cssstyle/lib/properties/borderBottomWidth.js | 57 + .../cssstyle/lib/properties/borderCollapse.js | 45 + .../cssstyle/lib/properties/borderColor.js | 110 + .../cssstyle/lib/properties/borderLeft.js | 100 + .../cssstyle/lib/properties/borderLeftColor.js | 54 + .../cssstyle/lib/properties/borderLeftStyle.js | 54 + .../cssstyle/lib/properties/borderLeftWidth.js | 57 + .../cssstyle/lib/properties/borderRight.js | 100 + .../cssstyle/lib/properties/borderRightColor.js | 54 + .../cssstyle/lib/properties/borderRightStyle.js | 54 + .../cssstyle/lib/properties/borderRightWidth.js | 57 + .../cssstyle/lib/properties/borderSpacing.js | 65 + .../cssstyle/lib/properties/borderStyle.js | 110 + .../cssstyle/lib/properties/borderTop.js | 100 + .../cssstyle/lib/properties/borderTopColor.js | 54 + .../cssstyle/lib/properties/borderTopStyle.js | 54 + .../cssstyle/lib/properties/borderTopWidth.js | 57 + .../cssstyle/lib/properties/borderWidth.js | 111 + .../node_modules/cssstyle/lib/properties/bottom.js | 47 + .../node_modules/cssstyle/lib/properties/clear.js | 45 + .../node_modules/cssstyle/lib/properties/clip.js | 73 + .../node_modules/cssstyle/lib/properties/color.js | 45 + .../cssstyle/lib/properties/display.js | 210 + .../node_modules/cssstyle/lib/properties/flex.js | 178 + .../cssstyle/lib/properties/flexBasis.js | 52 + .../cssstyle/lib/properties/flexGrow.js | 52 + .../cssstyle/lib/properties/flexShrink.js | 52 + .../node_modules/cssstyle/lib/properties/float.js | 45 + .../cssstyle/lib/properties/floodColor.js | 45 + .../node_modules/cssstyle/lib/properties/font.js | 302 + .../cssstyle/lib/properties/fontFamily.js | 98 + .../cssstyle/lib/properties/fontSize.js | 53 + .../cssstyle/lib/properties/fontStyle.js | 69 + .../cssstyle/lib/properties/fontVariant.js | 66 + .../cssstyle/lib/properties/fontWeight.js | 57 + .../node_modules/cssstyle/lib/properties/height.js | 48 + .../node_modules/cssstyle/lib/properties/left.js | 47 + .../cssstyle/lib/properties/lightingColor.js | 45 + .../cssstyle/lib/properties/lineHeight.js | 52 + .../node_modules/cssstyle/lib/properties/margin.js | 77 + .../cssstyle/lib/properties/marginBottom.js | 54 + .../cssstyle/lib/properties/marginLeft.js | 54 + .../cssstyle/lib/properties/marginRight.js | 54 + .../cssstyle/lib/properties/marginTop.js | 54 + .../cssstyle/lib/properties/opacity.js | 47 + .../cssstyle/lib/properties/outlineColor.js | 45 + .../cssstyle/lib/properties/padding.js | 78 + .../cssstyle/lib/properties/paddingBottom.js | 55 + .../cssstyle/lib/properties/paddingLeft.js | 55 + .../cssstyle/lib/properties/paddingRight.js | 55 + .../cssstyle/lib/properties/paddingTop.js | 55 + .../node_modules/cssstyle/lib/properties/right.js | 47 + .../cssstyle/lib/properties/stopColor.js | 45 + .../node_modules/cssstyle/lib/properties/top.js | 47 + .../lib/properties/webkitBorderAfterColor.js | 45 + .../lib/properties/webkitBorderBeforeColor.js | 45 + .../lib/properties/webkitBorderEndColor.js | 45 + .../lib/properties/webkitBorderStartColor.js | 45 + .../lib/properties/webkitColumnRuleColor.js | 45 + .../lib/properties/webkitTapHighlightColor.js | 45 + .../lib/properties/webkitTextEmphasisColor.js | 45 + .../cssstyle/lib/properties/webkitTextFillColor.js | 45 + .../lib/properties/webkitTextStrokeColor.js | 45 + .../node_modules/cssstyle/lib/properties/width.js | 48 + .../cssstyle/lib/utils/allExtraProperties.js | 155 + .../node_modules/cssstyle/lib/utils/camelize.js | 37 + .../cssstyle/lib/utils/propertyDescriptors.js | 55 + vanilla/node_modules/cssstyle/lib/utils/strings.js | 173 + vanilla/node_modules/cssstyle/package.json | 53 + vanilla/node_modules/data-urls/LICENSE.txt | 7 + vanilla/node_modules/data-urls/README.md | 66 + vanilla/node_modules/data-urls/lib/parser.js | 69 + vanilla/node_modules/data-urls/lib/utils.js | 20 + vanilla/node_modules/data-urls/package.json | 51 + vanilla/node_modules/debug/LICENSE | 20 + vanilla/node_modules/debug/README.md | 481 + vanilla/node_modules/debug/package.json | 64 + vanilla/node_modules/debug/src/browser.js | 272 + vanilla/node_modules/debug/src/common.js | 292 + vanilla/node_modules/debug/src/index.js | 10 + vanilla/node_modules/debug/src/node.js | 263 + vanilla/node_modules/decimal.js/LICENCE.md | 23 + vanilla/node_modules/decimal.js/README.md | 246 + vanilla/node_modules/decimal.js/decimal.d.ts | 301 + vanilla/node_modules/decimal.js/decimal.js | 4951 +++ vanilla/node_modules/decimal.js/decimal.mjs | 4914 +++ vanilla/node_modules/decimal.js/package.json | 55 + vanilla/node_modules/entities/LICENSE | 11 + vanilla/node_modules/entities/decode.d.ts | 1 + vanilla/node_modules/entities/decode.js | 3 + .../entities/dist/commonjs/decode-codepoint.d.ts | 19 + .../dist/commonjs/decode-codepoint.d.ts.map | 1 + .../entities/dist/commonjs/decode-codepoint.js | 77 + .../entities/dist/commonjs/decode-codepoint.js.map | 1 + .../entities/dist/commonjs/decode.d.ts | 209 + .../entities/dist/commonjs/decode.d.ts.map | 1 + .../node_modules/entities/dist/commonjs/decode.js | 511 + .../entities/dist/commonjs/decode.js.map | 1 + .../entities/dist/commonjs/encode.d.ts | 22 + .../entities/dist/commonjs/encode.d.ts.map | 1 + .../node_modules/entities/dist/commonjs/encode.js | 73 + .../entities/dist/commonjs/encode.js.map | 1 + .../entities/dist/commonjs/escape.d.ts | 43 + .../entities/dist/commonjs/escape.d.ts.map | 1 + .../node_modules/entities/dist/commonjs/escape.js | 121 + .../entities/dist/commonjs/escape.js.map | 1 + .../dist/commonjs/generated/decode-data-html.d.ts | 2 + .../commonjs/generated/decode-data-html.d.ts.map | 1 + .../dist/commonjs/generated/decode-data-html.js | 10 + .../commonjs/generated/decode-data-html.js.map | 1 + .../dist/commonjs/generated/decode-data-xml.d.ts | 2 + .../commonjs/generated/decode-data-xml.d.ts.map | 1 + .../dist/commonjs/generated/decode-data-xml.js | 10 + .../dist/commonjs/generated/decode-data-xml.js.map | 1 + .../dist/commonjs/generated/encode-html.d.ts | 8 + .../dist/commonjs/generated/encode-html.d.ts.map | 1 + .../dist/commonjs/generated/encode-html.js | 13 + .../dist/commonjs/generated/encode-html.js.map | 1 + .../node_modules/entities/dist/commonjs/index.d.ts | 96 + .../entities/dist/commonjs/index.d.ts.map | 1 + .../node_modules/entities/dist/commonjs/index.js | 131 + .../entities/dist/commonjs/index.js.map | 1 + .../entities/dist/commonjs/package.json | 3 + .../entities/dist/esm/decode-codepoint.d.ts | 19 + .../entities/dist/esm/decode-codepoint.d.ts.map | 1 + .../entities/dist/esm/decode-codepoint.js | 72 + .../entities/dist/esm/decode-codepoint.js.map | 1 + vanilla/node_modules/entities/dist/esm/decode.d.ts | 209 + .../node_modules/entities/dist/esm/decode.d.ts.map | 1 + vanilla/node_modules/entities/dist/esm/decode.js | 497 + .../node_modules/entities/dist/esm/decode.js.map | 1 + vanilla/node_modules/entities/dist/esm/encode.d.ts | 22 + .../node_modules/entities/dist/esm/encode.d.ts.map | 1 + vanilla/node_modules/entities/dist/esm/encode.js | 69 + .../node_modules/entities/dist/esm/encode.js.map | 1 + vanilla/node_modules/entities/dist/esm/escape.d.ts | 43 + .../node_modules/entities/dist/esm/escape.d.ts.map | 1 + vanilla/node_modules/entities/dist/esm/escape.js | 117 + .../node_modules/entities/dist/esm/escape.js.map | 1 + .../dist/esm/generated/decode-data-html.d.ts | 2 + .../dist/esm/generated/decode-data-html.d.ts.map | 1 + .../dist/esm/generated/decode-data-html.js | 7 + .../dist/esm/generated/decode-data-html.js.map | 1 + .../dist/esm/generated/decode-data-xml.d.ts | 2 + .../dist/esm/generated/decode-data-xml.d.ts.map | 1 + .../entities/dist/esm/generated/decode-data-xml.js | 7 + .../dist/esm/generated/decode-data-xml.js.map | 1 + .../entities/dist/esm/generated/encode-html.d.ts | 8 + .../dist/esm/generated/encode-html.d.ts.map | 1 + .../entities/dist/esm/generated/encode-html.js | 10 + .../entities/dist/esm/generated/encode-html.js.map | 1 + vanilla/node_modules/entities/dist/esm/index.d.ts | 96 + .../node_modules/entities/dist/esm/index.d.ts.map | 1 + vanilla/node_modules/entities/dist/esm/index.js | 107 + .../node_modules/entities/dist/esm/index.js.map | 1 + .../node_modules/entities/dist/esm/package.json | 3 + vanilla/node_modules/entities/escape.d.ts | 1 + vanilla/node_modules/entities/escape.js | 3 + vanilla/node_modules/entities/package.json | 118 + vanilla/node_modules/entities/readme.md | 122 + .../node_modules/entities/src/decode-codepoint.ts | 81 + vanilla/node_modules/entities/src/decode.spec.ts | 320 + vanilla/node_modules/entities/src/decode.ts | 620 + vanilla/node_modules/entities/src/encode.spec.ts | 78 + vanilla/node_modules/entities/src/encode.ts | 77 + vanilla/node_modules/entities/src/escape.spec.ts | 14 + vanilla/node_modules/entities/src/escape.ts | 148 + .../entities/src/generated/.eslintrc.json | 10 + .../entities/src/generated/decode-data-html.ts | 8 + .../entities/src/generated/decode-data-xml.ts | 8 + .../entities/src/generated/encode-html.ts | 17 + vanilla/node_modules/entities/src/index.spec.ts | 125 + vanilla/node_modules/entities/src/index.ts | 188 + vanilla/node_modules/es-module-lexer/LICENSE | 10 + vanilla/node_modules/es-module-lexer/README.md | 338 + .../node_modules/es-module-lexer/dist/lexer.asm.js | 2 + .../node_modules/es-module-lexer/dist/lexer.cjs | 1 + vanilla/node_modules/es-module-lexer/dist/lexer.js | 2 + vanilla/node_modules/es-module-lexer/lexer.js | 925 + vanilla/node_modules/es-module-lexer/package.json | 57 + .../node_modules/es-module-lexer/types/lexer.d.ts | 195 + vanilla/node_modules/esbuild/LICENSE.md | 21 + vanilla/node_modules/esbuild/README.md | 3 + vanilla/node_modules/esbuild/bin/esbuild | Bin 0 -> 10158264 bytes vanilla/node_modules/esbuild/install.js | 289 + vanilla/node_modules/esbuild/lib/main.d.ts | 716 + vanilla/node_modules/esbuild/lib/main.js | 2242 ++ vanilla/node_modules/esbuild/package.json | 49 + vanilla/node_modules/estree-walker/LICENSE | 7 + vanilla/node_modules/estree-walker/README.md | 48 + vanilla/node_modules/estree-walker/package.json | 38 + vanilla/node_modules/estree-walker/src/async.js | 152 + vanilla/node_modules/estree-walker/src/index.js | 34 + vanilla/node_modules/estree-walker/src/sync.js | 152 + vanilla/node_modules/estree-walker/src/walker.js | 61 + .../node_modules/estree-walker/types/async.d.ts | 36 + .../node_modules/estree-walker/types/index.d.ts | 32 + vanilla/node_modules/estree-walker/types/sync.d.ts | 36 + .../node_modules/estree-walker/types/walker.d.ts | 39 + vanilla/node_modules/expect-type/LICENSE | 191 + vanilla/node_modules/expect-type/README.md | 925 + vanilla/node_modules/expect-type/SECURITY.md | 14 + .../node_modules/expect-type/dist/branding.d.ts | 61 + vanilla/node_modules/expect-type/dist/branding.js | 2 + vanilla/node_modules/expect-type/dist/index.d.ts | 897 + vanilla/node_modules/expect-type/dist/index.js | 96 + .../node_modules/expect-type/dist/messages.d.ts | 168 + vanilla/node_modules/expect-type/dist/messages.js | 66 + .../node_modules/expect-type/dist/overloads.d.ts | 288 + vanilla/node_modules/expect-type/dist/overloads.js | 2 + vanilla/node_modules/expect-type/dist/utils.d.ts | 197 + vanilla/node_modules/expect-type/dist/utils.js | 19 + vanilla/node_modules/expect-type/package.json | 50 + vanilla/node_modules/fdir/LICENSE | 7 + vanilla/node_modules/fdir/README.md | 91 + vanilla/node_modules/fdir/dist/index.cjs | 588 + vanilla/node_modules/fdir/dist/index.d.cts | 155 + vanilla/node_modules/fdir/dist/index.d.mts | 155 + vanilla/node_modules/fdir/dist/index.mjs | 570 + vanilla/node_modules/fdir/package.json | 103 + vanilla/node_modules/has-flag/index.d.ts | 39 + vanilla/node_modules/has-flag/index.js | 8 + vanilla/node_modules/has-flag/license | 9 + vanilla/node_modules/has-flag/package.json | 46 + vanilla/node_modules/has-flag/readme.md | 89 + .../node_modules/html-encoding-sniffer/LICENSE.txt | 7 + .../node_modules/html-encoding-sniffer/README.md | 42 + .../lib/html-encoding-sniffer.js | 299 + .../html-encoding-sniffer/package.json | 34 + vanilla/node_modules/html-escaper/LICENSE.txt | 19 + vanilla/node_modules/html-escaper/README.md | 97 + vanilla/node_modules/html-escaper/cjs/index.js | 65 + vanilla/node_modules/html-escaper/cjs/package.json | 1 + vanilla/node_modules/html-escaper/esm/index.js | 62 + vanilla/node_modules/html-escaper/index.js | 70 + vanilla/node_modules/html-escaper/min.js | 1 + vanilla/node_modules/html-escaper/package.json | 42 + vanilla/node_modules/html-escaper/test/index.js | 23 + .../node_modules/html-escaper/test/package.json | 1 + vanilla/node_modules/http-proxy-agent/LICENSE | 22 + vanilla/node_modules/http-proxy-agent/README.md | 44 + .../node_modules/http-proxy-agent/dist/index.d.ts | 44 + .../http-proxy-agent/dist/index.d.ts.map | 1 + .../node_modules/http-proxy-agent/dist/index.js | 148 + .../http-proxy-agent/dist/index.js.map | 1 + vanilla/node_modules/http-proxy-agent/package.json | 47 + vanilla/node_modules/https-proxy-agent/LICENSE | 22 + vanilla/node_modules/https-proxy-agent/README.md | 70 + .../node_modules/https-proxy-agent/dist/index.d.ts | 47 + .../https-proxy-agent/dist/index.d.ts.map | 1 + .../node_modules/https-proxy-agent/dist/index.js | 180 + .../https-proxy-agent/dist/index.js.map | 1 + .../dist/parse-proxy-response.d.ts | 15 + .../dist/parse-proxy-response.d.ts.map | 1 + .../https-proxy-agent/dist/parse-proxy-response.js | 101 + .../dist/parse-proxy-response.js.map | 1 + .../node_modules/https-proxy-agent/package.json | 50 + .../LICENSE-MIT.txt | 20 + .../is-potential-custom-element-name/README.md | 40 + .../is-potential-custom-element-name/index.js | 9 + .../is-potential-custom-element-name/package.json | 35 + .../istanbul-lib-coverage/CHANGELOG.md | 209 + vanilla/node_modules/istanbul-lib-coverage/LICENSE | 24 + .../node_modules/istanbul-lib-coverage/README.md | 29 + .../node_modules/istanbul-lib-coverage/index.js | 64 + .../istanbul-lib-coverage/lib/coverage-map.js | 134 + .../istanbul-lib-coverage/lib/coverage-summary.js | 112 + .../istanbul-lib-coverage/lib/data-properties.js | 12 + .../istanbul-lib-coverage/lib/file-coverage.js | 444 + .../istanbul-lib-coverage/lib/percent.js | 15 + .../istanbul-lib-coverage/package.json | 47 + .../node_modules/istanbul-lib-report/CHANGELOG.md | 192 + vanilla/node_modules/istanbul-lib-report/LICENSE | 24 + vanilla/node_modules/istanbul-lib-report/README.md | 43 + vanilla/node_modules/istanbul-lib-report/index.js | 40 + .../istanbul-lib-report/lib/context.js | 132 + .../istanbul-lib-report/lib/file-writer.js | 189 + .../node_modules/istanbul-lib-report/lib/path.js | 169 + .../istanbul-lib-report/lib/report-base.js | 16 + .../istanbul-lib-report/lib/summarizer-factory.js | 284 + .../node_modules/istanbul-lib-report/lib/tree.js | 137 + .../istanbul-lib-report/lib/watermarks.js | 15 + .../istanbul-lib-report/lib/xml-writer.js | 90 + .../node_modules/istanbul-lib-report/package.json | 44 + vanilla/node_modules/istanbul-reports/CHANGELOG.md | 476 + vanilla/node_modules/istanbul-reports/LICENSE | 24 + vanilla/node_modules/istanbul-reports/README.md | 12 + vanilla/node_modules/istanbul-reports/index.js | 24 + .../istanbul-reports/lib/clover/index.js | 163 + .../istanbul-reports/lib/cobertura/index.js | 151 + .../istanbul-reports/lib/html-spa/.babelrc | 3 + .../istanbul-reports/lib/html-spa/assets/bundle.js | 30 + .../lib/html-spa/assets/sort-arrow-sprite.png | Bin 0 -> 138 bytes .../istanbul-reports/lib/html-spa/assets/spa.css | 298 + .../istanbul-reports/lib/html-spa/index.js | 176 + .../lib/html-spa/src/fileBreadcrumbs.js | 31 + .../lib/html-spa/src/filterToggle.js | 50 + .../lib/html-spa/src/flattenToggle.js | 25 + .../lib/html-spa/src/getChildData.js | 155 + .../istanbul-reports/lib/html-spa/src/index.js | 160 + .../istanbul-reports/lib/html-spa/src/routing.js | 52 + .../lib/html-spa/src/summaryHeader.js | 63 + .../lib/html-spa/src/summaryTableHeader.js | 130 + .../lib/html-spa/src/summaryTableLine.js | 159 + .../lib/html-spa/webpack.config.js | 22 + .../istanbul-reports/lib/html/annotator.js | 305 + .../istanbul-reports/lib/html/assets/base.css | 224 + .../lib/html/assets/block-navigation.js | 86 + .../istanbul-reports/lib/html/assets/favicon.png | Bin 0 -> 445 bytes .../lib/html/assets/sort-arrow-sprite.png | Bin 0 -> 138 bytes .../istanbul-reports/lib/html/assets/sorter.js | 209 + .../lib/html/assets/vendor/prettify.css | 1 + .../lib/html/assets/vendor/prettify.js | 1 + .../istanbul-reports/lib/html/index.js | 421 + .../istanbul-reports/lib/html/insertion-text.js | 114 + .../istanbul-reports/lib/json-summary/index.js | 56 + .../istanbul-reports/lib/json/index.js | 44 + .../istanbul-reports/lib/lcov/index.js | 33 + .../istanbul-reports/lib/lcovonly/index.js | 77 + .../istanbul-reports/lib/none/index.js | 10 + .../istanbul-reports/lib/teamcity/index.js | 67 + .../istanbul-reports/lib/text-lcov/index.js | 17 + .../istanbul-reports/lib/text-summary/index.js | 62 + .../istanbul-reports/lib/text/index.js | 298 + vanilla/node_modules/istanbul-reports/package.json | 60 + vanilla/node_modules/js-tokens/LICENSE | 21 + vanilla/node_modules/js-tokens/README.md | 14 + vanilla/node_modules/js-tokens/index.d.ts | 36 + vanilla/node_modules/js-tokens/index.js | 398 + vanilla/node_modules/js-tokens/package.json | 22 + vanilla/node_modules/jsdom/LICENSE.txt | 22 + vanilla/node_modules/jsdom/README.md | 555 + vanilla/node_modules/jsdom/lib/api.js | 373 + .../node_modules/jsdom/lib/jsdom/browser/Window.js | 1024 + .../jsdom/lib/jsdom/browser/default-stylesheet.css | 415 + .../jsdom/lib/jsdom/browser/js-globals.json | 332 + .../jsdom/lib/jsdom/browser/not-implemented.js | 20 + .../jsdom/lib/jsdom/browser/parser/html.js | 208 + .../jsdom/lib/jsdom/browser/parser/index.js | 37 + .../jsdom/lib/jsdom/browser/parser/xml.js | 202 + .../browser/resources/async-resource-queue.js | 114 + .../browser/resources/decompress-interceptor.js | 184 + .../jsdom/browser/resources/jsdom-dispatcher.js | 746 + .../resources/per-document-resource-loader.js | 116 + .../jsdom/browser/resources/request-interceptor.js | 171 + .../lib/jsdom/browser/resources/request-manager.js | 33 + .../lib/jsdom/browser/resources/resource-queue.js | 142 + .../lib/jsdom/browser/resources/stream-handler.js | 89 + .../node_modules/jsdom/lib/jsdom/level2/style.js | 65 + .../node_modules/jsdom/lib/jsdom/level3/xpath.js | 1875 + .../jsdom/living/aborting/AbortController-impl.js | 17 + .../lib/jsdom/living/aborting/AbortSignal-impl.js | 131 + .../jsdom/lib/jsdom/living/attributes.js | 312 + .../jsdom/lib/jsdom/living/attributes/Attr-impl.js | 60 + .../jsdom/living/attributes/NamedNodeMap-impl.js | 78 + .../DefaultConstraintValidation-impl.js | 75 + .../constraint-validation/ValidityState-impl.js | 66 + .../jsdom/lib/jsdom/living/crypto/Crypto-impl.js | 68 + .../lib/jsdom/living/cssom/StyleSheetList-impl.js | 38 + .../custom-elements/CustomElementRegistry-impl.js | 279 + .../custom-elements/ElementInternals-impl.js | 56 + .../DeviceMotionEventAcceleration-impl.js | 7 + .../DeviceMotionEventRotationRate-impl.js | 7 + .../jsdom/lib/jsdom/living/documents.js | 15 + .../lib/jsdom/living/domparsing/DOMParser-impl.js | 59 + .../lib/jsdom/living/domparsing/InnerHTML-impl.js | 30 + .../jsdom/living/domparsing/XMLSerializer-impl.js | 18 + .../domparsing/parse5-adapter-serialization.js | 63 + .../lib/jsdom/living/domparsing/serialization.js | 36 + .../lib/jsdom/living/encoding/TextDecoder-impl.js | 25 + .../lib/jsdom/living/encoding/TextEncoder-impl.js | 5 + .../jsdom/living/events/BeforeUnloadEvent-impl.js | 12 + .../lib/jsdom/living/events/BlobEvent-impl.js | 14 + .../lib/jsdom/living/events/CloseEvent-impl.js | 10 + .../jsdom/living/events/CompositionEvent-impl.js | 20 + .../lib/jsdom/living/events/CustomEvent-impl.js | 21 + .../jsdom/living/events/DeviceMotionEvent-impl.js | 49 + .../living/events/DeviceOrientationEvent-impl.js | 10 + .../lib/jsdom/living/events/ErrorEvent-impl.js | 14 + .../jsdom/lib/jsdom/living/events/Event-impl.js | 195 + .../jsdom/living/events/EventModifierMixin-impl.js | 24 + .../lib/jsdom/living/events/EventTarget-impl.js | 438 + .../lib/jsdom/living/events/FocusEvent-impl.js | 9 + .../jsdom/living/events/HashChangeEvent-impl.js | 14 + .../lib/jsdom/living/events/InputEvent-impl.js | 11 + .../lib/jsdom/living/events/KeyboardEvent-impl.js | 29 + .../lib/jsdom/living/events/MessageEvent-impl.js | 25 + .../lib/jsdom/living/events/MouseEvent-impl.js | 72 + .../living/events/PageTransitionEvent-impl.js | 20 + .../lib/jsdom/living/events/PointerEvent-impl.js | 21 + .../lib/jsdom/living/events/PopStateEvent-impl.js | 9 + .../lib/jsdom/living/events/ProgressEvent-impl.js | 14 + .../living/events/PromiseRejectionEvent-impl.js | 14 + .../lib/jsdom/living/events/StorageEvent-impl.js | 26 + .../lib/jsdom/living/events/SubmitEvent-impl.js | 13 + .../lib/jsdom/living/events/TouchEvent-impl.js | 14 + .../jsdom/living/events/TransitionEvent-impl.js | 10 + .../jsdom/lib/jsdom/living/events/UIEvent-impl.js | 43 + .../lib/jsdom/living/events/WheelEvent-impl.js | 12 + .../jsdom/lib/jsdom/living/fetch/Headers-impl.js | 173 + .../jsdom/lib/jsdom/living/fetch/header-list.js | 158 + .../jsdom/lib/jsdom/living/fetch/header-types.js | 205 + .../jsdom/lib/jsdom/living/fetch/header-utils.js | 26 + .../jsdom/lib/jsdom/living/file-api/Blob-impl.js | 111 + .../jsdom/lib/jsdom/living/file-api/File-impl.js | 12 + .../lib/jsdom/living/file-api/FileList-impl.js | 15 + .../lib/jsdom/living/file-api/FileReader-impl.js | 132 + .../lib/jsdom/living/generated/AbortController.js | 143 + .../lib/jsdom/living/generated/AbortSignal.js | 249 + .../lib/jsdom/living/generated/AbstractRange.js | 171 + .../living/generated/AddEventListenerOptions.js | 53 + .../jsdom/living/generated/AssignedNodesOptions.js | 28 + .../jsdom/lib/jsdom/living/generated/Attr.js | 217 + .../jsdom/lib/jsdom/living/generated/BarProp.js | 117 + .../jsdom/living/generated/BeforeUnloadEvent.js | 139 + .../jsdom/lib/jsdom/living/generated/BinaryType.js | 12 + .../jsdom/lib/jsdom/living/generated/Blob.js | 211 + .../lib/jsdom/living/generated/BlobCallback.js | 30 + .../jsdom/lib/jsdom/living/generated/BlobEvent.js | 157 + .../lib/jsdom/living/generated/BlobEventInit.js | 43 + .../lib/jsdom/living/generated/BlobPropertyBag.js | 42 + .../lib/jsdom/living/generated/CDATASection.js | 109 + .../jsdom/living/generated/CanPlayTypeResult.js | 12 + .../lib/jsdom/living/generated/CharacterData.js | 453 + .../jsdom/lib/jsdom/living/generated/CloseEvent.js | 168 + .../lib/jsdom/living/generated/CloseEventInit.js | 65 + .../jsdom/lib/jsdom/living/generated/Comment.js | 120 + .../lib/jsdom/living/generated/CompositionEvent.js | 219 + .../jsdom/living/generated/CompositionEventInit.js | 32 + .../jsdom/lib/jsdom/living/generated/Crypto.js | 148 + .../living/generated/CustomElementConstructor.js | 34 + .../living/generated/CustomElementRegistry.js | 267 + .../lib/jsdom/living/generated/CustomEvent.js | 206 + .../lib/jsdom/living/generated/CustomEventInit.js | 32 + .../lib/jsdom/living/generated/DOMException.js | 222 + .../jsdom/living/generated/DOMImplementation.js | 237 + .../jsdom/lib/jsdom/living/generated/DOMParser.js | 140 + .../jsdom/lib/jsdom/living/generated/DOMRect.js | 276 + .../lib/jsdom/living/generated/DOMRectInit.js | 76 + .../lib/jsdom/living/generated/DOMRectReadOnly.js | 285 + .../lib/jsdom/living/generated/DOMStringMap.js | 297 + .../lib/jsdom/living/generated/DOMTokenList.js | 537 + .../jsdom/living/generated/DeviceMotionEvent.js | 183 + .../generated/DeviceMotionEventAcceleration.js | 145 + .../generated/DeviceMotionEventAccelerationInit.js | 61 + .../living/generated/DeviceMotionEventInit.js | 70 + .../generated/DeviceMotionEventRotationRate.js | 145 + .../generated/DeviceMotionEventRotationRateInit.js | 61 + .../living/generated/DeviceOrientationEvent.js | 183 + .../living/generated/DeviceOrientationEventInit.js | 80 + .../jsdom/lib/jsdom/living/generated/Document.js | 4509 +++ .../lib/jsdom/living/generated/DocumentFragment.js | 334 + .../jsdom/living/generated/DocumentReadyState.js | 12 + .../lib/jsdom/living/generated/DocumentType.js | 252 + .../jsdom/lib/jsdom/living/generated/Element.js | 3718 ++ .../living/generated/ElementCreationOptions.js | 26 + .../living/generated/ElementDefinitionOptions.js | 29 + .../lib/jsdom/living/generated/ElementInternals.js | 2150 ++ .../jsdom/lib/jsdom/living/generated/EndingType.js | 12 + .../jsdom/lib/jsdom/living/generated/ErrorEvent.js | 192 + .../lib/jsdom/living/generated/ErrorEventInit.js | 92 + .../jsdom/lib/jsdom/living/generated/Event.js | 430 + .../jsdom/living/generated/EventHandlerNonNull.js | 36 + .../jsdom/lib/jsdom/living/generated/EventInit.js | 58 + .../lib/jsdom/living/generated/EventListener.js | 35 + .../jsdom/living/generated/EventListenerOptions.js | 28 + .../jsdom/living/generated/EventModifierInit.js | 221 + .../lib/jsdom/living/generated/EventTarget.js | 259 + .../jsdom/lib/jsdom/living/generated/External.js | 130 + .../jsdom/lib/jsdom/living/generated/File.js | 185 + .../jsdom/lib/jsdom/living/generated/FileList.js | 298 + .../lib/jsdom/living/generated/FilePropertyBag.js | 33 + .../jsdom/lib/jsdom/living/generated/FileReader.js | 468 + .../jsdom/lib/jsdom/living/generated/FocusEvent.js | 144 + .../lib/jsdom/living/generated/FocusEventInit.js | 36 + .../jsdom/lib/jsdom/living/generated/FormData.js | 468 + .../jsdom/lib/jsdom/living/generated/Function.js | 42 + .../jsdom/living/generated/GetRootNodeOptions.js | 31 + .../jsdom/living/generated/HTMLAnchorElement.js | 1023 + .../lib/jsdom/living/generated/HTMLAreaElement.js | 822 + .../lib/jsdom/living/generated/HTMLAudioElement.js | 110 + .../lib/jsdom/living/generated/HTMLBRElement.js | 153 + .../lib/jsdom/living/generated/HTMLBaseElement.js | 193 + .../lib/jsdom/living/generated/HTMLBodyElement.js | 877 + .../jsdom/living/generated/HTMLButtonElement.js | 522 + .../jsdom/living/generated/HTMLCanvasElement.js | 304 + .../lib/jsdom/living/generated/HTMLCollection.js | 352 + .../lib/jsdom/living/generated/HTMLDListElement.js | 156 + .../lib/jsdom/living/generated/HTMLDataElement.js | 153 + .../jsdom/living/generated/HTMLDataListElement.js | 125 + .../jsdom/living/generated/HTMLDetailsElement.js | 156 + .../jsdom/living/generated/HTMLDialogElement.js | 156 + .../jsdom/living/generated/HTMLDirectoryElement.js | 156 + .../lib/jsdom/living/generated/HTMLDivElement.js | 153 + .../lib/jsdom/living/generated/HTMLElement.js | 3489 ++ .../lib/jsdom/living/generated/HTMLEmbedElement.js | 378 + .../jsdom/living/generated/HTMLFieldSetElement.js | 329 + .../lib/jsdom/living/generated/HTMLFontElement.js | 236 + .../living/generated/HTMLFormControlsCollection.js | 318 + .../lib/jsdom/living/generated/HTMLFormElement.js | 658 + .../lib/jsdom/living/generated/HTMLFrameElement.js | 510 + .../jsdom/living/generated/HTMLFrameSetElement.js | 708 + .../lib/jsdom/living/generated/HTMLHRElement.js | 320 + .../lib/jsdom/living/generated/HTMLHeadElement.js | 110 + .../jsdom/living/generated/HTMLHeadingElement.js | 153 + .../lib/jsdom/living/generated/HTMLHtmlElement.js | 153 + .../jsdom/living/generated/HTMLIFrameElement.js | 686 + .../lib/jsdom/living/generated/HTMLImageElement.js | 902 + .../lib/jsdom/living/generated/HTMLInputElement.js | 1927 + .../lib/jsdom/living/generated/HTMLLIElement.js | 201 + .../lib/jsdom/living/generated/HTMLLabelElement.js | 179 + .../jsdom/living/generated/HTMLLegendElement.js | 166 + .../lib/jsdom/living/generated/HTMLLinkElement.js | 552 + .../lib/jsdom/living/generated/HTMLMapElement.js | 168 + .../jsdom/living/generated/HTMLMarqueeElement.js | 554 + .../lib/jsdom/living/generated/HTMLMediaElement.js | 898 + .../lib/jsdom/living/generated/HTMLMenuElement.js | 156 + .../lib/jsdom/living/generated/HTMLMetaElement.js | 276 + .../lib/jsdom/living/generated/HTMLMeterElement.js | 365 + .../lib/jsdom/living/generated/HTMLModElement.js | 214 + .../lib/jsdom/living/generated/HTMLOListElement.js | 281 + .../jsdom/living/generated/HTMLObjectElement.js | 941 + .../jsdom/living/generated/HTMLOptGroupElement.js | 197 + .../jsdom/living/generated/HTMLOptionElement.js | 376 + .../living/generated/HTMLOptionsCollection.js | 511 + .../jsdom/living/generated/HTMLOutputElement.js | 392 + .../jsdom/living/generated/HTMLParagraphElement.js | 153 + .../lib/jsdom/living/generated/HTMLParamElement.js | 276 + .../jsdom/living/generated/HTMLPictureElement.js | 110 + .../lib/jsdom/living/generated/HTMLPreElement.js | 160 + .../jsdom/living/generated/HTMLProgressElement.js | 228 + .../lib/jsdom/living/generated/HTMLQuoteElement.js | 173 + .../jsdom/living/generated/HTMLScriptElement.js | 469 + .../jsdom/living/generated/HTMLSelectElement.js | 989 + .../lib/jsdom/living/generated/HTMLSlotElement.js | 192 + .../jsdom/living/generated/HTMLSourceElement.js | 337 + .../lib/jsdom/living/generated/HTMLSpanElement.js | 110 + .../lib/jsdom/living/generated/HTMLStyleElement.js | 207 + .../living/generated/HTMLTableCaptionElement.js | 153 + .../jsdom/living/generated/HTMLTableCellElement.js | 729 + .../jsdom/living/generated/HTMLTableColElement.js | 372 + .../lib/jsdom/living/generated/HTMLTableElement.js | 799 + .../jsdom/living/generated/HTMLTableRowElement.js | 414 + .../living/generated/HTMLTableSectionElement.js | 346 + .../jsdom/living/generated/HTMLTemplateElement.js | 123 + .../jsdom/living/generated/HTMLTextAreaElement.js | 1206 + .../lib/jsdom/living/generated/HTMLTimeElement.js | 153 + .../lib/jsdom/living/generated/HTMLTitleElement.js | 152 + .../lib/jsdom/living/generated/HTMLTrackElement.js | 363 + .../lib/jsdom/living/generated/HTMLUListElement.js | 197 + .../jsdom/living/generated/HTMLUnknownElement.js | 109 + .../lib/jsdom/living/generated/HTMLVideoElement.js | 340 + .../lib/jsdom/living/generated/HashChangeEvent.js | 157 + .../jsdom/living/generated/HashChangeEventInit.js | 50 + .../jsdom/lib/jsdom/living/generated/Headers.js | 418 + .../jsdom/lib/jsdom/living/generated/History.js | 266 + .../jsdom/lib/jsdom/living/generated/InputEvent.js | 168 + .../lib/jsdom/living/generated/InputEventInit.js | 68 + .../lib/jsdom/living/generated/KeyboardEvent.js | 445 + .../jsdom/living/generated/KeyboardEventInit.js | 116 + .../jsdom/lib/jsdom/living/generated/Location.js | 404 + .../lib/jsdom/living/generated/MessageEvent.js | 317 + .../lib/jsdom/living/generated/MessageEventInit.js | 100 + .../jsdom/lib/jsdom/living/generated/MimeType.js | 156 + .../lib/jsdom/living/generated/MimeTypeArray.js | 326 + .../jsdom/lib/jsdom/living/generated/MouseEvent.js | 595 + .../lib/jsdom/living/generated/MouseEventInit.js | 189 + .../lib/jsdom/living/generated/MutationCallback.js | 34 + .../lib/jsdom/living/generated/MutationObserver.js | 178 + .../jsdom/living/generated/MutationObserverInit.js | 121 + .../lib/jsdom/living/generated/MutationRecord.js | 229 + .../lib/jsdom/living/generated/NamedNodeMap.js | 527 + .../jsdom/lib/jsdom/living/generated/Navigator.js | 326 + .../jsdom/lib/jsdom/living/generated/Node.js | 763 + .../jsdom/lib/jsdom/living/generated/NodeFilter.js | 75 + .../lib/jsdom/living/generated/NodeIterator.js | 207 + .../jsdom/lib/jsdom/living/generated/NodeList.js | 302 + .../generated/OnBeforeUnloadEventHandlerNonNull.js | 42 + .../living/generated/OnErrorEventHandlerNonNull.js | 56 + .../jsdom/living/generated/PageTransitionEvent.js | 144 + .../living/generated/PageTransitionEventInit.js | 35 + .../lib/jsdom/living/generated/Performance.js | 142 + .../jsdom/lib/jsdom/living/generated/Plugin.js | 359 + .../lib/jsdom/living/generated/PluginArray.js | 336 + .../lib/jsdom/living/generated/PointerEvent.js | 324 + .../lib/jsdom/living/generated/PointerEventInit.js | 241 + .../lib/jsdom/living/generated/PopStateEvent.js | 144 + .../jsdom/living/generated/PopStateEventInit.js | 32 + .../living/generated/ProcessingInstruction.js | 122 + .../lib/jsdom/living/generated/ProgressEvent.js | 170 + .../jsdom/living/generated/ProgressEventInit.js | 65 + .../living/generated/PromiseRejectionEvent.js | 157 + .../living/generated/PromiseRejectionEventInit.js | 42 + .../lib/jsdom/living/generated/RadioNodeList.js | 296 + .../jsdom/lib/jsdom/living/generated/Range.js | 641 + .../generated/SVGAnimatedPreserveAspectRatio.js | 136 + .../lib/jsdom/living/generated/SVGAnimatedRect.js | 136 + .../jsdom/living/generated/SVGAnimatedString.js | 149 + .../living/generated/SVGBoundingBoxOptions.js | 64 + .../lib/jsdom/living/generated/SVGDefsElement.js | 109 + .../lib/jsdom/living/generated/SVGDescElement.js | 109 + .../jsdom/lib/jsdom/living/generated/SVGElement.js | 3155 ++ .../lib/jsdom/living/generated/SVGGElement.js | 109 + .../jsdom/living/generated/SVGGraphicsElement.js | 139 + .../jsdom/living/generated/SVGMetadataElement.js | 109 + .../jsdom/lib/jsdom/living/generated/SVGNumber.js | 132 + .../living/generated/SVGPreserveAspectRatio.js | 196 + .../jsdom/lib/jsdom/living/generated/SVGRect.js | 210 + .../lib/jsdom/living/generated/SVGSVGElement.js | 786 + .../lib/jsdom/living/generated/SVGStringList.js | 511 + .../lib/jsdom/living/generated/SVGSwitchElement.js | 109 + .../lib/jsdom/living/generated/SVGSymbolElement.js | 146 + .../lib/jsdom/living/generated/SVGTitleElement.js | 109 + .../jsdom/lib/jsdom/living/generated/Screen.js | 180 + .../lib/jsdom/living/generated/ScrollBehavior.js | 12 + .../living/generated/ScrollIntoViewOptions.js | 45 + .../living/generated/ScrollLogicalPosition.js | 14 + .../lib/jsdom/living/generated/ScrollOptions.js | 30 + .../jsdom/living/generated/ScrollRestoration.js | 12 + .../jsdom/lib/jsdom/living/generated/Selection.js | 569 + .../lib/jsdom/living/generated/SelectionMode.js | 12 + .../jsdom/lib/jsdom/living/generated/ShadowRoot.js | 187 + .../lib/jsdom/living/generated/ShadowRootInit.js | 30 + .../lib/jsdom/living/generated/ShadowRootMode.js | 12 + .../lib/jsdom/living/generated/StaticRange.js | 123 + .../lib/jsdom/living/generated/StaticRangeInit.js | 72 + .../jsdom/lib/jsdom/living/generated/Storage.js | 397 + .../lib/jsdom/living/generated/StorageEvent.js | 318 + .../lib/jsdom/living/generated/StorageEventInit.js | 99 + .../lib/jsdom/living/generated/StyleSheetList.js | 300 + .../lib/jsdom/living/generated/SubmitEvent.js | 144 + .../lib/jsdom/living/generated/SubmitEventInit.js | 36 + .../lib/jsdom/living/generated/SupportedType.js | 18 + .../jsdom/lib/jsdom/living/generated/Text.js | 170 + .../jsdom/living/generated/TextDecodeOptions.js | 28 + .../lib/jsdom/living/generated/TextDecoder.js | 211 + .../jsdom/living/generated/TextDecoderOptions.js | 43 + .../lib/jsdom/living/generated/TextEncoder.js | 176 + .../generated/TextEncoderEncodeIntoResult.js | 42 + .../lib/jsdom/living/generated/TextTrackKind.js | 12 + .../jsdom/lib/jsdom/living/generated/TouchEvent.js | 222 + .../lib/jsdom/living/generated/TouchEventInit.js | 89 + .../lib/jsdom/living/generated/TransitionEvent.js | 170 + .../jsdom/living/generated/TransitionEventInit.js | 65 + .../jsdom/lib/jsdom/living/generated/TreeWalker.js | 255 + .../jsdom/lib/jsdom/living/generated/UIEvent.js | 235 + .../lib/jsdom/living/generated/UIEventInit.js | 62 + .../lib/jsdom/living/generated/ValidityState.js | 249 + .../lib/jsdom/living/generated/VisibilityState.js | 12 + .../lib/jsdom/living/generated/VoidFunction.js | 26 + .../jsdom/lib/jsdom/living/generated/WebSocket.js | 480 + .../jsdom/lib/jsdom/living/generated/WheelEvent.js | 191 + .../lib/jsdom/living/generated/WheelEventInit.js | 71 + .../lib/jsdom/living/generated/XMLDocument.js | 109 + .../lib/jsdom/living/generated/XMLHttpRequest.js | 663 + .../living/generated/XMLHttpRequestEventTarget.js | 334 + .../living/generated/XMLHttpRequestResponseType.js | 14 + .../jsdom/living/generated/XMLHttpRequestUpload.js | 109 + .../lib/jsdom/living/generated/XMLSerializer.js | 132 + .../jsdom/lib/jsdom/living/generated/utils.js | 252 + .../lib/jsdom/living/geometry/DOMRect-impl.js | 39 + .../jsdom/living/geometry/DOMRectReadOnly-impl.js | 72 + .../jsdom/lib/jsdom/living/helpers/binary-data.js | 63 + .../jsdom/lib/jsdom/living/helpers/colors.js | 245 + .../lib/jsdom/living/helpers/create-element.js | 329 + .../jsdom/living/helpers/create-event-accessor.js | 188 + .../lib/jsdom/living/helpers/custom-elements.js | 272 + .../lib/jsdom/living/helpers/dates-and-times.js | 270 + .../jsdom/lib/jsdom/living/helpers/details.js | 15 + .../jsdom/lib/jsdom/living/helpers/encoding.js | 60 + .../jsdom/lib/jsdom/living/helpers/events.js | 24 + .../jsdom/lib/jsdom/living/helpers/focusing.js | 104 + .../lib/jsdom/living/helpers/form-controls.js | 309 + .../lib/jsdom/living/helpers/html-constructor.js | 78 + .../lib/jsdom/living/helpers/internal-constants.js | 12 + .../jsdom/lib/jsdom/living/helpers/is-window.js | 18 + .../lib/jsdom/living/helpers/iterable-weak-set.js | 48 + .../jsdom/lib/jsdom/living/helpers/json.js | 7 + .../lib/jsdom/living/helpers/mutation-observers.js | 198 + .../jsdom/lib/jsdom/living/helpers/namespaces.js | 16 + .../jsdom/lib/jsdom/living/helpers/node.js | 68 + .../jsdom/living/helpers/number-and-date-inputs.js | 195 + .../jsdom/lib/jsdom/living/helpers/ordered-set.js | 104 + .../jsdom/living/helpers/page-transition-event.js | 9 + .../jsdom/living/helpers/runtime-script-errors.js | 75 + .../jsdom/lib/jsdom/living/helpers/shadow-dom.js | 285 + .../jsdom/lib/jsdom/living/helpers/strings.js | 168 + .../jsdom/lib/jsdom/living/helpers/style-rules.js | 328 + .../jsdom/lib/jsdom/living/helpers/stylesheets.js | 148 + .../lib/jsdom/living/helpers/svg/basic-types.js | 41 + .../jsdom/lib/jsdom/living/helpers/svg/render.js | 46 + .../lib/jsdom/living/helpers/system-colors.js | 147 + .../jsdom/lib/jsdom/living/helpers/text.js | 19 + .../jsdom/lib/jsdom/living/helpers/traversal.js | 72 + .../lib/jsdom/living/helpers/validate-names.js | 65 + .../lib/jsdom/living/hr-time/Performance-impl.js | 22 + .../jsdom/lib/jsdom/living/interfaces.js | 252 + .../mutation-observer/MutationObserver-impl.js | 95 + .../mutation-observer/MutationRecord-impl.js | 37 + .../lib/jsdom/living/navigator/MimeType-impl.js | 3 + .../jsdom/living/navigator/MimeTypeArray-impl.js | 21 + .../lib/jsdom/living/navigator/Navigator-impl.js | 29 + .../navigator/NavigatorConcurrentHardware-impl.js | 8 + .../living/navigator/NavigatorCookies-impl.js | 7 + .../lib/jsdom/living/navigator/NavigatorID-impl.js | 37 + .../living/navigator/NavigatorLanguage-impl.js | 9 + .../jsdom/living/navigator/NavigatorOnLine-impl.js | 7 + .../living/navigator/NavigatorPlugins-impl.js | 8 + .../lib/jsdom/living/navigator/Plugin-impl.js | 3 + .../lib/jsdom/living/navigator/PluginArray-impl.js | 23 + .../lib/jsdom/living/node-document-position.js | 10 + .../jsdom/lib/jsdom/living/node-type.js | 16 + .../node_modules/jsdom/lib/jsdom/living/node.js | 331 + .../lib/jsdom/living/nodes/CDATASection-impl.js | 16 + .../lib/jsdom/living/nodes/CharacterData-impl.js | 118 + .../jsdom/lib/jsdom/living/nodes/ChildNode-impl.js | 80 + .../jsdom/lib/jsdom/living/nodes/Comment-impl.js | 20 + .../jsdom/living/nodes/DOMImplementation-impl.js | 120 + .../lib/jsdom/living/nodes/DOMStringMap-impl.js | 64 + .../lib/jsdom/living/nodes/DOMTokenList-impl.js | 171 + .../jsdom/lib/jsdom/living/nodes/Document-impl.js | 1013 + .../jsdom/living/nodes/DocumentFragment-impl.js | 44 + .../living/nodes/DocumentOrShadowRoot-impl.js | 28 + .../lib/jsdom/living/nodes/DocumentType-impl.js | 24 + .../jsdom/lib/jsdom/living/nodes/Element-impl.js | 606 + .../living/nodes/ElementCSSInlineStyle-impl.js | 22 + .../living/nodes/ElementContentEditable-impl.js | 7 + .../jsdom/living/nodes/GlobalEventHandlers-impl.js | 157 + .../jsdom/living/nodes/HTMLAnchorElement-impl.js | 50 + .../lib/jsdom/living/nodes/HTMLAreaElement-impl.js | 43 + .../jsdom/living/nodes/HTMLAudioElement-impl.js | 9 + .../lib/jsdom/living/nodes/HTMLBRElement-impl.js | 9 + .../lib/jsdom/living/nodes/HTMLBaseElement-impl.js | 44 + .../lib/jsdom/living/nodes/HTMLBodyElement-impl.js | 17 + .../jsdom/living/nodes/HTMLButtonElement-impl.js | 79 + .../jsdom/living/nodes/HTMLCanvasElement-impl.js | 136 + .../lib/jsdom/living/nodes/HTMLCollection-impl.js | 96 + .../jsdom/living/nodes/HTMLDListElement-impl.js | 9 + .../lib/jsdom/living/nodes/HTMLDataElement-impl.js | 9 + .../jsdom/living/nodes/HTMLDataListElement-impl.js | 20 + .../jsdom/living/nodes/HTMLDetailsElement-impl.js | 35 + .../jsdom/living/nodes/HTMLDialogElement-impl.js | 9 + .../living/nodes/HTMLDirectoryElement-impl.js | 9 + .../lib/jsdom/living/nodes/HTMLDivElement-impl.js | 9 + .../lib/jsdom/living/nodes/HTMLElement-impl.js | 211 + .../jsdom/living/nodes/HTMLEmbedElement-impl.js | 8 + .../jsdom/living/nodes/HTMLFieldSetElement-impl.js | 43 + .../lib/jsdom/living/nodes/HTMLFontElement-impl.js | 9 + .../nodes/HTMLFormControlsCollection-impl.js | 33 + .../lib/jsdom/living/nodes/HTMLFormElement-impl.js | 248 + .../jsdom/living/nodes/HTMLFrameElement-impl.js | 266 + .../jsdom/living/nodes/HTMLFrameSetElement-impl.js | 17 + .../lib/jsdom/living/nodes/HTMLHRElement-impl.js | 9 + .../lib/jsdom/living/nodes/HTMLHeadElement-impl.js | 9 + .../jsdom/living/nodes/HTMLHeadingElement-impl.js | 9 + .../lib/jsdom/living/nodes/HTMLHtmlElement-impl.js | 9 + .../living/nodes/HTMLHyperlinkElementUtils-impl.js | 368 + .../jsdom/living/nodes/HTMLIFrameElement-impl.js | 9 + .../jsdom/living/nodes/HTMLImageElement-impl.js | 127 + .../jsdom/living/nodes/HTMLInputElement-impl.js | 1097 + .../lib/jsdom/living/nodes/HTMLLIElement-impl.js | 9 + .../jsdom/living/nodes/HTMLLabelElement-impl.js | 94 + .../jsdom/living/nodes/HTMLLegendElement-impl.js | 18 + .../lib/jsdom/living/nodes/HTMLLinkElement-impl.js | 107 + .../lib/jsdom/living/nodes/HTMLMapElement-impl.js | 13 + .../jsdom/living/nodes/HTMLMarqueeElement-impl.js | 9 + .../jsdom/living/nodes/HTMLMediaElement-impl.js | 138 + .../lib/jsdom/living/nodes/HTMLMenuElement-impl.js | 9 + .../lib/jsdom/living/nodes/HTMLMetaElement-impl.js | 9 + .../jsdom/living/nodes/HTMLMeterElement-impl.js | 180 + .../lib/jsdom/living/nodes/HTMLModElement-impl.js | 9 + .../jsdom/living/nodes/HTMLOListElement-impl.js | 22 + .../jsdom/living/nodes/HTMLObjectElement-impl.js | 26 + .../jsdom/living/nodes/HTMLOptGroupElement-impl.js | 9 + .../jsdom/living/nodes/HTMLOptionElement-impl.js | 146 + .../living/nodes/HTMLOptionsCollection-impl.js | 110 + .../jsdom/living/nodes/HTMLOrSVGElement-impl.js | 88 + .../jsdom/living/nodes/HTMLOutputElement-impl.js | 88 + .../living/nodes/HTMLParagraphElement-impl.js | 9 + .../jsdom/living/nodes/HTMLParamElement-impl.js | 9 + .../jsdom/living/nodes/HTMLPictureElement-impl.js | 9 + .../lib/jsdom/living/nodes/HTMLPreElement-impl.js | 9 + .../jsdom/living/nodes/HTMLProgressElement-impl.js | 72 + .../jsdom/living/nodes/HTMLQuoteElement-impl.js | 9 + .../jsdom/living/nodes/HTMLScriptElement-impl.js | 255 + .../jsdom/living/nodes/HTMLSelectElement-impl.js | 283 + .../lib/jsdom/living/nodes/HTMLSlotElement-impl.js | 59 + .../jsdom/living/nodes/HTMLSourceElement-impl.js | 8 + .../lib/jsdom/living/nodes/HTMLSpanElement-impl.js | 9 + .../jsdom/living/nodes/HTMLStyleElement-impl.js | 76 + .../living/nodes/HTMLTableCaptionElement-impl.js | 9 + .../living/nodes/HTMLTableCellElement-impl.js | 73 + .../jsdom/living/nodes/HTMLTableColElement-impl.js | 9 + .../jsdom/living/nodes/HTMLTableElement-impl.js | 236 + .../jsdom/living/nodes/HTMLTableRowElement-impl.js | 88 + .../living/nodes/HTMLTableSectionElement-impl.js | 61 + .../jsdom/living/nodes/HTMLTemplateElement-impl.js | 67 + .../jsdom/living/nodes/HTMLTextAreaElement-impl.js | 244 + .../lib/jsdom/living/nodes/HTMLTimeElement-impl.js | 9 + .../jsdom/living/nodes/HTMLTitleElement-impl.js | 18 + .../jsdom/living/nodes/HTMLTrackElement-impl.js | 13 + .../jsdom/living/nodes/HTMLUListElement-impl.js | 9 + .../jsdom/living/nodes/HTMLUnknownElement-impl.js | 9 + .../jsdom/living/nodes/HTMLVideoElement-impl.js | 17 + .../jsdom/lib/jsdom/living/nodes/LinkStyle-impl.js | 2 + .../jsdom/lib/jsdom/living/nodes/Node-impl.js | 1174 + .../jsdom/lib/jsdom/living/nodes/NodeList-impl.js | 43 + .../living/nodes/NonDocumentTypeChildNode-impl.js | 28 + .../living/nodes/NonElementParentNode-impl.js | 11 + .../lib/jsdom/living/nodes/ParentNode-impl.js | 90 + .../living/nodes/ProcessingInstruction-impl.js | 22 + .../lib/jsdom/living/nodes/RadioNodeList-impl.js | 49 + .../lib/jsdom/living/nodes/SVGDefsElement-impl.js | 9 + .../lib/jsdom/living/nodes/SVGDescElement-impl.js | 9 + .../lib/jsdom/living/nodes/SVGElement-impl.js | 64 + .../lib/jsdom/living/nodes/SVGGElement-impl.js | 9 + .../jsdom/living/nodes/SVGGraphicsElement-impl.js | 16 + .../jsdom/living/nodes/SVGMetadataElement-impl.js | 9 + .../lib/jsdom/living/nodes/SVGSVGElement-impl.js | 47 + .../jsdom/living/nodes/SVGSwitchElement-impl.js | 9 + .../jsdom/living/nodes/SVGSymbolElement-impl.js | 9 + .../jsdom/lib/jsdom/living/nodes/SVGTests-impl.js | 42 + .../lib/jsdom/living/nodes/SVGTitleElement-impl.js | 9 + .../lib/jsdom/living/nodes/ShadowRoot-impl.js | 41 + .../jsdom/lib/jsdom/living/nodes/Slotable-impl.js | 48 + .../jsdom/lib/jsdom/living/nodes/Text-impl.js | 96 + .../jsdom/living/nodes/WindowEventHandlers-impl.js | 52 + .../lib/jsdom/living/nodes/XMLDocument-impl.js | 4 + .../lib/jsdom/living/range/AbstractRange-impl.js | 43 + .../jsdom/lib/jsdom/living/range/Range-impl.js | 902 + .../lib/jsdom/living/range/StaticRange-impl.js | 39 + .../jsdom/lib/jsdom/living/range/boundary-point.js | 47 + .../lib/jsdom/living/selection/Selection-impl.js | 358 + .../svg/SVGAnimatedPreserveAspectRatio-impl.js | 24 + .../lib/jsdom/living/svg/SVGAnimatedRect-impl.js | 122 + .../lib/jsdom/living/svg/SVGAnimatedString-impl.js | 42 + .../jsdom/lib/jsdom/living/svg/SVGListBase.js | 195 + .../jsdom/lib/jsdom/living/svg/SVGNumber-impl.js | 48 + .../living/svg/SVGPreserveAspectRatio-impl.js | 100 + .../jsdom/lib/jsdom/living/svg/SVGRect-impl.js | 143 + .../lib/jsdom/living/svg/SVGStringList-impl.js | 16 + .../jsdom/living/traversal/NodeIterator-impl.js | 107 + .../lib/jsdom/living/traversal/TreeWalker-impl.js | 217 + .../jsdom/lib/jsdom/living/traversal/helpers.js | 44 + .../lib/jsdom/living/webidl/DOMException-impl.js | 46 + .../lib/jsdom/living/websockets/WebSocket-impl.js | 211 + .../lib/jsdom/living/webstorage/Storage-impl.js | 102 + .../jsdom/lib/jsdom/living/window-properties.js | 241 + .../jsdom/lib/jsdom/living/window/BarProp-impl.js | 10 + .../jsdom/lib/jsdom/living/window/External-impl.js | 9 + .../jsdom/lib/jsdom/living/window/History-impl.js | 148 + .../jsdom/lib/jsdom/living/window/Location-impl.js | 227 + .../jsdom/lib/jsdom/living/window/Screen-impl.js | 13 + .../lib/jsdom/living/window/SessionHistory.js | 163 + .../jsdom/lib/jsdom/living/window/navigation.js | 87 + .../jsdom/lib/jsdom/living/xhr/FormData-impl.js | 191 + .../lib/jsdom/living/xhr/XMLHttpRequest-impl.js | 1049 + .../living/xhr/XMLHttpRequestEventTarget-impl.js | 17 + .../jsdom/living/xhr/XMLHttpRequestUpload-impl.js | 4 + .../lib/jsdom/living/xhr/multipart-form-data.js | 99 + .../jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js | 36 + .../jsdom/lib/jsdom/living/xhr/xhr-utils.js | 206 + vanilla/node_modules/jsdom/lib/jsdom/utils.js | 105 + .../jsdom/lib/jsdom/virtual-console.js | 46 + vanilla/node_modules/jsdom/package.json | 94 + vanilla/node_modules/lru-cache/LICENSE.md | 55 + vanilla/node_modules/lru-cache/README.md | 383 + .../lru-cache/dist/commonjs/index.d.ts | 1323 + .../lru-cache/dist/commonjs/index.d.ts.map | 1 + .../node_modules/lru-cache/dist/commonjs/index.js | 1589 + .../lru-cache/dist/commonjs/index.js.map | 1 + .../lru-cache/dist/commonjs/index.min.js | 2 + .../lru-cache/dist/commonjs/index.min.js.map | 7 + .../lru-cache/dist/commonjs/package.json | 3 + vanilla/node_modules/lru-cache/dist/esm/index.d.ts | 1323 + .../node_modules/lru-cache/dist/esm/index.d.ts.map | 1 + vanilla/node_modules/lru-cache/dist/esm/index.js | 1585 + .../node_modules/lru-cache/dist/esm/index.js.map | 1 + .../node_modules/lru-cache/dist/esm/index.min.js | 2 + .../lru-cache/dist/esm/index.min.js.map | 7 + .../node_modules/lru-cache/dist/esm/package.json | 3 + vanilla/node_modules/lru-cache/package.json | 101 + vanilla/node_modules/magic-string/LICENSE | 7 + vanilla/node_modules/magic-string/README.md | 325 + .../magic-string/dist/magic-string.cjs.d.ts | 289 + .../magic-string/dist/magic-string.cjs.js | 1594 + .../magic-string/dist/magic-string.cjs.js.map | 1 + .../magic-string/dist/magic-string.es.d.mts | 289 + .../magic-string/dist/magic-string.es.mjs | 1588 + .../magic-string/dist/magic-string.es.mjs.map | 1 + .../magic-string/dist/magic-string.umd.js | 1682 + .../magic-string/dist/magic-string.umd.js.map | 1 + vanilla/node_modules/magic-string/package.json | 67 + vanilla/node_modules/magicast/LICENSE | 21 + vanilla/node_modules/magicast/README.md | 210 + .../magicast/dist/builders-B_BPSg0Q.js | 8570 +++++ vanilla/node_modules/magicast/dist/core.d.ts | 53 + vanilla/node_modules/magicast/dist/core.js | 3 + vanilla/node_modules/magicast/dist/helpers.d.ts | 74 + vanilla/node_modules/magicast/dist/helpers.js | 120 + vanilla/node_modules/magicast/dist/index.d.ts | 10 + vanilla/node_modules/magicast/dist/index.js | 18 + .../node_modules/magicast/dist/types-r4mG9WUV.d.ts | 283 + vanilla/node_modules/magicast/package.json | 72 + vanilla/node_modules/make-dir/index.d.ts | 66 + vanilla/node_modules/make-dir/index.js | 155 + vanilla/node_modules/make-dir/license | 9 + vanilla/node_modules/make-dir/package.json | 63 + vanilla/node_modules/make-dir/readme.md | 125 + vanilla/node_modules/mdn-data/LICENSE | 116 + vanilla/node_modules/mdn-data/README.md | 59 + vanilla/node_modules/mdn-data/api/index.js | 3 + vanilla/node_modules/mdn-data/api/inheritance.json | 2681 ++ .../mdn-data/api/inheritance.schema.json | 31 + vanilla/node_modules/mdn-data/css/at-rules.json | 504 + .../node_modules/mdn-data/css/at-rules.schema.json | 131 + vanilla/node_modules/mdn-data/css/definitions.json | 80 + vanilla/node_modules/mdn-data/css/functions.json | 593 + .../mdn-data/css/functions.schema.json | 45 + vanilla/node_modules/mdn-data/css/index.js | 9 + vanilla/node_modules/mdn-data/css/properties.json | 10806 ++++++ .../mdn-data/css/properties.schema.json | 449 + vanilla/node_modules/mdn-data/css/selectors.json | 1071 + .../mdn-data/css/selectors.schema.json | 36 + vanilla/node_modules/mdn-data/css/syntaxes.json | 899 + .../node_modules/mdn-data/css/syntaxes.schema.json | 15 + vanilla/node_modules/mdn-data/css/types.json | 287 + .../node_modules/mdn-data/css/types.schema.json | 32 + vanilla/node_modules/mdn-data/css/units.json | 213 + .../node_modules/mdn-data/css/units.schema.json | 28 + vanilla/node_modules/mdn-data/index.js | 5 + vanilla/node_modules/mdn-data/l10n/css.json | 1876 + vanilla/node_modules/mdn-data/l10n/index.js | 3 + vanilla/node_modules/mdn-data/package.json | 38 + vanilla/node_modules/ms/index.js | 162 + vanilla/node_modules/ms/license.md | 21 + vanilla/node_modules/ms/package.json | 38 + vanilla/node_modules/ms/readme.md | 59 + vanilla/node_modules/nanoid/LICENSE | 20 + vanilla/node_modules/nanoid/README.md | 39 + .../node_modules/nanoid/async/index.browser.cjs | 69 + vanilla/node_modules/nanoid/async/index.browser.js | 34 + vanilla/node_modules/nanoid/async/index.cjs | 71 + vanilla/node_modules/nanoid/async/index.d.ts | 56 + vanilla/node_modules/nanoid/async/index.js | 35 + vanilla/node_modules/nanoid/async/index.native.js | 26 + vanilla/node_modules/nanoid/async/package.json | 12 + vanilla/node_modules/nanoid/bin/nanoid.cjs | 55 + vanilla/node_modules/nanoid/index.browser.cjs | 72 + vanilla/node_modules/nanoid/index.browser.js | 34 + vanilla/node_modules/nanoid/index.cjs | 85 + vanilla/node_modules/nanoid/index.d.cts | 91 + vanilla/node_modules/nanoid/index.d.ts | 91 + vanilla/node_modules/nanoid/index.js | 45 + vanilla/node_modules/nanoid/nanoid.js | 1 + vanilla/node_modules/nanoid/non-secure/index.cjs | 34 + vanilla/node_modules/nanoid/non-secure/index.d.ts | 33 + vanilla/node_modules/nanoid/non-secure/index.js | 21 + .../node_modules/nanoid/non-secure/package.json | 6 + vanilla/node_modules/nanoid/package.json | 89 + vanilla/node_modules/nanoid/url-alphabet/index.cjs | 7 + vanilla/node_modules/nanoid/url-alphabet/index.js | 3 + .../node_modules/nanoid/url-alphabet/package.json | 6 + vanilla/node_modules/obug/LICENSE | 23 + vanilla/node_modules/obug/README.md | 106 + vanilla/node_modules/obug/dist/browser.d.ts | 11 + vanilla/node_modules/obug/dist/browser.js | 140 + vanilla/node_modules/obug/dist/browser.min.js | 1 + vanilla/node_modules/obug/dist/core.d.ts | 47 + vanilla/node_modules/obug/dist/core.js | 120 + vanilla/node_modules/obug/dist/node.d.ts | 11 + vanilla/node_modules/obug/dist/node.js | 151 + vanilla/node_modules/obug/package.json | 68 + vanilla/node_modules/parse5/LICENSE | 19 + vanilla/node_modules/parse5/README.md | 38 + .../node_modules/parse5/dist/common/doctype.d.ts | 4 + vanilla/node_modules/parse5/dist/common/doctype.js | 114 + .../parse5/dist/common/error-codes.d.ts | 67 + .../node_modules/parse5/dist/common/error-codes.js | 63 + .../parse5/dist/common/foreign-content.d.ts | 9 + .../parse5/dist/common/foreign-content.js | 228 + vanilla/node_modules/parse5/dist/common/html.d.ts | 289 + vanilla/node_modules/parse5/dist/common/html.js | 523 + vanilla/node_modules/parse5/dist/common/token.d.ts | 84 + vanilla/node_modules/parse5/dist/common/token.js | 20 + .../node_modules/parse5/dist/common/unicode.d.ts | 42 + vanilla/node_modules/parse5/dist/common/unicode.js | 62 + vanilla/node_modules/parse5/dist/index.d.ts | 71 + vanilla/node_modules/parse5/dist/index.js | 42 + .../dist/parser/formatting-element-list.d.ts | 36 + .../parse5/dist/parser/formatting-element-list.js | 110 + vanilla/node_modules/parse5/dist/parser/index.d.ts | 221 + vanilla/node_modules/parse5/dist/parser/index.js | 3245 ++ .../parse5/dist/parser/open-element-stack.d.ts | 53 + .../parse5/dist/parser/open-element-stack.js | 324 + .../node_modules/parse5/dist/serializer/index.d.ts | 60 + .../node_modules/parse5/dist/serializer/index.js | 168 + .../node_modules/parse5/dist/tokenizer/index.d.ts | 247 + .../node_modules/parse5/dist/tokenizer/index.js | 2710 ++ .../parse5/dist/tokenizer/preprocessor.d.ts | 36 + .../parse5/dist/tokenizer/preprocessor.js | 196 + .../parse5/dist/tree-adapters/default.d.ts | 84 + .../parse5/dist/tree-adapters/default.js | 173 + .../parse5/dist/tree-adapters/interface.d.ts | 255 + .../parse5/dist/tree-adapters/interface.js | 1 + vanilla/node_modules/parse5/package.json | 48 + vanilla/node_modules/pathe/LICENSE | 70 + vanilla/node_modules/pathe/README.md | 73 + vanilla/node_modules/pathe/dist/index.cjs | 39 + vanilla/node_modules/pathe/dist/index.d.cts | 47 + vanilla/node_modules/pathe/dist/index.d.mts | 47 + vanilla/node_modules/pathe/dist/index.d.ts | 47 + vanilla/node_modules/pathe/dist/index.mjs | 19 + .../pathe/dist/shared/pathe.BSlhyZSM.cjs | 266 + .../pathe/dist/shared/pathe.M-eThtNZ.mjs | 249 + vanilla/node_modules/pathe/dist/utils.cjs | 82 + vanilla/node_modules/pathe/dist/utils.d.cts | 32 + vanilla/node_modules/pathe/dist/utils.d.mts | 32 + vanilla/node_modules/pathe/dist/utils.d.ts | 32 + vanilla/node_modules/pathe/dist/utils.mjs | 77 + vanilla/node_modules/pathe/package.json | 61 + vanilla/node_modules/pathe/utils.d.ts | 1 + vanilla/node_modules/picocolors/LICENSE | 15 + vanilla/node_modules/picocolors/README.md | 21 + vanilla/node_modules/picocolors/package.json | 25 + .../node_modules/picocolors/picocolors.browser.js | 4 + vanilla/node_modules/picocolors/picocolors.d.ts | 5 + vanilla/node_modules/picocolors/picocolors.js | 75 + vanilla/node_modules/picocolors/types.d.ts | 51 + vanilla/node_modules/picomatch/LICENSE | 21 + vanilla/node_modules/picomatch/README.md | 738 + vanilla/node_modules/picomatch/index.js | 17 + vanilla/node_modules/picomatch/lib/constants.js | 180 + vanilla/node_modules/picomatch/lib/parse.js | 1085 + vanilla/node_modules/picomatch/lib/picomatch.js | 341 + vanilla/node_modules/picomatch/lib/scan.js | 391 + vanilla/node_modules/picomatch/lib/utils.js | 72 + vanilla/node_modules/picomatch/package.json | 83 + vanilla/node_modules/picomatch/posix.js | 3 + vanilla/node_modules/postcss/LICENSE | 20 + vanilla/node_modules/postcss/README.md | 29 + vanilla/node_modules/postcss/lib/at-rule.d.ts | 140 + vanilla/node_modules/postcss/lib/at-rule.js | 25 + vanilla/node_modules/postcss/lib/comment.d.ts | 68 + vanilla/node_modules/postcss/lib/comment.js | 13 + vanilla/node_modules/postcss/lib/container.d.ts | 483 + vanilla/node_modules/postcss/lib/container.js | 447 + .../node_modules/postcss/lib/css-syntax-error.d.ts | 248 + .../node_modules/postcss/lib/css-syntax-error.js | 133 + vanilla/node_modules/postcss/lib/declaration.d.ts | 151 + vanilla/node_modules/postcss/lib/declaration.js | 24 + vanilla/node_modules/postcss/lib/document.d.ts | 69 + vanilla/node_modules/postcss/lib/document.js | 33 + vanilla/node_modules/postcss/lib/fromJSON.d.ts | 9 + vanilla/node_modules/postcss/lib/fromJSON.js | 54 + vanilla/node_modules/postcss/lib/input.d.ts | 227 + vanilla/node_modules/postcss/lib/input.js | 265 + vanilla/node_modules/postcss/lib/lazy-result.d.ts | 190 + vanilla/node_modules/postcss/lib/lazy-result.js | 550 + vanilla/node_modules/postcss/lib/list.d.ts | 60 + vanilla/node_modules/postcss/lib/list.js | 58 + vanilla/node_modules/postcss/lib/map-generator.js | 368 + .../node_modules/postcss/lib/no-work-result.d.ts | 46 + vanilla/node_modules/postcss/lib/no-work-result.js | 138 + vanilla/node_modules/postcss/lib/node.d.ts | 556 + vanilla/node_modules/postcss/lib/node.js | 449 + vanilla/node_modules/postcss/lib/parse.d.ts | 9 + vanilla/node_modules/postcss/lib/parse.js | 42 + vanilla/node_modules/postcss/lib/parser.js | 611 + vanilla/node_modules/postcss/lib/postcss.d.mts | 69 + vanilla/node_modules/postcss/lib/postcss.d.ts | 458 + vanilla/node_modules/postcss/lib/postcss.js | 101 + vanilla/node_modules/postcss/lib/postcss.mjs | 30 + vanilla/node_modules/postcss/lib/previous-map.d.ts | 81 + vanilla/node_modules/postcss/lib/previous-map.js | 144 + vanilla/node_modules/postcss/lib/processor.d.ts | 115 + vanilla/node_modules/postcss/lib/processor.js | 67 + vanilla/node_modules/postcss/lib/result.d.ts | 205 + vanilla/node_modules/postcss/lib/result.js | 42 + vanilla/node_modules/postcss/lib/root.d.ts | 87 + vanilla/node_modules/postcss/lib/root.js | 61 + vanilla/node_modules/postcss/lib/rule.d.ts | 126 + vanilla/node_modules/postcss/lib/rule.js | 27 + vanilla/node_modules/postcss/lib/stringifier.d.ts | 46 + vanilla/node_modules/postcss/lib/stringifier.js | 353 + vanilla/node_modules/postcss/lib/stringify.d.ts | 9 + vanilla/node_modules/postcss/lib/stringify.js | 11 + vanilla/node_modules/postcss/lib/symbols.js | 5 + .../node_modules/postcss/lib/terminal-highlight.js | 70 + vanilla/node_modules/postcss/lib/tokenize.js | 266 + vanilla/node_modules/postcss/lib/warn-once.js | 13 + vanilla/node_modules/postcss/lib/warning.d.ts | 147 + vanilla/node_modules/postcss/lib/warning.js | 37 + vanilla/node_modules/postcss/package.json | 88 + vanilla/node_modules/punycode/LICENSE-MIT.txt | 20 + vanilla/node_modules/punycode/README.md | 148 + vanilla/node_modules/punycode/package.json | 58 + vanilla/node_modules/punycode/punycode.es6.js | 444 + vanilla/node_modules/punycode/punycode.js | 443 + vanilla/node_modules/require-from-string/index.js | 34 + vanilla/node_modules/require-from-string/license | 21 + .../node_modules/require-from-string/package.json | 28 + vanilla/node_modules/require-from-string/readme.md | 56 + vanilla/node_modules/rollup/LICENSE.md | 679 + vanilla/node_modules/rollup/README.md | 134 + vanilla/node_modules/rollup/dist/bin/rollup | 1912 + .../node_modules/rollup/dist/es/getLogFilter.js | 64 + vanilla/node_modules/rollup/dist/es/package.json | 1 + vanilla/node_modules/rollup/dist/es/parseAst.js | 12 + vanilla/node_modules/rollup/dist/es/rollup.js | 17 + .../rollup/dist/es/shared/node-entry.js | 24044 +++++++++++++ .../node_modules/rollup/dist/es/shared/parseAst.js | 2096 ++ .../node_modules/rollup/dist/es/shared/watch.js | 9297 +++++ vanilla/node_modules/rollup/dist/getLogFilter.d.ts | 5 + vanilla/node_modules/rollup/dist/getLogFilter.js | 69 + .../node_modules/rollup/dist/loadConfigFile.d.ts | 20 + vanilla/node_modules/rollup/dist/loadConfigFile.js | 29 + vanilla/node_modules/rollup/dist/native.js | 161 + vanilla/node_modules/rollup/dist/parseAst.d.ts | 4 + vanilla/node_modules/rollup/dist/parseAst.js | 22 + vanilla/node_modules/rollup/dist/rollup.d.ts | 1225 + vanilla/node_modules/rollup/dist/rollup.js | 127 + .../rollup/dist/shared/fsevents-importer.js | 37 + vanilla/node_modules/rollup/dist/shared/index.js | 9003 +++++ .../rollup/dist/shared/loadConfigFile.js | 572 + .../node_modules/rollup/dist/shared/parseAst.js | 2330 ++ vanilla/node_modules/rollup/dist/shared/rollup.js | 23966 ++++++++++++ .../node_modules/rollup/dist/shared/watch-cli.js | 542 + vanilla/node_modules/rollup/dist/shared/watch.js | 324 + vanilla/node_modules/rollup/package.json | 286 + vanilla/node_modules/saxes/README.md | 323 + vanilla/node_modules/saxes/package.json | 71 + vanilla/node_modules/saxes/saxes.d.ts | 635 + vanilla/node_modules/saxes/saxes.js | 2053 ++ vanilla/node_modules/saxes/saxes.js.map | 1 + vanilla/node_modules/semver/LICENSE | 15 + vanilla/node_modules/semver/README.md | 665 + vanilla/node_modules/semver/bin/semver.js | 191 + vanilla/node_modules/semver/classes/comparator.js | 143 + vanilla/node_modules/semver/classes/index.js | 7 + vanilla/node_modules/semver/classes/range.js | 557 + vanilla/node_modules/semver/classes/semver.js | 333 + vanilla/node_modules/semver/functions/clean.js | 8 + vanilla/node_modules/semver/functions/cmp.js | 54 + vanilla/node_modules/semver/functions/coerce.js | 62 + .../node_modules/semver/functions/compare-build.js | 9 + .../node_modules/semver/functions/compare-loose.js | 5 + vanilla/node_modules/semver/functions/compare.js | 7 + vanilla/node_modules/semver/functions/diff.js | 60 + vanilla/node_modules/semver/functions/eq.js | 5 + vanilla/node_modules/semver/functions/gt.js | 5 + vanilla/node_modules/semver/functions/gte.js | 5 + vanilla/node_modules/semver/functions/inc.js | 21 + vanilla/node_modules/semver/functions/lt.js | 5 + vanilla/node_modules/semver/functions/lte.js | 5 + vanilla/node_modules/semver/functions/major.js | 5 + vanilla/node_modules/semver/functions/minor.js | 5 + vanilla/node_modules/semver/functions/neq.js | 5 + vanilla/node_modules/semver/functions/parse.js | 18 + vanilla/node_modules/semver/functions/patch.js | 5 + .../node_modules/semver/functions/prerelease.js | 8 + vanilla/node_modules/semver/functions/rcompare.js | 5 + vanilla/node_modules/semver/functions/rsort.js | 5 + vanilla/node_modules/semver/functions/satisfies.js | 12 + vanilla/node_modules/semver/functions/sort.js | 5 + vanilla/node_modules/semver/functions/valid.js | 8 + vanilla/node_modules/semver/index.js | 91 + vanilla/node_modules/semver/internal/constants.js | 37 + vanilla/node_modules/semver/internal/debug.js | 11 + .../node_modules/semver/internal/identifiers.js | 29 + vanilla/node_modules/semver/internal/lrucache.js | 42 + .../node_modules/semver/internal/parse-options.js | 17 + vanilla/node_modules/semver/internal/re.js | 223 + vanilla/node_modules/semver/package.json | 78 + vanilla/node_modules/semver/preload.js | 4 + vanilla/node_modules/semver/range.bnf | 16 + vanilla/node_modules/semver/ranges/gtr.js | 6 + vanilla/node_modules/semver/ranges/intersects.js | 9 + vanilla/node_modules/semver/ranges/ltr.js | 6 + .../node_modules/semver/ranges/max-satisfying.js | 27 + .../node_modules/semver/ranges/min-satisfying.js | 26 + vanilla/node_modules/semver/ranges/min-version.js | 63 + vanilla/node_modules/semver/ranges/outside.js | 82 + vanilla/node_modules/semver/ranges/simplify.js | 49 + vanilla/node_modules/semver/ranges/subset.js | 249 + .../node_modules/semver/ranges/to-comparators.js | 10 + vanilla/node_modules/semver/ranges/valid.js | 13 + vanilla/node_modules/siginfo/.travis.yml | 13 + vanilla/node_modules/siginfo/LICENSE | 13 + vanilla/node_modules/siginfo/README.md | 47 + vanilla/node_modules/siginfo/index.js | 20 + vanilla/node_modules/siginfo/package.json | 32 + vanilla/node_modules/siginfo/test.js | 16 + vanilla/node_modules/source-map-js/LICENSE | 28 + vanilla/node_modules/source-map-js/README.md | 765 + .../node_modules/source-map-js/lib/array-set.js | 121 + .../node_modules/source-map-js/lib/base64-vlq.js | 140 + vanilla/node_modules/source-map-js/lib/base64.js | 67 + .../source-map-js/lib/binary-search.js | 111 + .../node_modules/source-map-js/lib/mapping-list.js | 79 + .../node_modules/source-map-js/lib/quick-sort.js | 132 + .../source-map-js/lib/source-map-consumer.d.ts | 1 + .../source-map-js/lib/source-map-consumer.js | 1188 + .../source-map-js/lib/source-map-generator.d.ts | 1 + .../source-map-js/lib/source-map-generator.js | 444 + .../source-map-js/lib/source-node.d.ts | 1 + .../node_modules/source-map-js/lib/source-node.js | 413 + vanilla/node_modules/source-map-js/lib/util.js | 594 + vanilla/node_modules/source-map-js/package.json | 71 + vanilla/node_modules/source-map-js/source-map.d.ts | 104 + vanilla/node_modules/source-map-js/source-map.js | 8 + vanilla/node_modules/stackback/.npmignore | 1 + vanilla/node_modules/stackback/.travis.yml | 4 + vanilla/node_modules/stackback/README.md | 41 + vanilla/node_modules/stackback/formatstack.js | 57 + vanilla/node_modules/stackback/index.js | 46 + vanilla/node_modules/stackback/package.json | 23 + vanilla/node_modules/stackback/test.js | 24 + vanilla/node_modules/std-env/LICENCE | 22 + vanilla/node_modules/std-env/README.md | 118 + vanilla/node_modules/std-env/dist/index.cjs | 1 + vanilla/node_modules/std-env/dist/index.d.cts | 92 + vanilla/node_modules/std-env/dist/index.d.mts | 92 + vanilla/node_modules/std-env/dist/index.d.ts | 92 + vanilla/node_modules/std-env/dist/index.mjs | 1 + vanilla/node_modules/std-env/package.json | 46 + vanilla/node_modules/supports-color/browser.js | 5 + vanilla/node_modules/supports-color/index.js | 135 + vanilla/node_modules/supports-color/license | 9 + vanilla/node_modules/supports-color/package.json | 53 + vanilla/node_modules/supports-color/readme.md | 76 + vanilla/node_modules/symbol-tree/LICENSE | 21 + vanilla/node_modules/symbol-tree/README.md | 545 + vanilla/node_modules/symbol-tree/lib/SymbolTree.js | 838 + .../node_modules/symbol-tree/lib/SymbolTreeNode.js | 54 + .../node_modules/symbol-tree/lib/TreeIterator.js | 69 + .../node_modules/symbol-tree/lib/TreePosition.js | 11 + vanilla/node_modules/symbol-tree/package.json | 47 + vanilla/node_modules/tinybench/LICENSE | 21 + vanilla/node_modules/tinybench/README.md | 422 + vanilla/node_modules/tinybench/dist/index.cjs | 585 + vanilla/node_modules/tinybench/dist/index.d.cts | 319 + vanilla/node_modules/tinybench/dist/index.d.ts | 319 + vanilla/node_modules/tinybench/dist/index.js | 560 + vanilla/node_modules/tinybench/package.json | 27 + vanilla/node_modules/tinyexec/LICENSE | 21 + vanilla/node_modules/tinyexec/README.md | 269 + vanilla/node_modules/tinyexec/dist/main.d.ts | 74 + vanilla/node_modules/tinyexec/dist/main.js | 633 + vanilla/node_modules/tinyexec/package.json | 61 + vanilla/node_modules/tinyglobby/LICENSE | 21 + vanilla/node_modules/tinyglobby/README.md | 25 + vanilla/node_modules/tinyglobby/dist/index.cjs | 350 + vanilla/node_modules/tinyglobby/dist/index.d.cts | 147 + vanilla/node_modules/tinyglobby/dist/index.d.mts | 147 + vanilla/node_modules/tinyglobby/dist/index.mjs | 318 + vanilla/node_modules/tinyglobby/package.json | 73 + vanilla/node_modules/tinyrainbow/LICENCE | 21 + vanilla/node_modules/tinyrainbow/README.md | 28 + vanilla/node_modules/tinyrainbow/dist/index.d.ts | 62 + vanilla/node_modules/tinyrainbow/dist/index.js | 95 + vanilla/node_modules/tinyrainbow/package.json | 34 + vanilla/node_modules/tldts-core/LICENSE | 13 + vanilla/node_modules/tldts-core/README.md | 3 + vanilla/node_modules/tldts-core/dist/cjs/index.js | 564 + .../node_modules/tldts-core/dist/cjs/index.js.map | 1 + .../dist/cjs/src/domain-without-suffix.js | 15 + .../dist/cjs/src/domain-without-suffix.js.map | 1 + .../node_modules/tldts-core/dist/cjs/src/domain.js | 83 + .../tldts-core/dist/cjs/src/domain.js.map | 1 + .../tldts-core/dist/cjs/src/extract-hostname.js | 149 + .../dist/cjs/src/extract-hostname.js.map | 1 + .../tldts-core/dist/cjs/src/factory.js | 107 + .../tldts-core/dist/cjs/src/factory.js.map | 1 + .../node_modules/tldts-core/dist/cjs/src/is-ip.js | 72 + .../tldts-core/dist/cjs/src/is-ip.js.map | 1 + .../tldts-core/dist/cjs/src/is-valid.js | 69 + .../tldts-core/dist/cjs/src/is-valid.js.map | 1 + .../tldts-core/dist/cjs/src/lookup/fast-path.js | 69 + .../dist/cjs/src/lookup/fast-path.js.map | 1 + .../tldts-core/dist/cjs/src/lookup/interface.js | 3 + .../dist/cjs/src/lookup/interface.js.map | 1 + .../tldts-core/dist/cjs/src/options.js | 22 + .../tldts-core/dist/cjs/src/options.js.map | 1 + .../tldts-core/dist/cjs/src/subdomain.js | 14 + .../tldts-core/dist/cjs/src/subdomain.js.map | 1 + .../tldts-core/dist/cjs/tsconfig.tsbuildinfo | 1 + vanilla/node_modules/tldts-core/dist/es6/index.js | 4 + .../node_modules/tldts-core/dist/es6/index.js.map | 1 + .../dist/es6/src/domain-without-suffix.js | 12 + .../dist/es6/src/domain-without-suffix.js.map | 1 + .../node_modules/tldts-core/dist/es6/src/domain.js | 80 + .../tldts-core/dist/es6/src/domain.js.map | 1 + .../tldts-core/dist/es6/src/extract-hostname.js | 146 + .../dist/es6/src/extract-hostname.js.map | 1 + .../tldts-core/dist/es6/src/factory.js | 102 + .../tldts-core/dist/es6/src/factory.js.map | 1 + .../node_modules/tldts-core/dist/es6/src/is-ip.js | 69 + .../tldts-core/dist/es6/src/is-ip.js.map | 1 + .../tldts-core/dist/es6/src/is-valid.js | 66 + .../tldts-core/dist/es6/src/is-valid.js.map | 1 + .../tldts-core/dist/es6/src/lookup/fast-path.js | 66 + .../dist/es6/src/lookup/fast-path.js.map | 1 + .../tldts-core/dist/es6/src/lookup/interface.js | 2 + .../dist/es6/src/lookup/interface.js.map | 1 + .../tldts-core/dist/es6/src/options.js | 19 + .../tldts-core/dist/es6/src/options.js.map | 1 + .../tldts-core/dist/es6/src/subdomain.js | 11 + .../tldts-core/dist/es6/src/subdomain.js.map | 1 + .../dist/es6/tsconfig.bundle.tsbuildinfo | 1 + .../node_modules/tldts-core/dist/types/index.d.ts | 4 + .../dist/types/src/domain-without-suffix.d.ts | 6 + .../tldts-core/dist/types/src/domain.d.ts | 5 + .../dist/types/src/extract-hostname.d.ts | 5 + .../tldts-core/dist/types/src/factory.d.ts | 28 + .../tldts-core/dist/types/src/is-ip.d.ts | 6 + .../tldts-core/dist/types/src/is-valid.d.ts | 15 + .../dist/types/src/lookup/fast-path.d.ts | 2 + .../dist/types/src/lookup/interface.d.ts | 9 + .../tldts-core/dist/types/src/options.d.ts | 10 + .../tldts-core/dist/types/src/subdomain.d.ts | 4 + vanilla/node_modules/tldts-core/index.ts | 10 + vanilla/node_modules/tldts-core/package.json | 68 + .../tldts-core/src/domain-without-suffix.ts | 14 + vanilla/node_modules/tldts-core/src/domain.ts | 100 + .../tldts-core/src/extract-hostname.ts | 170 + vanilla/node_modules/tldts-core/src/factory.ts | 163 + vanilla/node_modules/tldts-core/src/is-ip.ts | 87 + vanilla/node_modules/tldts-core/src/is-valid.ts | 79 + .../tldts-core/src/lookup/fast-path.ts | 80 + .../tldts-core/src/lookup/interface.ts | 10 + vanilla/node_modules/tldts-core/src/options.ts | 39 + vanilla/node_modules/tldts-core/src/subdomain.ts | 11 + vanilla/node_modules/tldts/LICENSE | 13 + vanilla/node_modules/tldts/README.md | 327 + vanilla/node_modules/tldts/bin/cli.js | 21 + vanilla/node_modules/tldts/dist/cjs/index.js | 669 + vanilla/node_modules/tldts/dist/cjs/index.js.map | 1 + .../node_modules/tldts/dist/cjs/src/data/trie.js | 14 + .../tldts/dist/cjs/src/data/trie.js.map | 1 + .../node_modules/tldts/dist/cjs/src/suffix-trie.js | 67 + .../tldts/dist/cjs/src/suffix-trie.js.map | 1 + .../tldts/dist/cjs/tsconfig.tsbuildinfo | 1 + vanilla/node_modules/tldts/dist/es6/index.js | 33 + vanilla/node_modules/tldts/dist/es6/index.js.map | 1 + .../node_modules/tldts/dist/es6/src/data/trie.js | 11 + .../tldts/dist/es6/src/data/trie.js.map | 1 + .../node_modules/tldts/dist/es6/src/suffix-trie.js | 64 + .../tldts/dist/es6/src/suffix-trie.js.map | 1 + .../tldts/dist/es6/tsconfig.bundle.tsbuildinfo | 1 + vanilla/node_modules/tldts/dist/index.cjs.min.js | 2 + .../node_modules/tldts/dist/index.cjs.min.js.map | 1 + vanilla/node_modules/tldts/dist/index.esm.min.js | 2 + .../node_modules/tldts/dist/index.esm.min.js.map | 1 + vanilla/node_modules/tldts/dist/index.umd.min.js | 2 + .../node_modules/tldts/dist/index.umd.min.js.map | 1 + vanilla/node_modules/tldts/dist/types/index.d.ts | 7 + .../tldts/dist/types/src/data/trie.d.ts | 5 + .../tldts/dist/types/src/suffix-trie.d.ts | 5 + vanilla/node_modules/tldts/index.ts | 62 + vanilla/node_modules/tldts/package.json | 89 + vanilla/node_modules/tldts/src/data/trie.ts | 14 + vanilla/node_modules/tldts/src/suffix-trie.ts | 110 + vanilla/node_modules/tough-cookie/LICENSE | 12 + vanilla/node_modules/tough-cookie/README.md | 195 + vanilla/node_modules/tough-cookie/dist/index.cjs | 2313 ++ .../node_modules/tough-cookie/dist/index.cjs.map | 1 + vanilla/node_modules/tough-cookie/dist/index.d.cts | 1879 + vanilla/node_modules/tough-cookie/dist/index.d.ts | 1879 + vanilla/node_modules/tough-cookie/dist/index.js | 2268 ++ .../node_modules/tough-cookie/dist/index.js.map | 1 + vanilla/node_modules/tough-cookie/package.json | 149 + vanilla/node_modules/tr46/LICENSE.md | 21 + vanilla/node_modules/tr46/README.md | 76 + vanilla/node_modules/tr46/index.js | 344 + vanilla/node_modules/tr46/lib/mappingTable.json | 1 + vanilla/node_modules/tr46/lib/regexes.js | 29 + vanilla/node_modules/tr46/lib/statusMapping.js | 9 + vanilla/node_modules/tr46/package.json | 47 + vanilla/node_modules/undici/LICENSE | 21 + vanilla/node_modules/undici/README.md | 685 + vanilla/node_modules/undici/docs/docs/api/Agent.md | 84 + .../undici/docs/docs/api/BalancedPool.md | 99 + .../undici/docs/docs/api/CacheStorage.md | 30 + .../undici/docs/docs/api/CacheStore.md | 164 + .../node_modules/undici/docs/docs/api/Client.md | 285 + .../undici/docs/docs/api/ClientStats.md | 27 + .../node_modules/undici/docs/docs/api/Connector.md | 115 + .../undici/docs/docs/api/ContentType.md | 57 + .../node_modules/undici/docs/docs/api/Cookies.md | 101 + vanilla/node_modules/undici/docs/docs/api/Debug.md | 62 + .../undici/docs/docs/api/DiagnosticsChannel.md | 313 + .../undici/docs/docs/api/Dispatcher.md | 1365 + .../undici/docs/docs/api/EnvHttpProxyAgent.md | 159 + .../node_modules/undici/docs/docs/api/Errors.md | 48 + .../undici/docs/docs/api/EventSource.md | 45 + vanilla/node_modules/undici/docs/docs/api/Fetch.md | 52 + .../undici/docs/docs/api/GlobalInstallation.md | 91 + .../node_modules/undici/docs/docs/api/H2CClient.md | 263 + .../node_modules/undici/docs/docs/api/MockAgent.md | 603 + .../undici/docs/docs/api/MockCallHistory.md | 197 + .../undici/docs/docs/api/MockCallHistoryLog.md | 43 + .../undici/docs/docs/api/MockClient.md | 81 + .../undici/docs/docs/api/MockErrors.md | 12 + .../node_modules/undici/docs/docs/api/MockPool.md | 555 + vanilla/node_modules/undici/docs/docs/api/Pool.md | 84 + .../node_modules/undici/docs/docs/api/PoolStats.md | 35 + .../undici/docs/docs/api/ProxyAgent.md | 229 + .../undici/docs/docs/api/RedirectHandler.md | 96 + .../undici/docs/docs/api/RetryAgent.md | 50 + .../undici/docs/docs/api/RetryHandler.md | 118 + .../undici/docs/docs/api/RoundRobinPool.md | 145 + .../undici/docs/docs/api/SnapshotAgent.md | 616 + vanilla/node_modules/undici/docs/docs/api/Util.md | 25 + .../node_modules/undici/docs/docs/api/WebSocket.md | 133 + .../undici/docs/docs/api/api-lifecycle.md | 91 + .../docs/docs/best-practices/client-certificate.md | 64 + .../undici/docs/docs/best-practices/crawling.md | 58 + .../docs/docs/best-practices/mocking-request.md | 190 + .../undici/docs/docs/best-practices/proxy.md | 127 + .../docs/docs/best-practices/writing-tests.md | 20 + vanilla/node_modules/undici/index-fetch.js | 65 + vanilla/node_modules/undici/index.d.ts | 3 + vanilla/node_modules/undici/index.js | 232 + .../node_modules/undici/lib/api/abort-signal.js | 59 + vanilla/node_modules/undici/lib/api/api-connect.js | 110 + .../node_modules/undici/lib/api/api-pipeline.js | 252 + vanilla/node_modules/undici/lib/api/api-request.js | 214 + vanilla/node_modules/undici/lib/api/api-stream.js | 209 + vanilla/node_modules/undici/lib/api/api-upgrade.js | 111 + vanilla/node_modules/undici/lib/api/index.js | 7 + vanilla/node_modules/undici/lib/api/readable.js | 580 + .../undici/lib/cache/memory-cache-store.js | 234 + .../undici/lib/cache/sqlite-cache-store.js | 461 + vanilla/node_modules/undici/lib/core/connect.js | 137 + vanilla/node_modules/undici/lib/core/constants.js | 143 + .../node_modules/undici/lib/core/diagnostics.js | 225 + vanilla/node_modules/undici/lib/core/errors.js | 448 + vanilla/node_modules/undici/lib/core/request.js | 412 + vanilla/node_modules/undici/lib/core/symbols.js | 74 + vanilla/node_modules/undici/lib/core/tree.js | 160 + vanilla/node_modules/undici/lib/core/util.js | 957 + .../node_modules/undici/lib/dispatcher/agent.js | 158 + .../undici/lib/dispatcher/balanced-pool.js | 216 + .../undici/lib/dispatcher/client-h1.js | 1606 + .../undici/lib/dispatcher/client-h2.js | 990 + .../node_modules/undici/lib/dispatcher/client.js | 647 + .../undici/lib/dispatcher/dispatcher-base.js | 165 + .../undici/lib/dispatcher/dispatcher.js | 48 + .../undici/lib/dispatcher/env-http-proxy-agent.js | 146 + .../undici/lib/dispatcher/fixed-queue.js | 135 + .../undici/lib/dispatcher/h2c-client.js | 51 + .../undici/lib/dispatcher/pool-base.js | 214 + vanilla/node_modules/undici/lib/dispatcher/pool.js | 118 + .../undici/lib/dispatcher/proxy-agent.js | 287 + .../undici/lib/dispatcher/retry-agent.js | 35 + .../undici/lib/dispatcher/round-robin-pool.js | 137 + vanilla/node_modules/undici/lib/encoding/index.js | 33 + vanilla/node_modules/undici/lib/global.js | 50 + .../undici/lib/handler/cache-handler.js | 561 + .../lib/handler/cache-revalidation-handler.js | 124 + .../undici/lib/handler/decorator-handler.js | 67 + .../undici/lib/handler/deduplication-handler.js | 216 + .../undici/lib/handler/redirect-handler.js | 237 + .../undici/lib/handler/retry-handler.js | 394 + .../undici/lib/handler/unwrap-handler.js | 96 + .../undici/lib/handler/wrap-handler.js | 95 + .../node_modules/undici/lib/interceptor/cache.js | 495 + .../undici/lib/interceptor/decompress.js | 259 + .../undici/lib/interceptor/deduplicate.js | 107 + vanilla/node_modules/undici/lib/interceptor/dns.js | 474 + .../node_modules/undici/lib/interceptor/dump.js | 112 + .../undici/lib/interceptor/redirect.js | 21 + .../undici/lib/interceptor/response-error.js | 95 + .../node_modules/undici/lib/interceptor/retry.js | 19 + vanilla/node_modules/undici/lib/llhttp/.gitkeep | 0 .../node_modules/undici/lib/llhttp/constants.d.ts | 195 + .../node_modules/undici/lib/llhttp/constants.js | 531 + .../node_modules/undici/lib/llhttp/llhttp-wasm.js | 15 + .../undici/lib/llhttp/llhttp_simd-wasm.js | 15 + vanilla/node_modules/undici/lib/llhttp/utils.d.ts | 2 + vanilla/node_modules/undici/lib/llhttp/utils.js | 12 + vanilla/node_modules/undici/lib/mock/mock-agent.js | 232 + .../undici/lib/mock/mock-call-history.js | 248 + .../node_modules/undici/lib/mock/mock-client.js | 68 + .../node_modules/undici/lib/mock/mock-errors.js | 29 + .../undici/lib/mock/mock-interceptor.js | 209 + vanilla/node_modules/undici/lib/mock/mock-pool.js | 68 + .../node_modules/undici/lib/mock/mock-symbols.js | 31 + vanilla/node_modules/undici/lib/mock/mock-utils.js | 480 + .../lib/mock/pending-interceptors-formatter.js | 43 + .../node_modules/undici/lib/mock/snapshot-agent.js | 353 + .../undici/lib/mock/snapshot-recorder.js | 588 + .../node_modules/undici/lib/mock/snapshot-utils.js | 158 + vanilla/node_modules/undici/lib/util/cache.js | 405 + vanilla/node_modules/undici/lib/util/date.js | 653 + vanilla/node_modules/undici/lib/util/promise.js | 28 + .../undici/lib/util/runtime-features.js | 124 + vanilla/node_modules/undici/lib/util/stats.js | 32 + vanilla/node_modules/undici/lib/util/timers.js | 425 + vanilla/node_modules/undici/lib/web/cache/cache.js | 864 + .../undici/lib/web/cache/cachestorage.js | 152 + vanilla/node_modules/undici/lib/web/cache/util.js | 45 + .../undici/lib/web/cookies/constants.js | 12 + .../node_modules/undici/lib/web/cookies/index.js | 199 + .../node_modules/undici/lib/web/cookies/parse.js | 322 + .../node_modules/undici/lib/web/cookies/util.js | 282 + .../lib/web/eventsource/eventsource-stream.js | 399 + .../undici/lib/web/eventsource/eventsource.js | 501 + .../undici/lib/web/eventsource/util.js | 29 + vanilla/node_modules/undici/lib/web/fetch/LICENSE | 21 + vanilla/node_modules/undici/lib/web/fetch/body.js | 509 + .../node_modules/undici/lib/web/fetch/constants.js | 131 + .../node_modules/undici/lib/web/fetch/data-url.js | 596 + .../undici/lib/web/fetch/formdata-parser.js | 575 + .../node_modules/undici/lib/web/fetch/formdata.js | 259 + .../node_modules/undici/lib/web/fetch/global.js | 40 + .../node_modules/undici/lib/web/fetch/headers.js | 719 + vanilla/node_modules/undici/lib/web/fetch/index.js | 2372 ++ .../node_modules/undici/lib/web/fetch/request.js | 1115 + .../node_modules/undici/lib/web/fetch/response.js | 641 + vanilla/node_modules/undici/lib/web/fetch/util.js | 1520 + vanilla/node_modules/undici/lib/web/infra/index.js | 229 + .../undici/lib/web/subresource-integrity/Readme.md | 9 + .../subresource-integrity/subresource-integrity.js | 307 + .../node_modules/undici/lib/web/webidl/index.js | 1003 + .../undici/lib/web/websocket/connection.js | 329 + .../undici/lib/web/websocket/constants.js | 126 + .../undici/lib/web/websocket/events.js | 331 + .../node_modules/undici/lib/web/websocket/frame.js | 133 + .../undici/lib/web/websocket/permessage-deflate.js | 70 + .../undici/lib/web/websocket/receiver.js | 444 + .../undici/lib/web/websocket/sender.js | 109 + .../lib/web/websocket/stream/websocketerror.js | 104 + .../lib/web/websocket/stream/websocketstream.js | 497 + .../node_modules/undici/lib/web/websocket/util.js | 339 + .../undici/lib/web/websocket/websocket.js | 739 + vanilla/node_modules/undici/package.json | 152 + .../node_modules/undici/scripts/strip-comments.js | 10 + vanilla/node_modules/undici/types/README.md | 6 + vanilla/node_modules/undici/types/agent.d.ts | 32 + vanilla/node_modules/undici/types/api.d.ts | 43 + .../node_modules/undici/types/balanced-pool.d.ts | 30 + .../undici/types/cache-interceptor.d.ts | 179 + vanilla/node_modules/undici/types/cache.d.ts | 36 + .../node_modules/undici/types/client-stats.d.ts | 15 + vanilla/node_modules/undici/types/client.d.ts | 123 + vanilla/node_modules/undici/types/connector.d.ts | 34 + .../node_modules/undici/types/content-type.d.ts | 21 + vanilla/node_modules/undici/types/cookies.d.ts | 30 + .../undici/types/diagnostics-channel.d.ts | 74 + vanilla/node_modules/undici/types/dispatcher.d.ts | 277 + .../undici/types/env-http-proxy-agent.d.ts | 22 + vanilla/node_modules/undici/types/errors.d.ts | 161 + vanilla/node_modules/undici/types/eventsource.d.ts | 66 + vanilla/node_modules/undici/types/fetch.d.ts | 211 + vanilla/node_modules/undici/types/formdata.d.ts | 108 + .../undici/types/global-dispatcher.d.ts | 9 + .../node_modules/undici/types/global-origin.d.ts | 7 + vanilla/node_modules/undici/types/h2c-client.d.ts | 73 + vanilla/node_modules/undici/types/handlers.d.ts | 15 + vanilla/node_modules/undici/types/header.d.ts | 160 + vanilla/node_modules/undici/types/index.d.ts | 88 + .../node_modules/undici/types/interceptors.d.ts | 73 + vanilla/node_modules/undici/types/mock-agent.d.ts | 68 + .../undici/types/mock-call-history.d.ts | 111 + vanilla/node_modules/undici/types/mock-client.d.ts | 27 + vanilla/node_modules/undici/types/mock-errors.d.ts | 12 + .../undici/types/mock-interceptor.d.ts | 94 + vanilla/node_modules/undici/types/mock-pool.d.ts | 27 + vanilla/node_modules/undici/types/patch.d.ts | 29 + vanilla/node_modules/undici/types/pool-stats.d.ts | 19 + vanilla/node_modules/undici/types/pool.d.ts | 41 + vanilla/node_modules/undici/types/proxy-agent.d.ts | 29 + vanilla/node_modules/undici/types/readable.d.ts | 68 + vanilla/node_modules/undici/types/retry-agent.d.ts | 8 + .../node_modules/undici/types/retry-handler.d.ts | 125 + .../undici/types/round-robin-pool.d.ts | 41 + .../node_modules/undici/types/snapshot-agent.d.ts | 109 + vanilla/node_modules/undici/types/util.d.ts | 18 + vanilla/node_modules/undici/types/utility.d.ts | 7 + vanilla/node_modules/undici/types/webidl.d.ts | 347 + vanilla/node_modules/undici/types/websocket.d.ts | 188 + vanilla/node_modules/vite/LICENSE.md | 2120 ++ vanilla/node_modules/vite/README.md | 20 + vanilla/node_modules/vite/bin/openChrome.js | 68 + vanilla/node_modules/vite/bin/vite.js | 79 + vanilla/node_modules/vite/client.d.ts | 279 + vanilla/node_modules/vite/dist/client/client.mjs | 1106 + vanilla/node_modules/vite/dist/client/env.mjs | 19 + .../node_modules/vite/dist/node/chunks/build.js | 4 + .../node_modules/vite/dist/node/chunks/build2.js | 5538 +++ .../node_modules/vite/dist/node/chunks/chunk.js | 48 + .../node_modules/vite/dist/node/chunks/config.js | 35978 +++++++++++++++++++ .../node_modules/vite/dist/node/chunks/config2.js | 4 + vanilla/node_modules/vite/dist/node/chunks/dist.js | 6758 ++++ vanilla/node_modules/vite/dist/node/chunks/lib.js | 377 + .../node_modules/vite/dist/node/chunks/logger.js | 329 + .../dist/node/chunks/moduleRunnerTransport.d.ts | 96 + .../vite/dist/node/chunks/optimizer.js | 4 + .../vite/dist/node/chunks/postcss-import.js | 479 + .../node_modules/vite/dist/node/chunks/preview.js | 4 + .../node_modules/vite/dist/node/chunks/server.js | 4 + vanilla/node_modules/vite/dist/node/cli.js | 698 + vanilla/node_modules/vite/dist/node/index.d.ts | 3713 ++ vanilla/node_modules/vite/dist/node/index.js | 30 + .../node_modules/vite/dist/node/module-runner.d.ts | 311 + .../node_modules/vite/dist/node/module-runner.js | 1160 + vanilla/node_modules/vite/misc/false.js | 1 + vanilla/node_modules/vite/misc/true.js | 1 + vanilla/node_modules/vite/package.json | 199 + vanilla/node_modules/vite/types/customEvent.d.ts | 50 + vanilla/node_modules/vite/types/hmrPayload.d.ts | 74 + vanilla/node_modules/vite/types/hot.d.ts | 39 + vanilla/node_modules/vite/types/import-meta.d.ts | 5 + vanilla/node_modules/vite/types/importGlob.d.ts | 89 + vanilla/node_modules/vite/types/importMeta.d.ts | 30 + .../types/internal/cssPreprocessorOptions.d.ts | 44 + .../vite/types/internal/lightningcssOptions.d.ts | 18 + .../vite/types/internal/terserOptions.d.ts | 11 + vanilla/node_modules/vite/types/metadata.d.ts | 33 + vanilla/node_modules/vite/types/package.json | 4 + vanilla/node_modules/vitest/LICENSE.md | 691 + vanilla/node_modules/vitest/README.md | 7 + vanilla/node_modules/vitest/browser/context.d.ts | 7 + vanilla/node_modules/vitest/browser/context.js | 20 + vanilla/node_modules/vitest/config.d.ts | 3 + vanilla/node_modules/vitest/coverage.d.ts | 1 + vanilla/node_modules/vitest/dist/browser.d.ts | 46 + vanilla/node_modules/vitest/dist/browser.js | 20 + .../dist/chunks/_commonjsHelpers.D26ty3Ew.js | 6 + .../vitest/dist/chunks/base.CJ0Y4ePK.js | 165 + .../vitest/dist/chunks/benchmark.B3N2zMcH.js | 40 + .../vitest/dist/chunks/benchmark.d.DAaHLpsq.d.ts | 24 + .../vitest/dist/chunks/browser.d.ChKACdzH.d.ts | 59 + .../vitest/dist/chunks/cac.DVeoLl0M.js | 1409 + .../vitest/dist/chunks/cli-api.B7PN_QUv.js | 13657 +++++++ .../vitest/dist/chunks/config.d.Cy95HiCx.d.ts | 210 + .../vitest/dist/chunks/console.Cf-YriPC.js | 146 + .../vitest/dist/chunks/constants.D_Q9UYh-.js | 36 + .../vitest/dist/chunks/coverage.AVPTjMgw.js | 3292 ++ .../vitest/dist/chunks/coverage.D_JHT54q.js | 25 + .../vitest/dist/chunks/coverage.d.BZtK59WP.d.ts | 37 + .../vitest/dist/chunks/creator.DAmOKTvJ.js | 673 + .../vitest/dist/chunks/date.Bq6ZW5rf.js | 73 + .../vitest/dist/chunks/defaults.BOqNVLsY.js | 74 + .../vitest/dist/chunks/env.D4Lgay0q.js | 8 + .../vitest/dist/chunks/environment.d.CrsxCzP1.d.ts | 29 + .../dist/chunks/evaluatedModules.Dg1zASAC.js | 17 + .../dist/chunks/evaluatedModules.d.BxJ5omdx.d.ts | 7 + .../vitest/dist/chunks/git.Bm2pzPAa.js | 71 + .../vitest/dist/chunks/global.d.B15mdLcR.d.ts | 99 + .../vitest/dist/chunks/globals.DOayXfHP.js | 30 + .../vitest/dist/chunks/index.6Qv1eEA6.js | 109 + .../vitest/dist/chunks/index.C5r1PdPD.js | 231 + .../vitest/dist/chunks/index.Chj8NDwU.js | 206 + .../vitest/dist/chunks/index.CyBMJtT7.js | 727 + .../vitest/dist/chunks/index.D3XRDfWc.js | 213 + .../vitest/dist/chunks/index.D4KonVSU.js | 6343 ++++ .../vitest/dist/chunks/index.M8mOzt4Y.js | 3839 ++ .../vitest/dist/chunks/index.Z5E_ObnR.js | 37 + .../vitest/dist/chunks/init-forks._y3TW739.js | 41 + .../vitest/dist/chunks/init-threads.DBO2kn-p.js | 18 + .../vitest/dist/chunks/init.B6MLFIaN.js | 334 + .../vitest/dist/chunks/inspector.CvyFGlXm.js | 53 + .../vitest/dist/chunks/modules.BJuCwlRJ.js | 36 + .../vitest/dist/chunks/node.Ce0vMQM7.js | 14 + .../vitest/dist/chunks/plugin.d.CtqpEehP.d.ts | 38 + .../vitest/dist/chunks/reporters.d.CWXNI2jG.d.ts | 3271 ++ .../vitest/dist/chunks/rpc.BoxB0q7B.js | 76 + .../vitest/dist/chunks/rpc.d.RH3apGEf.d.ts | 64 + .../vitest/dist/chunks/setup-common.Cm-kSBVi.js | 60 + .../dist/chunks/startModuleRunner.DEj0jb3e.js | 861 + .../vitest/dist/chunks/suite.d.BJWk38HB.d.ts | 10 + .../vitest/dist/chunks/test.B8ej_ZHS.js | 254 + .../vitest/dist/chunks/traces.CCmnQaNT.js | 217 + .../vitest/dist/chunks/traces.d.402V_yFI.d.ts | 18 + .../vitest/dist/chunks/utils.DvEY5TfP.js | 52 + .../node_modules/vitest/dist/chunks/vi.2VT5v0um.js | 3919 ++ .../node_modules/vitest/dist/chunks/vm.D3epNOPZ.js | 744 + .../vitest/dist/chunks/worker.d.Dyxm8DEL.d.ts | 255 + vanilla/node_modules/vitest/dist/cli.js | 28 + vanilla/node_modules/vitest/dist/config.cjs | 94 + vanilla/node_modules/vitest/dist/config.d.ts | 104 + vanilla/node_modules/vitest/dist/config.js | 15 + vanilla/node_modules/vitest/dist/coverage.d.ts | 118 + vanilla/node_modules/vitest/dist/coverage.js | 23 + vanilla/node_modules/vitest/dist/environments.d.ts | 22 + vanilla/node_modules/vitest/dist/environments.js | 3 + vanilla/node_modules/vitest/dist/index.d.ts | 510 + vanilla/node_modules/vitest/dist/index.js | 20 + vanilla/node_modules/vitest/dist/mocker.d.ts | 1 + vanilla/node_modules/vitest/dist/mocker.js | 1 + .../node_modules/vitest/dist/module-evaluator.d.ts | 124 + .../node_modules/vitest/dist/module-evaluator.js | 343 + vanilla/node_modules/vitest/dist/module-runner.js | 17 + vanilla/node_modules/vitest/dist/node.d.ts | 251 + vanilla/node_modules/vitest/dist/node.js | 98 + vanilla/node_modules/vitest/dist/path.js | 7 + vanilla/node_modules/vitest/dist/reporters.d.ts | 27 + vanilla/node_modules/vitest/dist/reporters.js | 24 + vanilla/node_modules/vitest/dist/runners.d.ts | 50 + vanilla/node_modules/vitest/dist/runners.js | 19 + vanilla/node_modules/vitest/dist/snapshot.d.ts | 9 + vanilla/node_modules/vitest/dist/snapshot.js | 4 + vanilla/node_modules/vitest/dist/spy.js | 1 + vanilla/node_modules/vitest/dist/suite.d.ts | 5 + vanilla/node_modules/vitest/dist/suite.js | 6 + vanilla/node_modules/vitest/dist/worker.d.ts | 32 + vanilla/node_modules/vitest/dist/worker.js | 48 + vanilla/node_modules/vitest/dist/workers/forks.js | 54 + .../node_modules/vitest/dist/workers/runVmTests.js | 95 + .../node_modules/vitest/dist/workers/threads.js | 55 + .../node_modules/vitest/dist/workers/vmForks.js | 36 + .../node_modules/vitest/dist/workers/vmThreads.js | 37 + vanilla/node_modules/vitest/environments.d.ts | 1 + vanilla/node_modules/vitest/globals.d.ts | 20 + vanilla/node_modules/vitest/import-meta.d.ts | 5 + vanilla/node_modules/vitest/importMeta.d.ts | 4 + vanilla/node_modules/vitest/index.cjs | 5 + vanilla/node_modules/vitest/index.d.cts | 1 + vanilla/node_modules/vitest/jsdom.d.ts | 6 + vanilla/node_modules/vitest/mocker.d.ts | 1 + vanilla/node_modules/vitest/node.d.ts | 1 + vanilla/node_modules/vitest/optional-types.d.ts | 7 + vanilla/node_modules/vitest/package.json | 224 + vanilla/node_modules/vitest/reporters.d.ts | 1 + vanilla/node_modules/vitest/runners.d.ts | 1 + vanilla/node_modules/vitest/snapshot.d.ts | 1 + vanilla/node_modules/vitest/suite.d.ts | 1 + vanilla/node_modules/vitest/suppress-warnings.cjs | 21 + vanilla/node_modules/vitest/vitest.mjs | 2 + vanilla/node_modules/vitest/worker.d.ts | 1 + vanilla/node_modules/w3c-xmlserializer/LICENSE.md | 25 + vanilla/node_modules/w3c-xmlserializer/README.md | 41 + .../w3c-xmlserializer/lib/attributes.js | 125 + .../w3c-xmlserializer/lib/constants.js | 44 + .../w3c-xmlserializer/lib/serialize.js | 365 + .../node_modules/w3c-xmlserializer/package.json | 32 + vanilla/node_modules/webidl-conversions/LICENSE.md | 12 + vanilla/node_modules/webidl-conversions/README.md | 99 + .../node_modules/webidl-conversions/lib/index.js | 436 + .../node_modules/webidl-conversions/package.json | 34 + vanilla/node_modules/whatwg-mimetype/LICENSE.txt | 7 + vanilla/node_modules/whatwg-mimetype/README.md | 132 + vanilla/node_modules/whatwg-mimetype/lib/index.js | 4 + .../whatwg-mimetype/lib/mime-type-parameters.js | 70 + .../node_modules/whatwg-mimetype/lib/mime-type.js | 127 + vanilla/node_modules/whatwg-mimetype/lib/parser.js | 105 + .../node_modules/whatwg-mimetype/lib/serializer.js | 25 + vanilla/node_modules/whatwg-mimetype/lib/sniff.js | 751 + vanilla/node_modules/whatwg-mimetype/lib/utils.js | 60 + vanilla/node_modules/whatwg-mimetype/package.json | 44 + vanilla/node_modules/whatwg-url/LICENSE.txt | 21 + vanilla/node_modules/whatwg-url/README.md | 104 + vanilla/node_modules/whatwg-url/index.js | 27 + vanilla/node_modules/whatwg-url/lib/Function.js | 42 + vanilla/node_modules/whatwg-url/lib/URL-impl.js | 233 + vanilla/node_modules/whatwg-url/lib/URL.js | 499 + .../whatwg-url/lib/URLSearchParams-impl.js | 135 + .../node_modules/whatwg-url/lib/URLSearchParams.js | 505 + .../node_modules/whatwg-url/lib/VoidFunction.js | 26 + vanilla/node_modules/whatwg-url/lib/encoding.js | 16 + vanilla/node_modules/whatwg-url/lib/infra.js | 26 + .../whatwg-url/lib/percent-encoding.js | 147 + .../whatwg-url/lib/url-state-machine.js | 1284 + vanilla/node_modules/whatwg-url/lib/urlencoded.js | 89 + vanilla/node_modules/whatwg-url/lib/utils.js | 252 + vanilla/node_modules/whatwg-url/package.json | 57 + .../node_modules/whatwg-url/webidl2js-wrapper.js | 7 + .../why-is-node-running/.github/FUNDING.yml | 1 + vanilla/node_modules/why-is-node-running/LICENSE | 21 + vanilla/node_modules/why-is-node-running/README.md | 104 + vanilla/node_modules/why-is-node-running/cli.js | 18 + .../node_modules/why-is-node-running/example.js | 15 + .../node_modules/why-is-node-running/include.js | 3 + vanilla/node_modules/why-is-node-running/index.js | 67 + .../node_modules/why-is-node-running/package.json | 39 + .../node_modules/xml-name-validator/LICENSE.txt | 176 + vanilla/node_modules/xml-name-validator/README.md | 35 + .../xml-name-validator/lib/xml-name-validator.js | 9 + .../node_modules/xml-name-validator/package.json | 30 + vanilla/node_modules/xmlchars/LICENSE | 18 + vanilla/node_modules/xmlchars/README.md | 33 + vanilla/node_modules/xmlchars/package.json | 51 + vanilla/node_modules/xmlchars/xml/1.0/ed4.d.ts | 31 + vanilla/node_modules/xmlchars/xml/1.0/ed4.js | 44 + vanilla/node_modules/xmlchars/xml/1.0/ed4.js.map | 1 + vanilla/node_modules/xmlchars/xml/1.0/ed5.d.ts | 51 + vanilla/node_modules/xmlchars/xml/1.0/ed5.js | 105 + vanilla/node_modules/xmlchars/xml/1.0/ed5.js.map | 1 + vanilla/node_modules/xmlchars/xml/1.1/ed2.d.ts | 73 + vanilla/node_modules/xmlchars/xml/1.1/ed2.js | 145 + vanilla/node_modules/xmlchars/xml/1.1/ed2.js.map | 1 + vanilla/node_modules/xmlchars/xmlchars.d.ts | 170 + vanilla/node_modules/xmlchars/xmlchars.js | 191 + vanilla/node_modules/xmlchars/xmlchars.js.map | 1 + vanilla/node_modules/xmlchars/xmlns/1.0/ed3.d.ts | 28 + vanilla/node_modules/xmlchars/xmlns/1.0/ed3.js | 65 + vanilla/node_modules/xmlchars/xmlns/1.0/ed3.js.map | 1 + 2835 files changed, 678121 insertions(+) create mode 120000 vanilla/node_modules/.bin/esbuild create mode 120000 vanilla/node_modules/.bin/nanoid create mode 120000 vanilla/node_modules/.bin/parser create mode 120000 vanilla/node_modules/.bin/rollup create mode 120000 vanilla/node_modules/.bin/semver create mode 120000 vanilla/node_modules/.bin/tldts create mode 120000 vanilla/node_modules/.bin/vite create mode 120000 vanilla/node_modules/.bin/vitest create mode 120000 vanilla/node_modules/.bin/why-is-node-running create mode 100644 vanilla/node_modules/.package-lock.json create mode 100644 vanilla/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json create mode 100644 vanilla/node_modules/@acemir/cssom/LICENSE.txt create mode 100644 vanilla/node_modules/@acemir/cssom/README.mdown create mode 100644 vanilla/node_modules/@acemir/cssom/build/CSSOM.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSConditionRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSContainerRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSCounterStyleRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSDocumentRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSFontFaceRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSGroupingRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSHostRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSImportRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSKeyframeRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSKeyframesRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSLayerBlockRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSLayerStatementRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSMediaRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSNamespaceRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSNestedDeclarations.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSOM.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSPageRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSPropertyRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSRuleList.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSScopeRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSStartingStyleRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSStyleDeclaration.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSStyleRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSStyleSheet.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSSupportsRule.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSValue.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/CSSValueExpression.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/MatcherList.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/MediaList.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/StyleSheet.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/clone.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/cssstyleTryCatchBlock.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/errorUtils.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/index.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/parse.js create mode 100644 vanilla/node_modules/@acemir/cssom/lib/regexPatterns.js create mode 100644 vanilla/node_modules/@acemir/cssom/package.json create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/LICENSE create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/README.md create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/browser/css-color.min.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/browser/css-color.min.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/cjs/index.cjs create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/cjs/index.cjs.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/cjs/index.d.cts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/index.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/index.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/index.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/color.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/color.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/color.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/common.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/common.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/common.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/constant.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/convert.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/css-calc.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/css-gradient.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/css-var.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/relative-color.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/resolve.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/typedef.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/util.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/util.js create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/dist/esm/js/util.js.map create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/package.json create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/index.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/cache.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/color.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/common.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/constant.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/convert.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/css-calc.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/css-gradient.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/css-var.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/relative-color.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/resolve.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/typedef.ts create mode 100644 vanilla/node_modules/@asamuzakjp/css-color/src/js/util.ts create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/LICENSE create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/README.md create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.cjs create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.cjs.map create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.d.cts create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/package.json create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/src/index.js create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/src/js/constant.js create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/src/js/finder.js create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/src/js/matcher.js create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/src/js/parser.js create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/src/js/utility.js create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/types/index.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/types/js/constant.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/types/js/finder.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/types/js/matcher.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/types/js/parser.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/dom-selector/types/js/utility.d.ts create mode 100644 vanilla/node_modules/@asamuzakjp/nwsapi/LICENSE create mode 100644 vanilla/node_modules/@asamuzakjp/nwsapi/README.md create mode 100644 vanilla/node_modules/@asamuzakjp/nwsapi/package.json create mode 100644 vanilla/node_modules/@asamuzakjp/nwsapi/src/nwsapi.js create mode 100644 vanilla/node_modules/@babel/helper-string-parser/LICENSE create mode 100644 vanilla/node_modules/@babel/helper-string-parser/README.md create mode 100644 vanilla/node_modules/@babel/helper-string-parser/lib/index.js create mode 100644 vanilla/node_modules/@babel/helper-string-parser/lib/index.js.map create mode 100644 vanilla/node_modules/@babel/helper-string-parser/package.json create mode 100644 vanilla/node_modules/@babel/helper-validator-identifier/LICENSE create mode 100644 vanilla/node_modules/@babel/helper-validator-identifier/README.md create mode 100644 vanilla/node_modules/@babel/helper-validator-identifier/lib/identifier.js create mode 100644 vanilla/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map create mode 100644 vanilla/node_modules/@babel/helper-validator-identifier/lib/index.js create mode 100644 vanilla/node_modules/@babel/helper-validator-identifier/lib/index.js.map create mode 100644 vanilla/node_modules/@babel/helper-validator-identifier/lib/keyword.js create mode 100644 vanilla/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map create mode 100644 vanilla/node_modules/@babel/helper-validator-identifier/package.json create mode 100644 vanilla/node_modules/@babel/parser/CHANGELOG.md create mode 100644 vanilla/node_modules/@babel/parser/LICENSE create mode 100644 vanilla/node_modules/@babel/parser/README.md create mode 100755 vanilla/node_modules/@babel/parser/bin/babel-parser.js create mode 100644 vanilla/node_modules/@babel/parser/lib/index.js create mode 100644 vanilla/node_modules/@babel/parser/lib/index.js.map create mode 100644 vanilla/node_modules/@babel/parser/package.json create mode 100644 vanilla/node_modules/@babel/parser/typings/babel-parser.d.ts create mode 100644 vanilla/node_modules/@babel/types/LICENSE create mode 100644 vanilla/node_modules/@babel/types/README.md create mode 100644 vanilla/node_modules/@babel/types/lib/asserts/assertNode.js create mode 100644 vanilla/node_modules/@babel/types/lib/asserts/assertNode.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/asserts/generated/index.js create mode 100644 vanilla/node_modules/@babel/types/lib/asserts/generated/index.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/ast-types/generated/index.js create mode 100644 vanilla/node_modules/@babel/types/lib/ast-types/generated/index.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/builders/flow/createFlowUnionType.js create mode 100644 vanilla/node_modules/@babel/types/lib/builders/flow/createFlowUnionType.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/builders/flow/createTypeAnnotationBasedOnTypeof.js create mode 100644 vanilla/node_modules/@babel/types/lib/builders/flow/createTypeAnnotationBasedOnTypeof.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/builders/generated/index.js create mode 100644 vanilla/node_modules/@babel/types/lib/builders/generated/index.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/builders/generated/lowercase.js create mode 100644 vanilla/node_modules/@babel/types/lib/builders/generated/lowercase.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/builders/generated/uppercase.js create mode 100644 vanilla/node_modules/@babel/types/lib/builders/generated/uppercase.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/builders/productions.js create mode 100644 vanilla/node_modules/@babel/types/lib/builders/productions.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/builders/react/buildChildren.js create mode 100644 vanilla/node_modules/@babel/types/lib/builders/react/buildChildren.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/builders/typescript/createTSUnionType.js create mode 100644 vanilla/node_modules/@babel/types/lib/builders/typescript/createTSUnionType.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/builders/validateNode.js create mode 100644 vanilla/node_modules/@babel/types/lib/builders/validateNode.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/clone/clone.js create mode 100644 vanilla/node_modules/@babel/types/lib/clone/clone.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/clone/cloneDeep.js create mode 100644 vanilla/node_modules/@babel/types/lib/clone/cloneDeep.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/clone/cloneDeepWithoutLoc.js create mode 100644 vanilla/node_modules/@babel/types/lib/clone/cloneDeepWithoutLoc.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/clone/cloneNode.js create mode 100644 vanilla/node_modules/@babel/types/lib/clone/cloneNode.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/clone/cloneWithoutLoc.js create mode 100644 vanilla/node_modules/@babel/types/lib/clone/cloneWithoutLoc.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/comments/addComment.js create mode 100644 vanilla/node_modules/@babel/types/lib/comments/addComment.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/comments/addComments.js create mode 100644 vanilla/node_modules/@babel/types/lib/comments/addComments.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/comments/inheritInnerComments.js create mode 100644 vanilla/node_modules/@babel/types/lib/comments/inheritInnerComments.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/comments/inheritLeadingComments.js create mode 100644 vanilla/node_modules/@babel/types/lib/comments/inheritLeadingComments.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/comments/inheritTrailingComments.js create mode 100644 vanilla/node_modules/@babel/types/lib/comments/inheritTrailingComments.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/comments/inheritsComments.js create mode 100644 vanilla/node_modules/@babel/types/lib/comments/inheritsComments.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/comments/removeComments.js create mode 100644 vanilla/node_modules/@babel/types/lib/comments/removeComments.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/constants/generated/index.js create mode 100644 vanilla/node_modules/@babel/types/lib/constants/generated/index.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/constants/index.js create mode 100644 vanilla/node_modules/@babel/types/lib/constants/index.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/ensureBlock.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/ensureBlock.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/gatherSequenceExpressions.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/gatherSequenceExpressions.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toBindingIdentifierName.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toBindingIdentifierName.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toBlock.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toBlock.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toComputedKey.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toComputedKey.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toExpression.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toExpression.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toIdentifier.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toIdentifier.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toKeyAlias.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toKeyAlias.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toSequenceExpression.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toSequenceExpression.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toStatement.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/toStatement.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/converters/valueToNode.js create mode 100644 vanilla/node_modules/@babel/types/lib/converters/valueToNode.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/core.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/core.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/deprecated-aliases.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/deprecated-aliases.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/experimental.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/experimental.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/flow.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/flow.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/index.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/index.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/jsx.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/jsx.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/misc.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/misc.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/placeholders.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/placeholders.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/typescript.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/typescript.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/utils.js create mode 100644 vanilla/node_modules/@babel/types/lib/definitions/utils.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/index-legacy.d.ts create mode 100644 vanilla/node_modules/@babel/types/lib/index.d.ts create mode 100644 vanilla/node_modules/@babel/types/lib/index.js create mode 100644 vanilla/node_modules/@babel/types/lib/index.js.flow create mode 100644 vanilla/node_modules/@babel/types/lib/index.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/appendToMemberExpression.js create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/appendToMemberExpression.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/flow/removeTypeDuplicates.js create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/flow/removeTypeDuplicates.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/inherits.js create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/inherits.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/prependToMemberExpression.js create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/prependToMemberExpression.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/removeProperties.js create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/removeProperties.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/removePropertiesDeep.js create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/removePropertiesDeep.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/typescript/removeTypeDuplicates.js create mode 100644 vanilla/node_modules/@babel/types/lib/modifications/typescript/removeTypeDuplicates.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/retrievers/getAssignmentIdentifiers.js create mode 100644 vanilla/node_modules/@babel/types/lib/retrievers/getAssignmentIdentifiers.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/retrievers/getBindingIdentifiers.js create mode 100644 vanilla/node_modules/@babel/types/lib/retrievers/getBindingIdentifiers.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/retrievers/getFunctionName.js create mode 100644 vanilla/node_modules/@babel/types/lib/retrievers/getFunctionName.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/retrievers/getOuterBindingIdentifiers.js create mode 100644 vanilla/node_modules/@babel/types/lib/retrievers/getOuterBindingIdentifiers.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/traverse/traverse.js create mode 100644 vanilla/node_modules/@babel/types/lib/traverse/traverse.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/traverse/traverseFast.js create mode 100644 vanilla/node_modules/@babel/types/lib/traverse/traverseFast.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/utils/deprecationWarning.js create mode 100644 vanilla/node_modules/@babel/types/lib/utils/deprecationWarning.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/utils/inherit.js create mode 100644 vanilla/node_modules/@babel/types/lib/utils/inherit.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/utils/react/cleanJSXElementLiteralChild.js create mode 100644 vanilla/node_modules/@babel/types/lib/utils/react/cleanJSXElementLiteralChild.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/utils/shallowEqual.js create mode 100644 vanilla/node_modules/@babel/types/lib/utils/shallowEqual.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/buildMatchMemberExpression.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/buildMatchMemberExpression.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/generated/index.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/generated/index.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/is.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/is.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isBinding.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isBinding.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isBlockScoped.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isBlockScoped.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isImmutable.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isImmutable.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isLet.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isLet.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isNode.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isNode.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isNodesEquivalent.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isNodesEquivalent.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isPlaceholderType.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isPlaceholderType.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isReferenced.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isReferenced.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isScope.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isScope.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isSpecifierDefault.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isSpecifierDefault.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isType.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isType.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isValidES3Identifier.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isValidES3Identifier.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isValidIdentifier.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isValidIdentifier.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isVar.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/isVar.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/matchesPattern.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/matchesPattern.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/react/isCompatTag.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/react/isCompatTag.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/react/isReactComponent.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/react/isReactComponent.js.map create mode 100644 vanilla/node_modules/@babel/types/lib/validators/validate.js create mode 100644 vanilla/node_modules/@babel/types/lib/validators/validate.js.map create mode 100644 vanilla/node_modules/@babel/types/package.json create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/LICENSE.md create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/LICENSE.txt create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/README.md create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/package.json create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/src/lib/ascii.js create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/src/lib/clone.js create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/src/lib/compare.js create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/src/lib/index.js create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/src/lib/merge.js create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/src/lib/normalize.js create mode 100644 vanilla/node_modules/@bcoe/v8-coverage/src/lib/range-tree.js create mode 100644 vanilla/node_modules/@csstools/color-helpers/CHANGELOG.md create mode 100644 vanilla/node_modules/@csstools/color-helpers/LICENSE.md create mode 100644 vanilla/node_modules/@csstools/color-helpers/README.md create mode 100644 vanilla/node_modules/@csstools/color-helpers/dist/index.d.ts create mode 100644 vanilla/node_modules/@csstools/color-helpers/dist/index.mjs create mode 100644 vanilla/node_modules/@csstools/color-helpers/package.json create mode 100644 vanilla/node_modules/@csstools/css-calc/CHANGELOG.md create mode 100644 vanilla/node_modules/@csstools/css-calc/LICENSE.md create mode 100644 vanilla/node_modules/@csstools/css-calc/README.md create mode 100644 vanilla/node_modules/@csstools/css-calc/dist/index.d.ts create mode 100644 vanilla/node_modules/@csstools/css-calc/dist/index.mjs create mode 100644 vanilla/node_modules/@csstools/css-calc/package.json create mode 100644 vanilla/node_modules/@csstools/css-color-parser/CHANGELOG.md create mode 100644 vanilla/node_modules/@csstools/css-color-parser/LICENSE.md create mode 100644 vanilla/node_modules/@csstools/css-color-parser/README.md create mode 100644 vanilla/node_modules/@csstools/css-color-parser/dist/index.d.ts create mode 100644 vanilla/node_modules/@csstools/css-color-parser/dist/index.mjs create mode 100644 vanilla/node_modules/@csstools/css-color-parser/package.json create mode 100644 vanilla/node_modules/@csstools/css-parser-algorithms/CHANGELOG.md create mode 100644 vanilla/node_modules/@csstools/css-parser-algorithms/LICENSE.md create mode 100644 vanilla/node_modules/@csstools/css-parser-algorithms/README.md create mode 100644 vanilla/node_modules/@csstools/css-parser-algorithms/dist/index.d.ts create mode 100644 vanilla/node_modules/@csstools/css-parser-algorithms/dist/index.mjs create mode 100644 vanilla/node_modules/@csstools/css-parser-algorithms/package.json create mode 100644 vanilla/node_modules/@csstools/css-syntax-patches-for-csstree/CHANGELOG.md create mode 100644 vanilla/node_modules/@csstools/css-syntax-patches-for-csstree/LICENSE.md create mode 100644 vanilla/node_modules/@csstools/css-syntax-patches-for-csstree/README.md create mode 100644 vanilla/node_modules/@csstools/css-syntax-patches-for-csstree/dist/index.d.ts create mode 100644 vanilla/node_modules/@csstools/css-syntax-patches-for-csstree/dist/index.json create mode 100644 vanilla/node_modules/@csstools/css-syntax-patches-for-csstree/package.json create mode 100644 vanilla/node_modules/@csstools/css-tokenizer/CHANGELOG.md create mode 100644 vanilla/node_modules/@csstools/css-tokenizer/LICENSE.md create mode 100644 vanilla/node_modules/@csstools/css-tokenizer/README.md create mode 100644 vanilla/node_modules/@csstools/css-tokenizer/dist/index.d.ts create mode 100644 vanilla/node_modules/@csstools/css-tokenizer/dist/index.mjs create mode 100644 vanilla/node_modules/@csstools/css-tokenizer/package.json create mode 100644 vanilla/node_modules/@esbuild/linux-arm64/README.md create mode 100755 vanilla/node_modules/@esbuild/linux-arm64/bin/esbuild create mode 100644 vanilla/node_modules/@esbuild/linux-arm64/package.json create mode 100644 vanilla/node_modules/@exodus/bytes/LICENSE create mode 100644 vanilla/node_modules/@exodus/bytes/README.md create mode 100644 vanilla/node_modules/@exodus/bytes/array.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/array.js create mode 100644 vanilla/node_modules/@exodus/bytes/assert.js create mode 100644 vanilla/node_modules/@exodus/bytes/base32.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/base32.js create mode 100644 vanilla/node_modules/@exodus/bytes/base58.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/base58.js create mode 100644 vanilla/node_modules/@exodus/bytes/base58check.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/base58check.js create mode 100644 vanilla/node_modules/@exodus/bytes/base58check.node.js create mode 100644 vanilla/node_modules/@exodus/bytes/base64.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/base64.js create mode 100644 vanilla/node_modules/@exodus/bytes/bech32.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/bech32.js create mode 100644 vanilla/node_modules/@exodus/bytes/bigint.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/bigint.js create mode 100644 vanilla/node_modules/@exodus/bytes/encoding-browser.browser.js create mode 100644 vanilla/node_modules/@exodus/bytes/encoding-browser.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/encoding-browser.js create mode 100644 vanilla/node_modules/@exodus/bytes/encoding-browser.native.js create mode 100644 vanilla/node_modules/@exodus/bytes/encoding-lite.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/encoding-lite.js create mode 100644 vanilla/node_modules/@exodus/bytes/encoding.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/encoding.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/_utils.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/base32.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/base58check.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/base64.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/encoding.api.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/encoding.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/encoding.labels.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/encoding.util.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/hex.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/latin1.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/multi-byte.encodings.cjs create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/multi-byte.encodings.json create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/multi-byte.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/multi-byte.table.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/percent.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/platform.browser.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/platform.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/platform.native.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/single-byte.encodings.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/single-byte.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/utf16.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/utf8.auto.browser.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/utf8.auto.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/utf8.auto.native.js create mode 100644 vanilla/node_modules/@exodus/bytes/fallback/utf8.js create mode 100644 vanilla/node_modules/@exodus/bytes/hex.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/hex.js create mode 100644 vanilla/node_modules/@exodus/bytes/hex.node.js create mode 100644 vanilla/node_modules/@exodus/bytes/index.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/index.js create mode 100644 vanilla/node_modules/@exodus/bytes/multi-byte.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/multi-byte.js create mode 100644 vanilla/node_modules/@exodus/bytes/multi-byte.node.js create mode 100644 vanilla/node_modules/@exodus/bytes/package.json create mode 100644 vanilla/node_modules/@exodus/bytes/single-byte.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/single-byte.js create mode 100644 vanilla/node_modules/@exodus/bytes/single-byte.node.js create mode 100644 vanilla/node_modules/@exodus/bytes/utf16.browser.js create mode 100644 vanilla/node_modules/@exodus/bytes/utf16.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/utf16.js create mode 100644 vanilla/node_modules/@exodus/bytes/utf16.native.js create mode 100644 vanilla/node_modules/@exodus/bytes/utf16.node.js create mode 100644 vanilla/node_modules/@exodus/bytes/utf8.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/utf8.js create mode 100644 vanilla/node_modules/@exodus/bytes/utf8.node.js create mode 100644 vanilla/node_modules/@exodus/bytes/whatwg.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/whatwg.js create mode 100644 vanilla/node_modules/@exodus/bytes/wif.d.ts create mode 100644 vanilla/node_modules/@exodus/bytes/wif.js create mode 100644 vanilla/node_modules/@jridgewell/resolve-uri/LICENSE create mode 100644 vanilla/node_modules/@jridgewell/resolve-uri/README.md create mode 100644 vanilla/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs create mode 100644 vanilla/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map create mode 100644 vanilla/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js create mode 100644 vanilla/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map create mode 100644 vanilla/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts create mode 100644 vanilla/node_modules/@jridgewell/resolve-uri/package.json create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/LICENSE create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/README.md create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/package.json create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/src/strings.ts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts create mode 100644 vanilla/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/LICENSE create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/README.md create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/package.json create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/src/binary-search.ts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/src/by-source.ts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/src/resolve.ts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/src/sort.ts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/src/types.ts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/sort.d.cts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/sort.d.mts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/types.d.cts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/types.d.mts create mode 100644 vanilla/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map create mode 100644 vanilla/node_modules/@rollup/rollup-linux-arm64-gnu/README.md create mode 100644 vanilla/node_modules/@rollup/rollup-linux-arm64-gnu/package.json create mode 100644 vanilla/node_modules/@rollup/rollup-linux-arm64-gnu/rollup.linux-arm64-gnu.node create mode 100644 vanilla/node_modules/@rollup/rollup-linux-arm64-musl/README.md create mode 100644 vanilla/node_modules/@rollup/rollup-linux-arm64-musl/package.json create mode 100644 vanilla/node_modules/@rollup/rollup-linux-arm64-musl/rollup.linux-arm64-musl.node create mode 100644 vanilla/node_modules/@standard-schema/spec/LICENSE create mode 100644 vanilla/node_modules/@standard-schema/spec/README.md create mode 100644 vanilla/node_modules/@standard-schema/spec/dist/index.cjs create mode 100644 vanilla/node_modules/@standard-schema/spec/dist/index.d.cts create mode 100644 vanilla/node_modules/@standard-schema/spec/dist/index.d.ts create mode 100644 vanilla/node_modules/@standard-schema/spec/dist/index.js create mode 100644 vanilla/node_modules/@standard-schema/spec/package.json create mode 100644 vanilla/node_modules/@types/chai/LICENSE create mode 100644 vanilla/node_modules/@types/chai/README.md create mode 100644 vanilla/node_modules/@types/chai/index.d.ts create mode 100644 vanilla/node_modules/@types/chai/package.json create mode 100644 vanilla/node_modules/@types/chai/register-should.d.ts create mode 100644 vanilla/node_modules/@types/deep-eql/LICENSE create mode 100644 vanilla/node_modules/@types/deep-eql/README.md create mode 100644 vanilla/node_modules/@types/deep-eql/index.d.ts create mode 100644 vanilla/node_modules/@types/deep-eql/package.json create mode 100644 vanilla/node_modules/@types/estree/LICENSE create mode 100644 vanilla/node_modules/@types/estree/README.md create mode 100644 vanilla/node_modules/@types/estree/flow.d.ts create mode 100644 vanilla/node_modules/@types/estree/index.d.ts create mode 100644 vanilla/node_modules/@types/estree/package.json create mode 100644 vanilla/node_modules/@vitest/coverage-v8/LICENSE create mode 100644 vanilla/node_modules/@vitest/coverage-v8/dist/browser.d.ts create mode 100644 vanilla/node_modules/@vitest/coverage-v8/dist/browser.js create mode 100644 vanilla/node_modules/@vitest/coverage-v8/dist/index.d.ts create mode 100644 vanilla/node_modules/@vitest/coverage-v8/dist/index.js create mode 100644 vanilla/node_modules/@vitest/coverage-v8/dist/load-provider-CdgAx3rL.js create mode 100644 vanilla/node_modules/@vitest/coverage-v8/dist/pathe.M-eThtNZ-BTaAGrLg.js create mode 100644 vanilla/node_modules/@vitest/coverage-v8/dist/provider.d.ts create mode 100644 vanilla/node_modules/@vitest/coverage-v8/dist/provider.js create mode 100644 vanilla/node_modules/@vitest/coverage-v8/package.json create mode 100644 vanilla/node_modules/@vitest/expect/LICENSE create mode 100644 vanilla/node_modules/@vitest/expect/README.md create mode 100644 vanilla/node_modules/@vitest/expect/dist/index.d.ts create mode 100644 vanilla/node_modules/@vitest/expect/dist/index.js create mode 100644 vanilla/node_modules/@vitest/expect/package.json create mode 100644 vanilla/node_modules/@vitest/mocker/LICENSE create mode 100644 vanilla/node_modules/@vitest/mocker/README.md create mode 100644 vanilla/node_modules/@vitest/mocker/dist/auto-register.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/dist/auto-register.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/automock.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/dist/automock.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/browser.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/dist/browser.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/chunk-automock.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/chunk-mocker.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/chunk-registry.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/chunk-utils.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/dist/index.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/dist/index.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/dist/node.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/dist/node.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/redirect.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/dist/redirect.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/register.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/dist/register.js create mode 100644 vanilla/node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts create mode 100644 vanilla/node_modules/@vitest/mocker/package.json create mode 100644 vanilla/node_modules/@vitest/pretty-format/LICENSE create mode 100644 vanilla/node_modules/@vitest/pretty-format/dist/index.d.ts create mode 100644 vanilla/node_modules/@vitest/pretty-format/dist/index.js create mode 100644 vanilla/node_modules/@vitest/pretty-format/package.json create mode 100644 vanilla/node_modules/@vitest/runner/LICENSE create mode 100644 vanilla/node_modules/@vitest/runner/README.md create mode 100644 vanilla/node_modules/@vitest/runner/dist/chunk-tasks.js create mode 100644 vanilla/node_modules/@vitest/runner/dist/index.d.ts create mode 100644 vanilla/node_modules/@vitest/runner/dist/index.js create mode 100644 vanilla/node_modules/@vitest/runner/dist/tasks.d-C7UxawJ9.d.ts create mode 100644 vanilla/node_modules/@vitest/runner/dist/types.d.ts create mode 100644 vanilla/node_modules/@vitest/runner/dist/types.js create mode 100644 vanilla/node_modules/@vitest/runner/dist/utils.d.ts create mode 100644 vanilla/node_modules/@vitest/runner/dist/utils.js create mode 100644 vanilla/node_modules/@vitest/runner/package.json create mode 100644 vanilla/node_modules/@vitest/runner/types.d.ts create mode 100644 vanilla/node_modules/@vitest/runner/utils.d.ts create mode 100644 vanilla/node_modules/@vitest/snapshot/LICENSE create mode 100644 vanilla/node_modules/@vitest/snapshot/README.md create mode 100644 vanilla/node_modules/@vitest/snapshot/dist/environment.d-DHdQ1Csl.d.ts create mode 100644 vanilla/node_modules/@vitest/snapshot/dist/environment.d.ts create mode 100644 vanilla/node_modules/@vitest/snapshot/dist/environment.js create mode 100644 vanilla/node_modules/@vitest/snapshot/dist/index.d.ts create mode 100644 vanilla/node_modules/@vitest/snapshot/dist/index.js create mode 100644 vanilla/node_modules/@vitest/snapshot/dist/manager.d.ts create mode 100644 vanilla/node_modules/@vitest/snapshot/dist/manager.js create mode 100644 vanilla/node_modules/@vitest/snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts create mode 100644 vanilla/node_modules/@vitest/snapshot/environment.d.ts create mode 100644 vanilla/node_modules/@vitest/snapshot/manager.d.ts create mode 100644 vanilla/node_modules/@vitest/snapshot/package.json create mode 100644 vanilla/node_modules/@vitest/spy/LICENSE create mode 100644 vanilla/node_modules/@vitest/spy/README.md create mode 100644 vanilla/node_modules/@vitest/spy/dist/index.d.ts create mode 100644 vanilla/node_modules/@vitest/spy/dist/index.js create mode 100644 vanilla/node_modules/@vitest/spy/package.json create mode 100644 vanilla/node_modules/@vitest/utils/LICENSE create mode 100644 vanilla/node_modules/@vitest/utils/diff.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/constants.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/constants.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/diff.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/diff.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/display.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/display.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/error.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/error.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/helpers.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/helpers.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/highlight.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/highlight.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/index.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/index.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/offset.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/offset.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/resolver.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/resolver.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/serialize.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/serialize.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/source-map.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/source-map.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/timers.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/timers.js create mode 100644 vanilla/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/types.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/dist/types.js create mode 100644 vanilla/node_modules/@vitest/utils/error.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/helpers.d.ts create mode 100644 vanilla/node_modules/@vitest/utils/package.json create mode 100644 vanilla/node_modules/agent-base/LICENSE create mode 100644 vanilla/node_modules/agent-base/README.md create mode 100644 vanilla/node_modules/agent-base/dist/helpers.d.ts create mode 100644 vanilla/node_modules/agent-base/dist/helpers.d.ts.map create mode 100644 vanilla/node_modules/agent-base/dist/helpers.js create mode 100644 vanilla/node_modules/agent-base/dist/helpers.js.map create mode 100644 vanilla/node_modules/agent-base/dist/index.d.ts create mode 100644 vanilla/node_modules/agent-base/dist/index.d.ts.map create mode 100644 vanilla/node_modules/agent-base/dist/index.js create mode 100644 vanilla/node_modules/agent-base/dist/index.js.map create mode 100644 vanilla/node_modules/agent-base/package.json create mode 100644 vanilla/node_modules/assertion-error/LICENSE create mode 100644 vanilla/node_modules/assertion-error/README.md create mode 100644 vanilla/node_modules/assertion-error/index.d.ts create mode 100644 vanilla/node_modules/assertion-error/index.js create mode 100644 vanilla/node_modules/assertion-error/package.json create mode 100644 vanilla/node_modules/ast-v8-to-istanbul/LICENSE create mode 100644 vanilla/node_modules/ast-v8-to-istanbul/README.md create mode 100644 vanilla/node_modules/ast-v8-to-istanbul/dist/index.d.mts create mode 100644 vanilla/node_modules/ast-v8-to-istanbul/dist/index.mjs create mode 100644 vanilla/node_modules/ast-v8-to-istanbul/package.json create mode 100644 vanilla/node_modules/bidi-js/LICENSE.txt create mode 100644 vanilla/node_modules/bidi-js/README.md create mode 100644 vanilla/node_modules/bidi-js/dist/bidi.js create mode 100644 vanilla/node_modules/bidi-js/dist/bidi.min.js create mode 100644 vanilla/node_modules/bidi-js/dist/bidi.min.mjs create mode 100644 vanilla/node_modules/bidi-js/dist/bidi.mjs create mode 100644 vanilla/node_modules/bidi-js/package.json create mode 100644 vanilla/node_modules/bidi-js/src/brackets.js create mode 100644 vanilla/node_modules/bidi-js/src/charTypes.js create mode 100644 vanilla/node_modules/bidi-js/src/data/bidiBrackets.data.js create mode 100644 vanilla/node_modules/bidi-js/src/data/bidiCharTypes.data.js create mode 100644 vanilla/node_modules/bidi-js/src/data/bidiMirroring.data.js create mode 100644 vanilla/node_modules/bidi-js/src/embeddingLevels.js create mode 100644 vanilla/node_modules/bidi-js/src/index.js create mode 100644 vanilla/node_modules/bidi-js/src/mirroring.js create mode 100644 vanilla/node_modules/bidi-js/src/reordering.js create mode 100644 vanilla/node_modules/bidi-js/src/util/parseCharacterMap.js create mode 100644 vanilla/node_modules/chai/LICENSE create mode 100644 vanilla/node_modules/chai/README.md create mode 100644 vanilla/node_modules/chai/index.js create mode 100644 vanilla/node_modules/chai/package.json create mode 100644 vanilla/node_modules/chai/register-assert.js create mode 100644 vanilla/node_modules/chai/register-expect.js create mode 100644 vanilla/node_modules/chai/register-should.js create mode 100644 vanilla/node_modules/css-tree/LICENSE create mode 100644 vanilla/node_modules/css-tree/README.md create mode 100644 vanilla/node_modules/css-tree/cjs/convertor/create.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/convertor/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/data-patch.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/data.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/definition-syntax/SyntaxError.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/definition-syntax/generate.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/definition-syntax/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/definition-syntax/parse.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/definition-syntax/scanner.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/definition-syntax/tokenizer.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/definition-syntax/walk.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/generator/create.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/generator/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/generator/sourceMap.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/generator/token-before.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/Lexer.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/error.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/generic-an-plus-b.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/generic-const.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/generic-urange.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/generic.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/match-graph.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/match.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/prepare-tokens.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/search.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/structure.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/trace.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/lexer/units.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/parser/SyntaxError.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/parser/create.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/parser/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/parser/parse-selector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/parser/sequence.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/container.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/font-face.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/import.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/layer.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/media.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/nest.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/page.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/scope.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/starting-style.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/atrule/supports.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/config/generator.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/config/lexer.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/config/mix.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/config/parser-selector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/config/parser.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/config/walker.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/create.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/function/expression.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/function/var.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/AnPlusB.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Atrule.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/AtrulePrelude.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/AttributeSelector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Block.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Brackets.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/CDC.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/CDO.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/ClassSelector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Combinator.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Comment.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Condition.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Declaration.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/DeclarationList.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Dimension.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Feature.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/FeatureFunction.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/FeatureRange.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Function.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/GeneralEnclosed.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Hash.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/IdSelector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Identifier.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Layer.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/LayerList.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/LayerName.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/LayerNameList.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/MediaCondition.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/MediaFeature.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/MediaFeatureRange.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/MediaQuery.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/MediaQueryList.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/NestingSelector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Nth.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Number.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Operator.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Parentheses.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Percentage.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/PseudoClassSelector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/PseudoElementSelector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Ratio.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Raw.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Rule.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Scope.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Selector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/SelectorList.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/String.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/StyleSheet.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/SupportsDeclaration.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/SupportsFeature.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/TypeSelector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/UnicodeRange.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Url.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/Value.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/WhiteSpace.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/common/feature-range.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/common/feature.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/index-generate.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/index-parse-selector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/index-parse.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/node/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/pseudo/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/pseudo/lang.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/scope/atrulePrelude.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/scope/default.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/scope/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/scope/selector.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/syntax/scope/value.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/tokenizer/OffsetToLocation.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/tokenizer/TokenStream.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/tokenizer/adopt-buffer.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/tokenizer/char-code-definitions.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/tokenizer/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/tokenizer/names.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/tokenizer/types.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/tokenizer/utils.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/utils/List.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/utils/clone.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/utils/create-custom-error.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/utils/ident.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/utils/index.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/utils/names.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/utils/string.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/utils/url.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/version.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/walker/create.cjs create mode 100644 vanilla/node_modules/css-tree/cjs/walker/index.cjs create mode 100644 vanilla/node_modules/css-tree/data/patch.json create mode 100644 vanilla/node_modules/css-tree/dist/csstree.esm.js create mode 100644 vanilla/node_modules/css-tree/dist/csstree.js create mode 100644 vanilla/node_modules/css-tree/dist/data.cjs create mode 100644 vanilla/node_modules/css-tree/dist/data.js create mode 100644 vanilla/node_modules/css-tree/dist/version.cjs create mode 100644 vanilla/node_modules/css-tree/dist/version.js create mode 100644 vanilla/node_modules/css-tree/lib/convertor/create.js create mode 100644 vanilla/node_modules/css-tree/lib/convertor/index.js create mode 100644 vanilla/node_modules/css-tree/lib/data-patch.js create mode 100755 vanilla/node_modules/css-tree/lib/data.js create mode 100644 vanilla/node_modules/css-tree/lib/definition-syntax/SyntaxError.js create mode 100644 vanilla/node_modules/css-tree/lib/definition-syntax/generate.js create mode 100644 vanilla/node_modules/css-tree/lib/definition-syntax/index.js create mode 100644 vanilla/node_modules/css-tree/lib/definition-syntax/parse.js create mode 100644 vanilla/node_modules/css-tree/lib/definition-syntax/scanner.js create mode 100644 vanilla/node_modules/css-tree/lib/definition-syntax/walk.js create mode 100644 vanilla/node_modules/css-tree/lib/generator/create.js create mode 100644 vanilla/node_modules/css-tree/lib/generator/index.js create mode 100644 vanilla/node_modules/css-tree/lib/generator/sourceMap.js create mode 100644 vanilla/node_modules/css-tree/lib/generator/token-before.js create mode 100644 vanilla/node_modules/css-tree/lib/index.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/Lexer.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/error.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/generic-an-plus-b.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/generic-const.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/generic-urange.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/generic.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/index.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/match-graph.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/match.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/prepare-tokens.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/search.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/structure.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/trace.js create mode 100644 vanilla/node_modules/css-tree/lib/lexer/units.js create mode 100644 vanilla/node_modules/css-tree/lib/parser/SyntaxError.js create mode 100644 vanilla/node_modules/css-tree/lib/parser/create.js create mode 100644 vanilla/node_modules/css-tree/lib/parser/index.js create mode 100644 vanilla/node_modules/css-tree/lib/parser/parse-selector.js create mode 100644 vanilla/node_modules/css-tree/lib/parser/sequence.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/container.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/font-face.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/import.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/index.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/layer.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/media.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/nest.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/page.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/scope.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/starting-style.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/atrule/supports.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/config/generator.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/config/lexer.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/config/mix.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/config/parser-selector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/config/parser.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/config/walker.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/create.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/function/expression.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/function/var.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/index.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/AnPlusB.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Atrule.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/AtrulePrelude.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/AttributeSelector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Block.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Brackets.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/CDC.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/CDO.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/ClassSelector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Combinator.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Comment.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Condition.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Declaration.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/DeclarationList.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Dimension.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Feature.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/FeatureFunction.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/FeatureRange.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Function.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/GeneralEnclosed.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Hash.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/IdSelector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Identifier.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Layer.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/LayerList.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/MediaQuery.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/MediaQueryList.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/NestingSelector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Nth.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Number.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Operator.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Parentheses.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Percentage.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/PseudoClassSelector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/PseudoElementSelector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Ratio.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Raw.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Rule.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Scope.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Selector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/SelectorList.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/String.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/StyleSheet.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/SupportsDeclaration.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/TypeSelector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/UnicodeRange.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Url.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/Value.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/WhiteSpace.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/index-generate.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/index-parse-selector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/index-parse.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/node/index.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/pseudo/index.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/pseudo/lang.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/scope/atrulePrelude.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/scope/default.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/scope/index.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/scope/selector.js create mode 100644 vanilla/node_modules/css-tree/lib/syntax/scope/value.js create mode 100644 vanilla/node_modules/css-tree/lib/tokenizer/OffsetToLocation.js create mode 100644 vanilla/node_modules/css-tree/lib/tokenizer/TokenStream.js create mode 100644 vanilla/node_modules/css-tree/lib/tokenizer/adopt-buffer.js create mode 100644 vanilla/node_modules/css-tree/lib/tokenizer/char-code-definitions.js create mode 100644 vanilla/node_modules/css-tree/lib/tokenizer/index.js create mode 100644 vanilla/node_modules/css-tree/lib/tokenizer/names.js create mode 100644 vanilla/node_modules/css-tree/lib/tokenizer/types.js create mode 100644 vanilla/node_modules/css-tree/lib/tokenizer/utils.js create mode 100644 vanilla/node_modules/css-tree/lib/utils/List.js create mode 100644 vanilla/node_modules/css-tree/lib/utils/clone.js create mode 100644 vanilla/node_modules/css-tree/lib/utils/create-custom-error.js create mode 100644 vanilla/node_modules/css-tree/lib/utils/ident.js create mode 100644 vanilla/node_modules/css-tree/lib/utils/index.js create mode 100644 vanilla/node_modules/css-tree/lib/utils/names.js create mode 100644 vanilla/node_modules/css-tree/lib/utils/string.js create mode 100644 vanilla/node_modules/css-tree/lib/utils/url.js create mode 100644 vanilla/node_modules/css-tree/lib/version.js create mode 100644 vanilla/node_modules/css-tree/lib/walker/create.js create mode 100644 vanilla/node_modules/css-tree/lib/walker/index.js create mode 100644 vanilla/node_modules/css-tree/package.json create mode 100644 vanilla/node_modules/cssstyle/LICENSE create mode 100644 vanilla/node_modules/cssstyle/README.md create mode 100644 vanilla/node_modules/cssstyle/lib/CSSStyleDeclaration.js create mode 100644 vanilla/node_modules/cssstyle/lib/generated/allProperties.js create mode 100644 vanilla/node_modules/cssstyle/lib/generated/implementedProperties.js create mode 100644 vanilla/node_modules/cssstyle/lib/generated/properties.js create mode 100644 vanilla/node_modules/cssstyle/lib/generated/propertyDefinitions.js create mode 100644 vanilla/node_modules/cssstyle/lib/normalize.js create mode 100644 vanilla/node_modules/cssstyle/lib/parsers.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/background.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/backgroundAttachment.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/backgroundClip.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/backgroundColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/backgroundImage.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/backgroundOrigin.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/backgroundPosition.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/backgroundRepeat.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/backgroundSize.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/border.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderBottom.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderBottomColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderBottomStyle.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderBottomWidth.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderCollapse.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderLeft.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderLeftColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderLeftStyle.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderLeftWidth.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderRight.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderRightColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderRightStyle.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderRightWidth.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderSpacing.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderStyle.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderTop.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderTopColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderTopStyle.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderTopWidth.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/borderWidth.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/bottom.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/clear.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/clip.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/color.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/display.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/flex.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/flexBasis.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/flexGrow.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/flexShrink.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/float.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/floodColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/font.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/fontFamily.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/fontSize.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/fontStyle.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/fontVariant.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/fontWeight.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/height.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/left.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/lightingColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/lineHeight.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/margin.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/marginBottom.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/marginLeft.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/marginRight.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/marginTop.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/opacity.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/outlineColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/padding.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/paddingBottom.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/paddingLeft.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/paddingRight.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/paddingTop.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/right.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/stopColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/top.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/webkitBorderAfterColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/webkitBorderBeforeColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/webkitBorderEndColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/webkitBorderStartColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/webkitColumnRuleColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/webkitTapHighlightColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/webkitTextEmphasisColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/webkitTextFillColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/webkitTextStrokeColor.js create mode 100644 vanilla/node_modules/cssstyle/lib/properties/width.js create mode 100644 vanilla/node_modules/cssstyle/lib/utils/allExtraProperties.js create mode 100644 vanilla/node_modules/cssstyle/lib/utils/camelize.js create mode 100644 vanilla/node_modules/cssstyle/lib/utils/propertyDescriptors.js create mode 100644 vanilla/node_modules/cssstyle/lib/utils/strings.js create mode 100644 vanilla/node_modules/cssstyle/package.json create mode 100644 vanilla/node_modules/data-urls/LICENSE.txt create mode 100644 vanilla/node_modules/data-urls/README.md create mode 100644 vanilla/node_modules/data-urls/lib/parser.js create mode 100644 vanilla/node_modules/data-urls/lib/utils.js create mode 100644 vanilla/node_modules/data-urls/package.json create mode 100644 vanilla/node_modules/debug/LICENSE create mode 100644 vanilla/node_modules/debug/README.md create mode 100644 vanilla/node_modules/debug/package.json create mode 100644 vanilla/node_modules/debug/src/browser.js create mode 100644 vanilla/node_modules/debug/src/common.js create mode 100644 vanilla/node_modules/debug/src/index.js create mode 100644 vanilla/node_modules/debug/src/node.js create mode 100644 vanilla/node_modules/decimal.js/LICENCE.md create mode 100644 vanilla/node_modules/decimal.js/README.md create mode 100644 vanilla/node_modules/decimal.js/decimal.d.ts create mode 100644 vanilla/node_modules/decimal.js/decimal.js create mode 100644 vanilla/node_modules/decimal.js/decimal.mjs create mode 100644 vanilla/node_modules/decimal.js/package.json create mode 100644 vanilla/node_modules/entities/LICENSE create mode 100644 vanilla/node_modules/entities/decode.d.ts create mode 100644 vanilla/node_modules/entities/decode.js create mode 100644 vanilla/node_modules/entities/dist/commonjs/decode-codepoint.d.ts create mode 100644 vanilla/node_modules/entities/dist/commonjs/decode-codepoint.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/decode-codepoint.js create mode 100644 vanilla/node_modules/entities/dist/commonjs/decode-codepoint.js.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/decode.d.ts create mode 100644 vanilla/node_modules/entities/dist/commonjs/decode.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/decode.js create mode 100644 vanilla/node_modules/entities/dist/commonjs/decode.js.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/encode.d.ts create mode 100644 vanilla/node_modules/entities/dist/commonjs/encode.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/encode.js create mode 100644 vanilla/node_modules/entities/dist/commonjs/encode.js.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/escape.d.ts create mode 100644 vanilla/node_modules/entities/dist/commonjs/escape.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/escape.js create mode 100644 vanilla/node_modules/entities/dist/commonjs/escape.js.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/decode-data-html.d.ts create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/decode-data-html.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/decode-data-html.js create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/decode-data-html.js.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/decode-data-xml.d.ts create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/decode-data-xml.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/decode-data-xml.js create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/decode-data-xml.js.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/encode-html.d.ts create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/encode-html.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/encode-html.js create mode 100644 vanilla/node_modules/entities/dist/commonjs/generated/encode-html.js.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/index.d.ts create mode 100644 vanilla/node_modules/entities/dist/commonjs/index.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/index.js create mode 100644 vanilla/node_modules/entities/dist/commonjs/index.js.map create mode 100644 vanilla/node_modules/entities/dist/commonjs/package.json create mode 100644 vanilla/node_modules/entities/dist/esm/decode-codepoint.d.ts create mode 100644 vanilla/node_modules/entities/dist/esm/decode-codepoint.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/esm/decode-codepoint.js create mode 100644 vanilla/node_modules/entities/dist/esm/decode-codepoint.js.map create mode 100644 vanilla/node_modules/entities/dist/esm/decode.d.ts create mode 100644 vanilla/node_modules/entities/dist/esm/decode.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/esm/decode.js create mode 100644 vanilla/node_modules/entities/dist/esm/decode.js.map create mode 100644 vanilla/node_modules/entities/dist/esm/encode.d.ts create mode 100644 vanilla/node_modules/entities/dist/esm/encode.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/esm/encode.js create mode 100644 vanilla/node_modules/entities/dist/esm/encode.js.map create mode 100644 vanilla/node_modules/entities/dist/esm/escape.d.ts create mode 100644 vanilla/node_modules/entities/dist/esm/escape.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/esm/escape.js create mode 100644 vanilla/node_modules/entities/dist/esm/escape.js.map create mode 100644 vanilla/node_modules/entities/dist/esm/generated/decode-data-html.d.ts create mode 100644 vanilla/node_modules/entities/dist/esm/generated/decode-data-html.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/esm/generated/decode-data-html.js create mode 100644 vanilla/node_modules/entities/dist/esm/generated/decode-data-html.js.map create mode 100644 vanilla/node_modules/entities/dist/esm/generated/decode-data-xml.d.ts create mode 100644 vanilla/node_modules/entities/dist/esm/generated/decode-data-xml.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/esm/generated/decode-data-xml.js create mode 100644 vanilla/node_modules/entities/dist/esm/generated/decode-data-xml.js.map create mode 100644 vanilla/node_modules/entities/dist/esm/generated/encode-html.d.ts create mode 100644 vanilla/node_modules/entities/dist/esm/generated/encode-html.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/esm/generated/encode-html.js create mode 100644 vanilla/node_modules/entities/dist/esm/generated/encode-html.js.map create mode 100644 vanilla/node_modules/entities/dist/esm/index.d.ts create mode 100644 vanilla/node_modules/entities/dist/esm/index.d.ts.map create mode 100644 vanilla/node_modules/entities/dist/esm/index.js create mode 100644 vanilla/node_modules/entities/dist/esm/index.js.map create mode 100644 vanilla/node_modules/entities/dist/esm/package.json create mode 100644 vanilla/node_modules/entities/escape.d.ts create mode 100644 vanilla/node_modules/entities/escape.js create mode 100644 vanilla/node_modules/entities/package.json create mode 100644 vanilla/node_modules/entities/readme.md create mode 100644 vanilla/node_modules/entities/src/decode-codepoint.ts create mode 100644 vanilla/node_modules/entities/src/decode.spec.ts create mode 100644 vanilla/node_modules/entities/src/decode.ts create mode 100644 vanilla/node_modules/entities/src/encode.spec.ts create mode 100644 vanilla/node_modules/entities/src/encode.ts create mode 100644 vanilla/node_modules/entities/src/escape.spec.ts create mode 100644 vanilla/node_modules/entities/src/escape.ts create mode 100644 vanilla/node_modules/entities/src/generated/.eslintrc.json create mode 100644 vanilla/node_modules/entities/src/generated/decode-data-html.ts create mode 100644 vanilla/node_modules/entities/src/generated/decode-data-xml.ts create mode 100644 vanilla/node_modules/entities/src/generated/encode-html.ts create mode 100644 vanilla/node_modules/entities/src/index.spec.ts create mode 100644 vanilla/node_modules/entities/src/index.ts create mode 100644 vanilla/node_modules/es-module-lexer/LICENSE create mode 100644 vanilla/node_modules/es-module-lexer/README.md create mode 100644 vanilla/node_modules/es-module-lexer/dist/lexer.asm.js create mode 100644 vanilla/node_modules/es-module-lexer/dist/lexer.cjs create mode 100644 vanilla/node_modules/es-module-lexer/dist/lexer.js create mode 100644 vanilla/node_modules/es-module-lexer/lexer.js create mode 100644 vanilla/node_modules/es-module-lexer/package.json create mode 100644 vanilla/node_modules/es-module-lexer/types/lexer.d.ts create mode 100644 vanilla/node_modules/esbuild/LICENSE.md create mode 100644 vanilla/node_modules/esbuild/README.md create mode 100755 vanilla/node_modules/esbuild/bin/esbuild create mode 100644 vanilla/node_modules/esbuild/install.js create mode 100644 vanilla/node_modules/esbuild/lib/main.d.ts create mode 100644 vanilla/node_modules/esbuild/lib/main.js create mode 100644 vanilla/node_modules/esbuild/package.json create mode 100644 vanilla/node_modules/estree-walker/LICENSE create mode 100644 vanilla/node_modules/estree-walker/README.md create mode 100644 vanilla/node_modules/estree-walker/package.json create mode 100644 vanilla/node_modules/estree-walker/src/async.js create mode 100644 vanilla/node_modules/estree-walker/src/index.js create mode 100644 vanilla/node_modules/estree-walker/src/sync.js create mode 100644 vanilla/node_modules/estree-walker/src/walker.js create mode 100644 vanilla/node_modules/estree-walker/types/async.d.ts create mode 100644 vanilla/node_modules/estree-walker/types/index.d.ts create mode 100644 vanilla/node_modules/estree-walker/types/sync.d.ts create mode 100644 vanilla/node_modules/estree-walker/types/walker.d.ts create mode 100644 vanilla/node_modules/expect-type/LICENSE create mode 100644 vanilla/node_modules/expect-type/README.md create mode 100644 vanilla/node_modules/expect-type/SECURITY.md create mode 100644 vanilla/node_modules/expect-type/dist/branding.d.ts create mode 100644 vanilla/node_modules/expect-type/dist/branding.js create mode 100644 vanilla/node_modules/expect-type/dist/index.d.ts create mode 100644 vanilla/node_modules/expect-type/dist/index.js create mode 100644 vanilla/node_modules/expect-type/dist/messages.d.ts create mode 100644 vanilla/node_modules/expect-type/dist/messages.js create mode 100644 vanilla/node_modules/expect-type/dist/overloads.d.ts create mode 100644 vanilla/node_modules/expect-type/dist/overloads.js create mode 100644 vanilla/node_modules/expect-type/dist/utils.d.ts create mode 100644 vanilla/node_modules/expect-type/dist/utils.js create mode 100644 vanilla/node_modules/expect-type/package.json create mode 100644 vanilla/node_modules/fdir/LICENSE create mode 100644 vanilla/node_modules/fdir/README.md create mode 100644 vanilla/node_modules/fdir/dist/index.cjs create mode 100644 vanilla/node_modules/fdir/dist/index.d.cts create mode 100644 vanilla/node_modules/fdir/dist/index.d.mts create mode 100644 vanilla/node_modules/fdir/dist/index.mjs create mode 100644 vanilla/node_modules/fdir/package.json create mode 100644 vanilla/node_modules/has-flag/index.d.ts create mode 100644 vanilla/node_modules/has-flag/index.js create mode 100644 vanilla/node_modules/has-flag/license create mode 100644 vanilla/node_modules/has-flag/package.json create mode 100644 vanilla/node_modules/has-flag/readme.md create mode 100644 vanilla/node_modules/html-encoding-sniffer/LICENSE.txt create mode 100644 vanilla/node_modules/html-encoding-sniffer/README.md create mode 100644 vanilla/node_modules/html-encoding-sniffer/lib/html-encoding-sniffer.js create mode 100644 vanilla/node_modules/html-encoding-sniffer/package.json create mode 100644 vanilla/node_modules/html-escaper/LICENSE.txt create mode 100644 vanilla/node_modules/html-escaper/README.md create mode 100644 vanilla/node_modules/html-escaper/cjs/index.js create mode 100644 vanilla/node_modules/html-escaper/cjs/package.json create mode 100644 vanilla/node_modules/html-escaper/esm/index.js create mode 100644 vanilla/node_modules/html-escaper/index.js create mode 100644 vanilla/node_modules/html-escaper/min.js create mode 100644 vanilla/node_modules/html-escaper/package.json create mode 100644 vanilla/node_modules/html-escaper/test/index.js create mode 100644 vanilla/node_modules/html-escaper/test/package.json create mode 100644 vanilla/node_modules/http-proxy-agent/LICENSE create mode 100644 vanilla/node_modules/http-proxy-agent/README.md create mode 100644 vanilla/node_modules/http-proxy-agent/dist/index.d.ts create mode 100644 vanilla/node_modules/http-proxy-agent/dist/index.d.ts.map create mode 100644 vanilla/node_modules/http-proxy-agent/dist/index.js create mode 100644 vanilla/node_modules/http-proxy-agent/dist/index.js.map create mode 100644 vanilla/node_modules/http-proxy-agent/package.json create mode 100644 vanilla/node_modules/https-proxy-agent/LICENSE create mode 100644 vanilla/node_modules/https-proxy-agent/README.md create mode 100644 vanilla/node_modules/https-proxy-agent/dist/index.d.ts create mode 100644 vanilla/node_modules/https-proxy-agent/dist/index.d.ts.map create mode 100644 vanilla/node_modules/https-proxy-agent/dist/index.js create mode 100644 vanilla/node_modules/https-proxy-agent/dist/index.js.map create mode 100644 vanilla/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts create mode 100644 vanilla/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts.map create mode 100644 vanilla/node_modules/https-proxy-agent/dist/parse-proxy-response.js create mode 100644 vanilla/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map create mode 100644 vanilla/node_modules/https-proxy-agent/package.json create mode 100644 vanilla/node_modules/is-potential-custom-element-name/LICENSE-MIT.txt create mode 100644 vanilla/node_modules/is-potential-custom-element-name/README.md create mode 100755 vanilla/node_modules/is-potential-custom-element-name/index.js create mode 100644 vanilla/node_modules/is-potential-custom-element-name/package.json create mode 100644 vanilla/node_modules/istanbul-lib-coverage/CHANGELOG.md create mode 100644 vanilla/node_modules/istanbul-lib-coverage/LICENSE create mode 100644 vanilla/node_modules/istanbul-lib-coverage/README.md create mode 100644 vanilla/node_modules/istanbul-lib-coverage/index.js create mode 100644 vanilla/node_modules/istanbul-lib-coverage/lib/coverage-map.js create mode 100644 vanilla/node_modules/istanbul-lib-coverage/lib/coverage-summary.js create mode 100644 vanilla/node_modules/istanbul-lib-coverage/lib/data-properties.js create mode 100644 vanilla/node_modules/istanbul-lib-coverage/lib/file-coverage.js create mode 100644 vanilla/node_modules/istanbul-lib-coverage/lib/percent.js create mode 100644 vanilla/node_modules/istanbul-lib-coverage/package.json create mode 100644 vanilla/node_modules/istanbul-lib-report/CHANGELOG.md create mode 100644 vanilla/node_modules/istanbul-lib-report/LICENSE create mode 100644 vanilla/node_modules/istanbul-lib-report/README.md create mode 100644 vanilla/node_modules/istanbul-lib-report/index.js create mode 100644 vanilla/node_modules/istanbul-lib-report/lib/context.js create mode 100644 vanilla/node_modules/istanbul-lib-report/lib/file-writer.js create mode 100644 vanilla/node_modules/istanbul-lib-report/lib/path.js create mode 100644 vanilla/node_modules/istanbul-lib-report/lib/report-base.js create mode 100644 vanilla/node_modules/istanbul-lib-report/lib/summarizer-factory.js create mode 100644 vanilla/node_modules/istanbul-lib-report/lib/tree.js create mode 100644 vanilla/node_modules/istanbul-lib-report/lib/watermarks.js create mode 100644 vanilla/node_modules/istanbul-lib-report/lib/xml-writer.js create mode 100644 vanilla/node_modules/istanbul-lib-report/package.json create mode 100644 vanilla/node_modules/istanbul-reports/CHANGELOG.md create mode 100644 vanilla/node_modules/istanbul-reports/LICENSE create mode 100644 vanilla/node_modules/istanbul-reports/README.md create mode 100644 vanilla/node_modules/istanbul-reports/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/clover/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/cobertura/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/.babelrc create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/assets/bundle.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/assets/sort-arrow-sprite.png create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/assets/spa.css create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/src/fileBreadcrumbs.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/src/filterToggle.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/src/flattenToggle.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/src/getChildData.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/src/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/src/routing.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/src/summaryHeader.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/src/summaryTableHeader.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/src/summaryTableLine.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html-spa/webpack.config.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/annotator.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/assets/base.css create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/assets/block-navigation.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/assets/favicon.png create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/assets/sort-arrow-sprite.png create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/assets/sorter.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/assets/vendor/prettify.css create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/assets/vendor/prettify.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/html/insertion-text.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/json-summary/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/json/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/lcov/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/lcovonly/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/none/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/teamcity/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/text-lcov/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/text-summary/index.js create mode 100644 vanilla/node_modules/istanbul-reports/lib/text/index.js create mode 100644 vanilla/node_modules/istanbul-reports/package.json create mode 100644 vanilla/node_modules/js-tokens/LICENSE create mode 100644 vanilla/node_modules/js-tokens/README.md create mode 100644 vanilla/node_modules/js-tokens/index.d.ts create mode 100644 vanilla/node_modules/js-tokens/index.js create mode 100644 vanilla/node_modules/js-tokens/package.json create mode 100644 vanilla/node_modules/jsdom/LICENSE.txt create mode 100644 vanilla/node_modules/jsdom/README.md create mode 100644 vanilla/node_modules/jsdom/lib/api.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/Window.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/default-stylesheet.css create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/js-globals.json create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/not-implemented.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/parser/html.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/parser/index.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/parser/xml.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/resources/async-resource-queue.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/resources/decompress-interceptor.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/resources/jsdom-dispatcher.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/resources/per-document-resource-loader.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/resources/request-interceptor.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/resources/request-manager.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/resources/resource-queue.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/browser/resources/stream-handler.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/level2/style.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/level3/xpath.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/aborting/AbortController-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/aborting/AbortSignal-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/attributes.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/attributes/Attr-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/attributes/NamedNodeMap-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/constraint-validation/DefaultConstraintValidation-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/constraint-validation/ValidityState-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/crypto/Crypto-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/cssom/StyleSheetList-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/custom-elements/CustomElementRegistry-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/custom-elements/ElementInternals-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/deviceorientation/DeviceMotionEventAcceleration-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/deviceorientation/DeviceMotionEventRotationRate-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/documents.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/domparsing/DOMParser-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/domparsing/InnerHTML-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/domparsing/XMLSerializer-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/domparsing/parse5-adapter-serialization.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/domparsing/serialization.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/encoding/TextDecoder-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/encoding/TextEncoder-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/BeforeUnloadEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/BlobEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/CloseEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/CompositionEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/CustomEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/DeviceMotionEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/DeviceOrientationEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/ErrorEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/Event-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/EventModifierMixin-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/FocusEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/HashChangeEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/InputEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/KeyboardEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/MessageEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/MouseEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/PageTransitionEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/PointerEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/PopStateEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/ProgressEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/PromiseRejectionEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/StorageEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/SubmitEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/TouchEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/TransitionEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/UIEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/events/WheelEvent-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/fetch/Headers-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/fetch/header-list.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/fetch/header-types.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/fetch/header-utils.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/file-api/Blob-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/file-api/File-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/file-api/FileList-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/file-api/FileReader-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/AbortController.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/AbortSignal.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/AbstractRange.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/AddEventListenerOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/AssignedNodesOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Attr.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/BarProp.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/BeforeUnloadEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/BinaryType.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Blob.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/BlobCallback.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/BlobEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/BlobEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/BlobPropertyBag.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CDATASection.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CanPlayTypeResult.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CharacterData.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CloseEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CloseEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Comment.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CompositionEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CompositionEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Crypto.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CustomElementConstructor.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CustomElementRegistry.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CustomEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/CustomEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DOMException.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DOMImplementation.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DOMParser.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DOMRect.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DOMRectInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DOMRectReadOnly.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DOMStringMap.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DOMTokenList.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DeviceMotionEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DeviceMotionEventAcceleration.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DeviceMotionEventAccelerationInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DeviceMotionEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DeviceMotionEventRotationRate.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DeviceMotionEventRotationRateInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DeviceOrientationEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DeviceOrientationEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Document.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DocumentFragment.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DocumentReadyState.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/DocumentType.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Element.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ElementCreationOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ElementDefinitionOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ElementInternals.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/EndingType.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ErrorEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ErrorEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Event.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/EventHandlerNonNull.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/EventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/EventListener.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/EventListenerOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/EventModifierInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/External.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/File.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/FileList.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/FilePropertyBag.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/FileReader.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/FocusEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/FocusEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/FormData.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Function.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/GetRootNodeOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLAnchorElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLAreaElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLAudioElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLBRElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLBaseElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLBodyElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLButtonElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLCanvasElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLCollection.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLDListElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLDataElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLDataListElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLDetailsElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLDialogElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLDirectoryElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLDivElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLEmbedElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLFieldSetElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLFontElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLFormControlsCollection.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLFormElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLFrameElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLFrameSetElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLHRElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLHeadElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLHeadingElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLHtmlElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLIFrameElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLImageElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLInputElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLLIElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLLabelElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLLegendElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLLinkElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLMapElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLMarqueeElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLMediaElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLMenuElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLMetaElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLMeterElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLModElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLOListElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLObjectElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLOptGroupElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLOptionElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLOptionsCollection.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLOutputElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLParagraphElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLParamElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLPictureElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLPreElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLProgressElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLQuoteElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLScriptElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLSelectElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLSlotElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLSourceElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLSpanElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLStyleElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTableCaptionElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTableCellElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTableColElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTableElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTableRowElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTableSectionElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTemplateElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTextAreaElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTimeElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTitleElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLTrackElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLUListElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLUnknownElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HTMLVideoElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HashChangeEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/HashChangeEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Headers.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/History.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/InputEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/InputEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/KeyboardEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/KeyboardEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Location.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MessageEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MessageEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MimeType.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MimeTypeArray.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MouseEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MouseEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MutationCallback.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MutationObserver.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MutationObserverInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/MutationRecord.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/NamedNodeMap.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Navigator.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Node.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/NodeFilter.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/NodeIterator.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/NodeList.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/OnBeforeUnloadEventHandlerNonNull.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/OnErrorEventHandlerNonNull.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/PageTransitionEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/PageTransitionEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Performance.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Plugin.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/PluginArray.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/PointerEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/PointerEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/PopStateEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/PopStateEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ProcessingInstruction.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ProgressEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ProgressEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/PromiseRejectionEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/PromiseRejectionEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/RadioNodeList.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Range.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGAnimatedPreserveAspectRatio.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGAnimatedRect.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGAnimatedString.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGBoundingBoxOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGDefsElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGDescElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGGElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGGraphicsElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGMetadataElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGNumber.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGPreserveAspectRatio.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGRect.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGSVGElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGStringList.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGSwitchElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGSymbolElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SVGTitleElement.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Screen.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ScrollBehavior.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ScrollIntoViewOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ScrollLogicalPosition.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ScrollOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ScrollRestoration.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Selection.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SelectionMode.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ShadowRoot.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ShadowRootInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ShadowRootMode.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/StaticRange.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/StaticRangeInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Storage.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/StorageEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/StorageEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/StyleSheetList.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SubmitEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SubmitEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/SupportedType.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/Text.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TextDecodeOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TextDecoder.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TextDecoderOptions.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TextEncoder.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TextEncoderEncodeIntoResult.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TextTrackKind.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TouchEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TouchEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TransitionEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TransitionEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/TreeWalker.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/UIEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/UIEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/ValidityState.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/VisibilityState.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/VoidFunction.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/WebSocket.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/WheelEvent.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/WheelEventInit.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/XMLDocument.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/XMLHttpRequest.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/XMLHttpRequestEventTarget.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/XMLHttpRequestResponseType.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/XMLHttpRequestUpload.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/XMLSerializer.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/generated/utils.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/geometry/DOMRect-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/geometry/DOMRectReadOnly-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/binary-data.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/colors.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/create-element.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/create-event-accessor.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/custom-elements.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/dates-and-times.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/details.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/encoding.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/events.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/focusing.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/form-controls.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/html-constructor.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/internal-constants.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/is-window.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/iterable-weak-set.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/json.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/mutation-observers.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/namespaces.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/node.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/number-and-date-inputs.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/ordered-set.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/page-transition-event.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/shadow-dom.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/strings.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/style-rules.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/stylesheets.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/svg/basic-types.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/svg/render.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/system-colors.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/text.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/traversal.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/helpers/validate-names.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/hr-time/Performance-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/interfaces.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/mutation-observer/MutationObserver-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/mutation-observer/MutationRecord-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/MimeType-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/MimeTypeArray-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/Navigator-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/NavigatorConcurrentHardware-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/NavigatorCookies-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/NavigatorID-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/NavigatorLanguage-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/NavigatorOnLine-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/NavigatorPlugins-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/Plugin-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/navigator/PluginArray-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/node-document-position.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/node-type.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/node.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/CDATASection-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/CharacterData-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/ChildNode-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/Comment-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/DOMImplementation-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/DOMStringMap-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/DOMTokenList-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/Document-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/DocumentFragment-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/DocumentOrShadowRoot-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/DocumentType-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/Element-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/ElementCSSInlineStyle-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/ElementContentEditable-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/GlobalEventHandlers-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLAnchorElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLAreaElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLAudioElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLBRElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLBaseElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLBodyElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLButtonElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLCanvasElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLCollection-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLDListElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLDataElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLDataListElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLDetailsElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLDialogElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLDirectoryElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLDivElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLEmbedElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLFieldSetElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLFontElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLFormControlsCollection-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLFormElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLFrameElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLFrameSetElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLHRElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLHeadElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLHeadingElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLHtmlElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLHyperlinkElementUtils-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLIFrameElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLImageElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLInputElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLLIElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLLabelElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLLegendElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLLinkElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLMapElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLMarqueeElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLMediaElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLMenuElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLMetaElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLMeterElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLModElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLOListElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLObjectElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLOptGroupElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLOptionElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLOptionsCollection-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLOrSVGElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLOutputElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLParagraphElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLParamElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLPictureElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLPreElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLProgressElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLQuoteElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLScriptElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLSelectElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLSlotElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLSourceElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLSpanElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLStyleElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTableCaptionElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTableCellElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTableColElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTableElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTableRowElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTableSectionElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTemplateElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTextAreaElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTimeElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTitleElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTrackElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLUListElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLUnknownElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/HTMLVideoElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/LinkStyle-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/Node-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/NodeList-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/NonDocumentTypeChildNode-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/NonElementParentNode-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/ParentNode-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/ProcessingInstruction-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/RadioNodeList-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGDefsElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGDescElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGGElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGGraphicsElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGMetadataElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGSVGElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGSwitchElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGSymbolElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGTests-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/SVGTitleElement-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/ShadowRoot-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/Slotable-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/Text-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/WindowEventHandlers-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/nodes/XMLDocument-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/range/AbstractRange-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/range/Range-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/range/StaticRange-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/range/boundary-point.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/selection/Selection-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/svg/SVGAnimatedPreserveAspectRatio-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/svg/SVGAnimatedRect-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/svg/SVGAnimatedString-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/svg/SVGListBase.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/svg/SVGNumber-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/svg/SVGPreserveAspectRatio-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/svg/SVGRect-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/svg/SVGStringList-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/traversal/NodeIterator-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/traversal/TreeWalker-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/traversal/helpers.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/webidl/DOMException-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/websockets/WebSocket-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/webstorage/Storage-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/window-properties.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/window/BarProp-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/window/External-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/window/History-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/window/Location-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/window/Screen-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/window/SessionHistory.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/window/navigation.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/xhr/FormData-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequestEventTarget-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequestUpload-impl.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/xhr/multipart-form-data.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/utils.js create mode 100644 vanilla/node_modules/jsdom/lib/jsdom/virtual-console.js create mode 100644 vanilla/node_modules/jsdom/package.json create mode 100644 vanilla/node_modules/lru-cache/LICENSE.md create mode 100644 vanilla/node_modules/lru-cache/README.md create mode 100644 vanilla/node_modules/lru-cache/dist/commonjs/index.d.ts create mode 100644 vanilla/node_modules/lru-cache/dist/commonjs/index.d.ts.map create mode 100644 vanilla/node_modules/lru-cache/dist/commonjs/index.js create mode 100644 vanilla/node_modules/lru-cache/dist/commonjs/index.js.map create mode 100644 vanilla/node_modules/lru-cache/dist/commonjs/index.min.js create mode 100644 vanilla/node_modules/lru-cache/dist/commonjs/index.min.js.map create mode 100644 vanilla/node_modules/lru-cache/dist/commonjs/package.json create mode 100644 vanilla/node_modules/lru-cache/dist/esm/index.d.ts create mode 100644 vanilla/node_modules/lru-cache/dist/esm/index.d.ts.map create mode 100644 vanilla/node_modules/lru-cache/dist/esm/index.js create mode 100644 vanilla/node_modules/lru-cache/dist/esm/index.js.map create mode 100644 vanilla/node_modules/lru-cache/dist/esm/index.min.js create mode 100644 vanilla/node_modules/lru-cache/dist/esm/index.min.js.map create mode 100644 vanilla/node_modules/lru-cache/dist/esm/package.json create mode 100644 vanilla/node_modules/lru-cache/package.json create mode 100644 vanilla/node_modules/magic-string/LICENSE create mode 100644 vanilla/node_modules/magic-string/README.md create mode 100644 vanilla/node_modules/magic-string/dist/magic-string.cjs.d.ts create mode 100644 vanilla/node_modules/magic-string/dist/magic-string.cjs.js create mode 100644 vanilla/node_modules/magic-string/dist/magic-string.cjs.js.map create mode 100644 vanilla/node_modules/magic-string/dist/magic-string.es.d.mts create mode 100644 vanilla/node_modules/magic-string/dist/magic-string.es.mjs create mode 100644 vanilla/node_modules/magic-string/dist/magic-string.es.mjs.map create mode 100644 vanilla/node_modules/magic-string/dist/magic-string.umd.js create mode 100644 vanilla/node_modules/magic-string/dist/magic-string.umd.js.map create mode 100644 vanilla/node_modules/magic-string/package.json create mode 100644 vanilla/node_modules/magicast/LICENSE create mode 100644 vanilla/node_modules/magicast/README.md create mode 100644 vanilla/node_modules/magicast/dist/builders-B_BPSg0Q.js create mode 100644 vanilla/node_modules/magicast/dist/core.d.ts create mode 100644 vanilla/node_modules/magicast/dist/core.js create mode 100644 vanilla/node_modules/magicast/dist/helpers.d.ts create mode 100644 vanilla/node_modules/magicast/dist/helpers.js create mode 100644 vanilla/node_modules/magicast/dist/index.d.ts create mode 100644 vanilla/node_modules/magicast/dist/index.js create mode 100644 vanilla/node_modules/magicast/dist/types-r4mG9WUV.d.ts create mode 100644 vanilla/node_modules/magicast/package.json create mode 100644 vanilla/node_modules/make-dir/index.d.ts create mode 100644 vanilla/node_modules/make-dir/index.js create mode 100644 vanilla/node_modules/make-dir/license create mode 100644 vanilla/node_modules/make-dir/package.json create mode 100644 vanilla/node_modules/make-dir/readme.md create mode 100644 vanilla/node_modules/mdn-data/LICENSE create mode 100644 vanilla/node_modules/mdn-data/README.md create mode 100644 vanilla/node_modules/mdn-data/api/index.js create mode 100644 vanilla/node_modules/mdn-data/api/inheritance.json create mode 100644 vanilla/node_modules/mdn-data/api/inheritance.schema.json create mode 100644 vanilla/node_modules/mdn-data/css/at-rules.json create mode 100644 vanilla/node_modules/mdn-data/css/at-rules.schema.json create mode 100644 vanilla/node_modules/mdn-data/css/definitions.json create mode 100644 vanilla/node_modules/mdn-data/css/functions.json create mode 100644 vanilla/node_modules/mdn-data/css/functions.schema.json create mode 100644 vanilla/node_modules/mdn-data/css/index.js create mode 100644 vanilla/node_modules/mdn-data/css/properties.json create mode 100644 vanilla/node_modules/mdn-data/css/properties.schema.json create mode 100644 vanilla/node_modules/mdn-data/css/selectors.json create mode 100644 vanilla/node_modules/mdn-data/css/selectors.schema.json create mode 100644 vanilla/node_modules/mdn-data/css/syntaxes.json create mode 100644 vanilla/node_modules/mdn-data/css/syntaxes.schema.json create mode 100644 vanilla/node_modules/mdn-data/css/types.json create mode 100644 vanilla/node_modules/mdn-data/css/types.schema.json create mode 100644 vanilla/node_modules/mdn-data/css/units.json create mode 100644 vanilla/node_modules/mdn-data/css/units.schema.json create mode 100644 vanilla/node_modules/mdn-data/index.js create mode 100644 vanilla/node_modules/mdn-data/l10n/css.json create mode 100644 vanilla/node_modules/mdn-data/l10n/index.js create mode 100644 vanilla/node_modules/mdn-data/package.json create mode 100644 vanilla/node_modules/ms/index.js create mode 100644 vanilla/node_modules/ms/license.md create mode 100644 vanilla/node_modules/ms/package.json create mode 100644 vanilla/node_modules/ms/readme.md create mode 100644 vanilla/node_modules/nanoid/LICENSE create mode 100644 vanilla/node_modules/nanoid/README.md create mode 100644 vanilla/node_modules/nanoid/async/index.browser.cjs create mode 100644 vanilla/node_modules/nanoid/async/index.browser.js create mode 100644 vanilla/node_modules/nanoid/async/index.cjs create mode 100644 vanilla/node_modules/nanoid/async/index.d.ts create mode 100644 vanilla/node_modules/nanoid/async/index.js create mode 100644 vanilla/node_modules/nanoid/async/index.native.js create mode 100644 vanilla/node_modules/nanoid/async/package.json create mode 100755 vanilla/node_modules/nanoid/bin/nanoid.cjs create mode 100644 vanilla/node_modules/nanoid/index.browser.cjs create mode 100644 vanilla/node_modules/nanoid/index.browser.js create mode 100644 vanilla/node_modules/nanoid/index.cjs create mode 100644 vanilla/node_modules/nanoid/index.d.cts create mode 100644 vanilla/node_modules/nanoid/index.d.ts create mode 100644 vanilla/node_modules/nanoid/index.js create mode 100644 vanilla/node_modules/nanoid/nanoid.js create mode 100644 vanilla/node_modules/nanoid/non-secure/index.cjs create mode 100644 vanilla/node_modules/nanoid/non-secure/index.d.ts create mode 100644 vanilla/node_modules/nanoid/non-secure/index.js create mode 100644 vanilla/node_modules/nanoid/non-secure/package.json create mode 100644 vanilla/node_modules/nanoid/package.json create mode 100644 vanilla/node_modules/nanoid/url-alphabet/index.cjs create mode 100644 vanilla/node_modules/nanoid/url-alphabet/index.js create mode 100644 vanilla/node_modules/nanoid/url-alphabet/package.json create mode 100644 vanilla/node_modules/obug/LICENSE create mode 100644 vanilla/node_modules/obug/README.md create mode 100644 vanilla/node_modules/obug/dist/browser.d.ts create mode 100644 vanilla/node_modules/obug/dist/browser.js create mode 100644 vanilla/node_modules/obug/dist/browser.min.js create mode 100644 vanilla/node_modules/obug/dist/core.d.ts create mode 100644 vanilla/node_modules/obug/dist/core.js create mode 100644 vanilla/node_modules/obug/dist/node.d.ts create mode 100644 vanilla/node_modules/obug/dist/node.js create mode 100644 vanilla/node_modules/obug/package.json create mode 100644 vanilla/node_modules/parse5/LICENSE create mode 100644 vanilla/node_modules/parse5/README.md create mode 100644 vanilla/node_modules/parse5/dist/common/doctype.d.ts create mode 100644 vanilla/node_modules/parse5/dist/common/doctype.js create mode 100644 vanilla/node_modules/parse5/dist/common/error-codes.d.ts create mode 100644 vanilla/node_modules/parse5/dist/common/error-codes.js create mode 100644 vanilla/node_modules/parse5/dist/common/foreign-content.d.ts create mode 100644 vanilla/node_modules/parse5/dist/common/foreign-content.js create mode 100644 vanilla/node_modules/parse5/dist/common/html.d.ts create mode 100644 vanilla/node_modules/parse5/dist/common/html.js create mode 100644 vanilla/node_modules/parse5/dist/common/token.d.ts create mode 100644 vanilla/node_modules/parse5/dist/common/token.js create mode 100644 vanilla/node_modules/parse5/dist/common/unicode.d.ts create mode 100644 vanilla/node_modules/parse5/dist/common/unicode.js create mode 100644 vanilla/node_modules/parse5/dist/index.d.ts create mode 100644 vanilla/node_modules/parse5/dist/index.js create mode 100644 vanilla/node_modules/parse5/dist/parser/formatting-element-list.d.ts create mode 100644 vanilla/node_modules/parse5/dist/parser/formatting-element-list.js create mode 100644 vanilla/node_modules/parse5/dist/parser/index.d.ts create mode 100644 vanilla/node_modules/parse5/dist/parser/index.js create mode 100644 vanilla/node_modules/parse5/dist/parser/open-element-stack.d.ts create mode 100644 vanilla/node_modules/parse5/dist/parser/open-element-stack.js create mode 100644 vanilla/node_modules/parse5/dist/serializer/index.d.ts create mode 100644 vanilla/node_modules/parse5/dist/serializer/index.js create mode 100644 vanilla/node_modules/parse5/dist/tokenizer/index.d.ts create mode 100644 vanilla/node_modules/parse5/dist/tokenizer/index.js create mode 100644 vanilla/node_modules/parse5/dist/tokenizer/preprocessor.d.ts create mode 100644 vanilla/node_modules/parse5/dist/tokenizer/preprocessor.js create mode 100644 vanilla/node_modules/parse5/dist/tree-adapters/default.d.ts create mode 100644 vanilla/node_modules/parse5/dist/tree-adapters/default.js create mode 100644 vanilla/node_modules/parse5/dist/tree-adapters/interface.d.ts create mode 100644 vanilla/node_modules/parse5/dist/tree-adapters/interface.js create mode 100644 vanilla/node_modules/parse5/package.json create mode 100644 vanilla/node_modules/pathe/LICENSE create mode 100644 vanilla/node_modules/pathe/README.md create mode 100644 vanilla/node_modules/pathe/dist/index.cjs create mode 100644 vanilla/node_modules/pathe/dist/index.d.cts create mode 100644 vanilla/node_modules/pathe/dist/index.d.mts create mode 100644 vanilla/node_modules/pathe/dist/index.d.ts create mode 100644 vanilla/node_modules/pathe/dist/index.mjs create mode 100644 vanilla/node_modules/pathe/dist/shared/pathe.BSlhyZSM.cjs create mode 100644 vanilla/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs create mode 100644 vanilla/node_modules/pathe/dist/utils.cjs create mode 100644 vanilla/node_modules/pathe/dist/utils.d.cts create mode 100644 vanilla/node_modules/pathe/dist/utils.d.mts create mode 100644 vanilla/node_modules/pathe/dist/utils.d.ts create mode 100644 vanilla/node_modules/pathe/dist/utils.mjs create mode 100644 vanilla/node_modules/pathe/package.json create mode 100644 vanilla/node_modules/pathe/utils.d.ts create mode 100644 vanilla/node_modules/picocolors/LICENSE create mode 100644 vanilla/node_modules/picocolors/README.md create mode 100644 vanilla/node_modules/picocolors/package.json create mode 100644 vanilla/node_modules/picocolors/picocolors.browser.js create mode 100644 vanilla/node_modules/picocolors/picocolors.d.ts create mode 100644 vanilla/node_modules/picocolors/picocolors.js create mode 100644 vanilla/node_modules/picocolors/types.d.ts create mode 100644 vanilla/node_modules/picomatch/LICENSE create mode 100644 vanilla/node_modules/picomatch/README.md create mode 100644 vanilla/node_modules/picomatch/index.js create mode 100644 vanilla/node_modules/picomatch/lib/constants.js create mode 100644 vanilla/node_modules/picomatch/lib/parse.js create mode 100644 vanilla/node_modules/picomatch/lib/picomatch.js create mode 100644 vanilla/node_modules/picomatch/lib/scan.js create mode 100644 vanilla/node_modules/picomatch/lib/utils.js create mode 100644 vanilla/node_modules/picomatch/package.json create mode 100644 vanilla/node_modules/picomatch/posix.js create mode 100644 vanilla/node_modules/postcss/LICENSE create mode 100644 vanilla/node_modules/postcss/README.md create mode 100644 vanilla/node_modules/postcss/lib/at-rule.d.ts create mode 100644 vanilla/node_modules/postcss/lib/at-rule.js create mode 100644 vanilla/node_modules/postcss/lib/comment.d.ts create mode 100644 vanilla/node_modules/postcss/lib/comment.js create mode 100644 vanilla/node_modules/postcss/lib/container.d.ts create mode 100644 vanilla/node_modules/postcss/lib/container.js create mode 100644 vanilla/node_modules/postcss/lib/css-syntax-error.d.ts create mode 100644 vanilla/node_modules/postcss/lib/css-syntax-error.js create mode 100644 vanilla/node_modules/postcss/lib/declaration.d.ts create mode 100644 vanilla/node_modules/postcss/lib/declaration.js create mode 100644 vanilla/node_modules/postcss/lib/document.d.ts create mode 100644 vanilla/node_modules/postcss/lib/document.js create mode 100644 vanilla/node_modules/postcss/lib/fromJSON.d.ts create mode 100644 vanilla/node_modules/postcss/lib/fromJSON.js create mode 100644 vanilla/node_modules/postcss/lib/input.d.ts create mode 100644 vanilla/node_modules/postcss/lib/input.js create mode 100644 vanilla/node_modules/postcss/lib/lazy-result.d.ts create mode 100644 vanilla/node_modules/postcss/lib/lazy-result.js create mode 100644 vanilla/node_modules/postcss/lib/list.d.ts create mode 100644 vanilla/node_modules/postcss/lib/list.js create mode 100644 vanilla/node_modules/postcss/lib/map-generator.js create mode 100644 vanilla/node_modules/postcss/lib/no-work-result.d.ts create mode 100644 vanilla/node_modules/postcss/lib/no-work-result.js create mode 100644 vanilla/node_modules/postcss/lib/node.d.ts create mode 100644 vanilla/node_modules/postcss/lib/node.js create mode 100644 vanilla/node_modules/postcss/lib/parse.d.ts create mode 100644 vanilla/node_modules/postcss/lib/parse.js create mode 100644 vanilla/node_modules/postcss/lib/parser.js create mode 100644 vanilla/node_modules/postcss/lib/postcss.d.mts create mode 100644 vanilla/node_modules/postcss/lib/postcss.d.ts create mode 100644 vanilla/node_modules/postcss/lib/postcss.js create mode 100644 vanilla/node_modules/postcss/lib/postcss.mjs create mode 100644 vanilla/node_modules/postcss/lib/previous-map.d.ts create mode 100644 vanilla/node_modules/postcss/lib/previous-map.js create mode 100644 vanilla/node_modules/postcss/lib/processor.d.ts create mode 100644 vanilla/node_modules/postcss/lib/processor.js create mode 100644 vanilla/node_modules/postcss/lib/result.d.ts create mode 100644 vanilla/node_modules/postcss/lib/result.js create mode 100644 vanilla/node_modules/postcss/lib/root.d.ts create mode 100644 vanilla/node_modules/postcss/lib/root.js create mode 100644 vanilla/node_modules/postcss/lib/rule.d.ts create mode 100644 vanilla/node_modules/postcss/lib/rule.js create mode 100644 vanilla/node_modules/postcss/lib/stringifier.d.ts create mode 100644 vanilla/node_modules/postcss/lib/stringifier.js create mode 100644 vanilla/node_modules/postcss/lib/stringify.d.ts create mode 100644 vanilla/node_modules/postcss/lib/stringify.js create mode 100644 vanilla/node_modules/postcss/lib/symbols.js create mode 100644 vanilla/node_modules/postcss/lib/terminal-highlight.js create mode 100644 vanilla/node_modules/postcss/lib/tokenize.js create mode 100644 vanilla/node_modules/postcss/lib/warn-once.js create mode 100644 vanilla/node_modules/postcss/lib/warning.d.ts create mode 100644 vanilla/node_modules/postcss/lib/warning.js create mode 100644 vanilla/node_modules/postcss/package.json create mode 100644 vanilla/node_modules/punycode/LICENSE-MIT.txt create mode 100644 vanilla/node_modules/punycode/README.md create mode 100644 vanilla/node_modules/punycode/package.json create mode 100644 vanilla/node_modules/punycode/punycode.es6.js create mode 100644 vanilla/node_modules/punycode/punycode.js create mode 100644 vanilla/node_modules/require-from-string/index.js create mode 100644 vanilla/node_modules/require-from-string/license create mode 100644 vanilla/node_modules/require-from-string/package.json create mode 100644 vanilla/node_modules/require-from-string/readme.md create mode 100644 vanilla/node_modules/rollup/LICENSE.md create mode 100644 vanilla/node_modules/rollup/README.md create mode 100755 vanilla/node_modules/rollup/dist/bin/rollup create mode 100644 vanilla/node_modules/rollup/dist/es/getLogFilter.js create mode 100644 vanilla/node_modules/rollup/dist/es/package.json create mode 100644 vanilla/node_modules/rollup/dist/es/parseAst.js create mode 100644 vanilla/node_modules/rollup/dist/es/rollup.js create mode 100644 vanilla/node_modules/rollup/dist/es/shared/node-entry.js create mode 100644 vanilla/node_modules/rollup/dist/es/shared/parseAst.js create mode 100644 vanilla/node_modules/rollup/dist/es/shared/watch.js create mode 100644 vanilla/node_modules/rollup/dist/getLogFilter.d.ts create mode 100644 vanilla/node_modules/rollup/dist/getLogFilter.js create mode 100644 vanilla/node_modules/rollup/dist/loadConfigFile.d.ts create mode 100644 vanilla/node_modules/rollup/dist/loadConfigFile.js create mode 100644 vanilla/node_modules/rollup/dist/native.js create mode 100644 vanilla/node_modules/rollup/dist/parseAst.d.ts create mode 100644 vanilla/node_modules/rollup/dist/parseAst.js create mode 100644 vanilla/node_modules/rollup/dist/rollup.d.ts create mode 100644 vanilla/node_modules/rollup/dist/rollup.js create mode 100644 vanilla/node_modules/rollup/dist/shared/fsevents-importer.js create mode 100644 vanilla/node_modules/rollup/dist/shared/index.js create mode 100644 vanilla/node_modules/rollup/dist/shared/loadConfigFile.js create mode 100644 vanilla/node_modules/rollup/dist/shared/parseAst.js create mode 100644 vanilla/node_modules/rollup/dist/shared/rollup.js create mode 100644 vanilla/node_modules/rollup/dist/shared/watch-cli.js create mode 100644 vanilla/node_modules/rollup/dist/shared/watch.js create mode 100644 vanilla/node_modules/rollup/package.json create mode 100644 vanilla/node_modules/saxes/README.md create mode 100644 vanilla/node_modules/saxes/package.json create mode 100644 vanilla/node_modules/saxes/saxes.d.ts create mode 100644 vanilla/node_modules/saxes/saxes.js create mode 100644 vanilla/node_modules/saxes/saxes.js.map create mode 100644 vanilla/node_modules/semver/LICENSE create mode 100644 vanilla/node_modules/semver/README.md create mode 100755 vanilla/node_modules/semver/bin/semver.js create mode 100644 vanilla/node_modules/semver/classes/comparator.js create mode 100644 vanilla/node_modules/semver/classes/index.js create mode 100644 vanilla/node_modules/semver/classes/range.js create mode 100644 vanilla/node_modules/semver/classes/semver.js create mode 100644 vanilla/node_modules/semver/functions/clean.js create mode 100644 vanilla/node_modules/semver/functions/cmp.js create mode 100644 vanilla/node_modules/semver/functions/coerce.js create mode 100644 vanilla/node_modules/semver/functions/compare-build.js create mode 100644 vanilla/node_modules/semver/functions/compare-loose.js create mode 100644 vanilla/node_modules/semver/functions/compare.js create mode 100644 vanilla/node_modules/semver/functions/diff.js create mode 100644 vanilla/node_modules/semver/functions/eq.js create mode 100644 vanilla/node_modules/semver/functions/gt.js create mode 100644 vanilla/node_modules/semver/functions/gte.js create mode 100644 vanilla/node_modules/semver/functions/inc.js create mode 100644 vanilla/node_modules/semver/functions/lt.js create mode 100644 vanilla/node_modules/semver/functions/lte.js create mode 100644 vanilla/node_modules/semver/functions/major.js create mode 100644 vanilla/node_modules/semver/functions/minor.js create mode 100644 vanilla/node_modules/semver/functions/neq.js create mode 100644 vanilla/node_modules/semver/functions/parse.js create mode 100644 vanilla/node_modules/semver/functions/patch.js create mode 100644 vanilla/node_modules/semver/functions/prerelease.js create mode 100644 vanilla/node_modules/semver/functions/rcompare.js create mode 100644 vanilla/node_modules/semver/functions/rsort.js create mode 100644 vanilla/node_modules/semver/functions/satisfies.js create mode 100644 vanilla/node_modules/semver/functions/sort.js create mode 100644 vanilla/node_modules/semver/functions/valid.js create mode 100644 vanilla/node_modules/semver/index.js create mode 100644 vanilla/node_modules/semver/internal/constants.js create mode 100644 vanilla/node_modules/semver/internal/debug.js create mode 100644 vanilla/node_modules/semver/internal/identifiers.js create mode 100644 vanilla/node_modules/semver/internal/lrucache.js create mode 100644 vanilla/node_modules/semver/internal/parse-options.js create mode 100644 vanilla/node_modules/semver/internal/re.js create mode 100644 vanilla/node_modules/semver/package.json create mode 100644 vanilla/node_modules/semver/preload.js create mode 100644 vanilla/node_modules/semver/range.bnf create mode 100644 vanilla/node_modules/semver/ranges/gtr.js create mode 100644 vanilla/node_modules/semver/ranges/intersects.js create mode 100644 vanilla/node_modules/semver/ranges/ltr.js create mode 100644 vanilla/node_modules/semver/ranges/max-satisfying.js create mode 100644 vanilla/node_modules/semver/ranges/min-satisfying.js create mode 100644 vanilla/node_modules/semver/ranges/min-version.js create mode 100644 vanilla/node_modules/semver/ranges/outside.js create mode 100644 vanilla/node_modules/semver/ranges/simplify.js create mode 100644 vanilla/node_modules/semver/ranges/subset.js create mode 100644 vanilla/node_modules/semver/ranges/to-comparators.js create mode 100644 vanilla/node_modules/semver/ranges/valid.js create mode 100644 vanilla/node_modules/siginfo/.travis.yml create mode 100644 vanilla/node_modules/siginfo/LICENSE create mode 100644 vanilla/node_modules/siginfo/README.md create mode 100644 vanilla/node_modules/siginfo/index.js create mode 100644 vanilla/node_modules/siginfo/package.json create mode 100644 vanilla/node_modules/siginfo/test.js create mode 100644 vanilla/node_modules/source-map-js/LICENSE create mode 100644 vanilla/node_modules/source-map-js/README.md create mode 100644 vanilla/node_modules/source-map-js/lib/array-set.js create mode 100644 vanilla/node_modules/source-map-js/lib/base64-vlq.js create mode 100644 vanilla/node_modules/source-map-js/lib/base64.js create mode 100644 vanilla/node_modules/source-map-js/lib/binary-search.js create mode 100644 vanilla/node_modules/source-map-js/lib/mapping-list.js create mode 100644 vanilla/node_modules/source-map-js/lib/quick-sort.js create mode 100644 vanilla/node_modules/source-map-js/lib/source-map-consumer.d.ts create mode 100644 vanilla/node_modules/source-map-js/lib/source-map-consumer.js create mode 100644 vanilla/node_modules/source-map-js/lib/source-map-generator.d.ts create mode 100644 vanilla/node_modules/source-map-js/lib/source-map-generator.js create mode 100644 vanilla/node_modules/source-map-js/lib/source-node.d.ts create mode 100644 vanilla/node_modules/source-map-js/lib/source-node.js create mode 100644 vanilla/node_modules/source-map-js/lib/util.js create mode 100644 vanilla/node_modules/source-map-js/package.json create mode 100644 vanilla/node_modules/source-map-js/source-map.d.ts create mode 100644 vanilla/node_modules/source-map-js/source-map.js create mode 100644 vanilla/node_modules/stackback/.npmignore create mode 100644 vanilla/node_modules/stackback/.travis.yml create mode 100644 vanilla/node_modules/stackback/README.md create mode 100644 vanilla/node_modules/stackback/formatstack.js create mode 100644 vanilla/node_modules/stackback/index.js create mode 100644 vanilla/node_modules/stackback/package.json create mode 100644 vanilla/node_modules/stackback/test.js create mode 100644 vanilla/node_modules/std-env/LICENCE create mode 100644 vanilla/node_modules/std-env/README.md create mode 100644 vanilla/node_modules/std-env/dist/index.cjs create mode 100644 vanilla/node_modules/std-env/dist/index.d.cts create mode 100644 vanilla/node_modules/std-env/dist/index.d.mts create mode 100644 vanilla/node_modules/std-env/dist/index.d.ts create mode 100644 vanilla/node_modules/std-env/dist/index.mjs create mode 100644 vanilla/node_modules/std-env/package.json create mode 100644 vanilla/node_modules/supports-color/browser.js create mode 100644 vanilla/node_modules/supports-color/index.js create mode 100644 vanilla/node_modules/supports-color/license create mode 100644 vanilla/node_modules/supports-color/package.json create mode 100644 vanilla/node_modules/supports-color/readme.md create mode 100644 vanilla/node_modules/symbol-tree/LICENSE create mode 100644 vanilla/node_modules/symbol-tree/README.md create mode 100644 vanilla/node_modules/symbol-tree/lib/SymbolTree.js create mode 100644 vanilla/node_modules/symbol-tree/lib/SymbolTreeNode.js create mode 100644 vanilla/node_modules/symbol-tree/lib/TreeIterator.js create mode 100644 vanilla/node_modules/symbol-tree/lib/TreePosition.js create mode 100644 vanilla/node_modules/symbol-tree/package.json create mode 100644 vanilla/node_modules/tinybench/LICENSE create mode 100644 vanilla/node_modules/tinybench/README.md create mode 100644 vanilla/node_modules/tinybench/dist/index.cjs create mode 100644 vanilla/node_modules/tinybench/dist/index.d.cts create mode 100644 vanilla/node_modules/tinybench/dist/index.d.ts create mode 100644 vanilla/node_modules/tinybench/dist/index.js create mode 100644 vanilla/node_modules/tinybench/package.json create mode 100644 vanilla/node_modules/tinyexec/LICENSE create mode 100644 vanilla/node_modules/tinyexec/README.md create mode 100644 vanilla/node_modules/tinyexec/dist/main.d.ts create mode 100644 vanilla/node_modules/tinyexec/dist/main.js create mode 100644 vanilla/node_modules/tinyexec/package.json create mode 100644 vanilla/node_modules/tinyglobby/LICENSE create mode 100644 vanilla/node_modules/tinyglobby/README.md create mode 100644 vanilla/node_modules/tinyglobby/dist/index.cjs create mode 100644 vanilla/node_modules/tinyglobby/dist/index.d.cts create mode 100644 vanilla/node_modules/tinyglobby/dist/index.d.mts create mode 100644 vanilla/node_modules/tinyglobby/dist/index.mjs create mode 100644 vanilla/node_modules/tinyglobby/package.json create mode 100644 vanilla/node_modules/tinyrainbow/LICENCE create mode 100644 vanilla/node_modules/tinyrainbow/README.md create mode 100644 vanilla/node_modules/tinyrainbow/dist/index.d.ts create mode 100644 vanilla/node_modules/tinyrainbow/dist/index.js create mode 100644 vanilla/node_modules/tinyrainbow/package.json create mode 100644 vanilla/node_modules/tldts-core/LICENSE create mode 100644 vanilla/node_modules/tldts-core/README.md create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/index.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/index.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/domain-without-suffix.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/domain-without-suffix.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/domain.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/domain.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/extract-hostname.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/extract-hostname.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/factory.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/factory.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/is-ip.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/is-ip.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/is-valid.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/is-valid.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/lookup/fast-path.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/lookup/fast-path.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/lookup/interface.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/lookup/interface.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/options.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/options.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/subdomain.js create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/src/subdomain.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/cjs/tsconfig.tsbuildinfo create mode 100644 vanilla/node_modules/tldts-core/dist/es6/index.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/index.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/domain-without-suffix.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/domain-without-suffix.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/domain.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/domain.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/extract-hostname.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/extract-hostname.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/factory.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/factory.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/is-ip.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/is-ip.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/is-valid.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/is-valid.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/lookup/fast-path.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/lookup/fast-path.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/lookup/interface.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/lookup/interface.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/options.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/options.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/subdomain.js create mode 100644 vanilla/node_modules/tldts-core/dist/es6/src/subdomain.js.map create mode 100644 vanilla/node_modules/tldts-core/dist/es6/tsconfig.bundle.tsbuildinfo create mode 100644 vanilla/node_modules/tldts-core/dist/types/index.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/domain-without-suffix.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/domain.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/extract-hostname.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/factory.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/is-ip.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/is-valid.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/lookup/fast-path.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/lookup/interface.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/options.d.ts create mode 100644 vanilla/node_modules/tldts-core/dist/types/src/subdomain.d.ts create mode 100644 vanilla/node_modules/tldts-core/index.ts create mode 100644 vanilla/node_modules/tldts-core/package.json create mode 100644 vanilla/node_modules/tldts-core/src/domain-without-suffix.ts create mode 100644 vanilla/node_modules/tldts-core/src/domain.ts create mode 100644 vanilla/node_modules/tldts-core/src/extract-hostname.ts create mode 100644 vanilla/node_modules/tldts-core/src/factory.ts create mode 100644 vanilla/node_modules/tldts-core/src/is-ip.ts create mode 100644 vanilla/node_modules/tldts-core/src/is-valid.ts create mode 100644 vanilla/node_modules/tldts-core/src/lookup/fast-path.ts create mode 100644 vanilla/node_modules/tldts-core/src/lookup/interface.ts create mode 100644 vanilla/node_modules/tldts-core/src/options.ts create mode 100644 vanilla/node_modules/tldts-core/src/subdomain.ts create mode 100644 vanilla/node_modules/tldts/LICENSE create mode 100644 vanilla/node_modules/tldts/README.md create mode 100755 vanilla/node_modules/tldts/bin/cli.js create mode 100644 vanilla/node_modules/tldts/dist/cjs/index.js create mode 100644 vanilla/node_modules/tldts/dist/cjs/index.js.map create mode 100644 vanilla/node_modules/tldts/dist/cjs/src/data/trie.js create mode 100644 vanilla/node_modules/tldts/dist/cjs/src/data/trie.js.map create mode 100644 vanilla/node_modules/tldts/dist/cjs/src/suffix-trie.js create mode 100644 vanilla/node_modules/tldts/dist/cjs/src/suffix-trie.js.map create mode 100644 vanilla/node_modules/tldts/dist/cjs/tsconfig.tsbuildinfo create mode 100644 vanilla/node_modules/tldts/dist/es6/index.js create mode 100644 vanilla/node_modules/tldts/dist/es6/index.js.map create mode 100644 vanilla/node_modules/tldts/dist/es6/src/data/trie.js create mode 100644 vanilla/node_modules/tldts/dist/es6/src/data/trie.js.map create mode 100644 vanilla/node_modules/tldts/dist/es6/src/suffix-trie.js create mode 100644 vanilla/node_modules/tldts/dist/es6/src/suffix-trie.js.map create mode 100644 vanilla/node_modules/tldts/dist/es6/tsconfig.bundle.tsbuildinfo create mode 100644 vanilla/node_modules/tldts/dist/index.cjs.min.js create mode 100644 vanilla/node_modules/tldts/dist/index.cjs.min.js.map create mode 100644 vanilla/node_modules/tldts/dist/index.esm.min.js create mode 100644 vanilla/node_modules/tldts/dist/index.esm.min.js.map create mode 100644 vanilla/node_modules/tldts/dist/index.umd.min.js create mode 100644 vanilla/node_modules/tldts/dist/index.umd.min.js.map create mode 100644 vanilla/node_modules/tldts/dist/types/index.d.ts create mode 100644 vanilla/node_modules/tldts/dist/types/src/data/trie.d.ts create mode 100644 vanilla/node_modules/tldts/dist/types/src/suffix-trie.d.ts create mode 100644 vanilla/node_modules/tldts/index.ts create mode 100644 vanilla/node_modules/tldts/package.json create mode 100644 vanilla/node_modules/tldts/src/data/trie.ts create mode 100644 vanilla/node_modules/tldts/src/suffix-trie.ts create mode 100644 vanilla/node_modules/tough-cookie/LICENSE create mode 100644 vanilla/node_modules/tough-cookie/README.md create mode 100644 vanilla/node_modules/tough-cookie/dist/index.cjs create mode 100644 vanilla/node_modules/tough-cookie/dist/index.cjs.map create mode 100644 vanilla/node_modules/tough-cookie/dist/index.d.cts create mode 100644 vanilla/node_modules/tough-cookie/dist/index.d.ts create mode 100644 vanilla/node_modules/tough-cookie/dist/index.js create mode 100644 vanilla/node_modules/tough-cookie/dist/index.js.map create mode 100644 vanilla/node_modules/tough-cookie/package.json create mode 100644 vanilla/node_modules/tr46/LICENSE.md create mode 100644 vanilla/node_modules/tr46/README.md create mode 100644 vanilla/node_modules/tr46/index.js create mode 100644 vanilla/node_modules/tr46/lib/mappingTable.json create mode 100644 vanilla/node_modules/tr46/lib/regexes.js create mode 100644 vanilla/node_modules/tr46/lib/statusMapping.js create mode 100644 vanilla/node_modules/tr46/package.json create mode 100644 vanilla/node_modules/undici/LICENSE create mode 100644 vanilla/node_modules/undici/README.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Agent.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/BalancedPool.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/CacheStorage.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/CacheStore.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Client.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/ClientStats.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Connector.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/ContentType.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Cookies.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Debug.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/DiagnosticsChannel.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Dispatcher.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Errors.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/EventSource.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Fetch.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/GlobalInstallation.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/H2CClient.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/MockAgent.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/MockCallHistory.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/MockCallHistoryLog.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/MockClient.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/MockErrors.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/MockPool.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Pool.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/PoolStats.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/ProxyAgent.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/RedirectHandler.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/RetryAgent.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/RetryHandler.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/RoundRobinPool.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/SnapshotAgent.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/Util.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/WebSocket.md create mode 100644 vanilla/node_modules/undici/docs/docs/api/api-lifecycle.md create mode 100644 vanilla/node_modules/undici/docs/docs/best-practices/client-certificate.md create mode 100644 vanilla/node_modules/undici/docs/docs/best-practices/crawling.md create mode 100644 vanilla/node_modules/undici/docs/docs/best-practices/mocking-request.md create mode 100644 vanilla/node_modules/undici/docs/docs/best-practices/proxy.md create mode 100644 vanilla/node_modules/undici/docs/docs/best-practices/writing-tests.md create mode 100644 vanilla/node_modules/undici/index-fetch.js create mode 100644 vanilla/node_modules/undici/index.d.ts create mode 100644 vanilla/node_modules/undici/index.js create mode 100644 vanilla/node_modules/undici/lib/api/abort-signal.js create mode 100644 vanilla/node_modules/undici/lib/api/api-connect.js create mode 100644 vanilla/node_modules/undici/lib/api/api-pipeline.js create mode 100644 vanilla/node_modules/undici/lib/api/api-request.js create mode 100644 vanilla/node_modules/undici/lib/api/api-stream.js create mode 100644 vanilla/node_modules/undici/lib/api/api-upgrade.js create mode 100644 vanilla/node_modules/undici/lib/api/index.js create mode 100644 vanilla/node_modules/undici/lib/api/readable.js create mode 100644 vanilla/node_modules/undici/lib/cache/memory-cache-store.js create mode 100644 vanilla/node_modules/undici/lib/cache/sqlite-cache-store.js create mode 100644 vanilla/node_modules/undici/lib/core/connect.js create mode 100644 vanilla/node_modules/undici/lib/core/constants.js create mode 100644 vanilla/node_modules/undici/lib/core/diagnostics.js create mode 100644 vanilla/node_modules/undici/lib/core/errors.js create mode 100644 vanilla/node_modules/undici/lib/core/request.js create mode 100644 vanilla/node_modules/undici/lib/core/symbols.js create mode 100644 vanilla/node_modules/undici/lib/core/tree.js create mode 100644 vanilla/node_modules/undici/lib/core/util.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/agent.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/balanced-pool.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/client-h1.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/client-h2.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/client.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/dispatcher-base.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/dispatcher.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/fixed-queue.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/h2c-client.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/pool-base.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/pool.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/proxy-agent.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/retry-agent.js create mode 100644 vanilla/node_modules/undici/lib/dispatcher/round-robin-pool.js create mode 100644 vanilla/node_modules/undici/lib/encoding/index.js create mode 100644 vanilla/node_modules/undici/lib/global.js create mode 100644 vanilla/node_modules/undici/lib/handler/cache-handler.js create mode 100644 vanilla/node_modules/undici/lib/handler/cache-revalidation-handler.js create mode 100644 vanilla/node_modules/undici/lib/handler/decorator-handler.js create mode 100644 vanilla/node_modules/undici/lib/handler/deduplication-handler.js create mode 100644 vanilla/node_modules/undici/lib/handler/redirect-handler.js create mode 100644 vanilla/node_modules/undici/lib/handler/retry-handler.js create mode 100644 vanilla/node_modules/undici/lib/handler/unwrap-handler.js create mode 100644 vanilla/node_modules/undici/lib/handler/wrap-handler.js create mode 100644 vanilla/node_modules/undici/lib/interceptor/cache.js create mode 100644 vanilla/node_modules/undici/lib/interceptor/decompress.js create mode 100644 vanilla/node_modules/undici/lib/interceptor/deduplicate.js create mode 100644 vanilla/node_modules/undici/lib/interceptor/dns.js create mode 100644 vanilla/node_modules/undici/lib/interceptor/dump.js create mode 100644 vanilla/node_modules/undici/lib/interceptor/redirect.js create mode 100644 vanilla/node_modules/undici/lib/interceptor/response-error.js create mode 100644 vanilla/node_modules/undici/lib/interceptor/retry.js create mode 100644 vanilla/node_modules/undici/lib/llhttp/.gitkeep create mode 100644 vanilla/node_modules/undici/lib/llhttp/constants.d.ts create mode 100644 vanilla/node_modules/undici/lib/llhttp/constants.js create mode 100644 vanilla/node_modules/undici/lib/llhttp/llhttp-wasm.js create mode 100644 vanilla/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js create mode 100644 vanilla/node_modules/undici/lib/llhttp/utils.d.ts create mode 100644 vanilla/node_modules/undici/lib/llhttp/utils.js create mode 100644 vanilla/node_modules/undici/lib/mock/mock-agent.js create mode 100644 vanilla/node_modules/undici/lib/mock/mock-call-history.js create mode 100644 vanilla/node_modules/undici/lib/mock/mock-client.js create mode 100644 vanilla/node_modules/undici/lib/mock/mock-errors.js create mode 100644 vanilla/node_modules/undici/lib/mock/mock-interceptor.js create mode 100644 vanilla/node_modules/undici/lib/mock/mock-pool.js create mode 100644 vanilla/node_modules/undici/lib/mock/mock-symbols.js create mode 100644 vanilla/node_modules/undici/lib/mock/mock-utils.js create mode 100644 vanilla/node_modules/undici/lib/mock/pending-interceptors-formatter.js create mode 100644 vanilla/node_modules/undici/lib/mock/snapshot-agent.js create mode 100644 vanilla/node_modules/undici/lib/mock/snapshot-recorder.js create mode 100644 vanilla/node_modules/undici/lib/mock/snapshot-utils.js create mode 100644 vanilla/node_modules/undici/lib/util/cache.js create mode 100644 vanilla/node_modules/undici/lib/util/date.js create mode 100644 vanilla/node_modules/undici/lib/util/promise.js create mode 100644 vanilla/node_modules/undici/lib/util/runtime-features.js create mode 100644 vanilla/node_modules/undici/lib/util/stats.js create mode 100644 vanilla/node_modules/undici/lib/util/timers.js create mode 100644 vanilla/node_modules/undici/lib/web/cache/cache.js create mode 100644 vanilla/node_modules/undici/lib/web/cache/cachestorage.js create mode 100644 vanilla/node_modules/undici/lib/web/cache/util.js create mode 100644 vanilla/node_modules/undici/lib/web/cookies/constants.js create mode 100644 vanilla/node_modules/undici/lib/web/cookies/index.js create mode 100644 vanilla/node_modules/undici/lib/web/cookies/parse.js create mode 100644 vanilla/node_modules/undici/lib/web/cookies/util.js create mode 100644 vanilla/node_modules/undici/lib/web/eventsource/eventsource-stream.js create mode 100644 vanilla/node_modules/undici/lib/web/eventsource/eventsource.js create mode 100644 vanilla/node_modules/undici/lib/web/eventsource/util.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/LICENSE create mode 100644 vanilla/node_modules/undici/lib/web/fetch/body.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/constants.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/data-url.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/formdata-parser.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/formdata.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/global.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/headers.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/index.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/request.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/response.js create mode 100644 vanilla/node_modules/undici/lib/web/fetch/util.js create mode 100644 vanilla/node_modules/undici/lib/web/infra/index.js create mode 100644 vanilla/node_modules/undici/lib/web/subresource-integrity/Readme.md create mode 100644 vanilla/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js create mode 100644 vanilla/node_modules/undici/lib/web/webidl/index.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/connection.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/constants.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/events.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/frame.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/permessage-deflate.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/receiver.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/sender.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/stream/websocketerror.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/stream/websocketstream.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/util.js create mode 100644 vanilla/node_modules/undici/lib/web/websocket/websocket.js create mode 100644 vanilla/node_modules/undici/package.json create mode 100644 vanilla/node_modules/undici/scripts/strip-comments.js create mode 100644 vanilla/node_modules/undici/types/README.md create mode 100644 vanilla/node_modules/undici/types/agent.d.ts create mode 100644 vanilla/node_modules/undici/types/api.d.ts create mode 100644 vanilla/node_modules/undici/types/balanced-pool.d.ts create mode 100644 vanilla/node_modules/undici/types/cache-interceptor.d.ts create mode 100644 vanilla/node_modules/undici/types/cache.d.ts create mode 100644 vanilla/node_modules/undici/types/client-stats.d.ts create mode 100644 vanilla/node_modules/undici/types/client.d.ts create mode 100644 vanilla/node_modules/undici/types/connector.d.ts create mode 100644 vanilla/node_modules/undici/types/content-type.d.ts create mode 100644 vanilla/node_modules/undici/types/cookies.d.ts create mode 100644 vanilla/node_modules/undici/types/diagnostics-channel.d.ts create mode 100644 vanilla/node_modules/undici/types/dispatcher.d.ts create mode 100644 vanilla/node_modules/undici/types/env-http-proxy-agent.d.ts create mode 100644 vanilla/node_modules/undici/types/errors.d.ts create mode 100644 vanilla/node_modules/undici/types/eventsource.d.ts create mode 100644 vanilla/node_modules/undici/types/fetch.d.ts create mode 100644 vanilla/node_modules/undici/types/formdata.d.ts create mode 100644 vanilla/node_modules/undici/types/global-dispatcher.d.ts create mode 100644 vanilla/node_modules/undici/types/global-origin.d.ts create mode 100644 vanilla/node_modules/undici/types/h2c-client.d.ts create mode 100644 vanilla/node_modules/undici/types/handlers.d.ts create mode 100644 vanilla/node_modules/undici/types/header.d.ts create mode 100644 vanilla/node_modules/undici/types/index.d.ts create mode 100644 vanilla/node_modules/undici/types/interceptors.d.ts create mode 100644 vanilla/node_modules/undici/types/mock-agent.d.ts create mode 100644 vanilla/node_modules/undici/types/mock-call-history.d.ts create mode 100644 vanilla/node_modules/undici/types/mock-client.d.ts create mode 100644 vanilla/node_modules/undici/types/mock-errors.d.ts create mode 100644 vanilla/node_modules/undici/types/mock-interceptor.d.ts create mode 100644 vanilla/node_modules/undici/types/mock-pool.d.ts create mode 100644 vanilla/node_modules/undici/types/patch.d.ts create mode 100644 vanilla/node_modules/undici/types/pool-stats.d.ts create mode 100644 vanilla/node_modules/undici/types/pool.d.ts create mode 100644 vanilla/node_modules/undici/types/proxy-agent.d.ts create mode 100644 vanilla/node_modules/undici/types/readable.d.ts create mode 100644 vanilla/node_modules/undici/types/retry-agent.d.ts create mode 100644 vanilla/node_modules/undici/types/retry-handler.d.ts create mode 100644 vanilla/node_modules/undici/types/round-robin-pool.d.ts create mode 100644 vanilla/node_modules/undici/types/snapshot-agent.d.ts create mode 100644 vanilla/node_modules/undici/types/util.d.ts create mode 100644 vanilla/node_modules/undici/types/utility.d.ts create mode 100644 vanilla/node_modules/undici/types/webidl.d.ts create mode 100644 vanilla/node_modules/undici/types/websocket.d.ts create mode 100644 vanilla/node_modules/vite/LICENSE.md create mode 100644 vanilla/node_modules/vite/README.md create mode 100644 vanilla/node_modules/vite/bin/openChrome.js create mode 100755 vanilla/node_modules/vite/bin/vite.js create mode 100644 vanilla/node_modules/vite/client.d.ts create mode 100644 vanilla/node_modules/vite/dist/client/client.mjs create mode 100644 vanilla/node_modules/vite/dist/client/env.mjs create mode 100644 vanilla/node_modules/vite/dist/node/chunks/build.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/build2.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/chunk.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/config.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/config2.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/dist.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/lib.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/logger.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/moduleRunnerTransport.d.ts create mode 100644 vanilla/node_modules/vite/dist/node/chunks/optimizer.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/postcss-import.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/preview.js create mode 100644 vanilla/node_modules/vite/dist/node/chunks/server.js create mode 100644 vanilla/node_modules/vite/dist/node/cli.js create mode 100644 vanilla/node_modules/vite/dist/node/index.d.ts create mode 100644 vanilla/node_modules/vite/dist/node/index.js create mode 100644 vanilla/node_modules/vite/dist/node/module-runner.d.ts create mode 100644 vanilla/node_modules/vite/dist/node/module-runner.js create mode 100644 vanilla/node_modules/vite/misc/false.js create mode 100644 vanilla/node_modules/vite/misc/true.js create mode 100644 vanilla/node_modules/vite/package.json create mode 100644 vanilla/node_modules/vite/types/customEvent.d.ts create mode 100644 vanilla/node_modules/vite/types/hmrPayload.d.ts create mode 100644 vanilla/node_modules/vite/types/hot.d.ts create mode 100644 vanilla/node_modules/vite/types/import-meta.d.ts create mode 100644 vanilla/node_modules/vite/types/importGlob.d.ts create mode 100644 vanilla/node_modules/vite/types/importMeta.d.ts create mode 100644 vanilla/node_modules/vite/types/internal/cssPreprocessorOptions.d.ts create mode 100644 vanilla/node_modules/vite/types/internal/lightningcssOptions.d.ts create mode 100644 vanilla/node_modules/vite/types/internal/terserOptions.d.ts create mode 100644 vanilla/node_modules/vite/types/metadata.d.ts create mode 100644 vanilla/node_modules/vite/types/package.json create mode 100644 vanilla/node_modules/vitest/LICENSE.md create mode 100644 vanilla/node_modules/vitest/README.md create mode 100644 vanilla/node_modules/vitest/browser/context.d.ts create mode 100644 vanilla/node_modules/vitest/browser/context.js create mode 100644 vanilla/node_modules/vitest/config.d.ts create mode 100644 vanilla/node_modules/vitest/coverage.d.ts create mode 100644 vanilla/node_modules/vitest/dist/browser.d.ts create mode 100644 vanilla/node_modules/vitest/dist/browser.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/base.CJ0Y4ePK.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/benchmark.B3N2zMcH.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/benchmark.d.DAaHLpsq.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/browser.d.ChKACdzH.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/cac.DVeoLl0M.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/cli-api.B7PN_QUv.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/config.d.Cy95HiCx.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/console.Cf-YriPC.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/constants.D_Q9UYh-.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/coverage.AVPTjMgw.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/coverage.D_JHT54q.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/coverage.d.BZtK59WP.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/creator.DAmOKTvJ.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/defaults.BOqNVLsY.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/env.D4Lgay0q.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/environment.d.CrsxCzP1.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/evaluatedModules.Dg1zASAC.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/evaluatedModules.d.BxJ5omdx.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/git.Bm2pzPAa.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/global.d.B15mdLcR.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/globals.DOayXfHP.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/index.6Qv1eEA6.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/index.C5r1PdPD.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/index.Chj8NDwU.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/index.CyBMJtT7.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/index.D3XRDfWc.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/index.D4KonVSU.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/index.M8mOzt4Y.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/index.Z5E_ObnR.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/init-forks._y3TW739.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/init-threads.DBO2kn-p.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/init.B6MLFIaN.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/inspector.CvyFGlXm.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/modules.BJuCwlRJ.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/node.Ce0vMQM7.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/plugin.d.CtqpEehP.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/reporters.d.CWXNI2jG.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/rpc.BoxB0q7B.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/rpc.d.RH3apGEf.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/setup-common.Cm-kSBVi.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/startModuleRunner.DEj0jb3e.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/suite.d.BJWk38HB.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/test.B8ej_ZHS.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/traces.CCmnQaNT.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/traces.d.402V_yFI.d.ts create mode 100644 vanilla/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/vi.2VT5v0um.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/vm.D3epNOPZ.js create mode 100644 vanilla/node_modules/vitest/dist/chunks/worker.d.Dyxm8DEL.d.ts create mode 100644 vanilla/node_modules/vitest/dist/cli.js create mode 100644 vanilla/node_modules/vitest/dist/config.cjs create mode 100644 vanilla/node_modules/vitest/dist/config.d.ts create mode 100644 vanilla/node_modules/vitest/dist/config.js create mode 100644 vanilla/node_modules/vitest/dist/coverage.d.ts create mode 100644 vanilla/node_modules/vitest/dist/coverage.js create mode 100644 vanilla/node_modules/vitest/dist/environments.d.ts create mode 100644 vanilla/node_modules/vitest/dist/environments.js create mode 100644 vanilla/node_modules/vitest/dist/index.d.ts create mode 100644 vanilla/node_modules/vitest/dist/index.js create mode 100644 vanilla/node_modules/vitest/dist/mocker.d.ts create mode 100644 vanilla/node_modules/vitest/dist/mocker.js create mode 100644 vanilla/node_modules/vitest/dist/module-evaluator.d.ts create mode 100644 vanilla/node_modules/vitest/dist/module-evaluator.js create mode 100644 vanilla/node_modules/vitest/dist/module-runner.js create mode 100644 vanilla/node_modules/vitest/dist/node.d.ts create mode 100644 vanilla/node_modules/vitest/dist/node.js create mode 100644 vanilla/node_modules/vitest/dist/path.js create mode 100644 vanilla/node_modules/vitest/dist/reporters.d.ts create mode 100644 vanilla/node_modules/vitest/dist/reporters.js create mode 100644 vanilla/node_modules/vitest/dist/runners.d.ts create mode 100644 vanilla/node_modules/vitest/dist/runners.js create mode 100644 vanilla/node_modules/vitest/dist/snapshot.d.ts create mode 100644 vanilla/node_modules/vitest/dist/snapshot.js create mode 100644 vanilla/node_modules/vitest/dist/spy.js create mode 100644 vanilla/node_modules/vitest/dist/suite.d.ts create mode 100644 vanilla/node_modules/vitest/dist/suite.js create mode 100644 vanilla/node_modules/vitest/dist/worker.d.ts create mode 100644 vanilla/node_modules/vitest/dist/worker.js create mode 100644 vanilla/node_modules/vitest/dist/workers/forks.js create mode 100644 vanilla/node_modules/vitest/dist/workers/runVmTests.js create mode 100644 vanilla/node_modules/vitest/dist/workers/threads.js create mode 100644 vanilla/node_modules/vitest/dist/workers/vmForks.js create mode 100644 vanilla/node_modules/vitest/dist/workers/vmThreads.js create mode 100644 vanilla/node_modules/vitest/environments.d.ts create mode 100644 vanilla/node_modules/vitest/globals.d.ts create mode 100644 vanilla/node_modules/vitest/import-meta.d.ts create mode 100644 vanilla/node_modules/vitest/importMeta.d.ts create mode 100644 vanilla/node_modules/vitest/index.cjs create mode 100644 vanilla/node_modules/vitest/index.d.cts create mode 100644 vanilla/node_modules/vitest/jsdom.d.ts create mode 100644 vanilla/node_modules/vitest/mocker.d.ts create mode 100644 vanilla/node_modules/vitest/node.d.ts create mode 100644 vanilla/node_modules/vitest/optional-types.d.ts create mode 100644 vanilla/node_modules/vitest/package.json create mode 100644 vanilla/node_modules/vitest/reporters.d.ts create mode 100644 vanilla/node_modules/vitest/runners.d.ts create mode 100644 vanilla/node_modules/vitest/snapshot.d.ts create mode 100644 vanilla/node_modules/vitest/suite.d.ts create mode 100644 vanilla/node_modules/vitest/suppress-warnings.cjs create mode 100755 vanilla/node_modules/vitest/vitest.mjs create mode 100644 vanilla/node_modules/vitest/worker.d.ts create mode 100644 vanilla/node_modules/w3c-xmlserializer/LICENSE.md create mode 100644 vanilla/node_modules/w3c-xmlserializer/README.md create mode 100644 vanilla/node_modules/w3c-xmlserializer/lib/attributes.js create mode 100644 vanilla/node_modules/w3c-xmlserializer/lib/constants.js create mode 100644 vanilla/node_modules/w3c-xmlserializer/lib/serialize.js create mode 100644 vanilla/node_modules/w3c-xmlserializer/package.json create mode 100644 vanilla/node_modules/webidl-conversions/LICENSE.md create mode 100644 vanilla/node_modules/webidl-conversions/README.md create mode 100644 vanilla/node_modules/webidl-conversions/lib/index.js create mode 100644 vanilla/node_modules/webidl-conversions/package.json create mode 100644 vanilla/node_modules/whatwg-mimetype/LICENSE.txt create mode 100644 vanilla/node_modules/whatwg-mimetype/README.md create mode 100644 vanilla/node_modules/whatwg-mimetype/lib/index.js create mode 100644 vanilla/node_modules/whatwg-mimetype/lib/mime-type-parameters.js create mode 100644 vanilla/node_modules/whatwg-mimetype/lib/mime-type.js create mode 100644 vanilla/node_modules/whatwg-mimetype/lib/parser.js create mode 100644 vanilla/node_modules/whatwg-mimetype/lib/serializer.js create mode 100644 vanilla/node_modules/whatwg-mimetype/lib/sniff.js create mode 100644 vanilla/node_modules/whatwg-mimetype/lib/utils.js create mode 100644 vanilla/node_modules/whatwg-mimetype/package.json create mode 100644 vanilla/node_modules/whatwg-url/LICENSE.txt create mode 100644 vanilla/node_modules/whatwg-url/README.md create mode 100644 vanilla/node_modules/whatwg-url/index.js create mode 100644 vanilla/node_modules/whatwg-url/lib/Function.js create mode 100644 vanilla/node_modules/whatwg-url/lib/URL-impl.js create mode 100644 vanilla/node_modules/whatwg-url/lib/URL.js create mode 100644 vanilla/node_modules/whatwg-url/lib/URLSearchParams-impl.js create mode 100644 vanilla/node_modules/whatwg-url/lib/URLSearchParams.js create mode 100644 vanilla/node_modules/whatwg-url/lib/VoidFunction.js create mode 100644 vanilla/node_modules/whatwg-url/lib/encoding.js create mode 100644 vanilla/node_modules/whatwg-url/lib/infra.js create mode 100644 vanilla/node_modules/whatwg-url/lib/percent-encoding.js create mode 100644 vanilla/node_modules/whatwg-url/lib/url-state-machine.js create mode 100644 vanilla/node_modules/whatwg-url/lib/urlencoded.js create mode 100644 vanilla/node_modules/whatwg-url/lib/utils.js create mode 100644 vanilla/node_modules/whatwg-url/package.json create mode 100644 vanilla/node_modules/whatwg-url/webidl2js-wrapper.js create mode 100644 vanilla/node_modules/why-is-node-running/.github/FUNDING.yml create mode 100644 vanilla/node_modules/why-is-node-running/LICENSE create mode 100644 vanilla/node_modules/why-is-node-running/README.md create mode 100755 vanilla/node_modules/why-is-node-running/cli.js create mode 100644 vanilla/node_modules/why-is-node-running/example.js create mode 100644 vanilla/node_modules/why-is-node-running/include.js create mode 100644 vanilla/node_modules/why-is-node-running/index.js create mode 100644 vanilla/node_modules/why-is-node-running/package.json create mode 100644 vanilla/node_modules/xml-name-validator/LICENSE.txt create mode 100644 vanilla/node_modules/xml-name-validator/README.md create mode 100644 vanilla/node_modules/xml-name-validator/lib/xml-name-validator.js create mode 100644 vanilla/node_modules/xml-name-validator/package.json create mode 100644 vanilla/node_modules/xmlchars/LICENSE create mode 100644 vanilla/node_modules/xmlchars/README.md create mode 100644 vanilla/node_modules/xmlchars/package.json create mode 100644 vanilla/node_modules/xmlchars/xml/1.0/ed4.d.ts create mode 100644 vanilla/node_modules/xmlchars/xml/1.0/ed4.js create mode 100644 vanilla/node_modules/xmlchars/xml/1.0/ed4.js.map create mode 100644 vanilla/node_modules/xmlchars/xml/1.0/ed5.d.ts create mode 100644 vanilla/node_modules/xmlchars/xml/1.0/ed5.js create mode 100644 vanilla/node_modules/xmlchars/xml/1.0/ed5.js.map create mode 100644 vanilla/node_modules/xmlchars/xml/1.1/ed2.d.ts create mode 100644 vanilla/node_modules/xmlchars/xml/1.1/ed2.js create mode 100644 vanilla/node_modules/xmlchars/xml/1.1/ed2.js.map create mode 100644 vanilla/node_modules/xmlchars/xmlchars.d.ts create mode 100644 vanilla/node_modules/xmlchars/xmlchars.js create mode 100644 vanilla/node_modules/xmlchars/xmlchars.js.map create mode 100644 vanilla/node_modules/xmlchars/xmlns/1.0/ed3.d.ts create mode 100644 vanilla/node_modules/xmlchars/xmlns/1.0/ed3.js create mode 100644 vanilla/node_modules/xmlchars/xmlns/1.0/ed3.js.map (limited to 'vanilla/node_modules') diff --git a/vanilla/node_modules/.bin/esbuild b/vanilla/node_modules/.bin/esbuild new file mode 120000 index 0000000..c83ac07 --- /dev/null +++ b/vanilla/node_modules/.bin/esbuild @@ -0,0 +1 @@ +../esbuild/bin/esbuild \ No newline at end of file diff --git a/vanilla/node_modules/.bin/nanoid b/vanilla/node_modules/.bin/nanoid new file mode 120000 index 0000000..e2be547 --- /dev/null +++ b/vanilla/node_modules/.bin/nanoid @@ -0,0 +1 @@ +../nanoid/bin/nanoid.cjs \ No newline at end of file diff --git a/vanilla/node_modules/.bin/parser b/vanilla/node_modules/.bin/parser new file mode 120000 index 0000000..ce7bf97 --- /dev/null +++ b/vanilla/node_modules/.bin/parser @@ -0,0 +1 @@ +../@babel/parser/bin/babel-parser.js \ No newline at end of file diff --git a/vanilla/node_modules/.bin/rollup b/vanilla/node_modules/.bin/rollup new file mode 120000 index 0000000..5939621 --- /dev/null +++ b/vanilla/node_modules/.bin/rollup @@ -0,0 +1 @@ +../rollup/dist/bin/rollup \ No newline at end of file diff --git a/vanilla/node_modules/.bin/semver b/vanilla/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/vanilla/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/vanilla/node_modules/.bin/tldts b/vanilla/node_modules/.bin/tldts new file mode 120000 index 0000000..8500124 --- /dev/null +++ b/vanilla/node_modules/.bin/tldts @@ -0,0 +1 @@ +../tldts/bin/cli.js \ No newline at end of file diff --git a/vanilla/node_modules/.bin/vite b/vanilla/node_modules/.bin/vite new file mode 120000 index 0000000..6d1e3be --- /dev/null +++ b/vanilla/node_modules/.bin/vite @@ -0,0 +1 @@ +../vite/bin/vite.js \ No newline at end of file diff --git a/vanilla/node_modules/.bin/vitest b/vanilla/node_modules/.bin/vitest new file mode 120000 index 0000000..2273497 --- /dev/null +++ b/vanilla/node_modules/.bin/vitest @@ -0,0 +1 @@ +../vitest/vitest.mjs \ No newline at end of file diff --git a/vanilla/node_modules/.bin/why-is-node-running b/vanilla/node_modules/.bin/why-is-node-running new file mode 120000 index 0000000..f08a594 --- /dev/null +++ b/vanilla/node_modules/.bin/why-is-node-running @@ -0,0 +1 @@ +../why-is-node-running/cli.js \ No newline at end of file diff --git a/vanilla/node_modules/.package-lock.json b/vanilla/node_modules/.package-lock.json new file mode 100644 index 0000000..d49d9a0 --- /dev/null +++ b/vanilla/node_modules/.package-lock.json @@ -0,0 +1,1414 @@ +{ + "name": "vanilla-frontend", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@acemir/cssom": { + "version": "0.9.31", + "resolved": "https://registry.npmjs.org/@acemir/cssom/-/cssom-0.9.31.tgz", + "integrity": "sha512-ZnR3GSaH+/vJ0YlHau21FjfLYjMpYVIzTD8M8vIEQvIGxeOXyXdzCI140rrCY862p/C/BbzWsjc1dgnM9mkoTA==", + "dev": true + }, + "node_modules/@asamuzakjp/css-color": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-4.1.2.tgz", + "integrity": "sha512-NfBUvBaYgKIuq6E/RBLY1m0IohzNHAYyaJGuTK79Z23uNwmz2jl1mPsC5ZxCCxylinKhT1Amn5oNTlx1wN8cQg==", + "dev": true, + "dependencies": { + "@csstools/css-calc": "^3.0.0", + "@csstools/css-color-parser": "^4.0.1", + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0", + "lru-cache": "^11.2.5" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "6.7.8", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-6.7.8.tgz", + "integrity": "sha512-stisC1nULNc9oH5lakAj8MH88ZxeGxzyWNDfbdCxvJSJIvDsHNZqYvscGTgy/ysgXWLJPt6K/4t0/GjvtKcFJQ==", + "dev": true, + "dependencies": { + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.1.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.5" + } + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.0.tgz", + "integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==", + "dev": true, + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "dev": true, + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.0.1.tgz", + "integrity": "sha512-NmXRccUJMk2AWA5A7e5a//3bCIMyOu2hAtdRYrhPPHjDxINuCwX1w6rnIZ4xjLcp0ayv6h8Pc3X0eJUGiAAXHQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.1.1.tgz", + "integrity": "sha512-HJ26Z/vmsZQqs/o3a6bgKslXGFAungXGbinULZO3eMsOyNJHeBBZfup5FiZInOghgoM4Hwnmw+OgbJCNg1wwUQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.0.1.tgz", + "integrity": "sha512-vYwO15eRBEkeF6xjAno/KQ61HacNhfQuuU/eGwH67DplL0zD5ZixUa563phQvUelA07yDczIXdtmYojCphKJcw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "dependencies": { + "@csstools/color-helpers": "^6.0.1", + "@csstools/css-calc": "^3.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz", + "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.0.27", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.0.27.tgz", + "integrity": "sha512-sxP33Jwg1bviSUXAV43cVYdmjt2TLnLXNqCWl9xmxHawWVjGz/kEbdkr7F9pxJNBN2Mh+dq0crgItbW6tQvyow==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ] + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz", + "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz", + "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@exodus/bytes": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.14.1.tgz", + "integrity": "sha512-OhkBFWI6GcRMUroChZiopRiSp2iAMvEBK47NhJooDqz1RERO4QuZIZnjP63TXX8GAiLABkYmX+fuQsdJ1dd2QQ==", + "dev": true, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.57.1.tgz", + "integrity": "sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.57.1.tgz", + "integrity": "sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true + }, + "node_modules/@vitest/coverage-v8": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.0.18.tgz", + "integrity": "sha512-7i+N2i0+ME+2JFZhfuz7Tg/FqKtilHjGyGvoHYQ6iLV0zahbsJ9sljC9OcFcPDbhYKCet+sG8SsVqlyGvPflZg==", + "dev": true, + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.0.18", + "ast-v8-to-istanbul": "^0.3.10", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.1", + "obug": "^2.1.1", + "std-env": "^3.10.0", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.0.18", + "vitest": "4.0.18" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/expect": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.18.tgz", + "integrity": "sha512-8sCWUyckXXYvx4opfzVY03EOiYVxyNrHS5QxX3DAIi5dpJAAkyJezHCP77VMX4HKA2LDT/Jpfo8i2r5BE3GnQQ==", + "dev": true, + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18", + "chai": "^6.2.1", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.0.18.tgz", + "integrity": "sha512-HhVd0MDnzzsgevnOWCBj5Otnzobjy5wLBe4EdeeFGv8luMsGcYqDuFRMcttKWZA5vVO8RFjexVovXvAM4JoJDQ==", + "dev": true, + "dependencies": { + "@vitest/spy": "4.0.18", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.0.18.tgz", + "integrity": "sha512-P24GK3GulZWC5tz87ux0m8OADrQIUVDPIjjj65vBXYG17ZeU3qD7r+MNZ1RNv4l8CGU2vtTRqixrOi9fYk/yKw==", + "dev": true, + "dependencies": { + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.0.18.tgz", + "integrity": "sha512-rpk9y12PGa22Jg6g5M3UVVnTS7+zycIGk9ZNGN+m6tZHKQb7jrP7/77WfZy13Y/EUDd52NDsLRQhYKtv7XfPQw==", + "dev": true, + "dependencies": { + "@vitest/utils": "4.0.18", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.0.18.tgz", + "integrity": "sha512-PCiV0rcl7jKQjbgYqjtakly6T1uwv/5BQ9SwBLekVg/EaYeQFPiXcgrC2Y7vDMA8dM1SUEAEV82kgSQIlXNMvA==", + "dev": true, + "dependencies": { + "@vitest/pretty-format": "4.0.18", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.0.18.tgz", + "integrity": "sha512-cbQt3PTSD7P2OARdVW3qWER5EGq7PHlvE+QfzSC0lbwO+xnt7+XH06ZzFjFRgzUX//JmpxrCu92VdwvEPlWSNw==", + "dev": true, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.0.18.tgz", + "integrity": "sha512-msMRKLMVLWygpK3u2Hybgi4MNjcYJvwTb0Ru09+fOyCXIgT5raYP041DRRdiJiI3k/2U6SEbAETB3YtBrUkCFA==", + "dev": true, + "dependencies": { + "@vitest/pretty-format": "4.0.18", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "engines": { + "node": ">= 14" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-v8-to-istanbul": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-0.3.11.tgz", + "integrity": "sha512-Qya9fkoofMjCBNVdWINMjB5KZvkYfaO9/anwkWnjxibpWUxo5iHl2sOdP7/uAqaRuUYuoo8rDwnbaaKVFxoUvw==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, + "node_modules/bidi-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", + "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "dev": true, + "dependencies": { + "require-from-string": "^2.0.2" + } + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/css-tree": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.1.0.tgz", + "integrity": "sha512-0eW44TGN5SQXU1mWSkKwFstI/22X2bG1nYzZTYMAWjylYURhse752YgbE4Cx46AC+bAvI+/dYTPRk1LqSUnu6w==", + "dev": true, + "dependencies": { + "mdn-data": "2.12.2", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/cssstyle": { + "version": "5.3.7", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-5.3.7.tgz", + "integrity": "sha512-7D2EPVltRrsTkhpQmksIu+LxeWAIEk6wRDMJ1qljlv+CKHJM+cJLlfhWIzNA44eAsHXSNe3+vO6DW1yCYx8SuQ==", + "dev": true, + "dependencies": { + "@asamuzakjp/css-color": "^4.1.1", + "@csstools/css-syntax-patches-for-csstree": "^1.0.21", + "css-tree": "^3.1.0", + "lru-cache": "^11.2.4" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/data-urls": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz", + "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==", + "dev": true, + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true + }, + "node_modules/esbuild": { + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz", + "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.3", + "@esbuild/android-arm": "0.27.3", + "@esbuild/android-arm64": "0.27.3", + "@esbuild/android-x64": "0.27.3", + "@esbuild/darwin-arm64": "0.27.3", + "@esbuild/darwin-x64": "0.27.3", + "@esbuild/freebsd-arm64": "0.27.3", + "@esbuild/freebsd-x64": "0.27.3", + "@esbuild/linux-arm": "0.27.3", + "@esbuild/linux-arm64": "0.27.3", + "@esbuild/linux-ia32": "0.27.3", + "@esbuild/linux-loong64": "0.27.3", + "@esbuild/linux-mips64el": "0.27.3", + "@esbuild/linux-ppc64": "0.27.3", + "@esbuild/linux-riscv64": "0.27.3", + "@esbuild/linux-s390x": "0.27.3", + "@esbuild/linux-x64": "0.27.3", + "@esbuild/netbsd-arm64": "0.27.3", + "@esbuild/netbsd-x64": "0.27.3", + "@esbuild/openbsd-arm64": "0.27.3", + "@esbuild/openbsd-x64": "0.27.3", + "@esbuild/openharmony-arm64": "0.27.3", + "@esbuild/sunos-x64": "0.27.3", + "@esbuild/win32-arm64": "0.27.3", + "@esbuild/win32-ia32": "0.27.3", + "@esbuild/win32-x64": "0.27.3" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", + "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", + "dev": true, + "dependencies": { + "@exodus/bytes": "^1.6.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true + }, + "node_modules/jsdom": { + "version": "28.0.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-28.0.0.tgz", + "integrity": "sha512-KDYJgZ6T2TKdU8yBfYueq5EPG/EylMsBvCaenWMJb2OXmjgczzwveRCoJ+Hgj1lXPDyasvrgneSn4GBuR1hYyA==", + "dev": true, + "dependencies": { + "@acemir/cssom": "^0.9.31", + "@asamuzakjp/dom-selector": "^6.7.6", + "@exodus/bytes": "^1.11.0", + "cssstyle": "^5.3.7", + "data-urls": "^7.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^6.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "parse5": "^8.0.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^6.0.0", + "undici": "^7.20.0", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/lru-cache": { + "version": "11.2.6", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.6.tgz", + "integrity": "sha512-ESL2CrkS/2wTPfuend7Zhkzo2u0daGJ/A2VucJOgQ/C48S/zB8MMeMHSGKYpXhIjbPxfuezITkaBH1wqv00DDQ==", + "dev": true, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magicast": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.2.tgz", + "integrity": "sha512-E3ZJh4J3S9KfwdjZhe2afj6R9lGIN5Pher1pF39UGrXRqq/VDaGVIGN13BjHd2u8B61hArAGOnso7nBOouW3TQ==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", + "source-map-js": "^1.2.1" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mdn-data": { + "version": "2.12.2", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.12.2.tgz", + "integrity": "sha512-IEn+pegP1aManZuckezWCO+XZQDplx1366JoVhTpMpBB1sPey/SbveZQUosKiKiGYjg1wH4pMlNgXbCiYgihQA==", + "dev": true + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ] + }, + "node_modules/parse5": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.0.tgz", + "integrity": "sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA==", + "dev": true, + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.57.1.tgz", + "integrity": "sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A==", + "dev": true, + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.57.1", + "@rollup/rollup-android-arm64": "4.57.1", + "@rollup/rollup-darwin-arm64": "4.57.1", + "@rollup/rollup-darwin-x64": "4.57.1", + "@rollup/rollup-freebsd-arm64": "4.57.1", + "@rollup/rollup-freebsd-x64": "4.57.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.57.1", + "@rollup/rollup-linux-arm-musleabihf": "4.57.1", + "@rollup/rollup-linux-arm64-gnu": "4.57.1", + "@rollup/rollup-linux-arm64-musl": "4.57.1", + "@rollup/rollup-linux-loong64-gnu": "4.57.1", + "@rollup/rollup-linux-loong64-musl": "4.57.1", + "@rollup/rollup-linux-ppc64-gnu": "4.57.1", + "@rollup/rollup-linux-ppc64-musl": "4.57.1", + "@rollup/rollup-linux-riscv64-gnu": "4.57.1", + "@rollup/rollup-linux-riscv64-musl": "4.57.1", + "@rollup/rollup-linux-s390x-gnu": "4.57.1", + "@rollup/rollup-linux-x64-gnu": "4.57.1", + "@rollup/rollup-linux-x64-musl": "4.57.1", + "@rollup/rollup-openbsd-x64": "4.57.1", + "@rollup/rollup-openharmony-arm64": "4.57.1", + "@rollup/rollup-win32-arm64-msvc": "4.57.1", + "@rollup/rollup-win32-ia32-msvc": "4.57.1", + "@rollup/rollup-win32-x64-gnu": "4.57.1", + "@rollup/rollup-win32-x64-msvc": "4.57.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true + }, + "node_modules/tinyexec": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", + "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "dev": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.0.3.tgz", + "integrity": "sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q==", + "dev": true, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "7.0.23", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.0.23.tgz", + "integrity": "sha512-ASdhgQIBSay0R/eXggAkQ53G4nTJqTXqC2kbaBbdDwM7SkjyZyO0OaaN1/FH7U/yCeqOHDwFO5j8+Os/IS1dXw==", + "dev": true, + "dependencies": { + "tldts-core": "^7.0.23" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.0.23", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.0.23.tgz", + "integrity": "sha512-0g9vrtDQLrNIiCj22HSe9d4mLVG3g5ph5DZ8zCKBr4OtrspmNB6ss7hVyzArAeE88ceZocIEGkyW1Ime7fxPtQ==", + "dev": true + }, + "node_modules/tough-cookie": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.0.tgz", + "integrity": "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w==", + "dev": true, + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/undici": { + "version": "7.22.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.22.0.tgz", + "integrity": "sha512-RqslV2Us5BrllB+JeiZnK4peryVTndy9Dnqq62S3yYRRTj0tFQCwEniUy2167skdGOy3vqRzEvl1Dm4sV2ReDg==", + "dev": true, + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/vite": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", + "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", + "dev": true, + "dependencies": { + "esbuild": "^0.27.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.0.18.tgz", + "integrity": "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ==", + "dev": true, + "dependencies": { + "@vitest/expect": "4.0.18", + "@vitest/mocker": "4.0.18", + "@vitest/pretty-format": "4.0.18", + "@vitest/runner": "4.0.18", + "@vitest/snapshot": "4.0.18", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18", + "es-module-lexer": "^1.7.0", + "expect-type": "^1.2.2", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^3.10.0", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.0.3", + "vite": "^6.0.0 || ^7.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.0.18", + "@vitest/browser-preview": "4.0.18", + "@vitest/browser-webdriverio": "4.0.18", + "@vitest/ui": "4.0.18", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "16.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.0.tgz", + "integrity": "sha512-9CcxtEKsf53UFwkSUZjG+9vydAsFO4lFHBpJUtjBcoJOCJpKnSJNwCw813zrYJHpCJ7sgfbtOe0V5Ku7Pa1XMQ==", + "dev": true, + "dependencies": { + "@exodus/bytes": "^1.11.0", + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true + } + } +} diff --git a/vanilla/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json b/vanilla/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json new file mode 100644 index 0000000..bce6a69 --- /dev/null +++ b/vanilla/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json @@ -0,0 +1 @@ +{"version":"4.0.18","results":[[":app.test.js",{"duration":80.13193000000001,"failed":false}]]} \ No newline at end of file diff --git a/vanilla/node_modules/@acemir/cssom/LICENSE.txt b/vanilla/node_modules/@acemir/cssom/LICENSE.txt new file mode 100644 index 0000000..bc57aac --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) Nikita Vasilyev + +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/vanilla/node_modules/@acemir/cssom/README.mdown b/vanilla/node_modules/@acemir/cssom/README.mdown new file mode 100644 index 0000000..8684ece --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/README.mdown @@ -0,0 +1,64 @@ +# CSSOM + +CSSOM.js is a CSS parser written in pure JavaScript. It is also a partial implementation of [CSS Object Model](http://dev.w3.org/csswg/cssom/). + + CSSOM.parse("body {color: black}") + -> { + cssRules: [ + { + selectorText: "body", + style: { + 0: "color", + color: "black", + length: 1 + } + } + ] + } + + +## [Parser demo](https://acemir.github.io/CSSOM/docs/parse.html) + +Works well in Google Chrome 6+, Safari 5+, Firefox 3.6+, Opera 10.63+. +Doesn't work in IE < 9 because of unsupported getters/setters. + +To use CSSOM.js in the browser you might want to build a one-file version that exposes a single `CSSOM` global variable: + + ➤ git clone https://github.com/acemir/CSSOM.git + ➤ cd CSSOM + ➤ node build.js + build/CSSOM.js is done + +To use it with Node.js or any other CommonJS loader: + + ➤ npm install @acemir/cssom + +## Don’t use it if... + +You parse CSS to mungle, minify or reformat code like this: + +```css +div { + background: gray; + background: linear-gradient(to bottom, white 0%, black 100%); +} +``` + +This pattern is often used to give browsers that don’t understand linear gradients a fallback solution (e.g. gray color in the example). +In CSSOM, `background: gray` [gets overwritten](http://nv.github.io/CSSOM/docs/parse.html#css=div%20%7B%0A%20%20%20%20%20%20background%3A%20gray%3B%0A%20%20%20%20background%3A%20linear-gradient(to%20bottom%2C%20white%200%25%2C%20black%20100%25)%3B%0A%7D). +It does **NOT** get preserved. + +If you do CSS mungling, minification, or image inlining, considere using one of the following: + + * [postcss](https://github.com/postcss/postcss) + * [reworkcss/css](https://github.com/reworkcss/css) + * [csso](https://github.com/css/csso) + * [mensch](https://github.com/brettstimmerman/mensch) + + +## [Tests](https://acemir.github.io/CSSOM/spec/) + +To run tests locally: + + ➤ git submodule init + ➤ git submodule update diff --git a/vanilla/node_modules/@acemir/cssom/build/CSSOM.js b/vanilla/node_modules/@acemir/cssom/build/CSSOM.js new file mode 100644 index 0000000..f4f7ddb --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/build/CSSOM.js @@ -0,0 +1,6611 @@ +var CSSOM = { + /** + * Creates and configures a new CSSOM instance with the specified options. + * + * @param {Object} opts - Configuration options for the CSSOM instance + * @param {Object} [opts.globalObject] - Optional global object to be assigned to CSSOM objects prototype + * @returns {Object} A new CSSOM instance with the applied configuration + * @description + * This method creates a new instance of CSSOM and optionally + * configures CSSStyleSheet with a global object reference. When a globalObject is provided + * and CSSStyleSheet exists on the instance, it creates a new CSSStyleSheet constructor + * using a factory function and assigns the globalObject to its prototype's __globalObject property. + */ + setup: function (opts) { + var instance = Object.create(this); + if (opts.globalObject) { + if (instance.CSSStyleSheet) { + var factoryCSSStyleSheet = createFunctionFactory(instance.CSSStyleSheet); + var CSSStyleSheet = factoryCSSStyleSheet(); + CSSStyleSheet.prototype.__globalObject = opts.globalObject; + + instance.CSSStyleSheet = CSSStyleSheet; + } + } + return instance; + } +}; + +function createFunctionFactory(fn) { + return function() { + // Create a new function that delegates to the original + var newFn = function() { + return fn.apply(this, arguments); + }; + + // Copy prototype chain + Object.setPrototypeOf(newFn, Object.getPrototypeOf(fn)); + + // Copy own properties + for (var key in fn) { + if (Object.prototype.hasOwnProperty.call(fn, key)) { + newFn[key] = fn[key]; + } + } + + // Clone the .prototype object for constructor-like behavior + if (fn.prototype) { + newFn.prototype = Object.create(fn.prototype); + } + + return newFn; + }; +} + + + +// Utility functions for CSSOM error handling + +/** + * Gets the appropriate error constructor from the global object context. + * Tries to find the error constructor from parentStyleSheet.__globalObject, + * then from __globalObject, then falls back to the native constructor. + * + * @param {Object} context - The CSSOM object (rule, stylesheet, etc.) + * @param {string} errorType - The error type ('TypeError', 'RangeError', 'DOMException', etc.) + * @return {Function} The error constructor + */ +function getErrorConstructor(context, errorType) { + // Try parentStyleSheet.__globalObject first + if (context.parentStyleSheet && context.parentStyleSheet.__globalObject && context.parentStyleSheet.__globalObject[errorType]) { + return context.parentStyleSheet.__globalObject[errorType]; + } + + // Try __parentStyleSheet (alternative naming) + if (context.__parentStyleSheet && context.__parentStyleSheet.__globalObject && context.__parentStyleSheet.__globalObject[errorType]) { + return context.__parentStyleSheet.__globalObject[errorType]; + } + + // Try __globalObject on the context itself + if (context.__globalObject && context.__globalObject[errorType]) { + return context.__globalObject[errorType]; + } + + // Fall back to native constructor + return (typeof global !== 'undefined' && global[errorType]) || + (typeof window !== 'undefined' && window[errorType]) || + eval(errorType); +} + +/** + * Creates an appropriate error with context-aware constructor. + * + * @param {Object} context - The CSSOM object (rule, stylesheet, etc.) + * @param {string} errorType - The error type ('TypeError', 'RangeError', 'DOMException', etc.) + * @param {string} message - The error message + * @param {string} [name] - Optional name for DOMException + */ +function createError(context, errorType, message, name) { + var ErrorConstructor = getErrorConstructor(context, errorType); + return new ErrorConstructor(message, name); +} + +/** + * Creates and throws an appropriate error with context-aware constructor. + * + * @param {Object} context - The CSSOM object (rule, stylesheet, etc.) + * @param {string} errorType - The error type ('TypeError', 'RangeError', 'DOMException', etc.) + * @param {string} message - The error message + * @param {string} [name] - Optional name for DOMException + */ +function throwError(context, errorType, message, name) { + throw createError(context, errorType, message, name); +} + +/** + * Throws a TypeError for missing required arguments. + * + * @param {Object} context - The CSSOM object + * @param {string} methodName - The method name (e.g., 'appendRule') + * @param {string} objectName - The object name (e.g., 'CSSKeyframesRule') + * @param {number} [required=1] - Number of required arguments + * @param {number} [provided=0] - Number of provided arguments + */ +function throwMissingArguments(context, methodName, objectName, required, provided) { + required = required || 1; + provided = provided || 0; + var message = "Failed to execute '" + methodName + "' on '" + objectName + "': " + + required + " argument" + (required > 1 ? "s" : "") + " required, but only " + + provided + " present."; + throwError(context, 'TypeError', message); +} + +/** + * Throws a DOMException for parse errors. + * + * @param {Object} context - The CSSOM object + * @param {string} methodName - The method name + * @param {string} objectName - The object name + * @param {string} rule - The rule that failed to parse + * @param {string} [name='SyntaxError'] - The DOMException name + */ +function throwParseError(context, methodName, objectName, rule, name) { + var message = "Failed to execute '" + methodName + "' on '" + objectName + "': " + + "Failed to parse the rule '" + rule + "'."; + throwError(context, 'DOMException', message, name || 'SyntaxError'); +} + +/** + * Throws a DOMException for index errors. + * + * @param {Object} context - The CSSOM object + * @param {string} methodName - The method name + * @param {string} objectName - The object name + * @param {number} index - The invalid index + * @param {number} maxIndex - The maximum valid index + * @param {string} [name='IndexSizeError'] - The DOMException name + */ +function throwIndexError(context, methodName, objectName, index, maxIndex, name) { + var message = "Failed to execute '" + methodName + "' on '" + objectName + "': " + + "The index provided (" + index + ") is larger than the maximum index (" + maxIndex + ")."; + throwError(context, 'DOMException', message, name || 'IndexSizeError'); +} + +var errorUtils = { + createError: createError, + getErrorConstructor: getErrorConstructor, + throwError: throwError, + throwMissingArguments: throwMissingArguments, + throwParseError: throwParseError, + throwIndexError: throwIndexError +}; + +// Shared regex patterns for CSS parsing and validation +// These patterns are compiled once and reused across multiple files for better performance + +// Regex patterns for CSS parsing +var atKeyframesRegExp = /@(-(?:\w+-)+)?keyframes/g; // Match @keyframes and vendor-prefixed @keyframes +var beforeRulePortionRegExp = /{(?!.*{)|}(?!.*})|;(?!.*;)|\*\/(?!.*\*\/)/g; // Match the closest allowed character (a opening or closing brace, a semicolon or a comment ending) before the rule +var beforeRuleValidationRegExp = /^[\s{};]*(\*\/\s*)?$/; // Match that the portion before the rule is empty or contains only whitespace, semicolons, opening/closing braces, and optionally a comment ending (*/) followed by whitespace +var forwardRuleValidationRegExp = /(?:\s|\/\*|\{|\()/; // Match that the rule is followed by any whitespace, a opening comment, a condition opening parenthesis or a opening brace +var forwardImportRuleValidationRegExp = /(?:\s|\/\*|'|")/; // Match that the rule is followed by any whitespace, an opening comment, a single quote or double quote +var forwardRuleClosingBraceRegExp = /{[^{}]*}|}/; // Finds the next closing brace of a rule block +var forwardRuleSemicolonAndOpeningBraceRegExp = /^.*?({|;)/; // Finds the next semicolon or opening brace after the at-rule + +// Regex patterns for CSS selector validation and parsing +var cssCustomIdentifierRegExp = /^(-?[_a-zA-Z]+(\.[_a-zA-Z]+)*[_a-zA-Z0-9-]*)$/; // Validates a css custom identifier +var startsWithCombinatorRegExp = /^\s*[>+~]/; // Checks if a selector starts with a CSS combinator (>, +, ~) + +/** + * Parse `@page` selectorText for page name and pseudo-pages + * Valid formats: + * - (empty - no name, no pseudo-page) + * - `:left`, `:right`, `:first`, `:blank` (pseudo-page only) + * - `named` (named page only) + * - `named:first` (named page with single pseudo-page) + * - `named:first:left` (named page with multiple pseudo-pages) + */ +var atPageRuleSelectorRegExp = /^([^\s:]+)?((?::\w+)*)$/; // Validates @page rule selectors + +// Regex patterns for CSSImportRule parsing +var layerRegExp = /layer\(([^)]*)\)/; // Matches layer() function in @import +var layerRuleNameRegExp = /^(-?[_a-zA-Z]+(\.[_a-zA-Z]+)*[_a-zA-Z0-9-]*)$/; // Validates layer name (same as custom identifier) +var doubleOrMoreSpacesRegExp = /\s{2,}/g; // Matches two or more consecutive whitespace characters + + +// Regex patterns for CSS escape sequences and identifiers +var startsWithHexEscapeRegExp = /^\\[0-9a-fA-F]/; // Checks if escape sequence starts with hex escape +var identStartCharRegExp = /[a-zA-Z_\u00A0-\uFFFF]/; // Valid identifier start character +var identCharRegExp = /^[a-zA-Z0-9_\-\u00A0-\uFFFF\\]/; // Valid identifier character +var specialCharsNeedEscapeRegExp = /[!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~\s]/; // Characters that need escaping +var combinatorOrSeparatorRegExp = /[\s>+~,()]/; // Selector boundaries and combinators +var afterHexEscapeSeparatorRegExp = /[\s>+~,(){}\[\]]/; // Characters that separate after hex escape +var trailingSpaceSeparatorRegExp = /[\s>+~,(){}]/; // Characters that allow trailing space +var endsWithHexEscapeRegExp = /\\[0-9a-fA-F]{1,6}\s+$/; // Matches selector ending with hex escape + space(s) + +/** + * Regular expression to detect invalid characters in the value portion of a CSS style declaration. + * + * This regex matches a colon (:) that is not inside parentheses and not inside single or double quotes. + * It is used to ensure that the value part of a CSS property does not contain unexpected colons, + * which would indicate a malformed declaration (e.g., "color: foo:bar;" is invalid). + * + * The negative lookahead `(?![^(]*\))` ensures that the colon is not followed by a closing + * parenthesis without encountering an opening parenthesis, effectively ignoring colons inside + * function-like values (e.g., `url(data:image/png;base64,...)`). + * + * The lookahead `(?=(?:[^'"]|'[^']*'|"[^"]*")*$)` ensures that the colon is not inside single or double quotes, + * allowing colons within quoted strings (e.g., `content: ":";` or `background: url("foo:bar.png");`). + * + * Example: + * - `color: red;` // valid, does not match + * - `background: url(data:image/png;base64,...);` // valid, does not match + * - `content: ':';` // valid, does not match + * - `color: foo:bar;` // invalid, matches + */ +var basicStylePropertyValueValidationRegExp = /:(?![^(]*\))(?=(?:[^'"]|'[^']*'|"[^"]*")*$)/; + +// Attribute selector pattern: matches attribute-name operator value +// Operators: =, ~=, |=, ^=, $=, *= +// Rewritten to avoid ReDoS by using greedy match and trimming in JavaScript +var attributeSelectorContentRegExp = /^([^\s=~|^$*]+)\s*(~=|\|=|\^=|\$=|\*=|=)\s*(.+)$/; + +// Selector validation patterns +var pseudoElementRegExp = /::[a-zA-Z][\w-]*|:(before|after|first-line|first-letter)(?![a-zA-Z0-9_-])/; // Matches pseudo-elements +var invalidCombinatorLtGtRegExp = /<>/; // Invalid <> combinator +var invalidCombinatorDoubleGtRegExp = />>/; // Invalid >> combinator +var consecutiveCombinatorsRegExp = /[>+~]\s*[>+~]/; // Invalid consecutive combinators +var invalidSlottedRegExp = /(?:^|[\s>+~,\[])slotted\s*\(/i; // Invalid slotted() without :: +var invalidPartRegExp = /(?:^|[\s>+~,\[])part\s*\(/i; // Invalid part() without :: +var invalidCueRegExp = /(?:^|[\s>+~,\[])cue\s*\(/i; // Invalid cue() without :: +var invalidCueRegionRegExp = /(?:^|[\s>+~,\[])cue-region\s*\(/i; // Invalid cue-region() without :: +var invalidNestingPattern = /&(?![.\#\[:>\+~\s])[a-zA-Z]/; // Invalid & followed by type selector +var emptyPseudoClassRegExp = /:(?:is|not|where|has)\(\s*\)/; // Empty pseudo-class like :is() +var whitespaceNormalizationRegExp = /(['"])(?:\\.|[^\\])*?\1|(\r\n|\r|\n)/g; // Normalize newlines outside quotes +var newlineRemovalRegExp = /\n/g; // Remove all newlines +var whitespaceAndDotRegExp = /[\s.]/; // Matches whitespace or dot +var declarationOrOpenBraceRegExp = /[{;}]/; // Matches declaration separator or open brace +var ampersandRegExp = /&/; // Matches nesting selector +var hexEscapeSequenceRegExp = /^([0-9a-fA-F]{1,6})[ \t\r\n\f]?/; // Matches hex escape sequence (1-6 hex digits optionally followed by whitespace) +var attributeCaseFlagRegExp = /^(.+?)\s+([is])$/i; // Matches case-sensitivity flag at end of attribute value +var prependedAmpersandRegExp = /^&\s+[:\\.]/; // Matches prepended ampersand pattern (& followed by space and : or .) +var openBraceGlobalRegExp = /{/g; // Matches opening braces (global) +var closeBraceGlobalRegExp = /}/g; // Matches closing braces (global) +var scopePreludeSplitRegExp = /\s*\)\s*to\s+\(/; // Splits scope prelude by ") to (" +var leadingWhitespaceRegExp = /^\s+/; // Matches leading whitespace (used to implement a ES5-compliant alternative to trimStart()) +var doubleQuoteRegExp = /"/g; // Match all double quotes (for escaping in attribute values) +var backslashRegExp = /\\/g; // Match all backslashes (for escaping in attribute values) + +var regexPatterns = { + // Parsing patterns + atKeyframesRegExp: atKeyframesRegExp, + beforeRulePortionRegExp: beforeRulePortionRegExp, + beforeRuleValidationRegExp: beforeRuleValidationRegExp, + forwardRuleValidationRegExp: forwardRuleValidationRegExp, + forwardImportRuleValidationRegExp: forwardImportRuleValidationRegExp, + forwardRuleClosingBraceRegExp: forwardRuleClosingBraceRegExp, + forwardRuleSemicolonAndOpeningBraceRegExp: forwardRuleSemicolonAndOpeningBraceRegExp, + + // Selector validation patterns + cssCustomIdentifierRegExp: cssCustomIdentifierRegExp, + startsWithCombinatorRegExp: startsWithCombinatorRegExp, + atPageRuleSelectorRegExp: atPageRuleSelectorRegExp, + + // Parsing patterns used in CSSImportRule + layerRegExp: layerRegExp, + layerRuleNameRegExp: layerRuleNameRegExp, + doubleOrMoreSpacesRegExp: doubleOrMoreSpacesRegExp, + + // Escape sequence and identifier patterns + startsWithHexEscapeRegExp: startsWithHexEscapeRegExp, + identStartCharRegExp: identStartCharRegExp, + identCharRegExp: identCharRegExp, + specialCharsNeedEscapeRegExp: specialCharsNeedEscapeRegExp, + combinatorOrSeparatorRegExp: combinatorOrSeparatorRegExp, + afterHexEscapeSeparatorRegExp: afterHexEscapeSeparatorRegExp, + trailingSpaceSeparatorRegExp: trailingSpaceSeparatorRegExp, + endsWithHexEscapeRegExp: endsWithHexEscapeRegExp, + + // Basic style property value validation + basicStylePropertyValueValidationRegExp: basicStylePropertyValueValidationRegExp, + + // Attribute selector patterns + attributeSelectorContentRegExp: attributeSelectorContentRegExp, + + // Selector validation patterns + pseudoElementRegExp: pseudoElementRegExp, + invalidCombinatorLtGtRegExp: invalidCombinatorLtGtRegExp, + invalidCombinatorDoubleGtRegExp: invalidCombinatorDoubleGtRegExp, + consecutiveCombinatorsRegExp: consecutiveCombinatorsRegExp, + invalidSlottedRegExp: invalidSlottedRegExp, + invalidPartRegExp: invalidPartRegExp, + invalidCueRegExp: invalidCueRegExp, + invalidCueRegionRegExp: invalidCueRegionRegExp, + invalidNestingPattern: invalidNestingPattern, + emptyPseudoClassRegExp: emptyPseudoClassRegExp, + whitespaceNormalizationRegExp: whitespaceNormalizationRegExp, + newlineRemovalRegExp: newlineRemovalRegExp, + whitespaceAndDotRegExp: whitespaceAndDotRegExp, + declarationOrOpenBraceRegExp: declarationOrOpenBraceRegExp, + ampersandRegExp: ampersandRegExp, + hexEscapeSequenceRegExp: hexEscapeSequenceRegExp, + attributeCaseFlagRegExp: attributeCaseFlagRegExp, + prependedAmpersandRegExp: prependedAmpersandRegExp, + openBraceGlobalRegExp: openBraceGlobalRegExp, + closeBraceGlobalRegExp: closeBraceGlobalRegExp, + scopePreludeSplitRegExp: scopePreludeSplitRegExp, + leadingWhitespaceRegExp: leadingWhitespaceRegExp, + doubleQuoteRegExp: doubleQuoteRegExp, + backslashRegExp: backslashRegExp +}; + + + + +/** + * @constructor + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration + */ +CSSOM.CSSStyleDeclaration = function CSSStyleDeclaration(){ + this.length = 0; + this.parentRule = null; + + // NON-STANDARD + this._importants = {}; +}; + + +CSSOM.CSSStyleDeclaration.prototype = { + + constructor: CSSOM.CSSStyleDeclaration, + + /** + * + * @param {string} name + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue + * @return {string} the value of the property if it has been explicitly set for this declaration block. + * Returns the empty string if the property has not been set. + */ + getPropertyValue: function(name) { + return this[name] || ""; + }, + + /** + * + * @param {string} name + * @param {string} value + * @param {string} [priority=null] "important" or null + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty + */ + setProperty: function(name, value, priority, parseErrorHandler) + { + // NOTE: Check viability to add a validation for css values or use a dependency like csstree-validator + var basicStylePropertyValueValidationRegExp = regexPatterns.basicStylePropertyValueValidationRegExp + if (basicStylePropertyValueValidationRegExp.test(value)) { + parseErrorHandler && parseErrorHandler('Invalid CSSStyleDeclaration property (name = "' + name + '", value = "' + value + '")'); + } else if (this[name]) { + // Property already exist. Overwrite it. + var index = Array.prototype.indexOf.call(this, name); + if (index < 0) { + this[this.length] = name; + this.length++; + } + + // If the priority value of the incoming property is "important", + // or the value of the existing property is not "important", + // then remove the existing property and rewrite it. + if (priority || !this._importants[name]) { + this.removeProperty(name); + this[this.length] = name; + this.length++; + this[name] = value + ''; + this._importants[name] = priority; + } + } else { + // New property. + this[this.length] = name; + this.length++; + this[name] = value + ''; + this._importants[name] = priority; + } + }, + + /** + * + * @param {string} name + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty + * @return {string} the value of the property if it has been explicitly set for this declaration block. + * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. + */ + removeProperty: function(name) { + if (!(name in this)) { + return ""; + } + var index = Array.prototype.indexOf.call(this, name); + if (index < 0) { + return ""; + } + var prevValue = this[name]; + this[name] = ""; + + // That's what WebKit and Opera do + Array.prototype.splice.call(this, index, 1); + + // That's what Firefox does + //this[index] = "" + + return prevValue; + }, + + getPropertyCSSValue: function() { + //FIXME + }, + + /** + * + * @param {String} name + */ + getPropertyPriority: function(name) { + return this._importants[name] || ""; + }, + + + /** + * element.style.overflow = "auto" + * element.style.getPropertyShorthand("overflow-x") + * -> "overflow" + */ + getPropertyShorthand: function() { + //FIXME + }, + + isPropertyImplicit: function() { + //FIXME + }, + + // Doesn't work in IE < 9 + get cssText(){ + var properties = []; + for (var i=0, length=this.length; i < length; ++i) { + var name = this[i]; + var value = this.getPropertyValue(name); + var priority = this.getPropertyPriority(name); + if (priority) { + priority = " !" + priority; + } + properties[i] = name + ": " + value + priority + ";"; + } + return properties.join(" "); + }, + + set cssText(text){ + var i, name; + for (i = this.length; i--;) { + name = this[i]; + this[name] = ""; + } + Array.prototype.splice.call(this, 0, this.length); + this._importants = {}; + + var dummyRule = CSSOM.parse('#bogus{' + text + '}').cssRules[0].style; + var length = dummyRule.length; + for (i = 0; i < length; ++i) { + name = dummyRule[i]; + this.setProperty(dummyRule[i], dummyRule.getPropertyValue(name), dummyRule.getPropertyPriority(name)); + } + } +}; + + + +try { + CSSOM.CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; +} catch (e) { + // ignore +} + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#the-cssrule-interface + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSRule + */ +CSSOM.CSSRule = function CSSRule() { + this.__parentRule = null; + this.__parentStyleSheet = null; +}; + +CSSOM.CSSRule.UNKNOWN_RULE = 0; // obsolete +CSSOM.CSSRule.STYLE_RULE = 1; +CSSOM.CSSRule.CHARSET_RULE = 2; // obsolete +CSSOM.CSSRule.IMPORT_RULE = 3; +CSSOM.CSSRule.MEDIA_RULE = 4; +CSSOM.CSSRule.FONT_FACE_RULE = 5; +CSSOM.CSSRule.PAGE_RULE = 6; +CSSOM.CSSRule.KEYFRAMES_RULE = 7; +CSSOM.CSSRule.KEYFRAME_RULE = 8; +CSSOM.CSSRule.MARGIN_RULE = 9; +CSSOM.CSSRule.NAMESPACE_RULE = 10; +CSSOM.CSSRule.COUNTER_STYLE_RULE = 11; +CSSOM.CSSRule.SUPPORTS_RULE = 12; +CSSOM.CSSRule.DOCUMENT_RULE = 13; +CSSOM.CSSRule.FONT_FEATURE_VALUES_RULE = 14; +CSSOM.CSSRule.VIEWPORT_RULE = 15; +CSSOM.CSSRule.REGION_STYLE_RULE = 16; +CSSOM.CSSRule.CONTAINER_RULE = 17; +CSSOM.CSSRule.LAYER_BLOCK_RULE = 18; +CSSOM.CSSRule.STARTING_STYLE_RULE = 1002; + +Object.defineProperties(CSSOM.CSSRule.prototype, { + + constructor: { value: CSSOM.CSSRule }, + + cssRule: { + value: "", + configurable: true, + enumerable: true + }, + + cssText: { + get: function() { + // Default getter: subclasses should override this + return ""; + }, + set: function(cssText) { + return cssText; + } + }, + + parentRule: { + get: function() { + return this.__parentRule + } + }, + + parentStyleSheet: { + get: function() { + return this.__parentStyleSheet + } + }, + + UNKNOWN_RULE: { value: 0, enumerable: true }, // obsolet + STYLE_RULE: { value: 1, enumerable: true }, + CHARSET_RULE: { value: 2, enumerable: true }, // obsolet + IMPORT_RULE: { value: 3, enumerable: true }, + MEDIA_RULE: { value: 4, enumerable: true }, + FONT_FACE_RULE: { value: 5, enumerable: true }, + PAGE_RULE: { value: 6, enumerable: true }, + KEYFRAMES_RULE: { value: 7, enumerable: true }, + KEYFRAME_RULE: { value: 8, enumerable: true }, + MARGIN_RULE: { value: 9, enumerable: true }, + NAMESPACE_RULE: { value: 10, enumerable: true }, + COUNTER_STYLE_RULE: { value: 11, enumerable: true }, + SUPPORTS_RULE: { value: 12, enumerable: true }, + DOCUMENT_RULE: { value: 13, enumerable: true }, + FONT_FEATURE_VALUES_RULE: { value: 14, enumerable: true }, + VIEWPORT_RULE: { value: 15, enumerable: true }, + REGION_STYLE_RULE: { value: 16, enumerable: true }, + CONTAINER_RULE: { value: 17, enumerable: true }, + LAYER_BLOCK_RULE: { value: 18, enumerable: true }, + STARTING_STYLE_RULE: { value: 1002, enumerable: true }, +}); + + + + + +/** + * @constructor + * @see https://drafts.csswg.org/cssom/#the-cssrulelist-interface + */ +CSSOM.CSSRuleList = function CSSRuleList(){ + var arr = new Array(); + Object.setPrototypeOf(arr, CSSOM.CSSRuleList.prototype); + return arr; +}; + +CSSOM.CSSRuleList.prototype = Object.create(Array.prototype); +CSSOM.CSSRuleList.prototype.constructor = CSSOM.CSSRuleList; + +CSSOM.CSSRuleList.prototype.item = function(index) { + return this[index] || null; +}; + + + + + + +/** + * @constructor + * @see https://drafts.csswg.org/css-nesting-1/ + */ +CSSOM.CSSNestedDeclarations = function CSSNestedDeclarations() { + CSSOM.CSSRule.call(this); + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSNestedDeclarations.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSNestedDeclarations.prototype.constructor = CSSOM.CSSNestedDeclarations; + +Object.setPrototypeOf(CSSOM.CSSNestedDeclarations, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSNestedDeclarations.prototype, "type", { + value: 0, + writable: false +}); + +Object.defineProperty(CSSOM.CSSNestedDeclarations.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + } +}); + +Object.defineProperty(CSSOM.CSSNestedDeclarations.prototype, "cssText", { + get: function () { + return this.style.cssText; + } +}); + + + + +/** + * @constructor + * @see https://drafts.csswg.org/cssom/#the-cssgroupingrule-interface + */ +CSSOM.CSSGroupingRule = function CSSGroupingRule() { + CSSOM.CSSRule.call(this); + this.__cssRules = new CSSOM.CSSRuleList(); +}; + +CSSOM.CSSGroupingRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSGroupingRule.prototype.constructor = CSSOM.CSSGroupingRule; + +Object.setPrototypeOf(CSSOM.CSSGroupingRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSGroupingRule.prototype, "cssRules", { + get: function() { + return this.__cssRules; + } +}); + +/** + * Used to insert a new CSS rule to a list of CSS rules. + * + * @example + * cssGroupingRule.cssText + * -> "body{margin:0;}" + * cssGroupingRule.insertRule("img{border:none;}", 1) + * -> 1 + * cssGroupingRule.cssText + * -> "body{margin:0;}img{border:none;}" + * + * @param {string} rule + * @param {number} [index] + * @see https://www.w3.org/TR/cssom-1/#dom-cssgroupingrule-insertrule + * @return {number} The index within the grouping rule's collection of the newly inserted rule. + */ + CSSOM.CSSGroupingRule.prototype.insertRule = function insertRule(rule, index) { + if (rule === undefined && index === undefined) { + errorUtils.throwMissingArguments(this, 'insertRule', this.constructor.name); + } + if (index === void 0) { + index = 0; + } + index = Number(index); + if (index < 0) { + index = 4294967296 + index; + } + if (index > this.cssRules.length) { + errorUtils.throwIndexError(this, 'insertRule', this.constructor.name, index, this.cssRules.length); + } + var ruleToParse = processedRuleToParse = String(rule); + ruleToParse = ruleToParse.trim().replace(/^\/\*[\s\S]*?\*\/\s*/, ""); + var isNestedSelector = this.constructor.name === "CSSStyleRule"; + if (isNestedSelector === false) { + var currentRule = this; + while (currentRule.parentRule) { + currentRule = currentRule.parentRule; + if (currentRule.constructor.name === "CSSStyleRule") { + isNestedSelector = true; + break; + } + } + } + if (isNestedSelector) { + processedRuleToParse = 's { n { } ' + ruleToParse + '}'; + } + var isScopeRule = this.constructor.name === "CSSScopeRule"; + if (isScopeRule) { + if (isNestedSelector) { + processedRuleToParse = 's { ' + '@scope {' + ruleToParse + '}}'; + } else { + processedRuleToParse = '@scope {' + ruleToParse + '}'; + } + } + var parsedRules = new CSSOM.CSSRuleList(); + CSSOM.parse(processedRuleToParse, { + styleSheet: this.parentStyleSheet, + cssRules: parsedRules + }); + if (isScopeRule) { + if (isNestedSelector) { + parsedRules = parsedRules[0].cssRules[0].cssRules; + } else { + parsedRules = parsedRules[0].cssRules + } + } + if (isNestedSelector) { + parsedRules = parsedRules[0].cssRules.slice(1); + } + if (parsedRules.length !== 1) { + if (isNestedSelector && parsedRules.length === 0 && ruleToParse.indexOf('@font-face') === 0) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': " + + "Only conditional nested group rules, style rules, @scope rules, @apply rules, and nested declaration rules may be nested.", + 'HierarchyRequestError'); + } else { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + } + var cssRule = parsedRules[0]; + + if (cssRule.constructor.name === 'CSSNestedDeclarations' && cssRule.style.length === 0) { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + + // Check for rules that cannot be inserted inside a CSSGroupingRule + if (cssRule.constructor.name === 'CSSImportRule' || cssRule.constructor.name === 'CSSNamespaceRule') { + var ruleKeyword = cssRule.constructor.name === 'CSSImportRule' ? '@import' : '@namespace'; + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': " + + "'" + ruleKeyword + "' rules cannot be inserted inside a group rule.", + 'HierarchyRequestError'); + } + + // Check for CSSLayerStatementRule (@layer statement rules) + if (cssRule.constructor.name === 'CSSLayerStatementRule') { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + + cssRule.__parentRule = this; + this.cssRules.splice(index, 0, cssRule); + return index; +}; + +/** + * Used to delete a rule from the grouping rule. + * + * cssGroupingRule.cssText + * -> "img{border:none;}body{margin:0;}" + * cssGroupingRule.deleteRule(0) + * cssGroupingRule.cssText + * -> "body{margin:0;}" + * + * @param {number} index within the grouping rule's rule list of the rule to remove. + * @see https://www.w3.org/TR/cssom-1/#dom-cssgroupingrule-deleterule + */ + CSSOM.CSSGroupingRule.prototype.deleteRule = function deleteRule(index) { + if (index === undefined) { + errorUtils.throwMissingArguments(this, 'deleteRule', this.constructor.name); + } + index = Number(index); + if (index < 0) { + index = 4294967296 + index; + } + if (index >= this.cssRules.length) { + errorUtils.throwIndexError(this, 'deleteRule', this.constructor.name, index, this.cssRules.length); + } + this.cssRules[index].__parentRule = null; + this.cssRules[index].__parentStyleSheet = null; + this.cssRules.splice(index, 1); +}; + + + + + +/** + * @constructor + * @see https://drafts.csswg.org/css-counter-styles/#the-csscounterstylerule-interface + */ +CSSOM.CSSCounterStyleRule = function CSSCounterStyleRule() { + CSSOM.CSSRule.call(this); + this.name = ""; + this.__props = ""; +}; + +CSSOM.CSSCounterStyleRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSCounterStyleRule.prototype.constructor = CSSOM.CSSCounterStyleRule; + +Object.setPrototypeOf(CSSOM.CSSCounterStyleRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSCounterStyleRule.prototype, "type", { + value: 11, + writable: false +}); + +Object.defineProperty(CSSOM.CSSCounterStyleRule.prototype, "cssText", { + get: function() { + // FIXME : Implement real cssText generation based on properties + return "@counter-style " + this.name + " { " + this.__props + " }"; + } +}); + +/** + * NON-STANDARD + * Rule text parser. + * @param {string} cssText + */ +Object.defineProperty(CSSOM.CSSCounterStyleRule.prototype, "parse", { + value: function(cssText) { + // Extract the name from "@counter-style { ... }" + var match = cssText.match(/@counter-style\s+([^\s{]+)\s*\{([^]*)\}/); + if (match) { + this.name = match[1]; + // Get the text inside the brackets and clean it up + var propsText = match[2]; + this.__props = propsText.trim().replace(/\n/g, " ").replace(/(['"])(?:\\.|[^\\])*?\1|(\s{2,})/g, function (match, quote) { + return quote ? match : ' '; + }); + } + } +}); + + + + + +/** + * @constructor + * @see https://drafts.css-houdini.org/css-properties-values-api/#the-css-property-rule-interface + */ +CSSOM.CSSPropertyRule = function CSSPropertyRule() { + CSSOM.CSSRule.call(this); + this.__name = ""; + this.__syntax = ""; + this.__inherits = false; + this.__initialValue = null; +}; + +CSSOM.CSSPropertyRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSPropertyRule.prototype.constructor = CSSOM.CSSPropertyRule; + +Object.setPrototypeOf(CSSOM.CSSPropertyRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "type", { + value: 0, + writable: false +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "cssText", { + get: function() { + var text = "@property " + this.name + " {"; + if (this.syntax !== "") { + text += " syntax: \"" + this.syntax.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + "\";"; + } + text += " inherits: " + (this.inherits ? "true" : "false") + ";"; + if (this.initialValue !== null) { + text += " initial-value: " + this.initialValue + ";"; + } + text += " }"; + return text; + } +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "name", { + get: function() { + return this.__name; + } +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "syntax", { + get: function() { + return this.__syntax; + } +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "inherits", { + get: function() { + return this.__inherits; + } +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "initialValue", { + get: function() { + return this.__initialValue; + } +}); + +/** + * NON-STANDARD + * Rule text parser. + * @param {string} cssText + * @returns {boolean} True if the rule is valid and was parsed successfully + */ +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "parse", { + value: function(cssText) { + // Extract the name from "@property { ... }" + var match = cssText.match(/@property\s+(--[^\s{]+)\s*\{([^]*)\}/); + if (!match) { + return false; + } + + this.__name = match[1]; + var bodyText = match[2]; + + // Parse syntax descriptor (REQUIRED) + var syntaxMatch = bodyText.match(/syntax\s*:\s*(['"])([^]*?)\1\s*;/); + if (!syntaxMatch) { + return false; // syntax is required + } + this.__syntax = syntaxMatch[2]; + + // Syntax cannot be empty + if (this.__syntax === "") { + return false; + } + + // Parse inherits descriptor (REQUIRED) + var inheritsMatch = bodyText.match(/inherits\s*:\s*(true|false)\s*;/); + if (!inheritsMatch) { + return false; // inherits is required + } + this.__inherits = inheritsMatch[1] === "true"; + + // Parse initial-value descriptor (OPTIONAL, but required if syntax is not "*") + var initialValueMatch = bodyText.match(/initial-value\s*:\s*([^;]+);/); + if (initialValueMatch) { + this.__initialValue = initialValueMatch[1].trim(); + } else { + // If syntax is not "*", initial-value is required + if (this.__syntax !== "*") { + return false; + } + } + + return true; // Successfully parsed + } +}); + + + + + +/** + * @constructor + * @see https://www.w3.org/TR/css-conditional-3/#the-cssconditionrule-interface + */ +CSSOM.CSSConditionRule = function CSSConditionRule() { + CSSOM.CSSGroupingRule.call(this); + this.__conditionText = ''; +}; + +CSSOM.CSSConditionRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSConditionRule.prototype.constructor = CSSOM.CSSConditionRule; + +Object.setPrototypeOf(CSSOM.CSSConditionRule, CSSOM.CSSGroupingRule); + +Object.defineProperty(CSSOM.CSSConditionRule.prototype, "conditionText", { + get: function () { + return this.__conditionText; + } +}); + + + + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#cssstylerule + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleRule + */ +CSSOM.CSSStyleRule = function CSSStyleRule() { + CSSOM.CSSGroupingRule.call(this); + this.__selectorText = ""; + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSStyleRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSStyleRule.prototype.constructor = CSSOM.CSSStyleRule; + +Object.setPrototypeOf(CSSOM.CSSStyleRule, CSSOM.CSSGroupingRule); + +Object.defineProperty(CSSOM.CSSStyleRule.prototype, "type", { + value: 1, + writable: false +}); + +Object.defineProperty(CSSOM.CSSStyleRule.prototype, "selectorText", { + get: function() { + return this.__selectorText; + }, + set: function(value) { + if (typeof value === "string") { + // Don't trim if the value ends with a hex escape sequence followed by space + // (e.g., ".\31 " where the space is part of the escape terminator) + var endsWithHexEscapeRegExp = regexPatterns.endsWithHexEscapeRegExp; + var endsWithEscape = endsWithHexEscapeRegExp.test(value); + var trimmedValue = endsWithEscape ? value.replace(/\s+$/, ' ').trimStart() : value.trim(); + + if (trimmedValue === '') { + return; + } + + // TODO: Setting invalid selectorText should be ignored + // There are some validations already on lib/parse.js + // but the same validations should be applied here. + // Check if we can move these validation logic to a shared function. + + this.__selectorText = trimmedValue; + } + }, + configurable: true +}); + +Object.defineProperty(CSSOM.CSSStyleRule.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + }, + configurable: true +}); + +Object.defineProperty(CSSOM.CSSStyleRule.prototype, "cssText", { + get: function() { + var text; + if (this.selectorText) { + var values = ""; + if (this.cssRules.length) { + var valuesArr = [" {"]; + this.style.cssText && valuesArr.push(this.style.cssText); + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + values = valuesArr.join("\n ") + "\n}"; + } else { + values = " {" + (this.style.cssText ? " " + this.style.cssText : "") + " }"; + } + text = this.selectorText + values; + } else { + text = ""; + } + return text; + } +}); + + + + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#the-medialist-interface + */ +CSSOM.MediaList = function MediaList(){ + this.length = 0; +}; + +CSSOM.MediaList.prototype = { + + constructor: CSSOM.MediaList, + + /** + * @return {string} + */ + get mediaText() { + return Array.prototype.join.call(this, ", "); + }, + + /** + * @param {string} value + */ + set mediaText(value) { + if (typeof value === "string") { + var values = value.split(",").filter(function(text){ + return !!text; + }); + var length = this.length = values.length; + for (var i=0; i 1 && parts[0] !== '(' && !parts[0].startsWith('(')) { + return parts[0]; + } + return ""; + } + }, + "containerQuery": { + get: function() { + var parts = this.conditionText.trim().split(/\s+/); + if (parts.length > 1 && parts[0] !== '(' && !parts[0].startsWith('(')) { + return parts.slice(1).join(' '); + } + return this.conditionText; + } + }, +}); + + + + + + +/** + * @constructor + * @see https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface + */ +CSSOM.CSSSupportsRule = function CSSSupportsRule() { + CSSOM.CSSConditionRule.call(this); +}; + +CSSOM.CSSSupportsRule.prototype = Object.create(CSSOM.CSSConditionRule.prototype); +CSSOM.CSSSupportsRule.prototype.constructor = CSSOM.CSSSupportsRule; + +Object.setPrototypeOf(CSSOM.CSSSupportsRule, CSSOM.CSSConditionRule); + +Object.defineProperty(CSSOM.CSSSupportsRule.prototype, "type", { + value: 12, + writable: false +}); + +Object.defineProperty(CSSOM.CSSSupportsRule.prototype, "cssText", { + get: function() { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@supports " + this.conditionText + values; + } +}); + + + + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#cssimportrule + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSImportRule + */ +CSSOM.CSSImportRule = function CSSImportRule() { + CSSOM.CSSRule.call(this); + this.__href = ""; + this.__media = new CSSOM.MediaList(); + this.__layerName = null; + this.__supportsText = null; + this.__styleSheet = new CSSOM.CSSStyleSheet(); +}; + +CSSOM.CSSImportRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSImportRule.prototype.constructor = CSSOM.CSSImportRule; + +Object.setPrototypeOf(CSSOM.CSSImportRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "type", { + value: 3, + writable: false +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "cssText", { + get: function() { + var mediaText = this.media.mediaText; + return "@import url(\"" + this.href.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + "\")" + (this.layerName !== null ? " layer" + (this.layerName && "(" + this.layerName + ")") : "" ) + (this.supportsText ? " supports(" + this.supportsText + ")" : "" ) + (mediaText ? " " + mediaText : "") + ";"; + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "href", { + get: function() { + return this.__href; + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "media", { + get: function() { + return this.__media; + }, + set: function(value) { + if (typeof value === "string") { + this.__media.mediaText = value; + } else { + this.__media = value; + } + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "layerName", { + get: function() { + return this.__layerName; + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "supportsText", { + get: function() { + return this.__supportsText; + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "styleSheet", { + get: function() { + return this.__styleSheet; + } +}); + +/** + * NON-STANDARD + * Rule text parser. + * @param {string} cssText + */ +Object.defineProperty(CSSOM.CSSImportRule.prototype, "parse", { + value: function(cssText) { + var i = 0; + + /** + * @import url(partial.css) screen, handheld; + * || | + * after-import media + * | + * url + */ + var state = ''; + + var buffer = ''; + var index; + + var layerRegExp = regexPatterns.layerRegExp; + var layerRuleNameRegExp = regexPatterns.layerRuleNameRegExp; + var doubleOrMoreSpacesRegExp = regexPatterns.doubleOrMoreSpacesRegExp; + + /** + * Extracts the content inside supports() handling nested parentheses. + * @param {string} text - The text to parse + * @returns {object|null} - {content: string, endIndex: number} or null if not found + */ + function extractSupportsContent(text) { + var supportsIndex = text.indexOf('supports('); + if (supportsIndex !== 0) { + return null; + } + + var depth = 0; + var start = supportsIndex + 'supports('.length; + var i = start; + + for (; i < text.length; i++) { + if (text[i] === '(') { + depth++; + } else if (text[i] === ')') { + if (depth === 0) { + // Found the closing parenthesis for supports() + return { + content: text.slice(start, i), + endIndex: i + }; + } + depth--; + } + } + + return null; // Unbalanced parentheses + } + + for (var character; (character = cssText.charAt(i)); i++) { + + switch (character) { + case ' ': + case '\t': + case '\r': + case '\n': + case '\f': + if (state === 'after-import') { + state = 'url'; + } else { + buffer += character; + } + break; + + case '@': + if (!state && cssText.indexOf('@import', i) === i) { + state = 'after-import'; + i += 'import'.length; + buffer = ''; + } + break; + + case 'u': + if (state === 'media') { + buffer += character; + } + if (state === 'url' && cssText.indexOf('url(', i) === i) { + index = cssText.indexOf(')', i + 1); + if (index === -1) { + throw i + ': ")" not found'; + } + i += 'url('.length; + var url = cssText.slice(i, index); + if (url[0] === url[url.length - 1]) { + if (url[0] === '"' || url[0] === "'") { + url = url.slice(1, -1); + } + } + this.__href = url; + i = index; + state = 'media'; + } + break; + + case '"': + if (state === 'after-import' || state === 'url') { + index = cssText.indexOf('"', i + 1); + if (!index) { + throw i + ": '\"' not found"; + } + this.__href = cssText.slice(i + 1, index); + i = index; + state = 'media'; + } + break; + + case "'": + if (state === 'after-import' || state === 'url') { + index = cssText.indexOf("'", i + 1); + if (!index) { + throw i + ': "\'" not found'; + } + this.__href = cssText.slice(i + 1, index); + i = index; + state = 'media'; + } + break; + + case ';': + if (state === 'media') { + if (buffer) { + var bufferTrimmed = buffer.trim(); + + if (bufferTrimmed.indexOf('layer') === 0) { + var layerMatch = bufferTrimmed.match(layerRegExp); + + if (layerMatch) { + var layerName = layerMatch[1].trim(); + + if (layerName.match(layerRuleNameRegExp) !== null) { + this.__layerName = layerMatch[1].trim(); + bufferTrimmed = bufferTrimmed.replace(layerRegExp, '') + .replace(doubleOrMoreSpacesRegExp, ' ') // Replace double or more spaces with single space + .trim(); + } else { + // REVIEW: In the browser, an empty layer() is not processed as a unamed layer + // and treats the rest of the string as mediaText, ignoring the parse of supports() + if (bufferTrimmed) { + this.media.mediaText = bufferTrimmed; + return; + } + } + } else { + this.__layerName = ""; + bufferTrimmed = bufferTrimmed.substring('layer'.length).trim() + } + } + + var supportsResult = extractSupportsContent(bufferTrimmed); + + if (supportsResult) { + // REVIEW: In the browser, an empty supports() invalidates and ignores the entire @import rule + this.__supportsText = supportsResult.content.trim(); + // Remove the entire supports(...) from the buffer + bufferTrimmed = bufferTrimmed.slice(0, 0) + bufferTrimmed.slice(supportsResult.endIndex + 1); + bufferTrimmed = bufferTrimmed.replace(doubleOrMoreSpacesRegExp, ' ').trim(); + } + + // REVIEW: In the browser, any invalid media is replaced with 'not all' + if (bufferTrimmed) { + this.media.mediaText = bufferTrimmed; + } + } + } + break; + + default: + if (state === 'media') { + buffer += character; + } + break; + } + } + } +}); + + + + + + +/** + * @constructor + * @see https://drafts.csswg.org/cssom/#the-cssnamespacerule-interface + */ +CSSOM.CSSNamespaceRule = function CSSNamespaceRule() { + CSSOM.CSSRule.call(this); + this.__prefix = ""; + this.__namespaceURI = ""; +}; + +CSSOM.CSSNamespaceRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSNamespaceRule.prototype.constructor = CSSOM.CSSNamespaceRule; + +Object.setPrototypeOf(CSSOM.CSSNamespaceRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "type", { + value: 10, + writable: false +}); + +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "cssText", { + get: function() { + return "@namespace" + (this.prefix && " " + this.prefix) + " url(\"" + this.namespaceURI + "\");"; + } +}); + +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "prefix", { + get: function() { + return this.__prefix; + } +}); + +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "namespaceURI", { + get: function() { + return this.__namespaceURI; + } +}); + + +/** + * NON-STANDARD + * Rule text parser. + * @param {string} cssText + */ +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "parse", { + value: function(cssText) { + var newPrefix = ""; + var newNamespaceURI = ""; + + // Remove @namespace and trim + var text = cssText.trim(); + if (text.indexOf('@namespace') === 0) { + text = text.slice('@namespace'.length).trim(); + } + + // Remove trailing semicolon if present + if (text.charAt(text.length - 1) === ';') { + text = text.slice(0, -1).trim(); + } + + // Regex to match valid namespace syntax: + // 1. [optional prefix] url("...") or [optional prefix] url('...') or [optional prefix] url() or [optional prefix] url(unquoted) + // 2. [optional prefix] "..." or [optional prefix] '...' + // The prefix must be a valid CSS identifier (letters, digits, hyphens, underscores, starting with letter or underscore) + var re = /^(?:([a-zA-Z_][a-zA-Z0-9_-]*)\s+)?(?:url\(\s*(?:(['"])(.*?)\2\s*|([^)]*?))\s*\)|(['"])(.*?)\5)$/; + var match = text.match(re); + + if (match) { + // If prefix is present + if (match[1]) { + newPrefix = match[1]; + } + // If url(...) form with quotes + if (typeof match[3] !== "undefined") { + newNamespaceURI = match[3]; + } + // If url(...) form without quotes + else if (typeof match[4] !== "undefined") { + newNamespaceURI = match[4].trim(); + } + // If quoted string form + else if (typeof match[6] !== "undefined") { + newNamespaceURI = match[6]; + } + + this.__prefix = newPrefix; + this.__namespaceURI = newNamespaceURI; + } else { + throw new DOMException("Invalid @namespace rule", "InvalidStateError"); + } + } +}); + + + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#css-font-face-rule + */ +CSSOM.CSSFontFaceRule = function CSSFontFaceRule() { + CSSOM.CSSRule.call(this); + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSFontFaceRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSFontFaceRule.prototype.constructor = CSSOM.CSSFontFaceRule; + +Object.setPrototypeOf(CSSOM.CSSFontFaceRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "type", { + value: 5, + writable: false +}); + +//FIXME +//CSSOM.CSSFontFaceRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSFontFaceRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + } +}); + +// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSFontFaceRule.cpp +Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "cssText", { + get: function() { + return "@font-face {" + (this.style.cssText ? " " + this.style.cssText : "") + " }"; + } +}); + + + + + + +/** + * @constructor + * @see http://www.w3.org/TR/shadow-dom/#host-at-rule + * @see http://html5index.org/Shadow%20DOM%20-%20CSSHostRule.html + * @deprecated This rule was part of early Shadow DOM drafts but was removed in favor of the more flexible :host and :host-context() pseudo-classes in modern CSS for Web Components. + */ +CSSOM.CSSHostRule = function CSSHostRule() { + CSSOM.CSSRule.call(this); + this.cssRules = new CSSOM.CSSRuleList(); +}; + +CSSOM.CSSHostRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSHostRule.prototype.constructor = CSSOM.CSSHostRule; + +Object.setPrototypeOf(CSSOM.CSSHostRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSHostRule.prototype, "type", { + value: 1001, + writable: false +}); + +//FIXME +//CSSOM.CSSHostRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSHostRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSHostRule.prototype, "cssText", { + get: function() { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@host" + values; + } +}); + + + + + + +/** + * @constructor + * @see http://www.w3.org/TR/shadow-dom/#host-at-rule + */ +CSSOM.CSSStartingStyleRule = function CSSStartingStyleRule() { + CSSOM.CSSGroupingRule.call(this); +}; + +CSSOM.CSSStartingStyleRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSStartingStyleRule.prototype.constructor = CSSOM.CSSStartingStyleRule; + +Object.setPrototypeOf(CSSOM.CSSStartingStyleRule, CSSOM.CSSGroupingRule); + +Object.defineProperty(CSSOM.CSSStartingStyleRule.prototype, "type", { + value: 1002, + writable: false +}); + +//FIXME +//CSSOM.CSSStartingStyleRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSStartingStyleRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSStartingStyleRule.prototype, "cssText", { + get: function() { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@starting-style" + values; + } +}); + + + + + + +/** + * @see http://dev.w3.org/csswg/cssom/#the-stylesheet-interface + */ +CSSOM.StyleSheet = function StyleSheet() { + this.__href = null; + this.__ownerNode = null; + this.__title = null; + this.__media = new CSSOM.MediaList(); + this.__parentStyleSheet = null; + this.disabled = false; +}; + +Object.defineProperties(CSSOM.StyleSheet.prototype, { + type: { + get: function() { + return "text/css"; + } + }, + href: { + get: function() { + return this.__href; + } + }, + ownerNode: { + get: function() { + return this.__ownerNode; + } + }, + title: { + get: function() { + return this.__title; + } + }, + media: { + get: function() { + return this.__media; + }, + set: function(value) { + if (typeof value === "string") { + this.__media.mediaText = value; + } else { + this.__media = value; + } + } + }, + parentStyleSheet: { + get: function() { + return this.__parentStyleSheet; + } + } +}); + + + + + +/** + * @constructor + * @param {CSSStyleSheetInit} [opts] - CSSStyleSheetInit options. + * @param {string} [opts.baseURL] - The base URL of the stylesheet. + * @param {boolean} [opts.disabled] - The disabled attribute of the stylesheet. + * @param {MediaList | string} [opts.media] - The media attribute of the stylesheet. + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet + */ +CSSOM.CSSStyleSheet = function CSSStyleSheet(opts) { + CSSOM.StyleSheet.call(this); + this.__constructed = true; + this.__cssRules = new CSSOM.CSSRuleList(); + this.__ownerRule = null; + + if (opts && typeof opts === "object") { + if (opts.baseURL && typeof opts.baseURL === "string") { + this.__baseURL = opts.baseURL; + } + if (opts.media && typeof opts.media === "string") { + this.media.mediaText = opts.media; + } + if (typeof opts.disabled === "boolean") { + this.disabled = opts.disabled; + } + } +}; + + +CSSOM.CSSStyleSheet.prototype = Object.create(CSSOM.StyleSheet.prototype); +CSSOM.CSSStyleSheet.prototype.constructor = CSSOM.CSSStyleSheet; + +Object.setPrototypeOf(CSSOM.CSSStyleSheet, CSSOM.StyleSheet); + +Object.defineProperty(CSSOM.CSSStyleSheet.prototype, "cssRules", { + get: function() { + return this.__cssRules; + } +}); + +Object.defineProperty(CSSOM.CSSStyleSheet.prototype, "rules", { + get: function() { + return this.__cssRules; + } +}); + +Object.defineProperty(CSSOM.CSSStyleSheet.prototype, "ownerRule", { + get: function() { + return this.__ownerRule; + } +}); + +/** + * Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade. + * + * sheet = new Sheet("body {margin: 0}") + * sheet.toString() + * -> "body{margin:0;}" + * sheet.insertRule("img {border: none}", 0) + * -> 0 + * sheet.toString() + * -> "img{border:none;}body{margin:0;}" + * + * @param {string} rule + * @param {number} [index=0] + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-insertRule + * @return {number} The index within the style sheet's rule collection of the newly inserted rule. + */ +CSSOM.CSSStyleSheet.prototype.insertRule = function(rule, index) { + if (rule === undefined && index === undefined) { + errorUtils.throwMissingArguments(this, 'insertRule', this.constructor.name); + } + if (index === void 0) { + index = 0; + } + index = Number(index); + if (index < 0) { + index = 4294967296 + index; + } + if (index > this.cssRules.length) { + errorUtils.throwIndexError(this, 'insertRule', this.constructor.name, index, this.cssRules.length); + } + + var ruleToParse = String(rule); + var parseErrors = []; + var parsedSheet = CSSOM.parse(ruleToParse, undefined, function(err) { + parseErrors.push(err); + } ); + if (parsedSheet.cssRules.length !== 1) { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + var cssRule = parsedSheet.cssRules[0]; + + // Helper function to find the last index of a specific rule constructor + function findLastIndexOfConstructor(rules, constructorName) { + for (var i = rules.length - 1; i >= 0; i--) { + if (rules[i].constructor.name === constructorName) { + return i; + } + } + return -1; + } + + // Helper function to find the first index of a rule that's NOT of specified constructors + function findFirstNonConstructorIndex(rules, constructorNames) { + for (var i = 0; i < rules.length; i++) { + if (constructorNames.indexOf(rules[i].constructor.name) === -1) { + return i; + } + } + return rules.length; + } + + // Validate rule ordering based on CSS specification + if (cssRule.constructor.name === 'CSSImportRule') { + if (this.__constructed === true) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Can't insert @import rules into a constructed stylesheet.", + 'SyntaxError'); + } + // @import rules cannot be inserted after @layer rules that already exist + // They can only be inserted at the beginning or after other @import rules + var firstLayerIndex = findFirstNonConstructorIndex(this.cssRules, ['CSSImportRule']); + if (firstLayerIndex < this.cssRules.length && this.cssRules[firstLayerIndex].constructor.name === 'CSSLayerStatementRule' && index > firstLayerIndex) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + + // Also cannot insert after @namespace or other rules + var firstNonImportIndex = findFirstNonConstructorIndex(this.cssRules, ['CSSImportRule']); + if (index > firstNonImportIndex && firstNonImportIndex < this.cssRules.length && + this.cssRules[firstNonImportIndex].constructor.name !== 'CSSLayerStatementRule') { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + } else if (cssRule.constructor.name === 'CSSNamespaceRule') { + // @namespace rules can come after @layer and @import, but before any other rules + // They cannot come before @import rules + var firstImportIndex = -1; + for (var i = 0; i < this.cssRules.length; i++) { + if (this.cssRules[i].constructor.name === 'CSSImportRule') { + firstImportIndex = i; + break; + } + } + var firstNonImportNamespaceIndex = findFirstNonConstructorIndex(this.cssRules, [ + 'CSSLayerStatementRule', + 'CSSImportRule', + 'CSSNamespaceRule' + ]); + + // Cannot insert before @import rules + if (firstImportIndex !== -1 && index <= firstImportIndex) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + + // Cannot insert if there are already non-special rules + if (firstNonImportNamespaceIndex < this.cssRules.length) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'InvalidStateError'); + } + + // Cannot insert after other types of rules + if (index > firstNonImportNamespaceIndex) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + + + } else if (cssRule.constructor.name === 'CSSLayerStatementRule') { + // @layer statement rules can be inserted anywhere before @import and @namespace + // No additional restrictions beyond what's already handled + } else { + // Any other rule cannot be inserted before @import and @namespace + var firstNonSpecialRuleIndex = findFirstNonConstructorIndex(this.cssRules, [ + 'CSSLayerStatementRule', + 'CSSImportRule', + 'CSSNamespaceRule' + ]); + + if (index < firstNonSpecialRuleIndex) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + + if (parseErrors.filter(function(error) { return !error.isNested; }).length !== 0) { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + } + + cssRule.__parentStyleSheet = this; + this.cssRules.splice(index, 0, cssRule); + return index; +}; + +CSSOM.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index) { + if (index === void 0) { + index = this.cssRules.length; + } + this.insertRule(selector + "{" + styleBlock + "}", index); + return -1; +}; + +/** + * Used to delete a rule from the style sheet. + * + * sheet = new Sheet("img{border:none} body{margin:0}") + * sheet.toString() + * -> "img{border:none;}body{margin:0;}" + * sheet.deleteRule(0) + * sheet.toString() + * -> "body{margin:0;}" + * + * @param {number} index within the style sheet's rule list of the rule to remove. + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-deleteRule + */ +CSSOM.CSSStyleSheet.prototype.deleteRule = function(index) { + if (index === undefined) { + errorUtils.throwMissingArguments(this, 'deleteRule', this.constructor.name); + } + index = Number(index); + if (index < 0) { + index = 4294967296 + index; + } + if (index >= this.cssRules.length) { + errorUtils.throwIndexError(this, 'deleteRule', this.constructor.name, index, this.cssRules.length); + } + if (this.cssRules[index]) { + if (this.cssRules[index].constructor.name == "CSSNamespaceRule") { + var shouldContinue = this.cssRules.every(function (rule) { + return ['CSSImportRule','CSSLayerStatementRule','CSSNamespaceRule'].indexOf(rule.constructor.name) !== -1 + }); + if (!shouldContinue) { + errorUtils.throwError(this, 'DOMException', "Failed to execute 'deleteRule' on '" + this.constructor.name + "': Failed to delete rule.", "InvalidStateError"); + } + } + if (this.cssRules[index].constructor.name == "CSSImportRule") { + this.cssRules[index].styleSheet.__parentStyleSheet = null; + } + + this.cssRules[index].__parentStyleSheet = null; + } + this.cssRules.splice(index, 1); +}; + +CSSOM.CSSStyleSheet.prototype.removeRule = function(index) { + if (index === void 0) { + index = 0; + } + this.deleteRule(index); +}; + + +/** + * Replaces the rules of a {@link CSSStyleSheet} + * + * @returns a promise + * @see https://www.w3.org/TR/cssom-1/#dom-cssstylesheet-replace + */ +CSSOM.CSSStyleSheet.prototype.replace = function(text) { + var _Promise; + if (this.__globalObject && this.__globalObject['Promise']) { + _Promise = this.__globalObject['Promise']; + } else { + _Promise = Promise; + } + var _setTimeout; + if (this.__globalObject && this.__globalObject['setTimeout']) { + _setTimeout = this.__globalObject['setTimeout']; + } else { + _setTimeout = setTimeout; + } + var sheet = this; + return new _Promise(function (resolve, reject) { + // If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException. + if (!sheet.__constructed || sheet.__disallowModification) { + reject(errorUtils.createError(sheet, 'DOMException', + "Failed to execute 'replaceSync' on '" + sheet.constructor.name + "': Not allowed.", + 'NotAllowedError')); + } + // Set the disallow modification flag. + sheet.__disallowModification = true; + + // In parallel, do these steps: + _setTimeout(function() { + // Let rules be the result of running parse a stylesheet's contents from text. + var rules = new CSSOM.CSSRuleList(); + CSSOM.parse(text, { styleSheet: sheet, cssRules: rules }); + // If rules contains one or more @import rules, remove those rules from rules. + var i = 0; + while (i < rules.length) { + if (rules[i].constructor.name === 'CSSImportRule') { + rules.splice(i, 1); + } else { + i++; + } + } + // Set sheet's CSS rules to rules. + sheet.__cssRules.splice.apply(sheet.__cssRules, [0, sheet.__cssRules.length].concat(rules)); + // Unset sheet’s disallow modification flag. + delete sheet.__disallowModification; + // Resolve promise with sheet. + resolve(sheet); + }) + }); +} + +/** + * Synchronously replaces the rules of a {@link CSSStyleSheet} + * + * @see https://www.w3.org/TR/cssom-1/#dom-cssstylesheet-replacesync + */ +CSSOM.CSSStyleSheet.prototype.replaceSync = function(text) { + var sheet = this; + // If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException. + if (!sheet.__constructed || sheet.__disallowModification) { + errorUtils.throwError(sheet, 'DOMException', + "Failed to execute 'replaceSync' on '" + sheet.constructor.name + "': Not allowed.", + 'NotAllowedError'); + } + // Let rules be the result of running parse a stylesheet's contents from text. + var rules = new CSSOM.CSSRuleList(); + CSSOM.parse(text, { styleSheet: sheet, cssRules: rules }); + // If rules contains one or more @import rules, remove those rules from rules. + var i = 0; + while (i < rules.length) { + if (rules[i].constructor.name === 'CSSImportRule') { + rules.splice(i, 1); + } else { + i++; + } + } + // Set sheet's CSS rules to rules. + sheet.__cssRules.splice.apply(sheet.__cssRules, [0, sheet.__cssRules.length].concat(rules)); +} + +/** + * NON-STANDARD + * @return {string} serialize stylesheet + */ +CSSOM.CSSStyleSheet.prototype.toString = function() { + var result = ""; + var rules = this.cssRules; + for (var i=0; i 0 && tempStyleSheet.cssRules[0].cssRules.length > 0) { + parsedRule = tempStyleSheet.cssRules[0].cssRules[0]; + } else { + throw new Error("Failed to parse keyframe rule"); + } + } catch (e) { + errorUtils.throwParseError(this, 'appendRule', 'CSSKeyframesRule', rule); + } + + parsedRule.__parentRule = this; + this.cssRules.push(parsedRule); +}; + +/** + * Deletes a keyframe rule that matches the specified key. + * + * @param {string} select - The keyframe selector to delete (e.g., "50%", "from", "to") + * @see https://www.w3.org/TR/css-animations-1/#dom-csskeyframesrule-deleterule + */ +CSSOM.CSSKeyframesRule.prototype.deleteRule = function deleteRule(select) { + if (arguments.length === 0) { + errorUtils.throwMissingArguments(this, 'deleteRule', 'CSSKeyframesRule'); + } + + var normalizedSelect = this._normalizeKeyText(select); + + for (var i = 0; i < this.cssRules.length; i++) { + var rule = this.cssRules[i]; + if (this._normalizeKeyText(rule.keyText) === normalizedSelect) { + rule.__parentRule = null; + this.cssRules.splice(i, 1); + return; + } + } +}; + +/** + * Finds and returns the keyframe rule that matches the specified key. + * When multiple rules have the same key, returns the last one. + * + * @param {string} select - The keyframe selector to find (e.g., "50%", "from", "to") + * @return {CSSKeyframeRule|null} The matching keyframe rule, or null if not found + * @see https://www.w3.org/TR/css-animations-1/#dom-csskeyframesrule-findrule + */ +CSSOM.CSSKeyframesRule.prototype.findRule = function findRule(select) { + if (arguments.length === 0) { + errorUtils.throwMissingArguments(this, 'findRule', 'CSSKeyframesRule'); + } + + var normalizedSelect = this._normalizeKeyText(select); + + // Iterate backwards to find the last matching rule + for (var i = this.cssRules.length - 1; i >= 0; i--) { + var rule = this.cssRules[i]; + if (this._normalizeKeyText(rule.keyText) === normalizedSelect) { + return rule; + } + } + + return null; +}; + +/** + * Normalizes keyframe selector text for comparison. + * Handles "from" -> "0%" and "to" -> "100%" conversions and trims whitespace. + * + * @private + * @param {string} keyText - The keyframe selector text to normalize + * @return {string} The normalized keyframe selector text + */ +CSSOM.CSSKeyframesRule.prototype._normalizeKeyText = function _normalizeKeyText(keyText) { + if (!keyText) return ''; + + var normalized = keyText.toString().trim().toLowerCase(); + + // Convert keywords to percentages for comparison + if (normalized === 'from') { + return '0%'; + } else if (normalized === 'to') { + return '100%'; + } + + return normalized; +}; + +/** + * Makes CSSKeyframesRule iterable over its cssRules. + * Allows for...of loops and other iterable methods. + */ +if (typeof Symbol !== 'undefined' && Symbol.iterator) { + CSSOM.CSSKeyframesRule.prototype[Symbol.iterator] = function() { + var index = 0; + var cssRules = this.cssRules; + + return { + next: function() { + if (index < cssRules.length) { + return { value: cssRules[index++], done: false }; + } else { + return { done: true }; + } + } + }; + }; +} + +/** + * Adds indexed getters for direct access to cssRules by index. + * This enables rule[0], rule[1], etc. access patterns. + * Works in environments where Proxy is not available (like jsdom). + */ +CSSOM.CSSKeyframesRule.prototype._setupIndexedAccess = function() { + // Remove any existing indexed properties + for (var i = 0; i < 1000; i++) { // reasonable upper limit + if (this.hasOwnProperty(i)) { + delete this[i]; + } else { + break; + } + } + + // Add indexed getters for current cssRules + for (var i = 0; i < this.cssRules.length; i++) { + (function(index) { + Object.defineProperty(this, index, { + get: function() { + return this.cssRules[index]; + }, + enumerable: false, + configurable: true + }); + }.call(this, i)); + } + + // Update length property + Object.defineProperty(this, 'length', { + get: function() { + return this.cssRules.length; + }, + enumerable: false, + configurable: true + }); +}; + + + + + + + + + +/** + * @constructor + * @see http://www.w3.org/TR/css3-animations/#DOM-CSSKeyframeRule + */ +CSSOM.CSSKeyframeRule = function CSSKeyframeRule() { + CSSOM.CSSRule.call(this); + this.keyText = ''; + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSKeyframeRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSKeyframeRule.prototype.constructor = CSSOM.CSSKeyframeRule; + +Object.setPrototypeOf(CSSOM.CSSKeyframeRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "type", { + value: 8, + writable: false +}); + +//FIXME +//CSSOM.CSSKeyframeRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSKeyframeRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + } +}); + +// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSKeyframeRule.cpp +Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "cssText", { + get: function() { + return this.keyText + " {" + (this.style.cssText ? " " + this.style.cssText : "") + " }"; + } +}); + + + + + + +/** + * @constructor + * @see https://developer.mozilla.org/en/CSS/@-moz-document + */ +CSSOM.MatcherList = function MatcherList(){ + this.length = 0; +}; + +CSSOM.MatcherList.prototype = { + + constructor: CSSOM.MatcherList, + + /** + * @return {string} + */ + get matcherText() { + return Array.prototype.join.call(this, ", "); + }, + + /** + * @param {string} value + */ + set matcherText(value) { + // just a temporary solution, actually it may be wrong by just split the value with ',', because a url can include ','. + var values = value.split(","); + var length = this.length = values.length; + for (var i=0; i 1000 ? '1000px' : 'auto'); + * } + */ +CSSOM.CSSValueExpression.prototype.parse = function() { + var token = this._token, + idx = this._idx; + + var character = '', + expression = '', + error = '', + info, + paren = []; + + + for (; ; ++idx) { + character = token.charAt(idx); + + // end of token + if (character === '') { + error = 'css expression error: unfinished expression!'; + break; + } + + switch(character) { + case '(': + paren.push(character); + expression += character; + break; + + case ')': + paren.pop(character); + expression += character; + break; + + case '/': + if ((info = this._parseJSComment(token, idx))) { // comment? + if (info.error) { + error = 'css expression error: unfinished comment in expression!'; + } else { + idx = info.idx; + // ignore the comment + } + } else if ((info = this._parseJSRexExp(token, idx))) { // regexp + idx = info.idx; + expression += info.text; + } else { // other + expression += character; + } + break; + + case "'": + case '"': + info = this._parseJSString(token, idx, character); + if (info) { // string + idx = info.idx; + expression += info.text; + } else { + expression += character; + } + break; + + default: + expression += character; + break; + } + + if (error) { + break; + } + + // end of expression + if (paren.length === 0) { + break; + } + } + + var ret; + if (error) { + ret = { + error: error + }; + } else { + ret = { + idx: idx, + expression: expression + }; + } + + return ret; +}; + + +/** + * + * @return {Object|false} + * - idx: + * - text: + * or + * - error: + * or + * false + * + */ +CSSOM.CSSValueExpression.prototype._parseJSComment = function(token, idx) { + var nextChar = token.charAt(idx + 1), + text; + + if (nextChar === '/' || nextChar === '*') { + var startIdx = idx, + endIdx, + commentEndChar; + + if (nextChar === '/') { // line comment + commentEndChar = '\n'; + } else if (nextChar === '*') { // block comment + commentEndChar = '*/'; + } + + endIdx = token.indexOf(commentEndChar, startIdx + 1 + 1); + if (endIdx !== -1) { + endIdx = endIdx + commentEndChar.length - 1; + text = token.substring(idx, endIdx + 1); + return { + idx: endIdx, + text: text + }; + } else { + var error = 'css expression error: unfinished comment in expression!'; + return { + error: error + }; + } + } else { + return false; + } +}; + + +/** + * + * @return {Object|false} + * - idx: + * - text: + * or + * false + * + */ +CSSOM.CSSValueExpression.prototype._parseJSString = function(token, idx, sep) { + var endIdx = this._findMatchedIdx(token, idx, sep), + text; + + if (endIdx === -1) { + return false; + } else { + text = token.substring(idx, endIdx + sep.length); + + return { + idx: endIdx, + text: text + }; + } +}; + + +/** + * parse regexp in css expression + * + * @return {Object|false} + * - idx: + * - regExp: + * or + * false + */ + +/* + +all legal RegExp + +/a/ +(/a/) +[/a/] +[12, /a/] + +!/a/ + ++/a/ +-/a/ +* /a/ +/ /a/ +%/a/ + +===/a/ +!==/a/ +==/a/ +!=/a/ +>/a/ +>=/a/ +>/a/ +>>>/a/ + +&&/a/ +||/a/ +?/a/ +=/a/ +,/a/ + + delete /a/ + in /a/ +instanceof /a/ + new /a/ + typeof /a/ + void /a/ + +*/ +CSSOM.CSSValueExpression.prototype._parseJSRexExp = function(token, idx) { + var before = token.substring(0, idx).replace(/\s+$/, ""), + legalRegx = [ + /^$/, + /\($/, + /\[$/, + /\!$/, + /\+$/, + /\-$/, + /\*$/, + /\/\s+/, + /\%$/, + /\=$/, + /\>$/, + /<$/, + /\&$/, + /\|$/, + /\^$/, + /\~$/, + /\?$/, + /\,$/, + /delete$/, + /in$/, + /instanceof$/, + /new$/, + /typeof$/, + /void$/ + ]; + + var isLegal = legalRegx.some(function(reg) { + return reg.test(before); + }); + + if (!isLegal) { + return false; + } else { + var sep = '/'; + + // same logic as string + return this._parseJSString(token, idx, sep); + } +}; + + +/** + * + * find next sep(same line) index in `token` + * + * @return {Number} + * + */ +CSSOM.CSSValueExpression.prototype._findMatchedIdx = function(token, idx, sep) { + var startIdx = idx, + endIdx; + + var NOT_FOUND = -1; + + while(true) { + endIdx = token.indexOf(sep, startIdx + 1); + + if (endIdx === -1) { // not found + endIdx = NOT_FOUND; + break; + } else { + var text = token.substring(idx + 1, endIdx), + matched = text.match(/\\+$/); + if (!matched || matched[0] % 2 === 0) { // not escaped + break; + } else { + startIdx = endIdx; + } + } + } + + // boundary must be in the same line(js sting or regexp) + var nextNewLineIdx = token.indexOf('\n', idx + 1); + if (nextNewLineIdx < endIdx) { + endIdx = NOT_FOUND; + } + + + return endIdx; +}; + + + + + + + +/** + * @constructor + * @see https://drafts.csswg.org/css-cascade-6/#cssscoperule + */ +CSSOM.CSSScopeRule = function CSSScopeRule() { + CSSOM.CSSGroupingRule.call(this); + this.__start = null; + this.__end = null; +}; + +CSSOM.CSSScopeRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSScopeRule.prototype.constructor = CSSOM.CSSScopeRule; + +Object.setPrototypeOf(CSSOM.CSSScopeRule, CSSOM.CSSGroupingRule); + +Object.defineProperties(CSSOM.CSSScopeRule.prototype, { + type: { + value: 0, + writable: false, + }, + cssText: { + get: function () { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@scope" + (this.start ? " (" + this.start + ")" : "") + (this.end ? " to (" + this.end + ")" : "") + values; + }, + configurable: true, + enumerable: true, + }, + start: { + get: function () { + return this.__start; + } + }, + end: { + get: function () { + return this.__end; + } + } +}); + + + + +/** + * @constructor + * @see https://drafts.csswg.org/css-cascade-5/#csslayerblockrule + */ +CSSOM.CSSLayerBlockRule = function CSSLayerBlockRule() { + CSSOM.CSSGroupingRule.call(this); + this.name = ""; +}; + +CSSOM.CSSLayerBlockRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSLayerBlockRule.prototype.constructor = CSSOM.CSSLayerBlockRule; + +Object.setPrototypeOf(CSSOM.CSSLayerBlockRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSLayerBlockRule.prototype, "type", { + value: 18, + writable: false +}); + +Object.defineProperties(CSSOM.CSSLayerBlockRule.prototype, { + cssText: { + get: function () { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@layer" + (this.name ? " " + this.name : "") + values; + } + }, +}); + + + + +/** + * @constructor + * @see https://drafts.csswg.org/css-cascade-5/#csslayerstatementrule + */ +CSSOM.CSSLayerStatementRule = function CSSLayerStatementRule() { + CSSOM.CSSRule.call(this); + this.nameList = []; +}; + +CSSOM.CSSLayerStatementRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSLayerStatementRule.prototype.constructor = CSSOM.CSSLayerStatementRule; + +Object.setPrototypeOf(CSSOM.CSSLayerStatementRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSLayerStatementRule.prototype, "type", { + value: 0, + writable: false +}); + +Object.defineProperties(CSSOM.CSSLayerStatementRule.prototype, { + cssText: { + get: function () { + return "@layer " + this.nameList.join(", ") + ";"; + } + }, +}); + + + + + +/** + * @constructor + * @see https://drafts.csswg.org/cssom/#the-csspagerule-interface + */ +CSSOM.CSSPageRule = function CSSPageRule() { + CSSOM.CSSGroupingRule.call(this); + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSPageRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSPageRule.prototype.constructor = CSSOM.CSSPageRule; + +Object.setPrototypeOf(CSSOM.CSSPageRule, CSSOM.CSSGroupingRule); + +Object.defineProperty(CSSOM.CSSPageRule.prototype, "type", { + value: 6, + writable: false +}); + +Object.defineProperty(CSSOM.CSSPageRule.prototype, "selectorText", { + get: function() { + return this.__selectorText; + }, + set: function(value) { + if (typeof value === "string") { + var trimmedValue = value.trim(); + + // Empty selector is valid for @page + if (trimmedValue === '') { + this.__selectorText = ''; + return; + } + + var atPageRuleSelectorRegExp = regexPatterns.atPageRuleSelectorRegExp; + var cssCustomIdentifierRegExp = regexPatterns.cssCustomIdentifierRegExp; + var match = trimmedValue.match(atPageRuleSelectorRegExp); + if (match) { + var pageName = match[1] || ''; + var pseudoPages = match[2] || ''; + + // Validate page name if present + if (pageName) { + // Page name can be an identifier or a string + if (!cssCustomIdentifierRegExp.test(pageName)) { + return; + } + } + + // Validate pseudo-pages if present + if (pseudoPages) { + var pseudos = pseudoPages.split(':').filter(function(p) { return p; }); + var validPseudos = ['left', 'right', 'first', 'blank']; + var allValid = true; + for (var j = 0; j < pseudos.length; j++) { + if (validPseudos.indexOf(pseudos[j].toLowerCase()) === -1) { + allValid = false; + break; + } + } + + if (!allValid) { + return; // Invalid pseudo-page, do nothing + } + } + + this.__selectorText = pageName + pseudoPages.toLowerCase(); + } + } + } +}); + +Object.defineProperty(CSSOM.CSSPageRule.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + } +}); + +Object.defineProperty(CSSOM.CSSPageRule.prototype, "cssText", { + get: function() { + var values = ""; + if (this.cssRules.length) { + var valuesArr = [" {"]; + this.style.cssText && valuesArr.push(this.style.cssText); + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + values = valuesArr.join("\n ") + "\n}"; + } else { + values = " {" + (this.style.cssText ? " " + this.style.cssText : "") + " }"; + } + return "@page" + (this.selectorText ? " " + this.selectorText : "") + values; + } +}); + + + + +/** + * Parses a CSS string and returns a `CSSStyleSheet` object representing the parsed stylesheet. + * + * @param {string} token - The CSS string to parse. + * @param {object} [opts] - Optional parsing options. + * @param {object} [opts.globalObject] - An optional global object to prioritize over the window object. Useful on jsdom webplatform tests. + * @param {Element | ProcessingInstruction} [opts.ownerNode] - The owner node of the stylesheet. + * @param {CSSRule} [opts.ownerRule] - The owner rule of the stylesheet. + * @param {CSSOM.CSSStyleSheet} [opts.styleSheet] - Reuse a style sheet instead of creating a new one (e.g. as `parentStyleSheet`) + * @param {CSSOM.CSSRuleList} [opts.cssRules] - Prepare all rules in this list instead of mutating the style sheet continually + * @param {function|boolean} [errorHandler] - Optional error handler function or `true` to use `console.error`. + * @returns {CSSOM.CSSStyleSheet} The parsed `CSSStyleSheet` object. + */ +CSSOM.parse = function parse(token, opts, errorHandler) { + errorHandler = errorHandler === true ? (console && console.error) : errorHandler; + + var i = 0; + + /** + "before-selector" or + "selector" or + "atRule" or + "atBlock" or + "conditionBlock" or + "before-name" or + "name" or + "before-value" or + "value" + */ + var state = "before-selector"; + + var index; + var buffer = ""; + var valueParenthesisDepth = 0; + var hasUnmatchedQuoteInSelector = false; // Track if current selector has unmatched quote + + var SIGNIFICANT_WHITESPACE = { + "name": true, + "before-name": true, + "selector": true, + "value": true, + "value-parenthesis": true, + "atRule": true, + "importRule-begin": true, + "importRule": true, + "namespaceRule-begin": true, + "namespaceRule": true, + "atBlock": true, + "containerBlock": true, + "conditionBlock": true, + "counterStyleBlock": true, + "propertyBlock": true, + 'documentRule-begin': true, + "scopeBlock": true, + "layerBlock": true, + "pageBlock": true + }; + + var styleSheet; + if (opts && opts.styleSheet) { + styleSheet = opts.styleSheet; + } else { + if (opts && opts.globalObject && opts.globalObject.CSSStyleSheet) { + styleSheet = new opts.globalObject.CSSStyleSheet(); + } else { + styleSheet = new CSSOM.CSSStyleSheet(); + } + styleSheet.__constructed = false; + } + + var topScope; + if (opts && opts.cssRules) { + topScope = { cssRules: opts.cssRules }; + } else { + topScope = styleSheet; + } + + if (opts && opts.ownerNode) { + styleSheet.__ownerNode = opts.ownerNode; + var ownerNodeMedia = opts.ownerNode.media || (opts.ownerNode.getAttribute && opts.ownerNode.getAttribute("media")); + if (ownerNodeMedia) { + styleSheet.media.mediaText = ownerNodeMedia; + } + var ownerNodeTitle = opts.ownerNode.title || (opts.ownerNode.getAttribute && opts.ownerNode.getAttribute("title")); + if (ownerNodeTitle) { + styleSheet.__title = ownerNodeTitle; + } + } + + if (opts && opts.ownerRule) { + styleSheet.__ownerRule = opts.ownerRule; + } + + // @type CSSStyleSheet|CSSMediaRule|CSSContainerRule|CSSSupportsRule|CSSFontFaceRule|CSSKeyframesRule|CSSDocumentRule + var currentScope = topScope; + + // @type CSSMediaRule|CSSContainerRule|CSSSupportsRule|CSSKeyframesRule|CSSDocumentRule + var parentRule; + + var ancestorRules = []; + var prevScope; + + var name, priority = "", styleRule, mediaRule, containerRule, counterStyleRule, propertyRule, supportsRule, importRule, fontFaceRule, keyframesRule, documentRule, hostRule, startingStyleRule, scopeRule, pageRule, layerBlockRule, layerStatementRule, nestedSelectorRule, namespaceRule; + + // Track defined namespace prefixes for validation + var definedNamespacePrefixes = {}; + + // Track which rules have been added + var ruleIdCounter = 0; + var addedToParent = {}; + var addedToTopScope = {}; + var addedToCurrentScope = {}; + + // Helper to get unique ID for tracking rules + function getRuleId(rule) { + if (!rule.__parseId) { + rule.__parseId = ++ruleIdCounter; + } + return rule.__parseId; + } + + // Cache last validation boundary position + // to avoid rescanning the entire token string for each at-rule + var lastValidationBoundary = 0; + + // Pre-compile validation regexes for common at-rules + var validationRegexCache = {}; + function getValidationRegex(atRuleKey) { + if (!validationRegexCache[atRuleKey]) { + var sourceRuleRegExp = atRuleKey === "@import" ? forwardImportRuleValidationRegExp : forwardRuleValidationRegExp; + validationRegexCache[atRuleKey] = new RegExp(atRuleKey + sourceRuleRegExp.source, sourceRuleRegExp.flags); + } + return validationRegexCache[atRuleKey]; + } + + // Import regex patterns from shared module + var atKeyframesRegExp = regexPatterns.atKeyframesRegExp; + var beforeRulePortionRegExp = regexPatterns.beforeRulePortionRegExp; + var beforeRuleValidationRegExp = regexPatterns.beforeRuleValidationRegExp; + var forwardRuleValidationRegExp = regexPatterns.forwardRuleValidationRegExp; + var forwardImportRuleValidationRegExp = regexPatterns.forwardImportRuleValidationRegExp; + + // Pre-compile regexBefore to avoid creating it on every validateAtRule call + var regexBefore = new RegExp(beforeRulePortionRegExp.source, beforeRulePortionRegExp.flags); + var forwardRuleClosingBraceRegExp = regexPatterns.forwardRuleClosingBraceRegExp; + var forwardRuleSemicolonAndOpeningBraceRegExp = regexPatterns.forwardRuleSemicolonAndOpeningBraceRegExp; + var cssCustomIdentifierRegExp = regexPatterns.cssCustomIdentifierRegExp; + var startsWithCombinatorRegExp = regexPatterns.startsWithCombinatorRegExp; + var atPageRuleSelectorRegExp = regexPatterns.atPageRuleSelectorRegExp; + var startsWithHexEscapeRegExp = regexPatterns.startsWithHexEscapeRegExp; + var identStartCharRegExp = regexPatterns.identStartCharRegExp; + var identCharRegExp = regexPatterns.identCharRegExp; + var specialCharsNeedEscapeRegExp = regexPatterns.specialCharsNeedEscapeRegExp; + var combinatorOrSeparatorRegExp = regexPatterns.combinatorOrSeparatorRegExp; + var afterHexEscapeSeparatorRegExp = regexPatterns.afterHexEscapeSeparatorRegExp; + var trailingSpaceSeparatorRegExp = regexPatterns.trailingSpaceSeparatorRegExp; + var endsWithHexEscapeRegExp = regexPatterns.endsWithHexEscapeRegExp; + var attributeSelectorContentRegExp = regexPatterns.attributeSelectorContentRegExp; + var pseudoElementRegExp = regexPatterns.pseudoElementRegExp; + var invalidCombinatorLtGtRegExp = regexPatterns.invalidCombinatorLtGtRegExp; + var invalidCombinatorDoubleGtRegExp = regexPatterns.invalidCombinatorDoubleGtRegExp; + var consecutiveCombinatorsRegExp = regexPatterns.consecutiveCombinatorsRegExp; + var invalidSlottedRegExp = regexPatterns.invalidSlottedRegExp; + var invalidPartRegExp = regexPatterns.invalidPartRegExp; + var invalidCueRegExp = regexPatterns.invalidCueRegExp; + var invalidCueRegionRegExp = regexPatterns.invalidCueRegionRegExp; + var invalidNestingPattern = regexPatterns.invalidNestingPattern; + var emptyPseudoClassRegExp = regexPatterns.emptyPseudoClassRegExp; + var whitespaceNormalizationRegExp = regexPatterns.whitespaceNormalizationRegExp; + var newlineRemovalRegExp = regexPatterns.newlineRemovalRegExp; + var whitespaceAndDotRegExp = regexPatterns.whitespaceAndDotRegExp; + var declarationOrOpenBraceRegExp = regexPatterns.declarationOrOpenBraceRegExp; + var ampersandRegExp = regexPatterns.ampersandRegExp; + var hexEscapeSequenceRegExp = regexPatterns.hexEscapeSequenceRegExp; + var attributeCaseFlagRegExp = regexPatterns.attributeCaseFlagRegExp; + var prependedAmpersandRegExp = regexPatterns.prependedAmpersandRegExp; + var openBraceGlobalRegExp = regexPatterns.openBraceGlobalRegExp; + var closeBraceGlobalRegExp = regexPatterns.closeBraceGlobalRegExp; + var scopePreludeSplitRegExp = regexPatterns.scopePreludeSplitRegExp; + var leadingWhitespaceRegExp = regexPatterns.leadingWhitespaceRegExp; + var doubleQuoteRegExp = regexPatterns.doubleQuoteRegExp; + var backslashRegExp = regexPatterns.backslashRegExp; + + /** + * Searches for the first occurrence of a CSS at-rule statement terminator (`;` or `}`) + * that is not inside a brace block within the given string. Mimics the behavior of a + * regular expression match for such terminators, including any trailing whitespace. + * @param {string} str - The string to search for at-rule statement terminators. + * @returns {object | null} {0: string, index: number} or null if no match is found. + */ + function atRulesStatemenRegExpES5Alternative(ruleSlice) { + for (var i = 0; i < ruleSlice.length; i++) { + var char = ruleSlice[i]; + + if (char === ';' || char === '}') { + // Simulate negative lookbehind: check if there is a { before this position + var sliceBefore = ruleSlice.substring(0, i); + var openBraceIndex = sliceBefore.indexOf('{'); + + if (openBraceIndex === -1) { + // No { found before, so we treat it as a valid match + var match = char; + var j = i + 1; + + while (j < ruleSlice.length && /\s/.test(ruleSlice[j])) { + match += ruleSlice[j]; + j++; + } + + var matchObj = [match]; + matchObj.index = i; + matchObj.input = ruleSlice; + return matchObj; + } + } + } + + return null; + } + + /** + * Finds the first balanced block (including nested braces) in the string, starting from fromIndex. + * Returns an object similar to RegExp.prototype.match output. + * @param {string} str - The string to search. + * @param {number} [fromIndex=0] - The index to start searching from. + * @returns {object|null} - { 0: matchedString, index: startIndex, input: str } or null if not found. + */ + function matchBalancedBlock(str, fromIndex) { + fromIndex = fromIndex || 0; + var openIndex = str.indexOf('{', fromIndex); + if (openIndex === -1) return null; + var depth = 0; + for (var i = openIndex; i < str.length; i++) { + if (str[i] === '{') { + depth++; + } else if (str[i] === '}') { + depth--; + if (depth === 0) { + var matchedString = str.slice(openIndex, i + 1); + return { + 0: matchedString, + index: openIndex, + input: str + }; + } + } + } + return null; + } + + /** + * Advances the index `i` to skip over a balanced block of curly braces in the given string. + * This is typically used to ignore the contents of a CSS rule block. + * + * @param {number} i - The current index in the string to start searching from. + * @param {string} str - The string containing the CSS code. + * @param {number} fromIndex - The index in the string where the balanced block search should begin. + * @returns {number} The updated index after skipping the balanced block. + */ + function ignoreBalancedBlock(i, str, fromIndex) { + var ruleClosingMatch = matchBalancedBlock(str, fromIndex); + if (ruleClosingMatch) { + var ignoreRange = ruleClosingMatch.index + ruleClosingMatch[0].length; + i += ignoreRange; + if (token.charAt(i) === '}') { + i -= 1; + } + } else { + i += str.length; + } + return i; + } + + /** + * Parses the scope prelude and extracts start and end selectors. + * @param {string} preludeContent - The scope prelude content (without @scope keyword) + * @returns {object} Object with startSelector and endSelector properties + */ + function parseScopePrelude(preludeContent) { + var parts = preludeContent.split(scopePreludeSplitRegExp); + + // Restore the parentheses that were consumed by the split + if (parts.length === 2) { + parts[0] = parts[0] + ')'; + parts[1] = '(' + parts[1]; + } + + var hasStart = parts[0] && + parts[0].charAt(0) === '(' && + parts[0].charAt(parts[0].length - 1) === ')'; + var hasEnd = parts[1] && + parts[1].charAt(0) === '(' && + parts[1].charAt(parts[1].length - 1) === ')'; + + // Handle case: @scope to () + var hasOnlyEnd = !hasStart && + !hasEnd && + parts[0].indexOf('to (') === 0 && + parts[0].charAt(parts[0].length - 1) === ')'; + + var startSelector = ''; + var endSelector = ''; + + if (hasStart) { + startSelector = parts[0].slice(1, -1).trim(); + } + if (hasEnd) { + endSelector = parts[1].slice(1, -1).trim(); + } + if (hasOnlyEnd) { + endSelector = parts[0].slice(4, -1).trim(); + } + + return { + startSelector: startSelector, + endSelector: endSelector, + hasStart: hasStart, + hasEnd: hasEnd, + hasOnlyEnd: hasOnlyEnd + }; + }; + + /** + * Checks if a selector contains pseudo-elements. + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if the selector contains pseudo-elements + */ + function hasPseudoElement(selector) { + // Match only double-colon (::) pseudo-elements + // Also match legacy single-colon pseudo-elements: :before, :after, :first-line, :first-letter + // These must NOT be followed by alphanumeric characters (to avoid matching :before-x or similar) + return pseudoElementRegExp.test(selector); + }; + + /** + * Validates balanced parentheses, brackets, and quotes in a selector. + * + * @param {string} selector - The CSS selector to validate + * @param {boolean} trackAttributes - Whether to track attribute selector context + * @param {boolean} useStack - Whether to use a stack for parentheses (needed for nested validation) + * @returns {boolean} True if the syntax is valid (all brackets, parentheses, and quotes are balanced) + */ + function validateBalancedSyntax(selector, trackAttributes, useStack) { + var parenDepth = 0; + var bracketDepth = 0; + var inSingleQuote = false; + var inDoubleQuote = false; + var inAttr = false; + var stack = useStack ? [] : null; + + for (var i = 0; i < selector.length; i++) { + var char = selector[i]; + + // Handle escape sequences - skip hex escapes or simple escapes + if (char === '\\') { + var escapeLen = getEscapeSequenceLength(selector, i); + if (escapeLen > 0) { + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + + if (inSingleQuote) { + if (char === "'") { + inSingleQuote = false; + } + } else if (inDoubleQuote) { + if (char === '"') { + inDoubleQuote = false; + } + } else if (trackAttributes && inAttr) { + if (char === "]") { + inAttr = false; + } else if (char === "'") { + inSingleQuote = true; + } else if (char === '"') { + inDoubleQuote = true; + } + } else { + if (trackAttributes && char === "[") { + inAttr = true; + } else if (char === "'") { + inSingleQuote = true; + } else if (char === '"') { + inDoubleQuote = true; + } else if (char === '(') { + if (useStack) { + stack.push("("); + } else { + parenDepth++; + } + } else if (char === ')') { + if (useStack) { + if (!stack.length || stack.pop() !== "(") { + return false; + } + } else { + parenDepth--; + if (parenDepth < 0) { + return false; + } + } + } else if (char === '[') { + bracketDepth++; + } else if (char === ']') { + bracketDepth--; + if (bracketDepth < 0) { + return false; + } + } + } + } + + // Check if everything is balanced + if (useStack) { + return stack.length === 0 && bracketDepth === 0 && !inSingleQuote && !inDoubleQuote && !inAttr; + } else { + return parenDepth === 0 && bracketDepth === 0 && !inSingleQuote && !inDoubleQuote; + } + }; + + /** + * Checks for basic syntax errors in selectors (mismatched parentheses, brackets, quotes). + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if there are syntax errors + */ + function hasBasicSyntaxError(selector) { + return !validateBalancedSyntax(selector, false, false); + }; + + /** + * Checks for invalid combinator patterns in selectors. + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if the selector contains invalid combinators + */ + function hasInvalidCombinators(selector) { + // Check for invalid combinator patterns: + // - <> (not a valid combinator) + // - >> (deep descendant combinator, deprecated and invalid) + // - Multiple consecutive combinators like >>, >~, etc. + if (invalidCombinatorLtGtRegExp.test(selector)) return true; + if (invalidCombinatorDoubleGtRegExp.test(selector)) return true; + // Check for other invalid consecutive combinator patterns + if (consecutiveCombinatorsRegExp.test(selector)) return true; + return false; + }; + + /** + * Checks for invalid pseudo-like syntax (function calls without proper pseudo prefix). + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if the selector contains invalid pseudo-like syntax + */ + function hasInvalidPseudoSyntax(selector) { + // Check for specific known pseudo-elements used without : or :: prefix + // Examples: slotted(div), part(name), cue(selector) + // These are ONLY valid as ::slotted(), ::part(), ::cue() + var invalidPatterns = [ + invalidSlottedRegExp, + invalidPartRegExp, + invalidCueRegExp, + invalidCueRegionRegExp + ]; + + for (var i = 0; i < invalidPatterns.length; i++) { + if (invalidPatterns[i].test(selector)) { + return true; + } + } + return false; + }; + + /** + * Checks for invalid nesting selector (&) usage. + * The & selector cannot be directly followed by a type selector without a delimiter. + * Valid: &.class, &#id, &[attr], &:hover, &::before, & div, &>div + * Invalid: &div, &span + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if the selector contains invalid & usage + */ + function hasInvalidNestingSelector(selector) { + // Check for & followed directly by a letter (type selector) without any delimiter + // This regex matches & followed by a letter (start of type selector) that's not preceded by an escape + // We need to exclude valid cases like &.class, &#id, &[attr], &:pseudo, &::pseudo, & (with space), &> + return invalidNestingPattern.test(selector); + }; + + /** + * Checks if an at-rule can be nested based on parent chain validation. + * Used for at-rules like `@counter-style`, `@property` and `@font-face` rules that can only be nested inside + * `CSSScopeRule` or `CSSConditionRule` without `CSSStyleRule` in parent chain. + * @returns {boolean} `true` if nesting is allowed, `false` otherwise + */ + function canAtRuleBeNested() { + if (currentScope === topScope) { + return true; // Top-level is always allowed + } + + var hasStyleRuleInChain = false; + var hasValidParent = false; + + // Check currentScope + if (currentScope.constructor.name === 'CSSStyleRule') { + hasStyleRuleInChain = true; + } else if (currentScope instanceof CSSOM.CSSScopeRule || currentScope instanceof CSSOM.CSSConditionRule) { + hasValidParent = true; + } + + // Check ancestorRules for CSSStyleRule + if (!hasStyleRuleInChain) { + for (var j = 0; j < ancestorRules.length; j++) { + if (ancestorRules[j].constructor.name === 'CSSStyleRule') { + hasStyleRuleInChain = true; + break; + } + if (ancestorRules[j] instanceof CSSOM.CSSScopeRule || ancestorRules[j] instanceof CSSOM.CSSConditionRule) { + hasValidParent = true; + } + } + } + + // Allow nesting if we have a valid parent and no style rule in the chain + return hasValidParent && !hasStyleRuleInChain; + } + + function validateAtRule(atRuleKey, validCallback, cannotBeNested) { + var isValid = false; + // Use cached regex instead of creating new one each time + var ruleRegExp = getValidationRegex(atRuleKey); + // Only slice what we need for validation (max 100 chars) + // since we only check match at position 0 + var lookAheadLength = Math.min(100, token.length - i); + var ruleSlice = token.slice(i, i + lookAheadLength); + // Not all rules can be nested, if the rule cannot be nested and is in the root scope, do not perform the check + var shouldPerformCheck = cannotBeNested && currentScope !== topScope ? false : true; + // First, check if there is no invalid characters just after the at-rule + if (shouldPerformCheck && ruleSlice.search(ruleRegExp) === 0) { + // Only scan from the last known validation boundary + var searchStart = Math.max(0, lastValidationBoundary); + var beforeSlice = token.slice(searchStart, i); + + // Use pre-compiled regex instead of creating new one each time + var matches = beforeSlice.match(regexBefore); + var lastI = matches ? searchStart + beforeSlice.lastIndexOf(matches[matches.length - 1]) : searchStart; + var toCheckSlice = token.slice(lastI, i); + // Check if we don't have any invalid in the portion before the `at-rule` and the closest allowed character + var checkedSlice = toCheckSlice.search(beforeRuleValidationRegExp); + if (checkedSlice === 0) { + isValid = true; + // Update the validation boundary cache to this position + lastValidationBoundary = lastI; + } + } + + // Additional validation for @scope rule + if (isValid && atRuleKey === "@scope") { + var openBraceIndex = ruleSlice.indexOf('{'); + if (openBraceIndex !== -1) { + // Extract the rule prelude (everything between the at-rule and {) + var rulePrelude = ruleSlice.slice(0, openBraceIndex).trim(); + + // Skip past at-rule keyword and whitespace + var preludeContent = rulePrelude.slice("@scope".length).trim(); + + if (preludeContent.length > 0) { + // Parse the scope prelude + var parsedScopePrelude = parseScopePrelude(preludeContent); + var startSelector = parsedScopePrelude.startSelector; + var endSelector = parsedScopePrelude.endSelector; + var hasStart = parsedScopePrelude.hasStart; + var hasEnd = parsedScopePrelude.hasEnd; + var hasOnlyEnd = parsedScopePrelude.hasOnlyEnd; + + // Validation rules for @scope: + // 1. Empty selectors in parentheses are invalid: @scope () {} or @scope (.a) to () {} + if ((hasStart && startSelector === '') || (hasEnd && endSelector === '') || (hasOnlyEnd && endSelector === '')) { + isValid = false; + } + // 2. Pseudo-elements are invalid in scope selectors + else if ((startSelector && hasPseudoElement(startSelector)) || (endSelector && hasPseudoElement(endSelector))) { + isValid = false; + } + // 3. Basic syntax errors (mismatched parens, brackets, quotes) + else if ((startSelector && hasBasicSyntaxError(startSelector)) || (endSelector && hasBasicSyntaxError(endSelector))) { + isValid = false; + } + // 4. Invalid combinator patterns + else if ((startSelector && hasInvalidCombinators(startSelector)) || (endSelector && hasInvalidCombinators(endSelector))) { + isValid = false; + } + // 5. Invalid pseudo-like syntax (function without : or :: prefix) + else if ((startSelector && hasInvalidPseudoSyntax(startSelector)) || (endSelector && hasInvalidPseudoSyntax(endSelector))) { + isValid = false; + } + // 6. Invalid structure (no proper parentheses found when prelude is not empty) + else if (!hasStart && !hasOnlyEnd) { + isValid = false; + } + } + // Empty prelude (@scope {}) is valid + } + } + + if (isValid && atRuleKey === "@page") { + var openBraceIndex = ruleSlice.indexOf('{'); + if (openBraceIndex !== -1) { + // Extract the rule prelude (everything between the at-rule and {) + var rulePrelude = ruleSlice.slice(0, openBraceIndex).trim(); + + // Skip past at-rule keyword and whitespace + var preludeContent = rulePrelude.slice("@page".length).trim(); + + if (preludeContent.length > 0) { + var trimmedValue = preludeContent.trim(); + + // Empty selector is valid for @page + if (trimmedValue !== '') { + // Parse @page selectorText for page name and pseudo-pages + // Valid formats: + // - (empty - no name, no pseudo-page) + // - :left, :right, :first, :blank (pseudo-page only) + // - named (named page only) + // - named:first (named page with single pseudo-page) + // - named:first:left (named page with multiple pseudo-pages) + var match = trimmedValue.match(atPageRuleSelectorRegExp); + if (match) { + var pageName = match[1] || ''; + var pseudoPages = match[2] || ''; + + // Validate page name if present + if (pageName) { + if (!cssCustomIdentifierRegExp.test(pageName)) { + isValid = false; + } + } + + // Validate pseudo-pages if present + if (pseudoPages) { + var pseudos = pseudoPages.split(':').filter(function (p) { return p; }); + var validPseudos = ['left', 'right', 'first', 'blank']; + var allValid = true; + for (var j = 0; j < pseudos.length; j++) { + if (validPseudos.indexOf(pseudos[j].toLowerCase()) === -1) { + allValid = false; + break; + } + } + + if (!allValid) { + isValid = false; + } + } + } else { + isValid = false; + } + } + + } + } + } + + if (!isValid) { + // If it's invalid the browser will simply ignore the entire invalid block + // Use regex to find the closing brace of the invalid rule + + // Regex used above is not ES5 compliant. Using alternative. + // var ruleStatementMatch = ruleSlice.match(atRulesStatemenRegExp); // + var ruleStatementMatch = atRulesStatemenRegExpES5Alternative(ruleSlice); + + // If it's a statement inside a nested rule, ignore only the statement + if (ruleStatementMatch && currentScope !== topScope) { + var ignoreEnd = ruleStatementMatch[0].indexOf(";"); + i += ruleStatementMatch.index + ignoreEnd; + return; + } + + // Check if there's a semicolon before the invalid at-rule and the first opening brace + if (atRuleKey === "@layer") { + var ruleSemicolonAndOpeningBraceMatch = ruleSlice.match(forwardRuleSemicolonAndOpeningBraceRegExp); + if (ruleSemicolonAndOpeningBraceMatch && ruleSemicolonAndOpeningBraceMatch[1] === ";") { + // Ignore the rule block until the semicolon + i += ruleSemicolonAndOpeningBraceMatch.index + ruleSemicolonAndOpeningBraceMatch[0].length; + state = "before-selector"; + return; + } + } + + // Ignore the entire rule block (if it's a statement it should ignore the statement plus the next block) + i = ignoreBalancedBlock(i, ruleSlice); + state = "before-selector"; + } else { + validCallback.call(this); + } + } + + // Helper functions for looseSelectorValidator + // Defined outside to avoid recreation on every validation call + + /** + * Check if character is a valid identifier start + * @param {string} c - Character to check + * @returns {boolean} + */ + function isIdentStart(c) { + return /[a-zA-Z_\u00A0-\uFFFF]/.test(c); + } + + /** + * Check if character is a valid identifier character + * @param {string} c - Character to check + * @returns {boolean} + */ + function isIdentChar(c) { + return /[a-zA-Z0-9_\u00A0-\uFFFF\-]/.test(c); + } + + /** + * Helper function to validate CSS selector syntax without regex backtracking. + * Iteratively parses the selector string to identify valid components. + * + * Supports: + * - Escaped characters (e.g., .class\!, #id\@name) + * - Namespace selectors (ns|element, *|element, |element) + * - All standard CSS selectors (class, ID, type, attribute, pseudo, etc.) + * - Combinators (>, +, ~, whitespace) + * - Nesting selector (&) + * + * This approach eliminates exponential backtracking by using explicit character-by-character + * parsing instead of nested quantifiers in regex. + * + * @param {string} selector - The selector to validate + * @returns {boolean} - True if valid selector syntax + */ + function looseSelectorValidator(selector) { + if (!selector || selector.length === 0) { + return false; + } + + var i = 0; + var len = selector.length; + var hasMatchedComponent = false; + + // Helper: Skip escaped character (backslash + hex escape or any char) + function skipEscape() { + if (i < len && selector[i] === '\\') { + var escapeLen = getEscapeSequenceLength(selector, i); + if (escapeLen > 0) { + i += escapeLen; // Skip entire escape sequence + return true; + } + } + return false; + } + + // Helper: Parse identifier (with possible escapes) + function parseIdentifier() { + var start = i; + while (i < len) { + if (skipEscape()) { + continue; + } else if (isIdentChar(selector[i])) { + i++; + } else { + break; + } + } + return i > start; + } + + // Helper: Parse namespace prefix (optional) + function parseNamespace() { + var start = i; + + // Match: *| or identifier| or | + if (i < len && selector[i] === '*') { + i++; + } else if (i < len && (isIdentStart(selector[i]) || selector[i] === '\\')) { + parseIdentifier(); + } + + if (i < len && selector[i] === '|') { + i++; + return true; + } + + // Rollback if no pipe found + i = start; + return false; + } + + // Helper: Parse pseudo-class/element arguments (with balanced parens) + function parsePseudoArgs() { + if (i >= len || selector[i] !== '(') { + return false; + } + + i++; // Skip opening paren + var depth = 1; + var inString = false; + var stringChar = ''; + + while (i < len && depth > 0) { + var c = selector[i]; + + if (c === '\\' && i + 1 < len) { + i += 2; // Skip escaped character + } else if (!inString && (c === '"' || c === '\'')) { + inString = true; + stringChar = c; + i++; + } else if (inString && c === stringChar) { + inString = false; + i++; + } else if (!inString && c === '(') { + depth++; + i++; + } else if (!inString && c === ')') { + depth--; + i++; + } else { + i++; + } + } + + return depth === 0; + } + + // Main parsing loop + while (i < len) { + var matched = false; + var start = i; + + // Skip whitespace + while (i < len && /\s/.test(selector[i])) { + i++; + } + if (i > start) { + hasMatchedComponent = true; + continue; + } + + // Match combinators: >, +, ~ + if (i < len && /[>+~]/.test(selector[i])) { + i++; + hasMatchedComponent = true; + // Skip trailing whitespace + while (i < len && /\s/.test(selector[i])) { + i++; + } + continue; + } + + // Match nesting selector: & + if (i < len && selector[i] === '&') { + i++; + hasMatchedComponent = true; + matched = true; + } + // Match class selector: .identifier + else if (i < len && selector[i] === '.') { + i++; + if (parseIdentifier()) { + hasMatchedComponent = true; + matched = true; + } + } + // Match ID selector: #identifier + else if (i < len && selector[i] === '#') { + i++; + if (parseIdentifier()) { + hasMatchedComponent = true; + matched = true; + } + } + // Match pseudo-class/element: :identifier or ::identifier + else if (i < len && selector[i] === ':') { + i++; + if (i < len && selector[i] === ':') { + i++; // Pseudo-element + } + if (parseIdentifier()) { + parsePseudoArgs(); // Optional arguments + hasMatchedComponent = true; + matched = true; + } + } + // Match attribute selector: [...] + else if (i < len && selector[i] === '[') { + i++; + var depth = 1; + while (i < len && depth > 0) { + if (selector[i] === '\\') { + i += 2; + } else if (selector[i] === '\'') { + i++; + while (i < len && selector[i] !== '\'') { + if (selector[i] === '\\') i += 2; + else i++; + } + if (i < len) i++; // Skip closing quote + } else if (selector[i] === '"') { + i++; + while (i < len && selector[i] !== '"') { + if (selector[i] === '\\') i += 2; + else i++; + } + if (i < len) i++; // Skip closing quote + } else if (selector[i] === '[') { + depth++; + i++; + } else if (selector[i] === ']') { + depth--; + i++; + } else { + i++; + } + } + if (depth === 0) { + hasMatchedComponent = true; + matched = true; + } + } + // Match type selector with optional namespace: [namespace|]identifier + else if (i < len && (isIdentStart(selector[i]) || selector[i] === '\\' || selector[i] === '*' || selector[i] === '|')) { + parseNamespace(); // Optional namespace prefix + + if (i < len && selector[i] === '*') { + i++; // Universal selector + hasMatchedComponent = true; + matched = true; + } else if (i < len && (isIdentStart(selector[i]) || selector[i] === '\\')) { + if (parseIdentifier()) { + hasMatchedComponent = true; + matched = true; + } + } + } + + // If no match found, invalid selector + if (!matched && i === start) { + return false; + } + } + + return hasMatchedComponent; + } + + /** + * Validates a basic CSS selector, allowing for deeply nested balanced parentheses in pseudo-classes. + * This function replaces the previous basicSelectorRegExp. + * + * This function matches: + * - Type selectors (e.g., `div`, `span`) + * - Universal selector (`*`) + * - Namespace selectors (e.g., `*|div`, `custom|div`, `|div`) + * - ID selectors (e.g., `#header`, `#a\ b`, `#åèiöú`) + * - Class selectors (e.g., `.container`, `.a\ b`, `.åèiöú`) + * - Attribute selectors (e.g., `[type="text"]`) + * - Pseudo-classes and pseudo-elements (e.g., `:hover`, `::before`, `:nth-child(2)`) + * - Pseudo-classes with nested parentheses, including cases where parentheses are nested inside arguments, + * such as `:has(.sel:nth-child(3n))` + * - The parent selector (`&`) + * - Combinators (`>`, `+`, `~`) with optional whitespace + * - Whitespace (descendant combinator) + * + * Unicode and escape sequences are allowed in identifiers. + * + * @param {string} selector + * @returns {boolean} + */ + function basicSelectorValidator(selector) { + // Guard against extremely long selectors to prevent potential regex performance issues + // Reasonable selectors are typically under 1000 characters + if (selector.length > 10000) { + return false; + } + + // Validate balanced syntax with attribute tracking and stack-based parentheses matching + if (!validateBalancedSyntax(selector, true, true)) { + return false; + } + + // Check for invalid combinator patterns + if (hasInvalidCombinators(selector)) { + return false; + } + + // Check for invalid pseudo-like syntax + if (hasInvalidPseudoSyntax(selector)) { + return false; + } + + // Check for invalid nesting selector (&) usage + if (hasInvalidNestingSelector(selector)) { + return false; + } + + // Check for invalid pseudo-class usage with quoted strings + // Pseudo-classes like :lang(), :dir(), :nth-*() should not accept quoted strings + // Using iterative parsing instead of regex to avoid exponential backtracking + var noQuotesPseudos = ['lang', 'dir', 'nth-child', 'nth-last-child', 'nth-of-type', 'nth-last-of-type']; + + for (var idx = 0; idx < selector.length; idx++) { + // Look for pseudo-class/element start + if (selector[idx] === ':') { + var pseudoStart = idx; + idx++; + + // Skip second colon for pseudo-elements + if (idx < selector.length && selector[idx] === ':') { + idx++; + } + + // Extract pseudo name + var nameStart = idx; + while (idx < selector.length && /[a-zA-Z0-9\-]/.test(selector[idx])) { + idx++; + } + + if (idx === nameStart) { + continue; // No name found + } + + var pseudoName = selector.substring(nameStart, idx).toLowerCase(); + + // Check if this pseudo has arguments + if (idx < selector.length && selector[idx] === '(') { + idx++; + var contentStart = idx; + var depth = 1; + + // Find matching closing paren (handle nesting) + while (idx < selector.length && depth > 0) { + if (selector[idx] === '\\') { + idx += 2; // Skip escaped character + } else if (selector[idx] === '(') { + depth++; + idx++; + } else if (selector[idx] === ')') { + depth--; + idx++; + } else { + idx++; + } + } + + if (depth === 0) { + var pseudoContent = selector.substring(contentStart, idx - 1); + + // Check if this pseudo should not have quoted strings + for (var j = 0; j < noQuotesPseudos.length; j++) { + if (pseudoName === noQuotesPseudos[j] && /['"]/.test(pseudoContent)) { + return false; + } + } + } + } + } + } + + // Use the iterative validator to avoid regex backtracking issues + return looseSelectorValidator(selector); + } + + /** + * Regular expression to match CSS pseudo-classes with arguments. + * + * Matches patterns like `:pseudo-class(argument)`, capturing the pseudo-class name and its argument. + * + * Capture groups: + * 1. The pseudo-class name (letters and hyphens). + * 2. The argument inside the parentheses (can contain nested parentheses, quoted strings, and other characters.). + * + * Global flag (`g`) is used to find all matches in the input string. + * + * Example matches: + * - :nth-child(2n+1) + * - :has(.sel:nth-child(3n)) + * - :not(".foo, .bar") + * + * REPLACED WITH FUNCTION to avoid exponential backtracking. + */ + + /** + * Extract pseudo-classes with arguments from a selector using iterative parsing. + * Replaces the previous globalPseudoClassRegExp to avoid exponential backtracking. + * + * Handles: + * - Regular content without parentheses or quotes + * - Single-quoted strings + * - Double-quoted strings + * - Nested parentheses (arbitrary depth) + * + * @param {string} selector - The CSS selector to parse + * @returns {Array} Array of matches, each with: [fullMatch, pseudoName, pseudoArgs, startIndex] + */ + function extractPseudoClasses(selector) { + var matches = []; + + for (var i = 0; i < selector.length; i++) { + // Look for pseudo-class start (single or double colon) + if (selector[i] === ':') { + var pseudoStart = i; + i++; + + // Skip second colon for pseudo-elements (::) + if (i < selector.length && selector[i] === ':') { + i++; + } + + // Extract pseudo name + var nameStart = i; + while (i < selector.length && /[a-zA-Z\-]/.test(selector[i])) { + i++; + } + + if (i === nameStart) { + continue; // No name found + } + + var pseudoName = selector.substring(nameStart, i); + + // Check if this pseudo has arguments + if (i < selector.length && selector[i] === '(') { + i++; + var argsStart = i; + var depth = 1; + var inSingleQuote = false; + var inDoubleQuote = false; + + // Find matching closing paren (handle nesting and strings) + while (i < selector.length && depth > 0) { + var ch = selector[i]; + + if (ch === '\\') { + i += 2; // Skip escaped character + } else if (ch === "'" && !inDoubleQuote) { + inSingleQuote = !inSingleQuote; + i++; + } else if (ch === '"' && !inSingleQuote) { + inDoubleQuote = !inDoubleQuote; + i++; + } else if (ch === '(' && !inSingleQuote && !inDoubleQuote) { + depth++; + i++; + } else if (ch === ')' && !inSingleQuote && !inDoubleQuote) { + depth--; + i++; + } else { + i++; + } + } + + if (depth === 0) { + var pseudoArgs = selector.substring(argsStart, i - 1); + var fullMatch = selector.substring(pseudoStart, i); + + // Store match in same format as regex: [fullMatch, pseudoName, pseudoArgs, startIndex] + matches.push([fullMatch, pseudoName, pseudoArgs, pseudoStart]); + } + + // Move back one since loop will increment + i--; + } + } + } + + return matches; + } + + /** + * Parses a CSS selector string and splits it into parts, handling nested parentheses. + * + * This function is useful for splitting selectors that may contain nested function-like + * syntax (e.g., :not(.foo, .bar)), ensuring that commas inside parentheses do not split + * the selector. + * + * @param {string} selector - The CSS selector string to parse. + * @returns {string[]} An array of selector parts, split by top-level commas, with whitespace trimmed. + */ + function parseAndSplitNestedSelectors(selector) { + var depth = 0; // Track parenthesis nesting depth + var buffer = ""; // Accumulate characters for current selector part + var parts = []; // Array of split selector parts + var inSingleQuote = false; // Track if we're inside single quotes + var inDoubleQuote = false; // Track if we're inside double quotes + var i, char; + + for (i = 0; i < selector.length; i++) { + char = selector.charAt(i); + + // Handle escape sequences - skip them entirely + if (char === '\\' && i + 1 < selector.length) { + buffer += char; + i++; + buffer += selector.charAt(i); + continue; + } + + // Handle single quote strings + if (char === "'" && !inDoubleQuote) { + inSingleQuote = !inSingleQuote; + buffer += char; + } + // Handle double quote strings + else if (char === '"' && !inSingleQuote) { + inDoubleQuote = !inDoubleQuote; + buffer += char; + } + // Process characters outside of quoted strings + else if (!inSingleQuote && !inDoubleQuote) { + if (char === '(') { + // Entering a nested level (e.g., :is(...)) + depth++; + buffer += char; + } else if (char === ')') { + // Exiting a nested level + depth--; + buffer += char; + } else if (char === ',' && depth === 0) { + // Found a top-level comma separator - split here + // Note: escaped commas (\,) are already handled above + if (buffer.trim()) { + parts.push(buffer.trim()); + } + buffer = ""; + } else { + // Regular character - add to buffer + buffer += char; + } + } + // Characters inside quoted strings - add to buffer + else { + buffer += char; + } + } + + // Add any remaining content in buffer as the last part + var trimmed = buffer.trim(); + if (trimmed) { + // Preserve trailing space if selector ends with hex escape + var endsWithHexEscape = endsWithHexEscapeRegExp.test(buffer); + parts.push(endsWithHexEscape ? buffer.replace(leadingWhitespaceRegExp, '') : trimmed); + } + + return parts; + } + + /** + * Validates a CSS selector string, including handling of nested selectors within certain pseudo-classes. + * + * This function checks if the provided selector is valid according to the rules defined by + * `basicSelectorValidator`. For pseudo-classes that accept selector lists (such as :not, :is, :has, :where), + * it recursively validates each nested selector using the same validation logic. + * + * @param {string} selector - The CSS selector string to validate. + * @returns {boolean} Returns `true` if the selector is valid, otherwise `false`. + */ + + // Cache to store validated selectors (previously a ES6 Map, now an ES5-compliant object) + var validatedSelectorsCache = {}; + + // Only pseudo-classes that accept selector lists should recurse + var selectorListPseudoClasses = { + 'not': true, + 'is': true, + 'has': true, + 'where': true + }; + + function validateSelector(selector) { + if (validatedSelectorsCache.hasOwnProperty(selector)) { + return validatedSelectorsCache[selector]; + } + + // Use function-based parsing to extract pseudo-classes (avoids backtracking) + var pseudoClassMatches = extractPseudoClasses(selector); + + for (var j = 0; j < pseudoClassMatches.length; j++) { + var pseudoClass = pseudoClassMatches[j][1]; + if (selectorListPseudoClasses.hasOwnProperty(pseudoClass)) { + var nestedSelectors = parseAndSplitNestedSelectors(pseudoClassMatches[j][2]); + + // Check if ANY selector in the list contains & (nesting selector) + // If so, skip validation for the entire selector list since & will be replaced at runtime + var hasAmpersand = false; + for (var k = 0; k < nestedSelectors.length; k++) { + if (ampersandRegExp.test(nestedSelectors[k])) { + hasAmpersand = true; + break; + } + } + + // If any selector has &, skip validation for this entire pseudo-class + if (hasAmpersand) { + continue; + } + + // Otherwise, validate each selector normally + for (var i = 0; i < nestedSelectors.length; i++) { + var nestedSelector = nestedSelectors[i]; + if (!validatedSelectorsCache.hasOwnProperty(nestedSelector)) { + var nestedSelectorValidation = validateSelector(nestedSelector); + validatedSelectorsCache[nestedSelector] = nestedSelectorValidation; + if (!nestedSelectorValidation) { + validatedSelectorsCache[selector] = false; + return false; + } + } else if (!validatedSelectorsCache[nestedSelector]) { + validatedSelectorsCache[selector] = false; + return false; + } + } + } + } + + var basicSelectorValidation = basicSelectorValidator(selector); + validatedSelectorsCache[selector] = basicSelectorValidation; + + return basicSelectorValidation; + } + + /** + * Validates namespace selectors by checking if the namespace prefix is defined. + * + * @param {string} selector - The CSS selector to validate + * @returns {boolean} Returns true if the namespace is valid, false otherwise + */ + function validateNamespaceSelector(selector) { + // Check if selector contains a namespace prefix + // We need to ignore pipes inside attribute selectors + var pipeIndex = -1; + var inAttr = false; + var inSingleQuote = false; + var inDoubleQuote = false; + + for (var i = 0; i < selector.length; i++) { + var char = selector[i]; + + // Handle escape sequences - skip hex escapes or simple escapes + if (char === '\\') { + var escapeLen = getEscapeSequenceLength(selector, i); + if (escapeLen > 0) { + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + + if (inSingleQuote) { + if (char === "'") { + inSingleQuote = false; + } + } else if (inDoubleQuote) { + if (char === '"') { + inDoubleQuote = false; + } + } else if (inAttr) { + if (char === "]") { + inAttr = false; + } else if (char === "'") { + inSingleQuote = true; + } else if (char === '"') { + inDoubleQuote = true; + } + } else { + if (char === "[") { + inAttr = true; + } else if (char === "|" && !inAttr) { + // This is a namespace separator, not an attribute operator + pipeIndex = i; + break; + } + } + } + + if (pipeIndex === -1) { + return true; // No namespace, always valid + } + + var namespacePrefix = selector.substring(0, pipeIndex); + + // Universal namespace (*|) and default namespace (|) are always valid + if (namespacePrefix === '*' || namespacePrefix === '') { + return true; + } + + // Check if the custom namespace prefix is defined + return definedNamespacePrefixes.hasOwnProperty(namespacePrefix); + } + + /** + * Normalizes escape sequences in a selector to match browser behavior. + * Decodes escape sequences and re-encodes them in canonical form. + * + * @param {string} selector - The selector to normalize + * @returns {string} Normalized selector + */ + function normalizeSelectorEscapes(selector) { + var result = ''; + var i = 0; + var nextChar = ''; + + // Track context for identifier boundaries + var inIdentifier = false; + var inAttribute = false; + var attributeDepth = 0; + var needsEscapeForIdent = false; + var lastWasHexEscape = false; + + while (i < selector.length) { + var char = selector[i]; + + // Track attribute selector context + if (char === '[' && !inAttribute) { + inAttribute = true; + attributeDepth = 1; + result += char; + i++; + needsEscapeForIdent = false; + inIdentifier = false; + lastWasHexEscape = false; + continue; + } + + if (inAttribute) { + if (char === '[') attributeDepth++; + if (char === ']') { + attributeDepth--; + if (attributeDepth === 0) inAttribute = false; + } + // Don't normalize escapes inside attribute selectors + if (char === '\\' && i + 1 < selector.length) { + var escapeLen = getEscapeSequenceLength(selector, i); + result += selector.substr(i, escapeLen); + i += escapeLen; + } else { + result += char; + i++; + } + lastWasHexEscape = false; + continue; + } + + // Handle escape sequences + if (char === '\\') { + var escapeLen = getEscapeSequenceLength(selector, i); + if (escapeLen > 0) { + var escapeSeq = selector.substr(i, escapeLen); + var decoded = decodeEscapeSequence(escapeSeq); + var wasHexEscape = startsWithHexEscapeRegExp.test(escapeSeq); + var hadTerminatingSpace = wasHexEscape && escapeSeq[escapeLen - 1] === ' '; + nextChar = selector[i + escapeLen] || ''; + + // Check if this character needs escaping + var needsEscape = false; + var useHexEscape = false; + + if (needsEscapeForIdent) { + // At start of identifier (after . # or -) + // Digits must be escaped, letters/underscore/_/- don't need escaping + if (isDigit(decoded)) { + needsEscape = true; + useHexEscape = true; + } else if (decoded === '-') { + // Dash at identifier start: keep escaped if it's the only character, + // otherwise it can be decoded + var remainingSelector = selector.substring(i + escapeLen); + var hasMoreIdentChars = remainingSelector && identCharRegExp.test(remainingSelector[0]); + needsEscape = !hasMoreIdentChars; + } else if (!identStartCharRegExp.test(decoded)) { + needsEscape = true; + } + } else { + if (specialCharsNeedEscapeRegExp.test(decoded)) { + needsEscape = true; + } + } + + if (needsEscape) { + if (useHexEscape) { + // Use normalized hex escape + var codePoint = decoded.charCodeAt(0); + var hex = codePoint.toString(16); + result += '\\' + hex; + // Add space if next char could continue the hex sequence, + // or if at end of selector (to disambiguate the escape) + if (isHexDigit(nextChar) || !nextChar || afterHexEscapeSeparatorRegExp.test(nextChar)) { + result += ' '; + lastWasHexEscape = false; + } else { + lastWasHexEscape = true; + } + } else { + // Use simple character escape + result += '\\' + decoded; + lastWasHexEscape = false; + } + } else { + // No escape needed, use the character directly + // But if previous was hex escape (without terminating space) and this is alphanumeric, add space + if (lastWasHexEscape && !hadTerminatingSpace && isAlphanumeric(decoded)) { + result += ' '; + } + result += decoded; + // Preserve terminating space at end of selector (when followed by non-ident char) + if (hadTerminatingSpace && (!nextChar || afterHexEscapeSeparatorRegExp.test(nextChar))) { + result += ' '; + } + lastWasHexEscape = false; + } + + i += escapeLen; + // After processing escape, check if we're still needing ident validation + // Only stay in needsEscapeForIdent state if decoded was '-' + needsEscapeForIdent = needsEscapeForIdent && decoded === '-'; + inIdentifier = true; + continue; + } + } + + // Handle regular characters + if (char === '.' || char === '#') { + result += char; + needsEscapeForIdent = true; + inIdentifier = false; + lastWasHexEscape = false; + i++; + } else if (char === '-' && needsEscapeForIdent) { + // Dash after . or # - next char must be valid ident start or digit (which needs escaping) + result += char; + needsEscapeForIdent = true; + lastWasHexEscape = false; + i++; + } else if (isDigit(char) && needsEscapeForIdent) { + // Digit at identifier start must be hex escaped + var codePoint = char.charCodeAt(0); + var hex = codePoint.toString(16); + result += '\\' + hex; + nextChar = selector[i + 1] || ''; + // Add space if next char could continue the hex sequence, + // or if at end of selector (to disambiguate the escape) + if (isHexDigit(nextChar) || !nextChar || afterHexEscapeSeparatorRegExp.test(nextChar)) { + result += ' '; + lastWasHexEscape = false; + } else { + lastWasHexEscape = true; + } + needsEscapeForIdent = false; + inIdentifier = true; + i++; + } else if (char === ':' || combinatorOrSeparatorRegExp.test(char)) { + // Combinators, separators, and pseudo-class markers reset identifier state + // Preserve trailing space from hex escape + if (!(char === ' ' && lastWasHexEscape && result[result.length - 1] === ' ')) { + result += char; + } + needsEscapeForIdent = false; + inIdentifier = false; + lastWasHexEscape = false; + i++; + } else if (isLetter(char) && lastWasHexEscape) { + // Letter after hex escape needs a space separator + result += ' ' + char; + needsEscapeForIdent = false; + inIdentifier = true; + lastWasHexEscape = false; + i++; + } else if (char === ' ' && lastWasHexEscape) { + // Trailing space - keep it if at end or before non-ident char + nextChar = selector[i + 1] || ''; + if (!nextChar || trailingSpaceSeparatorRegExp.test(nextChar)) { + result += char; + } + needsEscapeForIdent = false; + inIdentifier = false; + lastWasHexEscape = false; + i++; + } else { + result += char; + needsEscapeForIdent = false; + inIdentifier = true; + lastWasHexEscape = false; + i++; + } + } + + return result; + } + + /** + * Helper function to decode all escape sequences in a string. + * + * @param {string} str - The string to decode + * @returns {string} The decoded string + */ + function decodeEscapeSequencesInString(str) { + var result = ''; + for (var i = 0; i < str.length; i++) { + if (str[i] === '\\' && i + 1 < str.length) { + // Get the escape sequence length + var escapeLen = getEscapeSequenceLength(str, i); + if (escapeLen > 0) { + var escapeSeq = str.substr(i, escapeLen); + var decoded = decodeEscapeSequence(escapeSeq); + result += decoded; + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + result += str[i]; + } + return result; + } + + /** + * Decodes a CSS escape sequence to its character value. + * + * @param {string} escapeSeq - The escape sequence (including backslash) + * @returns {string} The decoded character + */ + function decodeEscapeSequence(escapeSeq) { + if (escapeSeq.length < 2 || escapeSeq[0] !== '\\') { + return escapeSeq; + } + + var content = escapeSeq.substring(1); + + // Check if it's a hex escape + var hexMatch = content.match(hexEscapeSequenceRegExp); + if (hexMatch) { + var codePoint = parseInt(hexMatch[1], 16); + // Handle surrogate pairs for code points > 0xFFFF + if (codePoint > 0xFFFF) { + // Convert to surrogate pair + codePoint -= 0x10000; + var high = 0xD800 + (codePoint >> 10); + var low = 0xDC00 + (codePoint & 0x3FF); + return String.fromCharCode(high, low); + } + return String.fromCharCode(codePoint); + } + + // Simple escape - return the character after backslash + return content[0] || ''; + } + + /** + * Normalizes attribute selectors by ensuring values are properly quoted with double quotes. + * Examples: + * [attr=value] -> [attr="value"] + * [attr="value"] -> [attr="value"] (unchanged) + * [attr='value'] -> [attr="value"] (converted to double quotes) + * + * @param {string} selector - The selector to normalize + * @returns {string|null} Normalized selector, or null if invalid + */ + function normalizeAttributeSelectors(selector) { + var result = ''; + var i = 0; + + while (i < selector.length) { + // Look for attribute selector start + if (selector[i] === '[') { + result += '['; + i++; + + var attrContent = ''; + var depth = 1; + + // Find the closing bracket, handling nested brackets and escapes + while (i < selector.length && depth > 0) { + if (selector[i] === '\\' && i + 1 < selector.length) { + attrContent += selector.substring(i, i + 2); + i += 2; + continue; + } + if (selector[i] === '[') depth++; + if (selector[i] === ']') { + depth--; + if (depth === 0) break; + } + attrContent += selector[i]; + i++; + } + + // Normalize the attribute content + var normalized = normalizeAttributeContent(attrContent); + if (normalized === null) { + // Invalid attribute selector (e.g., unclosed quote) + return null; + } + result += normalized; + if (i < selector.length && selector[i] === ']') { + result += ']'; + i++; + } + } else { + result += selector[i]; + i++; + } + } + + return result; + } + + /** + * Processes a quoted attribute value by checking for proper closure and decoding escape sequences. + * @param {string} trimmedValue - The quoted value (with quotes) + * @param {string} quoteChar - The quote character ('"' or "'") + * @param {string} attrName - The attribute name + * @param {string} operator - The attribute operator + * @param {string} flag - Optional case-sensitivity flag + * @returns {string|null} Normalized attribute content, or null if invalid + */ + function processQuotedAttributeValue(trimmedValue, quoteChar, attrName, operator, flag) { + // Check if the closing quote is properly closed (not escaped) + if (trimmedValue.length < 2) { + return null; // Too short + } + // Find the actual closing quote (not escaped) + var i = 1; + var foundClose = false; + while (i < trimmedValue.length) { + if (trimmedValue[i] === '\\' && i + 1 < trimmedValue.length) { + // Skip escape sequence + var escapeLen = getEscapeSequenceLength(trimmedValue, i); + i += escapeLen; + continue; + } + if (trimmedValue[i] === quoteChar) { + // Found closing quote + foundClose = (i === trimmedValue.length - 1); + break; + } + i++; + } + if (!foundClose) { + return null; // Unclosed quote - invalid + } + // Extract inner value and decode escape sequences + var innerValue = trimmedValue.slice(1, -1); + var decodedValue = decodeEscapeSequencesInString(innerValue); + // If decoded value contains quotes, we need to escape them + var escapedValue = decodedValue.replace(doubleQuoteRegExp, '\\"'); + return attrName + operator + '"' + escapedValue + '"' + (flag ? ' ' + flag : ''); + } + + /** + * Normalizes the content inside an attribute selector. + * @param {string} content - The content between [ and ] + * @returns {string} Normalized content, or null if invalid + */ + function normalizeAttributeContent(content) { + // Match: attribute-name [operator] [value] [flag] + var match = content.match(attributeSelectorContentRegExp); + + if (!match) { + // No operator (e.g., [disabled]) or malformed - return as is + return content; + } + + var attrName = match[1]; + var operator = match[2]; + var valueAndFlag = match[3].trim(); // Trim here instead of in regex + + // Check if there's a case-sensitivity flag (i or s) at the end + var flagMatch = valueAndFlag.match(attributeCaseFlagRegExp); + var value = flagMatch ? flagMatch[1] : valueAndFlag; + var flag = flagMatch ? flagMatch[2] : ''; + + // Check for unclosed quotes - this makes the selector invalid + var trimmedValue = value.trim(); + var firstChar = trimmedValue[0]; + + if (firstChar === '"') { + return processQuotedAttributeValue(trimmedValue, '"', attrName, operator, flag); + } + + if (firstChar === "'") { + return processQuotedAttributeValue(trimmedValue, "'", attrName, operator, flag); + } + + // Check for unescaped special characters in unquoted values + // Escaped special characters are valid (e.g., \` is valid, but ` is not) + var hasUnescapedSpecialChar = false; + for (var i = 0; i < trimmedValue.length; i++) { + var char = trimmedValue[i]; + if (char === '\\' && i + 1 < trimmedValue.length) { + // Skip the entire escape sequence + var escapeLen = getEscapeSequenceLength(trimmedValue, i); + if (escapeLen > 0) { + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + // Check if this is an unescaped special character + if (specialCharsNeedEscapeRegExp.test(char)) { + hasUnescapedSpecialChar = true; + break; + } + } + + if (hasUnescapedSpecialChar) { + return null; // Unescaped special characters not allowed in unquoted attribute values + } + + // Decode escape sequences in the value before quoting + // Inside quotes, special characters don't need escaping + var decodedValue = decodeEscapeSequencesInString(trimmedValue); + + // If the decoded value contains double quotes, escape them for the output + // (since we're using double quotes as delimiters) + var escapedValue = decodedValue.replace(backslashRegExp, '\\\\').replace(doubleQuoteRegExp, '\\"'); + + // Unquoted value - add double quotes with decoded and re-escaped content + return attrName + operator + '"' + escapedValue + '"' + (flag ? ' ' + flag : ''); + } + + /** + * Processes a CSS selector text + * + * @param {string} selectorText - The CSS selector text to process + * @returns {string} The processed selector text with normalized whitespace and invalid selectors removed + */ + function processSelectorText(selectorText) { + // Normalize whitespace first + var normalized = selectorText.replace(whitespaceNormalizationRegExp, function (match, _, newline) { + if (newline) return " "; + return match; + }); + + // Normalize escape sequences to match browser behavior + normalized = normalizeSelectorEscapes(normalized); + + // Normalize attribute selectors (add quotes to unquoted values) + // Returns null if invalid (e.g., unclosed quotes) + normalized = normalizeAttributeSelectors(normalized); + if (normalized === null) { + return ''; // Invalid selector - return empty to trigger validation failure + } + + // Recursively process pseudo-classes to handle nesting + return processNestedPseudoClasses(normalized); + } + + /** + * Recursively processes pseudo-classes to filter invalid selectors + * + * @param {string} selectorText - The CSS selector text to process + * @param {number} depth - Current recursion depth (to prevent infinite loops) + * @returns {string} The processed selector text with invalid selectors removed + */ + function processNestedPseudoClasses(selectorText, depth) { + // Prevent infinite recursion + if (typeof depth === 'undefined') { + depth = 0; + } + if (depth > 10) { + return selectorText; + } + + var pseudoClassMatches = extractPseudoClasses(selectorText); + + // If no pseudo-classes found, return as-is + if (pseudoClassMatches.length === 0) { + return selectorText; + } + + // Build result by processing matches from right to left (to preserve positions) + var result = selectorText; + + for (var j = pseudoClassMatches.length - 1; j >= 0; j--) { + var pseudoClass = pseudoClassMatches[j][1]; + if (selectorListPseudoClasses.hasOwnProperty(pseudoClass)) { + var fullMatch = pseudoClassMatches[j][0]; + var pseudoArgs = pseudoClassMatches[j][2]; + var matchStart = pseudoClassMatches[j][3]; + + // Check if ANY selector contains & BEFORE processing + var nestedSelectorsRaw = parseAndSplitNestedSelectors(pseudoArgs); + var hasAmpersand = false; + for (var k = 0; k < nestedSelectorsRaw.length; k++) { + if (ampersandRegExp.test(nestedSelectorsRaw[k])) { + hasAmpersand = true; + break; + } + } + + // If & is present, skip all processing (keep everything unchanged) + if (hasAmpersand) { + continue; + } + + // Recursively process the arguments + var processedArgs = processNestedPseudoClasses(pseudoArgs, depth + 1); + var nestedSelectors = parseAndSplitNestedSelectors(processedArgs); + + // Filter out invalid selectors + var validSelectors = []; + for (var i = 0; i < nestedSelectors.length; i++) { + var nestedSelector = nestedSelectors[i]; + if (basicSelectorValidator(nestedSelector)) { + validSelectors.push(nestedSelector); + } + } + + // Reconstruct the pseudo-class with only valid selectors + var newArgs = validSelectors.join(', '); + var newPseudoClass = ':' + pseudoClass + '(' + newArgs + ')'; + + // Replace in the result string using position (processing right to left preserves positions) + result = result.substring(0, matchStart) + newPseudoClass + result.substring(matchStart + fullMatch.length); + } + } + + return result; + + return normalized; + } + + /** + * Checks if a selector contains newlines inside quoted strings. + * Uses iterative parsing to avoid regex backtracking issues. + * @param {string} selectorText - The selector to check + * @returns {boolean} True if newlines found inside quotes + */ + function hasNewlineInQuotedString(selectorText) { + for (var i = 0; i < selectorText.length; i++) { + var char = selectorText[i]; + + // Start of single-quoted string + if (char === "'") { + i++; + while (i < selectorText.length) { + if (selectorText[i] === '\\' && i + 1 < selectorText.length) { + // Skip escape sequence + i += 2; + continue; + } + if (selectorText[i] === "'") { + // End of string + break; + } + if (selectorText[i] === '\r' || selectorText[i] === '\n') { + return true; + } + i++; + } + } + // Start of double-quoted string + else if (char === '"') { + i++; + while (i < selectorText.length) { + if (selectorText[i] === '\\' && i + 1 < selectorText.length) { + // Skip escape sequence + i += 2; + continue; + } + if (selectorText[i] === '"') { + // End of string + break; + } + if (selectorText[i] === '\r' || selectorText[i] === '\n') { + return true; + } + i++; + } + } + } + return false; + } + + /** + * Checks if a given CSS selector text is valid by splitting it by commas + * and validating each individual selector using the `validateSelector` function. + * + * @param {string} selectorText - The CSS selector text to validate. Can contain multiple selectors separated by commas. + * @returns {boolean} Returns true if all selectors are valid, otherwise false. + */ + function isValidSelectorText(selectorText) { + // TODO: The same validations here needs to be reused in CSSStyleRule.selectorText setter + // TODO: Move these validation logic to a shared function to be reused in CSSStyleRule.selectorText setter + + // Check for empty or whitespace-only selector + if (!selectorText || selectorText.trim() === '') { + return false; + } + + // Check for empty selector lists in pseudo-classes (e.g., :is(), :not(), :where(), :has()) + // These are invalid after filtering out invalid selectors + if (emptyPseudoClassRegExp.test(selectorText)) { + return false; + } + + // Check for newlines inside single or double quotes + // Uses helper function to avoid regex security issues + if (hasNewlineInQuotedString(selectorText)) { + return false; + } + + // Split selectorText by commas and validate each part + var selectors = parseAndSplitNestedSelectors(selectorText); + for (var i = 0; i < selectors.length; i++) { + var selector = selectors[i].trim(); + if (!validateSelector(selector) || !validateNamespaceSelector(selector)) { + return false; + } + } + return true; + } + + function pushToAncestorRules(rule) { + ancestorRules.push(rule); + } + + function parseError(message, isNested) { + var lines = token.substring(0, i).split('\n'); + var lineCount = lines.length; + var charCount = lines.pop().length + 1; + var error = new Error(message + ' (line ' + lineCount + ', char ' + charCount + ')'); + error.line = lineCount; + /* jshint sub : true */ + error['char'] = charCount; + error.styleSheet = styleSheet; + error.isNested = !!isNested; + // Print the error but continue parsing the sheet + try { + throw error; + } catch (e) { + errorHandler && errorHandler(e); + } + }; + + /** + * Handles invalid selectors with unmatched quotes by skipping the entire rule block. + * @param {string} nextState - The parser state to transition to after skipping + */ + function handleUnmatchedQuoteInSelector(nextState) { + // parseError('Invalid selector with unmatched quote: ' + buffer.trim()); + // Skip this entire invalid rule including its block + var ruleClosingMatch = token.slice(i).match(forwardRuleClosingBraceRegExp); + if (ruleClosingMatch) { + i += ruleClosingMatch.index + ruleClosingMatch[0].length - 1; + } + styleRule = null; + buffer = ""; + hasUnmatchedQuoteInSelector = false; // Reset flag + state = nextState; + } + + // Helper functions to check character types + function isSelectorStartChar(char) { + return '.:#&*['.indexOf(char) !== -1; + } + + function isWhitespaceChar(char) { + return ' \t\n\r'.indexOf(char) !== -1; + } + + // Helper functions for character type checking (faster than regex for single chars) + function isDigit(char) { + var code = char.charCodeAt(0); + return code >= 0x0030 && code <= 0x0039; // 0-9 + } + + function isHexDigit(char) { + if (!char) return false; + var code = char.charCodeAt(0); + return (code >= 0x0030 && code <= 0x0039) || // 0-9 + (code >= 0x0041 && code <= 0x0046) || // A-F + (code >= 0x0061 && code <= 0x0066); // a-f + } + + function isLetter(char) { + if (!char) return false; + var code = char.charCodeAt(0); + return (code >= 0x0041 && code <= 0x005A) || // A-Z + (code >= 0x0061 && code <= 0x007A); // a-z + } + + function isAlphanumeric(char) { + var code = char.charCodeAt(0); + return (code >= 0x0030 && code <= 0x0039) || // 0-9 + (code >= 0x0041 && code <= 0x005A) || // A-Z + (code >= 0x0061 && code <= 0x007A); // a-z + } + + /** + * Get the length of an escape sequence starting at the given position. + * CSS escape sequences are: + * - Backslash followed by 1-6 hex digits, optionally followed by a whitespace (consumed) + * - Backslash followed by any non-hex character + * @param {string} str - The string to check + * @param {number} pos - Position of the backslash + * @returns {number} Number of characters in the escape sequence (including backslash) + */ + function getEscapeSequenceLength(str, pos) { + if (str[pos] !== '\\' || pos + 1 >= str.length) { + return 0; + } + + var nextChar = str[pos + 1]; + + // Check if it's a hex escape + if (isHexDigit(nextChar)) { + var hexLength = 1; + // Count up to 6 hex digits + while (hexLength < 6 && pos + 1 + hexLength < str.length && isHexDigit(str[pos + 1 + hexLength])) { + hexLength++; + } + // Check if followed by optional whitespace (which gets consumed) + if (pos + 1 + hexLength < str.length && isWhitespaceChar(str[pos + 1 + hexLength])) { + return 1 + hexLength + 1; // backslash + hex digits + whitespace + } + return 1 + hexLength; // backslash + hex digits + } + + // Simple escape: backslash + any character + return 2; + } + + /** + * Check if a string contains an unescaped occurrence of a specific character + * @param {string} str - The string to search + * @param {string} char - The character to look for + * @returns {boolean} True if the character appears unescaped + */ + function containsUnescaped(str, char) { + for (var i = 0; i < str.length; i++) { + if (str[i] === '\\') { + var escapeLen = getEscapeSequenceLength(str, i); + if (escapeLen > 0) { + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + if (str[i] === char) { + return true; + } + } + return false; + } + + var endingIndex = token.length - 1; + var initialEndingIndex = endingIndex; + + for (var character; (character = token.charAt(i)); i++) { + if (i === endingIndex) { + switch (state) { + case "importRule": + case "namespaceRule": + case "layerBlock": + if (character !== ";") { + token += ";"; + endingIndex += 1; + } + break; + case "value": + if (character !== "}") { + if (character === ";") { + token += "}" + } else { + token += ";"; + } + endingIndex += 1; + break; + } + case "name": + case "before-name": + if (character === "}") { + token += " " + } else { + token += "}" + } + endingIndex += 1 + break; + case "before-selector": + if (character !== "}" && currentScope !== styleSheet) { + token += "}" + endingIndex += 1 + break; + } + } + } + + // Handle escape sequences before processing special characters + // CSS escape sequences: \HHHHHH (1-6 hex digits) optionally followed by whitespace, or \ + any char + if (character === '\\' && i + 1 < token.length) { + var escapeLen = getEscapeSequenceLength(token, i); + if (escapeLen > 0) { + buffer += token.substr(i, escapeLen); + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + + switch (character) { + + case " ": + case "\t": + case "\r": + case "\n": + case "\f": + if (SIGNIFICANT_WHITESPACE[state]) { + buffer += character; + } + break; + + // String + case '"': + index = i + 1; + do { + index = token.indexOf('"', index) + 1; + if (!index) { + parseError('Unmatched "'); + // If we're parsing a selector, flag it as invalid + if (state === "selector" || state === "atRule") { + hasUnmatchedQuoteInSelector = true; + } + } + } while (token[index - 2] === '\\'); + if (index === 0) { + break; + } + buffer += token.slice(i, index); + i = index - 1; + switch (state) { + case 'before-value': + state = 'value'; + break; + case 'importRule-begin': + state = 'importRule'; + if (i === endingIndex) { + token += ';' + } + break; + case 'namespaceRule-begin': + state = 'namespaceRule'; + if (i === endingIndex) { + token += ';' + } + break; + } + break; + + case "'": + index = i + 1; + do { + index = token.indexOf("'", index) + 1; + if (!index) { + parseError("Unmatched '"); + // If we're parsing a selector, flag it as invalid + if (state === "selector" || state === "atRule") { + hasUnmatchedQuoteInSelector = true; + } + } + } while (token[index - 2] === '\\'); + if (index === 0) { + break; + } + buffer += token.slice(i, index); + i = index - 1; + switch (state) { + case 'before-value': + state = 'value'; + break; + case 'importRule-begin': + state = 'importRule'; + break; + case 'namespaceRule-begin': + state = 'namespaceRule'; + break; + } + break; + + // Comment + case "/": + if (token.charAt(i + 1) === "*") { + i += 2; + index = token.indexOf("*/", i); + if (index === -1) { + i = token.length - 1; + buffer = ""; + } else { + i = index + 1; + } + } else { + buffer += character; + } + if (state === "importRule-begin") { + buffer += " "; + state = "importRule"; + } + if (state === "namespaceRule-begin") { + buffer += " "; + state = "namespaceRule"; + } + break; + + // At-rule + case "@": + if (nestedSelectorRule) { + if (styleRule && styleRule.constructor.name === "CSSNestedDeclarations") { + currentScope.cssRules.push(styleRule); + } + // Only reset styleRule to parent if styleRule is not the nestedSelectorRule itself + // This preserves nested selectors when followed immediately by @-rules + if (styleRule !== nestedSelectorRule && nestedSelectorRule.parentRule && nestedSelectorRule.parentRule.constructor.name === "CSSStyleRule") { + styleRule = nestedSelectorRule.parentRule; + } + // Don't reset nestedSelectorRule here - preserve it through @-rules + } + if (token.indexOf("@-moz-document", i) === i) { + validateAtRule("@-moz-document", function () { + state = "documentRule-begin"; + documentRule = new CSSOM.CSSDocumentRule(); + documentRule.__starts = i; + i += "-moz-document".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@media", i) === i) { + validateAtRule("@media", function () { + state = "atBlock"; + mediaRule = new CSSOM.CSSMediaRule(); + mediaRule.__starts = i; + i += "media".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@container", i) === i) { + validateAtRule("@container", function () { + state = "containerBlock"; + containerRule = new CSSOM.CSSContainerRule(); + containerRule.__starts = i; + i += "container".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@counter-style", i) === i) { + buffer = ""; + // @counter-style can be nested only inside CSSScopeRule or CSSConditionRule + // and only if there's no CSSStyleRule in the parent chain + var cannotBeNested = !canAtRuleBeNested(); + validateAtRule("@counter-style", function () { + state = "counterStyleBlock" + counterStyleRule = new CSSOM.CSSCounterStyleRule(); + counterStyleRule.__starts = i; + i += "counter-style".length; + }, cannotBeNested); + break; + } else if (token.indexOf("@property", i) === i) { + buffer = ""; + // @property can be nested only inside CSSScopeRule or CSSConditionRule + // and only if there's no CSSStyleRule in the parent chain + var cannotBeNested = !canAtRuleBeNested(); + validateAtRule("@property", function () { + state = "propertyBlock" + propertyRule = new CSSOM.CSSPropertyRule(); + propertyRule.__starts = i; + i += "property".length; + }, cannotBeNested); + break; + } else if (token.indexOf("@scope", i) === i) { + validateAtRule("@scope", function () { + state = "scopeBlock"; + scopeRule = new CSSOM.CSSScopeRule(); + scopeRule.__starts = i; + i += "scope".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@layer", i) === i) { + validateAtRule("@layer", function () { + state = "layerBlock" + layerBlockRule = new CSSOM.CSSLayerBlockRule(); + layerBlockRule.__starts = i; + i += "layer".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@page", i) === i) { + validateAtRule("@page", function () { + state = "pageBlock" + pageRule = new CSSOM.CSSPageRule(); + pageRule.__starts = i; + i += "page".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@supports", i) === i) { + validateAtRule("@supports", function () { + state = "conditionBlock"; + supportsRule = new CSSOM.CSSSupportsRule(); + supportsRule.__starts = i; + i += "supports".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@host", i) === i) { + validateAtRule("@host", function () { + state = "hostRule-begin"; + i += "host".length; + hostRule = new CSSOM.CSSHostRule(); + hostRule.__starts = i; + }); + buffer = ""; + break; + } else if (token.indexOf("@starting-style", i) === i) { + validateAtRule("@starting-style", function () { + state = "startingStyleRule-begin"; + i += "starting-style".length; + startingStyleRule = new CSSOM.CSSStartingStyleRule(); + startingStyleRule.__starts = i; + }); + buffer = ""; + break; + } else if (token.indexOf("@import", i) === i) { + buffer = ""; + validateAtRule("@import", function () { + state = "importRule-begin"; + i += "import".length; + buffer += "@import"; + }, true); + break; + } else if (token.indexOf("@namespace", i) === i) { + buffer = ""; + validateAtRule("@namespace", function () { + state = "namespaceRule-begin"; + i += "namespace".length; + buffer += "@namespace"; + }, true); + break; + } else if (token.indexOf("@font-face", i) === i) { + buffer = ""; + // @font-face can be nested only inside CSSScopeRule or CSSConditionRule + // and only if there's no CSSStyleRule in the parent chain + var cannotBeNested = !canAtRuleBeNested(); + validateAtRule("@font-face", function () { + state = "fontFaceRule-begin"; + i += "font-face".length; + fontFaceRule = new CSSOM.CSSFontFaceRule(); + fontFaceRule.__starts = i; + }, cannotBeNested); + break; + } else { + // Reset lastIndex before using global regex (shared instance) + atKeyframesRegExp.lastIndex = i; + var matchKeyframes = atKeyframesRegExp.exec(token); + if (matchKeyframes && matchKeyframes.index === i) { + state = "keyframesRule-begin"; + keyframesRule = new CSSOM.CSSKeyframesRule(); + keyframesRule.__starts = i; + keyframesRule._vendorPrefix = matchKeyframes[1]; // Will come out as undefined if no prefix was found + i += matchKeyframes[0].length - 1; + buffer = ""; + break; + } else if (state === "selector") { + state = "atRule"; + } + } + buffer += character; + break; + + case "{": + if (currentScope === topScope) { + nestedSelectorRule = null; + } + if (state === 'before-selector') { + parseError("Unexpected {"); + i = ignoreBalancedBlock(i, token.slice(i)); + break; + } + if (state === "selector" || state === "atRule") { + if (!nestedSelectorRule && containsUnescaped(buffer, ";")) { + var ruleClosingMatch = token.slice(i).match(forwardRuleClosingBraceRegExp); + if (ruleClosingMatch) { + styleRule = null; + buffer = ""; + state = "before-selector"; + i += ruleClosingMatch.index + ruleClosingMatch[0].length; + break; + } + } + + // Ensure styleRule exists before trying to set properties on it + if (!styleRule) { + styleRule = new CSSOM.CSSStyleRule(); + styleRule.__starts = i; + } + + // Check if tokenizer detected an unmatched quote BEFORE setting up the rule + if (hasUnmatchedQuoteInSelector) { + handleUnmatchedQuoteInSelector("before-selector"); + break; + } + + var originalParentRule = parentRule; + + if (parentRule) { + styleRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + } + + currentScope = parentRule = styleRule; + + var processedSelectorText = processSelectorText(buffer.trim()); + // In a nested selector, ensure each selector contains '&' at the beginning, except for selectors that already have '&' somewhere + if (originalParentRule && originalParentRule.constructor.name === "CSSStyleRule") { + styleRule.selectorText = parseAndSplitNestedSelectors(processedSelectorText).map(function (sel) { + // Add & at the beginning if there's no & in the selector, or if it starts with a combinator + return (sel.indexOf('&') === -1 || startsWithCombinatorRegExp.test(sel)) ? '& ' + sel : sel; + }).join(', '); + } else { + // Normalize comma spacing: split by commas and rejoin with ", " + styleRule.selectorText = parseAndSplitNestedSelectors(processedSelectorText).join(', '); + } + styleRule.style.__starts = i; + styleRule.__parentStyleSheet = styleSheet; + buffer = ""; + state = "before-name"; + } else if (state === "atBlock") { + mediaRule.media.mediaText = buffer.trim(); + + if (parentRule) { + mediaRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + // If entering @media from within a CSSStyleRule, set nestedSelectorRule + // so that & selectors and declarations work correctly inside + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + + currentScope = parentRule = mediaRule; + pushToAncestorRules(mediaRule); + mediaRule.__parentStyleSheet = styleSheet; + + // Don't reset styleRule to null if it's a nested CSSStyleRule that will contain this @-rule + if (!styleRule || styleRule.constructor.name !== "CSSStyleRule" || !styleRule.__parentRule) { + styleRule = null; // Reset styleRule when entering @-rule + } + + buffer = ""; + state = "before-selector"; + } else if (state === "containerBlock") { + containerRule.__conditionText = buffer.trim(); + + if (parentRule) { + containerRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + currentScope = parentRule = containerRule; + pushToAncestorRules(containerRule); + containerRule.__parentStyleSheet = styleSheet; + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + } else if (state === "counterStyleBlock") { + var counterStyleName = buffer.trim().replace(newlineRemovalRegExp, ""); + // Validate: name cannot be empty, contain whitespace, or contain dots + var isValidCounterStyleName = counterStyleName.length > 0 && !whitespaceAndDotRegExp.test(counterStyleName); + + if (isValidCounterStyleName) { + counterStyleRule.name = counterStyleName; + if (parentRule) { + counterStyleRule.__parentRule = parentRule; + } + counterStyleRule.__parentStyleSheet = styleSheet; + styleRule = counterStyleRule; + } + buffer = ""; + } else if (state === "propertyBlock") { + var propertyName = buffer.trim().replace(newlineRemovalRegExp, ""); + // Validate: name must start with -- (custom property) + var isValidPropertyName = propertyName.indexOf("--") === 0; + + if (isValidPropertyName) { + propertyRule.__name = propertyName; + if (parentRule) { + propertyRule.__parentRule = parentRule; + } + propertyRule.__parentStyleSheet = styleSheet; + styleRule = propertyRule; + } + buffer = ""; + } else if (state === "conditionBlock") { + supportsRule.__conditionText = buffer.trim(); + + if (parentRule) { + supportsRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + + currentScope = parentRule = supportsRule; + pushToAncestorRules(supportsRule); + supportsRule.__parentStyleSheet = styleSheet; + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + } else if (state === "scopeBlock") { + var parsedScopePrelude = parseScopePrelude(buffer.trim()); + + if (parsedScopePrelude.hasStart) { + scopeRule.__start = parsedScopePrelude.startSelector; + } + if (parsedScopePrelude.hasEnd) { + scopeRule.__end = parsedScopePrelude.endSelector; + } + if (parsedScopePrelude.hasOnlyEnd) { + scopeRule.__end = parsedScopePrelude.endSelector; + } + + if (parentRule) { + scopeRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + currentScope = parentRule = scopeRule; + pushToAncestorRules(scopeRule); + scopeRule.__parentStyleSheet = styleSheet; + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + } else if (state === "layerBlock") { + layerBlockRule.name = buffer.trim(); + + var isValidName = layerBlockRule.name.length === 0 || layerBlockRule.name.match(cssCustomIdentifierRegExp) !== null; + + if (isValidName) { + if (parentRule) { + layerBlockRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + + currentScope = parentRule = layerBlockRule; + pushToAncestorRules(layerBlockRule); + layerBlockRule.__parentStyleSheet = styleSheet; + } + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + } else if (state === "pageBlock") { + pageRule.selectorText = buffer.trim(); + + if (parentRule) { + pageRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + } + + currentScope = parentRule = pageRule; + pageRule.__parentStyleSheet = styleSheet; + styleRule = pageRule; + buffer = ""; + state = "before-name"; + } else if (state === "hostRule-begin") { + if (parentRule) { + pushToAncestorRules(parentRule); + } + + currentScope = parentRule = hostRule; + pushToAncestorRules(hostRule); + hostRule.__parentStyleSheet = styleSheet; + buffer = ""; + state = "before-selector"; + } else if (state === "startingStyleRule-begin") { + if (parentRule) { + startingStyleRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + + currentScope = parentRule = startingStyleRule; + pushToAncestorRules(startingStyleRule); + startingStyleRule.__parentStyleSheet = styleSheet; + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + + } else if (state === "fontFaceRule-begin") { + if (parentRule) { + fontFaceRule.__parentRule = parentRule; + } + fontFaceRule.__parentStyleSheet = styleSheet; + styleRule = fontFaceRule; + buffer = ""; + state = "before-name"; + } else if (state === "keyframesRule-begin") { + keyframesRule.name = buffer.trim(); + if (parentRule) { + pushToAncestorRules(parentRule); + keyframesRule.__parentRule = parentRule; + } + keyframesRule.__parentStyleSheet = styleSheet; + currentScope = parentRule = keyframesRule; + buffer = ""; + state = "keyframeRule-begin"; + } else if (state === "keyframeRule-begin") { + styleRule = new CSSOM.CSSKeyframeRule(); + styleRule.keyText = buffer.trim(); + styleRule.__starts = i; + buffer = ""; + state = "before-name"; + } else if (state === "documentRule-begin") { + // FIXME: what if this '{' is in the url text of the match function? + documentRule.matcher.matcherText = buffer.trim(); + if (parentRule) { + pushToAncestorRules(parentRule); + documentRule.__parentRule = parentRule; + } + currentScope = parentRule = documentRule; + pushToAncestorRules(documentRule); + documentRule.__parentStyleSheet = styleSheet; + buffer = ""; + state = "before-selector"; + } else if (state === "before-name" || state === "name") { + // @font-face and similar rules don't support nested selectors + // If we encounter a nested selector block inside them, skip it + if (styleRule.constructor.name === "CSSFontFaceRule" || + styleRule.constructor.name === "CSSKeyframeRule" || + (styleRule.constructor.name === "CSSPageRule" && parentRule === styleRule)) { + // Skip the nested block + var ruleClosingMatch = token.slice(i).match(forwardRuleClosingBraceRegExp); + if (ruleClosingMatch) { + i += ruleClosingMatch.index + ruleClosingMatch[0].length - 1; + buffer = ""; + state = "before-name"; + break; + } + } + + if (styleRule.constructor.name === "CSSNestedDeclarations") { + if (styleRule.style.length) { + parentRule.cssRules.push(styleRule); + styleRule.__parentRule = parentRule; + styleRule.__parentStyleSheet = styleSheet; + pushToAncestorRules(parentRule); + } else { + // If the styleRule is empty, we can assume that it's a nested selector + pushToAncestorRules(parentRule); + } + } else { + currentScope = parentRule = styleRule; + pushToAncestorRules(parentRule); + styleRule.__parentStyleSheet = styleSheet; + } + + styleRule = new CSSOM.CSSStyleRule(); + + // Check if tokenizer detected an unmatched quote BEFORE setting up the rule + if (hasUnmatchedQuoteInSelector) { + handleUnmatchedQuoteInSelector("before-name"); + break; + } + + var processedSelectorText = processSelectorText(buffer.trim()); + // In a nested selector, ensure each selector contains '&' at the beginning, except for selectors that already have '&' somewhere + if (parentRule.constructor.name === "CSSScopeRule" || (parentRule.constructor.name !== "CSSStyleRule" && parentRule.parentRule === null)) { + // Normalize comma spacing: split by commas and rejoin with ", " + styleRule.selectorText = parseAndSplitNestedSelectors(processedSelectorText).join(', '); + } else { + styleRule.selectorText = parseAndSplitNestedSelectors(processedSelectorText).map(function (sel) { + // Add & at the beginning if there's no & in the selector, or if it starts with a combinator + return (sel.indexOf('&') === -1 || startsWithCombinatorRegExp.test(sel)) ? '& ' + sel : sel; + }).join(', '); + } + styleRule.style.__starts = i - buffer.length; + styleRule.__parentRule = parentRule; + // Only set nestedSelectorRule if we're directly inside a CSSStyleRule or CSSScopeRule, + // not inside other grouping rules like @media/@supports + if (parentRule.constructor.name === "CSSStyleRule" || parentRule.constructor.name === "CSSScopeRule") { + nestedSelectorRule = styleRule; + } + + // Set __parentStyleSheet for the new nested styleRule + styleRule.__parentStyleSheet = styleSheet; + + // Update currentScope and parentRule to the new nested styleRule + // so that subsequent content (like @-rules) will be children of this rule + currentScope = parentRule = styleRule; + + buffer = ""; + state = "before-name"; + } + break; + + case ":": + if (state === "name") { + // It can be a nested selector, let's check + var openBraceBeforeMatch = token.slice(i).match(declarationOrOpenBraceRegExp); + var hasOpenBraceBefore = openBraceBeforeMatch && openBraceBeforeMatch[0] === '{'; + if (hasOpenBraceBefore) { + // Is a selector + buffer += character; + } else { + // Is a declaration + name = buffer.trim(); + buffer = ""; + state = "before-value"; + } + } else { + buffer += character; + } + break; + + case "(": + if (state === 'value') { + // ie css expression mode + if (buffer.trim() === 'expression') { + var info = (new CSSOM.CSSValueExpression(token, i)).parse(); + + if (info.error) { + parseError(info.error); + } else { + buffer += info.expression; + i = info.idx; + } + } else { + state = 'value-parenthesis'; + //always ensure this is reset to 1 on transition + //from value to value-parenthesis + valueParenthesisDepth = 1; + buffer += character; + } + } else if (state === 'value-parenthesis') { + valueParenthesisDepth++; + buffer += character; + } else { + buffer += character; + } + break; + + case ")": + if (state === 'value-parenthesis') { + valueParenthesisDepth--; + if (valueParenthesisDepth === 0) state = 'value'; + } + buffer += character; + break; + + case "!": + if (state === "value" && token.indexOf("!important", i) === i) { + priority = "important"; + i += "important".length; + } else { + buffer += character; + } + break; + + case ";": + switch (state) { + case "before-value": + case "before-name": + parseError("Unexpected ;"); + buffer = ""; + state = "before-name"; + break; + case "value": + styleRule.style.setProperty(name, buffer.trim(), priority, parseError); + priority = ""; + buffer = ""; + state = "before-name"; + break; + case "atRule": + buffer = ""; + state = "before-selector"; + break; + case "importRule": + var isValid = topScope.cssRules.length === 0 || topScope.cssRules.some(function (rule) { + return ['CSSImportRule', 'CSSLayerStatementRule'].indexOf(rule.constructor.name) !== -1 + }); + if (isValid) { + importRule = new CSSOM.CSSImportRule(); + if (opts && opts.globalObject && opts.globalObject.CSSStyleSheet) { + importRule.__styleSheet = new opts.globalObject.CSSStyleSheet(); + } + importRule.styleSheet.__constructed = false; + importRule.__parentStyleSheet = importRule.styleSheet.__parentStyleSheet = styleSheet; + importRule.parse(buffer + character); + topScope.cssRules.push(importRule); + } + buffer = ""; + state = "before-selector"; + break; + case "namespaceRule": + var isValid = topScope.cssRules.length === 0 || topScope.cssRules.every(function (rule) { + return ['CSSImportRule', 'CSSLayerStatementRule', 'CSSNamespaceRule'].indexOf(rule.constructor.name) !== -1 + }); + if (isValid) { + try { + // Validate namespace syntax before creating the rule + var testNamespaceRule = new CSSOM.CSSNamespaceRule(); + testNamespaceRule.parse(buffer + character); + + namespaceRule = testNamespaceRule; + namespaceRule.__parentStyleSheet = styleSheet; + topScope.cssRules.push(namespaceRule); + + // Track the namespace prefix for validation + if (namespaceRule.prefix) { + definedNamespacePrefixes[namespaceRule.prefix] = namespaceRule.namespaceURI; + } + } catch (e) { + parseError(e.message); + } + } + buffer = ""; + state = "before-selector"; + break; + case "layerBlock": + var nameListStr = buffer.trim().split(",").map(function (name) { + return name.trim(); + }); + var isInvalid = nameListStr.some(function (name) { + return name.trim().match(cssCustomIdentifierRegExp) === null; + }); + + // Check if there's a CSSStyleRule in the parent chain + var hasStyleRuleParent = false; + if (parentRule) { + var checkParent = parentRule; + while (checkParent) { + if (checkParent.constructor.name === "CSSStyleRule") { + hasStyleRuleParent = true; + break; + } + checkParent = checkParent.__parentRule; + } + } + + if (!isInvalid && !hasStyleRuleParent) { + layerStatementRule = new CSSOM.CSSLayerStatementRule(); + layerStatementRule.__parentStyleSheet = styleSheet; + layerStatementRule.__starts = layerBlockRule.__starts; + layerStatementRule.__ends = i; + layerStatementRule.nameList = nameListStr; + + // Add to parent rule if nested, otherwise to top scope + if (parentRule) { + layerStatementRule.__parentRule = parentRule; + parentRule.cssRules.push(layerStatementRule); + } else { + topScope.cssRules.push(layerStatementRule); + } + } + buffer = ""; + state = "before-selector"; + break; + default: + buffer += character; + break; + } + break; + + case "}": + if (state === "counterStyleBlock") { + // FIXME : Implement missing properties on CSSCounterStyleRule interface and update parse method + // For now it's just assigning entire rule text + if (counterStyleRule.name) { + // Only process if name was set (valid) + counterStyleRule.parse("@counter-style " + counterStyleRule.name + " { " + buffer + " }"); + counterStyleRule.__ends = i + 1; + // Add to parent's cssRules + if (counterStyleRule.__parentRule) { + counterStyleRule.__parentRule.cssRules.push(counterStyleRule); + } else { + topScope.cssRules.push(counterStyleRule); + } + } + // Restore currentScope to parent after closing this rule + if (counterStyleRule.__parentRule) { + currentScope = counterStyleRule.__parentRule; + } + styleRule = null; + buffer = ""; + state = "before-selector"; + break; + } + if (state === "propertyBlock") { + // Only process if name was set (valid) + if (propertyRule.__name) { + var parseSuccess = propertyRule.parse("@property " + propertyRule.__name + " { " + buffer + " }"); + // Only add the rule if parse was successful (syntax, inherits, and initial-value validation passed) + if (parseSuccess) { + propertyRule.__ends = i + 1; + // Add to parent's cssRules + if (propertyRule.__parentRule) { + propertyRule.__parentRule.cssRules.push(propertyRule); + } else { + topScope.cssRules.push(propertyRule); + } + } + } + // Restore currentScope to parent after closing this rule + if (propertyRule.__parentRule) { + currentScope = propertyRule.__parentRule; + } + styleRule = null; + buffer = ""; + state = "before-selector"; + break; + } + switch (state) { + case "value": + styleRule.style.setProperty(name, buffer.trim(), priority, parseError); + priority = ""; + /* falls through */ + case "before-value": + case "before-name": + case "name": + styleRule.__ends = i + 1; + + if (parentRule === styleRule) { + parentRule = ancestorRules.pop() + } + + if (parentRule) { + styleRule.__parentRule = parentRule; + } + styleRule.__parentStyleSheet = styleSheet; + + if (currentScope === styleRule) { + currentScope = parentRule || topScope; + } + + if (styleRule.constructor.name === "CSSStyleRule" && !isValidSelectorText(styleRule.selectorText)) { + if (styleRule === nestedSelectorRule) { + nestedSelectorRule = null; + } + parseError('Invalid CSSStyleRule (selectorText = "' + styleRule.selectorText + '")', styleRule.parentRule !== null); + } else { + if (styleRule.parentRule) { + styleRule.parentRule.cssRules.push(styleRule); + } else { + currentScope.cssRules.push(styleRule); + } + } + buffer = ""; + if (currentScope.constructor === CSSOM.CSSKeyframesRule) { + state = "keyframeRule-begin"; + } else { + state = "before-selector"; + } + + if (styleRule.constructor.name === "CSSNestedDeclarations") { + if (currentScope !== topScope) { + // Only set nestedSelectorRule if currentScope is CSSStyleRule or CSSScopeRule + // Not for other grouping rules like @media/@supports + if (currentScope.constructor.name === "CSSStyleRule" || currentScope.constructor.name === "CSSScopeRule") { + nestedSelectorRule = currentScope; + } + } + styleRule = null; + } else { + // Update nestedSelectorRule when closing a CSSStyleRule + if (styleRule === nestedSelectorRule) { + var selector = styleRule.selectorText && styleRule.selectorText.trim(); + // Check if this is proper nesting (&.class, &:pseudo) vs prepended & (& :is, & .class with space) + // Prepended & has pattern "& X" where X starts with : or . + var isPrependedAmpersand = selector && selector.match(prependedAmpersandRegExp); + + // Check if parent is a grouping rule that can contain nested selectors + var isGroupingRule = currentScope && currentScope instanceof CSSOM.CSSGroupingRule; + + if (!isPrependedAmpersand && isGroupingRule) { + // Proper nesting - set nestedSelectorRule to parent for more nested selectors + // But only if it's a CSSStyleRule or CSSScopeRule, not other grouping rules like @media + if (currentScope.constructor.name === "CSSStyleRule" || currentScope.constructor.name === "CSSScopeRule") { + nestedSelectorRule = currentScope; + } + // If currentScope is another type of grouping rule (like @media), keep nestedSelectorRule unchanged + } else { + // Prepended & or not nested in grouping rule - reset to prevent CSSNestedDeclarations + nestedSelectorRule = null; + } + } else if (nestedSelectorRule && currentScope instanceof CSSOM.CSSGroupingRule) { + // When closing a nested rule that's not the nestedSelectorRule itself, + // maintain nestedSelectorRule if we're still inside a grouping rule + // This ensures declarations after nested selectors inside @media/@supports etc. work correctly + } + styleRule = null; + break; + } + case "keyframeRule-begin": + case "before-selector": + case "selector": + // End of media/supports/document rule. + if (!parentRule) { + parseError("Unexpected }"); + + var hasPreviousStyleRule = currentScope.cssRules.length && currentScope.cssRules[currentScope.cssRules.length - 1].constructor.name === "CSSStyleRule"; + if (hasPreviousStyleRule) { + i = ignoreBalancedBlock(i, token.slice(i), 1); + } + + break; + } + + // Find the actual parent rule by popping from ancestor stack + while (ancestorRules.length > 0) { + parentRule = ancestorRules.pop(); + + // Skip if we popped the current scope itself (happens because we push both rule and parent) + if (parentRule === currentScope) { + continue; + } + + // Only process valid grouping rules + if (!(parentRule instanceof CSSOM.CSSGroupingRule && (parentRule.constructor.name !== 'CSSStyleRule' || parentRule.__parentRule))) { + continue; + } + + // Determine if we're closing a special nested selector context + var isClosingNestedSelectorContext = nestedSelectorRule && + (currentScope === nestedSelectorRule || nestedSelectorRule.__parentRule === currentScope); + + if (isClosingNestedSelectorContext) { + // Closing the nestedSelectorRule or its direct container + if (nestedSelectorRule.parentRule) { + // Add nestedSelectorRule to its parent and update scope + prevScope = nestedSelectorRule; + currentScope = nestedSelectorRule.parentRule; + // Use object lookup instead of O(n) indexOf + var scopeId = getRuleId(prevScope); + if (!addedToCurrentScope[scopeId]) { + currentScope.cssRules.push(prevScope); + addedToCurrentScope[scopeId] = true; + } + nestedSelectorRule = currentScope; + // Stop here to preserve context for sibling selectors + break; + } else { + // Top-level CSSStyleRule with nested grouping rule + prevScope = currentScope; + var actualParent = ancestorRules.length > 0 ? ancestorRules[ancestorRules.length - 1] : nestedSelectorRule; + if (actualParent !== prevScope) { + actualParent.cssRules.push(prevScope); + } + currentScope = actualParent; + parentRule = actualParent; + break; + } + } else { + // Regular case: add currentScope to parentRule + prevScope = currentScope; + if (parentRule !== prevScope) { + parentRule.cssRules.push(prevScope); + } + break; + } + } + + // If currentScope has a __parentRule and wasn't added yet, add it + if (ancestorRules.length === 0 && currentScope.__parentRule && currentScope.__parentRule.cssRules) { + // Use object lookup instead of O(n) findIndex + var parentId = getRuleId(currentScope); + if (!addedToParent[parentId]) { + currentScope.__parentRule.cssRules.push(currentScope); + addedToParent[parentId] = true; + } + } + + // Only handle top-level rule closing if we processed all ancestors + if (ancestorRules.length === 0 && currentScope.parentRule == null) { + currentScope.__ends = i + 1; + // Use object lookup instead of O(n) findIndex + var topId = getRuleId(currentScope); + if (currentScope !== topScope && !addedToTopScope[topId]) { + topScope.cssRules.push(currentScope); + addedToTopScope[topId] = true; + } + currentScope = topScope; + if (nestedSelectorRule === parentRule) { + // Check if this selector is really starting inside another selector + var nestedSelectorTokenToCurrentSelectorToken = token.slice(nestedSelectorRule.__starts, i + 1); + var openingBraceMatch = nestedSelectorTokenToCurrentSelectorToken.match(openBraceGlobalRegExp); + var closingBraceMatch = nestedSelectorTokenToCurrentSelectorToken.match(closeBraceGlobalRegExp); + var openingBraceLen = openingBraceMatch && openingBraceMatch.length; + var closingBraceLen = closingBraceMatch && closingBraceMatch.length; + + if (openingBraceLen === closingBraceLen) { + // If the number of opening and closing braces are equal, we can assume that the new selector is starting outside the nestedSelectorRule + nestedSelectorRule.__ends = i + 1; + nestedSelectorRule = null; + parentRule = null; + } + } else { + parentRule = null; + } + } else { + currentScope = parentRule; + } + + buffer = ""; + state = "before-selector"; + break; + } + break; + + default: + switch (state) { + case "before-selector": + state = "selector"; + if ((styleRule || scopeRule) && parentRule) { + // Assuming it's a declaration inside Nested Selector OR a Nested Declaration + // If Declaration inside Nested Selector let's keep the same styleRule + if (!isSelectorStartChar(character) && !isWhitespaceChar(character) && parentRule instanceof CSSOM.CSSGroupingRule) { + // parentRule.__parentRule = styleRule; + state = "before-name"; + if (styleRule !== parentRule) { + styleRule = new CSSOM.CSSNestedDeclarations(); + styleRule.__starts = i; + } + } + + } else if (nestedSelectorRule && parentRule && parentRule instanceof CSSOM.CSSGroupingRule) { + if (isSelectorStartChar(character)) { + // If starting with a selector character, create CSSStyleRule instead of CSSNestedDeclarations + styleRule = new CSSOM.CSSStyleRule(); + styleRule.__starts = i; + } else if (!isWhitespaceChar(character)) { + // Starting a declaration (not whitespace, not a selector) + state = "before-name"; + // Check if we should create CSSNestedDeclarations + // This happens if: parent has cssRules OR nestedSelectorRule exists (indicating CSSStyleRule in hierarchy) + if (parentRule.cssRules.length || nestedSelectorRule) { + currentScope = parentRule; + // Only set nestedSelectorRule if parentRule is CSSStyleRule or CSSScopeRule + if (parentRule.constructor.name === "CSSStyleRule" || parentRule.constructor.name === "CSSScopeRule") { + nestedSelectorRule = parentRule; + } + styleRule = new CSSOM.CSSNestedDeclarations(); + styleRule.__starts = i; + } else { + if (parentRule.constructor.name === "CSSStyleRule") { + styleRule = parentRule; + } else { + styleRule = new CSSOM.CSSStyleRule(); + styleRule.__starts = i; + } + } + } + } + break; + case "before-name": + state = "name"; + break; + case "before-value": + state = "value"; + break; + case "importRule-begin": + state = "importRule"; + break; + case "namespaceRule-begin": + state = "namespaceRule"; + break; + } + buffer += character; + break; + } + + // Auto-close all unclosed nested structures + // Check AFTER processing the character, at the ORIGINAL ending index + // Only add closing braces if CSS is incomplete (not at top scope) + if (i === initialEndingIndex && (currentScope !== topScope || ancestorRules.length > 0)) { + var needsClosing = ancestorRules.length; + if (currentScope !== topScope && ancestorRules.indexOf(currentScope) === -1) { + needsClosing += 1; + } + // Add closing braces for all unclosed structures + for (var closeIdx = 0; closeIdx < needsClosing; closeIdx++) { + token += "}"; + endingIndex += 1; + } + } + } + + if (buffer.trim() !== "") { + parseError("Unexpected end of input"); + } + + return styleSheet; +}; + + + + + + +/** + * Produces a deep copy of stylesheet — the instance variables of stylesheet are copied recursively. + * @param {CSSStyleSheet|CSSOM.CSSStyleSheet} stylesheet + * @nosideeffects + * @return {CSSOM.CSSStyleSheet} + */ +CSSOM.clone = function clone(stylesheet) { + + var cloned = new CSSOM.CSSStyleSheet(); + + var rules = stylesheet.cssRules; + if (!rules) { + return cloned; + } + + for (var i = 0, rulesLength = rules.length; i < rulesLength; i++) { + var rule = rules[i]; + var ruleClone = cloned.cssRules[i] = new rule.constructor(); + + var style = rule.style; + if (style) { + var styleClone = ruleClone.style = new CSSOM.CSSStyleDeclaration(); + for (var j = 0, styleLength = style.length; j < styleLength; j++) { + var name = styleClone[j] = style[j]; + styleClone[name] = style[name]; + styleClone._importants[name] = style.getPropertyPriority(name); + } + styleClone.length = style.length; + } + + if (rule.hasOwnProperty('keyText')) { + ruleClone.keyText = rule.keyText; + } + + if (rule.hasOwnProperty('selectorText')) { + ruleClone.selectorText = rule.selectorText; + } + + if (rule.hasOwnProperty('mediaText')) { + ruleClone.mediaText = rule.mediaText; + } + + if (rule.hasOwnProperty('supportsText')) { + ruleClone.supports = rule.supports; + } + + if (rule.hasOwnProperty('conditionText')) { + ruleClone.conditionText = rule.conditionText; + } + + if (rule.hasOwnProperty('layerName')) { + ruleClone.layerName = rule.layerName; + } + + if (rule.hasOwnProperty('href')) { + ruleClone.href = rule.href; + } + + if (rule.hasOwnProperty('name')) { + ruleClone.name = rule.name; + } + + if (rule.hasOwnProperty('nameList')) { + ruleClone.nameList = rule.nameList; + } + + if (rule.hasOwnProperty('cssRules')) { + ruleClone.cssRules = clone(rule).cssRules; + } + } + + return cloned; + +}; + + diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSConditionRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSConditionRule.js new file mode 100644 index 0000000..528cdfc --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSConditionRule.js @@ -0,0 +1,32 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + CSSGroupingRule: require("./CSSGroupingRule").CSSGroupingRule +}; +///CommonJS + + +/** + * @constructor + * @see https://www.w3.org/TR/css-conditional-3/#the-cssconditionrule-interface + */ +CSSOM.CSSConditionRule = function CSSConditionRule() { + CSSOM.CSSGroupingRule.call(this); + this.__conditionText = ''; +}; + +CSSOM.CSSConditionRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSConditionRule.prototype.constructor = CSSOM.CSSConditionRule; + +Object.setPrototypeOf(CSSOM.CSSConditionRule, CSSOM.CSSGroupingRule); + +Object.defineProperty(CSSOM.CSSConditionRule.prototype, "conditionText", { + get: function () { + return this.__conditionText; + } +}); + +//.CommonJS +exports.CSSConditionRule = CSSOM.CSSConditionRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSContainerRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSContainerRule.js new file mode 100644 index 0000000..68fa332 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSContainerRule.js @@ -0,0 +1,70 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + CSSGroupingRule: require("./CSSGroupingRule").CSSGroupingRule, + CSSConditionRule: require("./CSSConditionRule").CSSConditionRule, +}; +///CommonJS + + +/** + * @constructor + * @see https://drafts.csswg.org/css-contain-3/ + * @see https://www.w3.org/TR/css-contain-3/ + */ +CSSOM.CSSContainerRule = function CSSContainerRule() { + CSSOM.CSSConditionRule.call(this); +}; + +CSSOM.CSSContainerRule.prototype = Object.create(CSSOM.CSSConditionRule.prototype); +CSSOM.CSSContainerRule.prototype.constructor = CSSOM.CSSContainerRule; + +Object.setPrototypeOf(CSSOM.CSSContainerRule, CSSOM.CSSConditionRule); + +Object.defineProperty(CSSOM.CSSContainerRule.prototype, "type", { + value: 17, + writable: false +}); + +Object.defineProperties(CSSOM.CSSContainerRule.prototype, { + "cssText": { + get: function() { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@container " + this.conditionText + values; + } + }, + "containerName": { + get: function() { + var parts = this.conditionText.trim().split(/\s+/); + if (parts.length > 1 && parts[0] !== '(' && !parts[0].startsWith('(')) { + return parts[0]; + } + return ""; + } + }, + "containerQuery": { + get: function() { + var parts = this.conditionText.trim().split(/\s+/); + if (parts.length > 1 && parts[0] !== '(' && !parts[0].startsWith('(')) { + return parts.slice(1).join(' '); + } + return this.conditionText; + } + }, +}); + + +//.CommonJS +exports.CSSContainerRule = CSSOM.CSSContainerRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSCounterStyleRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSCounterStyleRule.js new file mode 100644 index 0000000..44c4330 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSCounterStyleRule.js @@ -0,0 +1,57 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule +}; +///CommonJS + + +/** + * @constructor + * @see https://drafts.csswg.org/css-counter-styles/#the-csscounterstylerule-interface + */ +CSSOM.CSSCounterStyleRule = function CSSCounterStyleRule() { + CSSOM.CSSRule.call(this); + this.name = ""; + this.__props = ""; +}; + +CSSOM.CSSCounterStyleRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSCounterStyleRule.prototype.constructor = CSSOM.CSSCounterStyleRule; + +Object.setPrototypeOf(CSSOM.CSSCounterStyleRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSCounterStyleRule.prototype, "type", { + value: 11, + writable: false +}); + +Object.defineProperty(CSSOM.CSSCounterStyleRule.prototype, "cssText", { + get: function() { + // FIXME : Implement real cssText generation based on properties + return "@counter-style " + this.name + " { " + this.__props + " }"; + } +}); + +/** + * NON-STANDARD + * Rule text parser. + * @param {string} cssText + */ +Object.defineProperty(CSSOM.CSSCounterStyleRule.prototype, "parse", { + value: function(cssText) { + // Extract the name from "@counter-style { ... }" + var match = cssText.match(/@counter-style\s+([^\s{]+)\s*\{([^]*)\}/); + if (match) { + this.name = match[1]; + // Get the text inside the brackets and clean it up + var propsText = match[2]; + this.__props = propsText.trim().replace(/\n/g, " ").replace(/(['"])(?:\\.|[^\\])*?\1|(\s{2,})/g, function (match, quote) { + return quote ? match : ' '; + }); + } + } +}); + +//.CommonJS +exports.CSSCounterStyleRule = CSSOM.CSSCounterStyleRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSDocumentRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSDocumentRule.js new file mode 100644 index 0000000..06d9872 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSDocumentRule.js @@ -0,0 +1,48 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + MatcherList: require("./MatcherList").MatcherList +}; +///CommonJS + + +/** + * @constructor + * @see https://developer.mozilla.org/en/CSS/@-moz-document + * @deprecated This rule is a non-standard Mozilla-specific extension and is not part of any official CSS specification. + */ +CSSOM.CSSDocumentRule = function CSSDocumentRule() { + CSSOM.CSSRule.call(this); + this.matcher = new CSSOM.MatcherList(); + this.cssRules = new CSSOM.CSSRuleList(); +}; + +CSSOM.CSSDocumentRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSDocumentRule.prototype.constructor = CSSOM.CSSDocumentRule; + +Object.setPrototypeOf(CSSOM.CSSDocumentRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSDocumentRule.prototype, "type", { + value: 10, + writable: false +}); + +//FIXME +//CSSOM.CSSDocumentRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSDocumentRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSDocumentRule.prototype, "cssText", { + get: function() { + var cssTexts = []; + for (var i=0, length=this.cssRules.length; i < length; i++) { + cssTexts.push(this.cssRules[i].cssText); + } + return "@-moz-document " + this.matcher.matcherText + " {" + (cssTexts.length ? "\n " + cssTexts.join("\n ") : "") + "\n}"; + } +}); + + +//.CommonJS +exports.CSSDocumentRule = CSSOM.CSSDocumentRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSFontFaceRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSFontFaceRule.js new file mode 100644 index 0000000..e1534d3 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSFontFaceRule.js @@ -0,0 +1,62 @@ +//.CommonJS +var CSSOM = { + CSSStyleDeclaration: require("./CSSStyleDeclaration").CSSStyleDeclaration, + CSSRule: require("./CSSRule").CSSRule +}; +// Use cssstyle if available +try { + CSSOM.CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; +} catch (e) { + // ignore +} +///CommonJS + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#css-font-face-rule + */ +CSSOM.CSSFontFaceRule = function CSSFontFaceRule() { + CSSOM.CSSRule.call(this); + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSFontFaceRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSFontFaceRule.prototype.constructor = CSSOM.CSSFontFaceRule; + +Object.setPrototypeOf(CSSOM.CSSFontFaceRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "type", { + value: 5, + writable: false +}); + +//FIXME +//CSSOM.CSSFontFaceRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSFontFaceRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + } +}); + +// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSFontFaceRule.cpp +Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "cssText", { + get: function() { + return "@font-face {" + (this.style.cssText ? " " + this.style.cssText : "") + " }"; + } +}); + + +//.CommonJS +exports.CSSFontFaceRule = CSSOM.CSSFontFaceRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSGroupingRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSGroupingRule.js new file mode 100644 index 0000000..31d3010 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSGroupingRule.js @@ -0,0 +1,165 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + parse: require('./parse').parse +}; +var errorUtils = require("./errorUtils").errorUtils; +///CommonJS + + +/** + * @constructor + * @see https://drafts.csswg.org/cssom/#the-cssgroupingrule-interface + */ +CSSOM.CSSGroupingRule = function CSSGroupingRule() { + CSSOM.CSSRule.call(this); + this.__cssRules = new CSSOM.CSSRuleList(); +}; + +CSSOM.CSSGroupingRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSGroupingRule.prototype.constructor = CSSOM.CSSGroupingRule; + +Object.setPrototypeOf(CSSOM.CSSGroupingRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSGroupingRule.prototype, "cssRules", { + get: function() { + return this.__cssRules; + } +}); + +/** + * Used to insert a new CSS rule to a list of CSS rules. + * + * @example + * cssGroupingRule.cssText + * -> "body{margin:0;}" + * cssGroupingRule.insertRule("img{border:none;}", 1) + * -> 1 + * cssGroupingRule.cssText + * -> "body{margin:0;}img{border:none;}" + * + * @param {string} rule + * @param {number} [index] + * @see https://www.w3.org/TR/cssom-1/#dom-cssgroupingrule-insertrule + * @return {number} The index within the grouping rule's collection of the newly inserted rule. + */ + CSSOM.CSSGroupingRule.prototype.insertRule = function insertRule(rule, index) { + if (rule === undefined && index === undefined) { + errorUtils.throwMissingArguments(this, 'insertRule', this.constructor.name); + } + if (index === void 0) { + index = 0; + } + index = Number(index); + if (index < 0) { + index = 4294967296 + index; + } + if (index > this.cssRules.length) { + errorUtils.throwIndexError(this, 'insertRule', this.constructor.name, index, this.cssRules.length); + } + var ruleToParse = processedRuleToParse = String(rule); + ruleToParse = ruleToParse.trim().replace(/^\/\*[\s\S]*?\*\/\s*/, ""); + var isNestedSelector = this.constructor.name === "CSSStyleRule"; + if (isNestedSelector === false) { + var currentRule = this; + while (currentRule.parentRule) { + currentRule = currentRule.parentRule; + if (currentRule.constructor.name === "CSSStyleRule") { + isNestedSelector = true; + break; + } + } + } + if (isNestedSelector) { + processedRuleToParse = 's { n { } ' + ruleToParse + '}'; + } + var isScopeRule = this.constructor.name === "CSSScopeRule"; + if (isScopeRule) { + if (isNestedSelector) { + processedRuleToParse = 's { ' + '@scope {' + ruleToParse + '}}'; + } else { + processedRuleToParse = '@scope {' + ruleToParse + '}'; + } + } + var parsedRules = new CSSOM.CSSRuleList(); + CSSOM.parse(processedRuleToParse, { + styleSheet: this.parentStyleSheet, + cssRules: parsedRules + }); + if (isScopeRule) { + if (isNestedSelector) { + parsedRules = parsedRules[0].cssRules[0].cssRules; + } else { + parsedRules = parsedRules[0].cssRules + } + } + if (isNestedSelector) { + parsedRules = parsedRules[0].cssRules.slice(1); + } + if (parsedRules.length !== 1) { + if (isNestedSelector && parsedRules.length === 0 && ruleToParse.indexOf('@font-face') === 0) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': " + + "Only conditional nested group rules, style rules, @scope rules, @apply rules, and nested declaration rules may be nested.", + 'HierarchyRequestError'); + } else { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + } + var cssRule = parsedRules[0]; + + if (cssRule.constructor.name === 'CSSNestedDeclarations' && cssRule.style.length === 0) { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + + // Check for rules that cannot be inserted inside a CSSGroupingRule + if (cssRule.constructor.name === 'CSSImportRule' || cssRule.constructor.name === 'CSSNamespaceRule') { + var ruleKeyword = cssRule.constructor.name === 'CSSImportRule' ? '@import' : '@namespace'; + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': " + + "'" + ruleKeyword + "' rules cannot be inserted inside a group rule.", + 'HierarchyRequestError'); + } + + // Check for CSSLayerStatementRule (@layer statement rules) + if (cssRule.constructor.name === 'CSSLayerStatementRule') { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + + cssRule.__parentRule = this; + this.cssRules.splice(index, 0, cssRule); + return index; +}; + +/** + * Used to delete a rule from the grouping rule. + * + * cssGroupingRule.cssText + * -> "img{border:none;}body{margin:0;}" + * cssGroupingRule.deleteRule(0) + * cssGroupingRule.cssText + * -> "body{margin:0;}" + * + * @param {number} index within the grouping rule's rule list of the rule to remove. + * @see https://www.w3.org/TR/cssom-1/#dom-cssgroupingrule-deleterule + */ + CSSOM.CSSGroupingRule.prototype.deleteRule = function deleteRule(index) { + if (index === undefined) { + errorUtils.throwMissingArguments(this, 'deleteRule', this.constructor.name); + } + index = Number(index); + if (index < 0) { + index = 4294967296 + index; + } + if (index >= this.cssRules.length) { + errorUtils.throwIndexError(this, 'deleteRule', this.constructor.name, index, this.cssRules.length); + } + this.cssRules[index].__parentRule = null; + this.cssRules[index].__parentStyleSheet = null; + this.cssRules.splice(index, 1); +}; + +//.CommonJS +exports.CSSGroupingRule = CSSOM.CSSGroupingRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSHostRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSHostRule.js new file mode 100644 index 0000000..3982121 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSHostRule.js @@ -0,0 +1,54 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList +}; +///CommonJS + + +/** + * @constructor + * @see http://www.w3.org/TR/shadow-dom/#host-at-rule + * @see http://html5index.org/Shadow%20DOM%20-%20CSSHostRule.html + * @deprecated This rule was part of early Shadow DOM drafts but was removed in favor of the more flexible :host and :host-context() pseudo-classes in modern CSS for Web Components. + */ +CSSOM.CSSHostRule = function CSSHostRule() { + CSSOM.CSSRule.call(this); + this.cssRules = new CSSOM.CSSRuleList(); +}; + +CSSOM.CSSHostRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSHostRule.prototype.constructor = CSSOM.CSSHostRule; + +Object.setPrototypeOf(CSSOM.CSSHostRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSHostRule.prototype, "type", { + value: 1001, + writable: false +}); + +//FIXME +//CSSOM.CSSHostRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSHostRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSHostRule.prototype, "cssText", { + get: function() { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@host" + values; + } +}); + + +//.CommonJS +exports.CSSHostRule = CSSOM.CSSHostRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSImportRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSImportRule.js new file mode 100644 index 0000000..872c98b --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSImportRule.js @@ -0,0 +1,267 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSStyleSheet: require("./CSSStyleSheet").CSSStyleSheet, + MediaList: require("./MediaList").MediaList +}; +var regexPatterns = require("./regexPatterns").regexPatterns; +///CommonJS + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#cssimportrule + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSImportRule + */ +CSSOM.CSSImportRule = function CSSImportRule() { + CSSOM.CSSRule.call(this); + this.__href = ""; + this.__media = new CSSOM.MediaList(); + this.__layerName = null; + this.__supportsText = null; + this.__styleSheet = new CSSOM.CSSStyleSheet(); +}; + +CSSOM.CSSImportRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSImportRule.prototype.constructor = CSSOM.CSSImportRule; + +Object.setPrototypeOf(CSSOM.CSSImportRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "type", { + value: 3, + writable: false +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "cssText", { + get: function() { + var mediaText = this.media.mediaText; + return "@import url(\"" + this.href.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + "\")" + (this.layerName !== null ? " layer" + (this.layerName && "(" + this.layerName + ")") : "" ) + (this.supportsText ? " supports(" + this.supportsText + ")" : "" ) + (mediaText ? " " + mediaText : "") + ";"; + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "href", { + get: function() { + return this.__href; + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "media", { + get: function() { + return this.__media; + }, + set: function(value) { + if (typeof value === "string") { + this.__media.mediaText = value; + } else { + this.__media = value; + } + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "layerName", { + get: function() { + return this.__layerName; + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "supportsText", { + get: function() { + return this.__supportsText; + } +}); + +Object.defineProperty(CSSOM.CSSImportRule.prototype, "styleSheet", { + get: function() { + return this.__styleSheet; + } +}); + +/** + * NON-STANDARD + * Rule text parser. + * @param {string} cssText + */ +Object.defineProperty(CSSOM.CSSImportRule.prototype, "parse", { + value: function(cssText) { + var i = 0; + + /** + * @import url(partial.css) screen, handheld; + * || | + * after-import media + * | + * url + */ + var state = ''; + + var buffer = ''; + var index; + + var layerRegExp = regexPatterns.layerRegExp; + var layerRuleNameRegExp = regexPatterns.layerRuleNameRegExp; + var doubleOrMoreSpacesRegExp = regexPatterns.doubleOrMoreSpacesRegExp; + + /** + * Extracts the content inside supports() handling nested parentheses. + * @param {string} text - The text to parse + * @returns {object|null} - {content: string, endIndex: number} or null if not found + */ + function extractSupportsContent(text) { + var supportsIndex = text.indexOf('supports('); + if (supportsIndex !== 0) { + return null; + } + + var depth = 0; + var start = supportsIndex + 'supports('.length; + var i = start; + + for (; i < text.length; i++) { + if (text[i] === '(') { + depth++; + } else if (text[i] === ')') { + if (depth === 0) { + // Found the closing parenthesis for supports() + return { + content: text.slice(start, i), + endIndex: i + }; + } + depth--; + } + } + + return null; // Unbalanced parentheses + } + + for (var character; (character = cssText.charAt(i)); i++) { + + switch (character) { + case ' ': + case '\t': + case '\r': + case '\n': + case '\f': + if (state === 'after-import') { + state = 'url'; + } else { + buffer += character; + } + break; + + case '@': + if (!state && cssText.indexOf('@import', i) === i) { + state = 'after-import'; + i += 'import'.length; + buffer = ''; + } + break; + + case 'u': + if (state === 'media') { + buffer += character; + } + if (state === 'url' && cssText.indexOf('url(', i) === i) { + index = cssText.indexOf(')', i + 1); + if (index === -1) { + throw i + ': ")" not found'; + } + i += 'url('.length; + var url = cssText.slice(i, index); + if (url[0] === url[url.length - 1]) { + if (url[0] === '"' || url[0] === "'") { + url = url.slice(1, -1); + } + } + this.__href = url; + i = index; + state = 'media'; + } + break; + + case '"': + if (state === 'after-import' || state === 'url') { + index = cssText.indexOf('"', i + 1); + if (!index) { + throw i + ": '\"' not found"; + } + this.__href = cssText.slice(i + 1, index); + i = index; + state = 'media'; + } + break; + + case "'": + if (state === 'after-import' || state === 'url') { + index = cssText.indexOf("'", i + 1); + if (!index) { + throw i + ': "\'" not found'; + } + this.__href = cssText.slice(i + 1, index); + i = index; + state = 'media'; + } + break; + + case ';': + if (state === 'media') { + if (buffer) { + var bufferTrimmed = buffer.trim(); + + if (bufferTrimmed.indexOf('layer') === 0) { + var layerMatch = bufferTrimmed.match(layerRegExp); + + if (layerMatch) { + var layerName = layerMatch[1].trim(); + + if (layerName.match(layerRuleNameRegExp) !== null) { + this.__layerName = layerMatch[1].trim(); + bufferTrimmed = bufferTrimmed.replace(layerRegExp, '') + .replace(doubleOrMoreSpacesRegExp, ' ') // Replace double or more spaces with single space + .trim(); + } else { + // REVIEW: In the browser, an empty layer() is not processed as a unamed layer + // and treats the rest of the string as mediaText, ignoring the parse of supports() + if (bufferTrimmed) { + this.media.mediaText = bufferTrimmed; + return; + } + } + } else { + this.__layerName = ""; + bufferTrimmed = bufferTrimmed.substring('layer'.length).trim() + } + } + + var supportsResult = extractSupportsContent(bufferTrimmed); + + if (supportsResult) { + // REVIEW: In the browser, an empty supports() invalidates and ignores the entire @import rule + this.__supportsText = supportsResult.content.trim(); + // Remove the entire supports(...) from the buffer + bufferTrimmed = bufferTrimmed.slice(0, 0) + bufferTrimmed.slice(supportsResult.endIndex + 1); + bufferTrimmed = bufferTrimmed.replace(doubleOrMoreSpacesRegExp, ' ').trim(); + } + + // REVIEW: In the browser, any invalid media is replaced with 'not all' + if (bufferTrimmed) { + this.media.mediaText = bufferTrimmed; + } + } + } + break; + + default: + if (state === 'media') { + buffer += character; + } + break; + } + } + } +}); + + +//.CommonJS +exports.CSSImportRule = CSSOM.CSSImportRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSKeyframeRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSKeyframeRule.js new file mode 100644 index 0000000..ebf628c --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSKeyframeRule.js @@ -0,0 +1,63 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSStyleDeclaration: require('./CSSStyleDeclaration').CSSStyleDeclaration +}; +// Use cssstyle if available +try { + CSSOM.CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; +} catch (e) { + // ignore +} +///CommonJS + + +/** + * @constructor + * @see http://www.w3.org/TR/css3-animations/#DOM-CSSKeyframeRule + */ +CSSOM.CSSKeyframeRule = function CSSKeyframeRule() { + CSSOM.CSSRule.call(this); + this.keyText = ''; + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSKeyframeRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSKeyframeRule.prototype.constructor = CSSOM.CSSKeyframeRule; + +Object.setPrototypeOf(CSSOM.CSSKeyframeRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "type", { + value: 8, + writable: false +}); + +//FIXME +//CSSOM.CSSKeyframeRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSKeyframeRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + } +}); + +// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSKeyframeRule.cpp +Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "cssText", { + get: function() { + return this.keyText + " {" + (this.style.cssText ? " " + this.style.cssText : "") + " }"; + } +}); + + +//.CommonJS +exports.CSSKeyframeRule = CSSOM.CSSKeyframeRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSKeyframesRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSKeyframesRule.js new file mode 100644 index 0000000..a98cd78 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSKeyframesRule.js @@ -0,0 +1,247 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + parse: require("./parse").parse +}; +var errorUtils = require("./errorUtils").errorUtils; +///CommonJS + + +/** + * @constructor + * @see http://www.w3.org/TR/css3-animations/#DOM-CSSKeyframesRule + */ +CSSOM.CSSKeyframesRule = function CSSKeyframesRule() { + CSSOM.CSSRule.call(this); + this.name = ''; + this.cssRules = new CSSOM.CSSRuleList(); + + // Set up initial indexed access + this._setupIndexedAccess(); + + // Override cssRules methods after initial setup, store references as non-enumerable properties + var self = this; + var originalPush = this.cssRules.push; + var originalSplice = this.cssRules.splice; + + // Create non-enumerable method overrides + Object.defineProperty(this.cssRules, 'push', { + value: function() { + var result = originalPush.apply(this, arguments); + self._setupIndexedAccess(); + return result; + }, + writable: true, + enumerable: false, + configurable: true + }); + + Object.defineProperty(this.cssRules, 'splice', { + value: function() { + var result = originalSplice.apply(this, arguments); + self._setupIndexedAccess(); + return result; + }, + writable: true, + enumerable: false, + configurable: true + }); +}; + +CSSOM.CSSKeyframesRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSKeyframesRule.prototype.constructor = CSSOM.CSSKeyframesRule; + +Object.setPrototypeOf(CSSOM.CSSKeyframesRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSKeyframesRule.prototype, "type", { + value: 7, + writable: false +}); + +// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSKeyframesRule.cpp +Object.defineProperty(CSSOM.CSSKeyframesRule.prototype, "cssText", { + get: function() { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + var cssWideKeywords = ['initial', 'inherit', 'revert', 'revert-layer', 'unset', 'none']; + var processedName = cssWideKeywords.includes(this.name) ? '"' + this.name + '"' : this.name; + return "@" + (this._vendorPrefix || '') + "keyframes " + processedName + values; + } +}); + +/** + * Appends a new keyframe rule to the list of keyframes. + * + * @param {string} rule - The keyframe rule string to append (e.g., "50% { opacity: 0.5; }") + * @see https://www.w3.org/TR/css-animations-1/#dom-csskeyframesrule-appendrule + */ +CSSOM.CSSKeyframesRule.prototype.appendRule = function appendRule(rule) { + if (arguments.length === 0) { + errorUtils.throwMissingArguments(this, 'appendRule', 'CSSKeyframesRule'); + } + + var parsedRule; + try { + // Parse the rule string as a keyframe rule + var tempStyleSheet = CSSOM.parse("@keyframes temp { " + rule + " }"); + if (tempStyleSheet.cssRules.length > 0 && tempStyleSheet.cssRules[0].cssRules.length > 0) { + parsedRule = tempStyleSheet.cssRules[0].cssRules[0]; + } else { + throw new Error("Failed to parse keyframe rule"); + } + } catch (e) { + errorUtils.throwParseError(this, 'appendRule', 'CSSKeyframesRule', rule); + } + + parsedRule.__parentRule = this; + this.cssRules.push(parsedRule); +}; + +/** + * Deletes a keyframe rule that matches the specified key. + * + * @param {string} select - The keyframe selector to delete (e.g., "50%", "from", "to") + * @see https://www.w3.org/TR/css-animations-1/#dom-csskeyframesrule-deleterule + */ +CSSOM.CSSKeyframesRule.prototype.deleteRule = function deleteRule(select) { + if (arguments.length === 0) { + errorUtils.throwMissingArguments(this, 'deleteRule', 'CSSKeyframesRule'); + } + + var normalizedSelect = this._normalizeKeyText(select); + + for (var i = 0; i < this.cssRules.length; i++) { + var rule = this.cssRules[i]; + if (this._normalizeKeyText(rule.keyText) === normalizedSelect) { + rule.__parentRule = null; + this.cssRules.splice(i, 1); + return; + } + } +}; + +/** + * Finds and returns the keyframe rule that matches the specified key. + * When multiple rules have the same key, returns the last one. + * + * @param {string} select - The keyframe selector to find (e.g., "50%", "from", "to") + * @return {CSSKeyframeRule|null} The matching keyframe rule, or null if not found + * @see https://www.w3.org/TR/css-animations-1/#dom-csskeyframesrule-findrule + */ +CSSOM.CSSKeyframesRule.prototype.findRule = function findRule(select) { + if (arguments.length === 0) { + errorUtils.throwMissingArguments(this, 'findRule', 'CSSKeyframesRule'); + } + + var normalizedSelect = this._normalizeKeyText(select); + + // Iterate backwards to find the last matching rule + for (var i = this.cssRules.length - 1; i >= 0; i--) { + var rule = this.cssRules[i]; + if (this._normalizeKeyText(rule.keyText) === normalizedSelect) { + return rule; + } + } + + return null; +}; + +/** + * Normalizes keyframe selector text for comparison. + * Handles "from" -> "0%" and "to" -> "100%" conversions and trims whitespace. + * + * @private + * @param {string} keyText - The keyframe selector text to normalize + * @return {string} The normalized keyframe selector text + */ +CSSOM.CSSKeyframesRule.prototype._normalizeKeyText = function _normalizeKeyText(keyText) { + if (!keyText) return ''; + + var normalized = keyText.toString().trim().toLowerCase(); + + // Convert keywords to percentages for comparison + if (normalized === 'from') { + return '0%'; + } else if (normalized === 'to') { + return '100%'; + } + + return normalized; +}; + +/** + * Makes CSSKeyframesRule iterable over its cssRules. + * Allows for...of loops and other iterable methods. + */ +if (typeof Symbol !== 'undefined' && Symbol.iterator) { + CSSOM.CSSKeyframesRule.prototype[Symbol.iterator] = function() { + var index = 0; + var cssRules = this.cssRules; + + return { + next: function() { + if (index < cssRules.length) { + return { value: cssRules[index++], done: false }; + } else { + return { done: true }; + } + } + }; + }; +} + +/** + * Adds indexed getters for direct access to cssRules by index. + * This enables rule[0], rule[1], etc. access patterns. + * Works in environments where Proxy is not available (like jsdom). + */ +CSSOM.CSSKeyframesRule.prototype._setupIndexedAccess = function() { + // Remove any existing indexed properties + for (var i = 0; i < 1000; i++) { // reasonable upper limit + if (this.hasOwnProperty(i)) { + delete this[i]; + } else { + break; + } + } + + // Add indexed getters for current cssRules + for (var i = 0; i < this.cssRules.length; i++) { + (function(index) { + Object.defineProperty(this, index, { + get: function() { + return this.cssRules[index]; + }, + enumerable: false, + configurable: true + }); + }.call(this, i)); + } + + // Update length property + Object.defineProperty(this, 'length', { + get: function() { + return this.cssRules.length; + }, + enumerable: false, + configurable: true + }); +}; + + + + + +//.CommonJS +exports.CSSKeyframesRule = CSSOM.CSSKeyframesRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSLayerBlockRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSLayerBlockRule.js new file mode 100644 index 0000000..69bed0f --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSLayerBlockRule.js @@ -0,0 +1,49 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + CSSGroupingRule: require("./CSSGroupingRule").CSSGroupingRule, +}; +///CommonJS + +/** + * @constructor + * @see https://drafts.csswg.org/css-cascade-5/#csslayerblockrule + */ +CSSOM.CSSLayerBlockRule = function CSSLayerBlockRule() { + CSSOM.CSSGroupingRule.call(this); + this.name = ""; +}; + +CSSOM.CSSLayerBlockRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSLayerBlockRule.prototype.constructor = CSSOM.CSSLayerBlockRule; + +Object.setPrototypeOf(CSSOM.CSSLayerBlockRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSLayerBlockRule.prototype, "type", { + value: 18, + writable: false +}); + +Object.defineProperties(CSSOM.CSSLayerBlockRule.prototype, { + cssText: { + get: function () { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@layer" + (this.name ? " " + this.name : "") + values; + } + }, +}); + +//.CommonJS +exports.CSSLayerBlockRule = CSSOM.CSSLayerBlockRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSLayerStatementRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSLayerStatementRule.js new file mode 100644 index 0000000..238abaf --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSLayerStatementRule.js @@ -0,0 +1,36 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, +}; +///CommonJS + +/** + * @constructor + * @see https://drafts.csswg.org/css-cascade-5/#csslayerstatementrule + */ +CSSOM.CSSLayerStatementRule = function CSSLayerStatementRule() { + CSSOM.CSSRule.call(this); + this.nameList = []; +}; + +CSSOM.CSSLayerStatementRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSLayerStatementRule.prototype.constructor = CSSOM.CSSLayerStatementRule; + +Object.setPrototypeOf(CSSOM.CSSLayerStatementRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSLayerStatementRule.prototype, "type", { + value: 0, + writable: false +}); + +Object.defineProperties(CSSOM.CSSLayerStatementRule.prototype, { + cssText: { + get: function () { + return "@layer " + this.nameList.join(", ") + ";"; + } + }, +}); + +//.CommonJS +exports.CSSLayerStatementRule = CSSOM.CSSLayerStatementRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSMediaRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSMediaRule.js new file mode 100644 index 0000000..5f07d6a --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSMediaRule.js @@ -0,0 +1,74 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + CSSGroupingRule: require("./CSSGroupingRule").CSSGroupingRule, + CSSConditionRule: require("./CSSConditionRule").CSSConditionRule, + MediaList: require("./MediaList").MediaList +}; +///CommonJS + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#cssmediarule + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSMediaRule + */ +CSSOM.CSSMediaRule = function CSSMediaRule() { + CSSOM.CSSConditionRule.call(this); + this.__media = new CSSOM.MediaList(); +}; + +CSSOM.CSSMediaRule.prototype = Object.create(CSSOM.CSSConditionRule.prototype); +CSSOM.CSSMediaRule.prototype.constructor = CSSOM.CSSMediaRule; + +Object.setPrototypeOf(CSSOM.CSSMediaRule, CSSOM.CSSConditionRule); + +Object.defineProperty(CSSOM.CSSMediaRule.prototype, "type", { + value: 4, + writable: false +}); + +// https://opensource.apple.com/source/WebCore/WebCore-7611.1.21.161.3/css/CSSMediaRule.cpp +Object.defineProperties(CSSOM.CSSMediaRule.prototype, { + "media": { + get: function() { + return this.__media; + }, + set: function(value) { + if (typeof value === "string") { + this.__media.mediaText = value; + } else { + this.__media = value; + } + }, + configurable: true, + enumerable: true + }, + "conditionText": { + get: function() { + return this.media.mediaText; + } + }, + "cssText": { + get: function() { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@media " + this.media.mediaText + values; + } + } +}); + + +//.CommonJS +exports.CSSMediaRule = CSSOM.CSSMediaRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSNamespaceRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSNamespaceRule.js new file mode 100644 index 0000000..b48ef89 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSNamespaceRule.js @@ -0,0 +1,103 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSStyleSheet: require("./CSSStyleSheet").CSSStyleSheet +}; +///CommonJS + + +/** + * @constructor + * @see https://drafts.csswg.org/cssom/#the-cssnamespacerule-interface + */ +CSSOM.CSSNamespaceRule = function CSSNamespaceRule() { + CSSOM.CSSRule.call(this); + this.__prefix = ""; + this.__namespaceURI = ""; +}; + +CSSOM.CSSNamespaceRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSNamespaceRule.prototype.constructor = CSSOM.CSSNamespaceRule; + +Object.setPrototypeOf(CSSOM.CSSNamespaceRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "type", { + value: 10, + writable: false +}); + +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "cssText", { + get: function() { + return "@namespace" + (this.prefix && " " + this.prefix) + " url(\"" + this.namespaceURI + "\");"; + } +}); + +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "prefix", { + get: function() { + return this.__prefix; + } +}); + +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "namespaceURI", { + get: function() { + return this.__namespaceURI; + } +}); + + +/** + * NON-STANDARD + * Rule text parser. + * @param {string} cssText + */ +Object.defineProperty(CSSOM.CSSNamespaceRule.prototype, "parse", { + value: function(cssText) { + var newPrefix = ""; + var newNamespaceURI = ""; + + // Remove @namespace and trim + var text = cssText.trim(); + if (text.indexOf('@namespace') === 0) { + text = text.slice('@namespace'.length).trim(); + } + + // Remove trailing semicolon if present + if (text.charAt(text.length - 1) === ';') { + text = text.slice(0, -1).trim(); + } + + // Regex to match valid namespace syntax: + // 1. [optional prefix] url("...") or [optional prefix] url('...') or [optional prefix] url() or [optional prefix] url(unquoted) + // 2. [optional prefix] "..." or [optional prefix] '...' + // The prefix must be a valid CSS identifier (letters, digits, hyphens, underscores, starting with letter or underscore) + var re = /^(?:([a-zA-Z_][a-zA-Z0-9_-]*)\s+)?(?:url\(\s*(?:(['"])(.*?)\2\s*|([^)]*?))\s*\)|(['"])(.*?)\5)$/; + var match = text.match(re); + + if (match) { + // If prefix is present + if (match[1]) { + newPrefix = match[1]; + } + // If url(...) form with quotes + if (typeof match[3] !== "undefined") { + newNamespaceURI = match[3]; + } + // If url(...) form without quotes + else if (typeof match[4] !== "undefined") { + newNamespaceURI = match[4].trim(); + } + // If quoted string form + else if (typeof match[6] !== "undefined") { + newNamespaceURI = match[6]; + } + + this.__prefix = newPrefix; + this.__namespaceURI = newNamespaceURI; + } else { + throw new DOMException("Invalid @namespace rule", "InvalidStateError"); + } + } +}); +//.CommonJS +exports.CSSNamespaceRule = CSSOM.CSSNamespaceRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSNestedDeclarations.js b/vanilla/node_modules/@acemir/cssom/lib/CSSNestedDeclarations.js new file mode 100644 index 0000000..459f282 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSNestedDeclarations.js @@ -0,0 +1,56 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSStyleDeclaration: require('./CSSStyleDeclaration').CSSStyleDeclaration +}; +// Use cssstyle if available +try { + CSSOM.CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; +} catch (e) { + // ignore +} +///CommonJS + + +/** + * @constructor + * @see https://drafts.csswg.org/css-nesting-1/ + */ +CSSOM.CSSNestedDeclarations = function CSSNestedDeclarations() { + CSSOM.CSSRule.call(this); + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSNestedDeclarations.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSNestedDeclarations.prototype.constructor = CSSOM.CSSNestedDeclarations; + +Object.setPrototypeOf(CSSOM.CSSNestedDeclarations, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSNestedDeclarations.prototype, "type", { + value: 0, + writable: false +}); + +Object.defineProperty(CSSOM.CSSNestedDeclarations.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + } +}); + +Object.defineProperty(CSSOM.CSSNestedDeclarations.prototype, "cssText", { + get: function () { + return this.style.cssText; + } +}); + +//.CommonJS +exports.CSSNestedDeclarations = CSSOM.CSSNestedDeclarations; +///CommonJS \ No newline at end of file diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSOM.js b/vanilla/node_modules/@acemir/cssom/lib/CSSOM.js new file mode 100644 index 0000000..08d47cb --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSOM.js @@ -0,0 +1,58 @@ +var CSSOM = { + /** + * Creates and configures a new CSSOM instance with the specified options. + * + * @param {Object} opts - Configuration options for the CSSOM instance + * @param {Object} [opts.globalObject] - Optional global object to be assigned to CSSOM objects prototype + * @returns {Object} A new CSSOM instance with the applied configuration + * @description + * This method creates a new instance of CSSOM and optionally + * configures CSSStyleSheet with a global object reference. When a globalObject is provided + * and CSSStyleSheet exists on the instance, it creates a new CSSStyleSheet constructor + * using a factory function and assigns the globalObject to its prototype's __globalObject property. + */ + setup: function (opts) { + var instance = Object.create(this); + if (opts.globalObject) { + if (instance.CSSStyleSheet) { + var factoryCSSStyleSheet = createFunctionFactory(instance.CSSStyleSheet); + var CSSStyleSheet = factoryCSSStyleSheet(); + CSSStyleSheet.prototype.__globalObject = opts.globalObject; + + instance.CSSStyleSheet = CSSStyleSheet; + } + } + return instance; + } +}; + +function createFunctionFactory(fn) { + return function() { + // Create a new function that delegates to the original + var newFn = function() { + return fn.apply(this, arguments); + }; + + // Copy prototype chain + Object.setPrototypeOf(newFn, Object.getPrototypeOf(fn)); + + // Copy own properties + for (var key in fn) { + if (Object.prototype.hasOwnProperty.call(fn, key)) { + newFn[key] = fn[key]; + } + } + + // Clone the .prototype object for constructor-like behavior + if (fn.prototype) { + newFn.prototype = Object.create(fn.prototype); + } + + return newFn; + }; +} + +//.CommonJS +module.exports = CSSOM; +///CommonJS + diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSPageRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSPageRule.js new file mode 100644 index 0000000..1d75326 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSPageRule.js @@ -0,0 +1,125 @@ +//.CommonJS +var CSSOM = { + CSSStyleDeclaration: require("./CSSStyleDeclaration").CSSStyleDeclaration, + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + CSSGroupingRule: require("./CSSGroupingRule").CSSGroupingRule, +}; +var regexPatterns = require("./regexPatterns").regexPatterns; +// Use cssstyle if available +try { + CSSOM.CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; +} catch (e) { + // ignore +} +///CommonJS + + +/** + * @constructor + * @see https://drafts.csswg.org/cssom/#the-csspagerule-interface + */ +CSSOM.CSSPageRule = function CSSPageRule() { + CSSOM.CSSGroupingRule.call(this); + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSPageRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSPageRule.prototype.constructor = CSSOM.CSSPageRule; + +Object.setPrototypeOf(CSSOM.CSSPageRule, CSSOM.CSSGroupingRule); + +Object.defineProperty(CSSOM.CSSPageRule.prototype, "type", { + value: 6, + writable: false +}); + +Object.defineProperty(CSSOM.CSSPageRule.prototype, "selectorText", { + get: function() { + return this.__selectorText; + }, + set: function(value) { + if (typeof value === "string") { + var trimmedValue = value.trim(); + + // Empty selector is valid for @page + if (trimmedValue === '') { + this.__selectorText = ''; + return; + } + + var atPageRuleSelectorRegExp = regexPatterns.atPageRuleSelectorRegExp; + var cssCustomIdentifierRegExp = regexPatterns.cssCustomIdentifierRegExp; + var match = trimmedValue.match(atPageRuleSelectorRegExp); + if (match) { + var pageName = match[1] || ''; + var pseudoPages = match[2] || ''; + + // Validate page name if present + if (pageName) { + // Page name can be an identifier or a string + if (!cssCustomIdentifierRegExp.test(pageName)) { + return; + } + } + + // Validate pseudo-pages if present + if (pseudoPages) { + var pseudos = pseudoPages.split(':').filter(function(p) { return p; }); + var validPseudos = ['left', 'right', 'first', 'blank']; + var allValid = true; + for (var j = 0; j < pseudos.length; j++) { + if (validPseudos.indexOf(pseudos[j].toLowerCase()) === -1) { + allValid = false; + break; + } + } + + if (!allValid) { + return; // Invalid pseudo-page, do nothing + } + } + + this.__selectorText = pageName + pseudoPages.toLowerCase(); + } + } + } +}); + +Object.defineProperty(CSSOM.CSSPageRule.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + } +}); + +Object.defineProperty(CSSOM.CSSPageRule.prototype, "cssText", { + get: function() { + var values = ""; + if (this.cssRules.length) { + var valuesArr = [" {"]; + this.style.cssText && valuesArr.push(this.style.cssText); + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + values = valuesArr.join("\n ") + "\n}"; + } else { + values = " {" + (this.style.cssText ? " " + this.style.cssText : "") + " }"; + } + return "@page" + (this.selectorText ? " " + this.selectorText : "") + values; + } +}); + +//.CommonJS +exports.CSSPageRule = CSSOM.CSSPageRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSPropertyRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSPropertyRule.js new file mode 100644 index 0000000..892bb59 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSPropertyRule.js @@ -0,0 +1,122 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule +}; +///CommonJS + + +/** + * @constructor + * @see https://drafts.css-houdini.org/css-properties-values-api/#the-css-property-rule-interface + */ +CSSOM.CSSPropertyRule = function CSSPropertyRule() { + CSSOM.CSSRule.call(this); + this.__name = ""; + this.__syntax = ""; + this.__inherits = false; + this.__initialValue = null; +}; + +CSSOM.CSSPropertyRule.prototype = Object.create(CSSOM.CSSRule.prototype); +CSSOM.CSSPropertyRule.prototype.constructor = CSSOM.CSSPropertyRule; + +Object.setPrototypeOf(CSSOM.CSSPropertyRule, CSSOM.CSSRule); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "type", { + value: 0, + writable: false +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "cssText", { + get: function() { + var text = "@property " + this.name + " {"; + if (this.syntax !== "") { + text += " syntax: \"" + this.syntax.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + "\";"; + } + text += " inherits: " + (this.inherits ? "true" : "false") + ";"; + if (this.initialValue !== null) { + text += " initial-value: " + this.initialValue + ";"; + } + text += " }"; + return text; + } +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "name", { + get: function() { + return this.__name; + } +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "syntax", { + get: function() { + return this.__syntax; + } +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "inherits", { + get: function() { + return this.__inherits; + } +}); + +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "initialValue", { + get: function() { + return this.__initialValue; + } +}); + +/** + * NON-STANDARD + * Rule text parser. + * @param {string} cssText + * @returns {boolean} True if the rule is valid and was parsed successfully + */ +Object.defineProperty(CSSOM.CSSPropertyRule.prototype, "parse", { + value: function(cssText) { + // Extract the name from "@property { ... }" + var match = cssText.match(/@property\s+(--[^\s{]+)\s*\{([^]*)\}/); + if (!match) { + return false; + } + + this.__name = match[1]; + var bodyText = match[2]; + + // Parse syntax descriptor (REQUIRED) + var syntaxMatch = bodyText.match(/syntax\s*:\s*(['"])([^]*?)\1\s*;/); + if (!syntaxMatch) { + return false; // syntax is required + } + this.__syntax = syntaxMatch[2]; + + // Syntax cannot be empty + if (this.__syntax === "") { + return false; + } + + // Parse inherits descriptor (REQUIRED) + var inheritsMatch = bodyText.match(/inherits\s*:\s*(true|false)\s*;/); + if (!inheritsMatch) { + return false; // inherits is required + } + this.__inherits = inheritsMatch[1] === "true"; + + // Parse initial-value descriptor (OPTIONAL, but required if syntax is not "*") + var initialValueMatch = bodyText.match(/initial-value\s*:\s*([^;]+);/); + if (initialValueMatch) { + this.__initialValue = initialValueMatch[1].trim(); + } else { + // If syntax is not "*", initial-value is required + if (this.__syntax !== "*") { + return false; + } + } + + return true; // Successfully parsed + } +}); + +//.CommonJS +exports.CSSPropertyRule = CSSOM.CSSPropertyRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSRule.js new file mode 100644 index 0000000..bcd47f3 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSRule.js @@ -0,0 +1,92 @@ +//.CommonJS +var CSSOM = {}; +///CommonJS + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#the-cssrule-interface + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSRule + */ +CSSOM.CSSRule = function CSSRule() { + this.__parentRule = null; + this.__parentStyleSheet = null; +}; + +CSSOM.CSSRule.UNKNOWN_RULE = 0; // obsolete +CSSOM.CSSRule.STYLE_RULE = 1; +CSSOM.CSSRule.CHARSET_RULE = 2; // obsolete +CSSOM.CSSRule.IMPORT_RULE = 3; +CSSOM.CSSRule.MEDIA_RULE = 4; +CSSOM.CSSRule.FONT_FACE_RULE = 5; +CSSOM.CSSRule.PAGE_RULE = 6; +CSSOM.CSSRule.KEYFRAMES_RULE = 7; +CSSOM.CSSRule.KEYFRAME_RULE = 8; +CSSOM.CSSRule.MARGIN_RULE = 9; +CSSOM.CSSRule.NAMESPACE_RULE = 10; +CSSOM.CSSRule.COUNTER_STYLE_RULE = 11; +CSSOM.CSSRule.SUPPORTS_RULE = 12; +CSSOM.CSSRule.DOCUMENT_RULE = 13; +CSSOM.CSSRule.FONT_FEATURE_VALUES_RULE = 14; +CSSOM.CSSRule.VIEWPORT_RULE = 15; +CSSOM.CSSRule.REGION_STYLE_RULE = 16; +CSSOM.CSSRule.CONTAINER_RULE = 17; +CSSOM.CSSRule.LAYER_BLOCK_RULE = 18; +CSSOM.CSSRule.STARTING_STYLE_RULE = 1002; + +Object.defineProperties(CSSOM.CSSRule.prototype, { + + constructor: { value: CSSOM.CSSRule }, + + cssRule: { + value: "", + configurable: true, + enumerable: true + }, + + cssText: { + get: function() { + // Default getter: subclasses should override this + return ""; + }, + set: function(cssText) { + return cssText; + } + }, + + parentRule: { + get: function() { + return this.__parentRule + } + }, + + parentStyleSheet: { + get: function() { + return this.__parentStyleSheet + } + }, + + UNKNOWN_RULE: { value: 0, enumerable: true }, // obsolet + STYLE_RULE: { value: 1, enumerable: true }, + CHARSET_RULE: { value: 2, enumerable: true }, // obsolet + IMPORT_RULE: { value: 3, enumerable: true }, + MEDIA_RULE: { value: 4, enumerable: true }, + FONT_FACE_RULE: { value: 5, enumerable: true }, + PAGE_RULE: { value: 6, enumerable: true }, + KEYFRAMES_RULE: { value: 7, enumerable: true }, + KEYFRAME_RULE: { value: 8, enumerable: true }, + MARGIN_RULE: { value: 9, enumerable: true }, + NAMESPACE_RULE: { value: 10, enumerable: true }, + COUNTER_STYLE_RULE: { value: 11, enumerable: true }, + SUPPORTS_RULE: { value: 12, enumerable: true }, + DOCUMENT_RULE: { value: 13, enumerable: true }, + FONT_FEATURE_VALUES_RULE: { value: 14, enumerable: true }, + VIEWPORT_RULE: { value: 15, enumerable: true }, + REGION_STYLE_RULE: { value: 16, enumerable: true }, + CONTAINER_RULE: { value: 17, enumerable: true }, + LAYER_BLOCK_RULE: { value: 18, enumerable: true }, + STARTING_STYLE_RULE: { value: 1002, enumerable: true }, +}); + +//.CommonJS +exports.CSSRule = CSSOM.CSSRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSRuleList.js b/vanilla/node_modules/@acemir/cssom/lib/CSSRuleList.js new file mode 100644 index 0000000..8b3bfc2 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSRuleList.js @@ -0,0 +1,26 @@ +//.CommonJS +var CSSOM = {}; +///CommonJS + + +/** + * @constructor + * @see https://drafts.csswg.org/cssom/#the-cssrulelist-interface + */ +CSSOM.CSSRuleList = function CSSRuleList(){ + var arr = new Array(); + Object.setPrototypeOf(arr, CSSOM.CSSRuleList.prototype); + return arr; +}; + +CSSOM.CSSRuleList.prototype = Object.create(Array.prototype); +CSSOM.CSSRuleList.prototype.constructor = CSSOM.CSSRuleList; + +CSSOM.CSSRuleList.prototype.item = function(index) { + return this[index] || null; +}; + + +//.CommonJS +exports.CSSRuleList = CSSOM.CSSRuleList; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSScopeRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSScopeRule.js new file mode 100644 index 0000000..68e42de --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSScopeRule.js @@ -0,0 +1,61 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + CSSGroupingRule: require("./CSSGroupingRule").CSSGroupingRule, +}; +///CommonJS + +/** + * @constructor + * @see https://drafts.csswg.org/css-cascade-6/#cssscoperule + */ +CSSOM.CSSScopeRule = function CSSScopeRule() { + CSSOM.CSSGroupingRule.call(this); + this.__start = null; + this.__end = null; +}; + +CSSOM.CSSScopeRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSScopeRule.prototype.constructor = CSSOM.CSSScopeRule; + +Object.setPrototypeOf(CSSOM.CSSScopeRule, CSSOM.CSSGroupingRule); + +Object.defineProperties(CSSOM.CSSScopeRule.prototype, { + type: { + value: 0, + writable: false, + }, + cssText: { + get: function () { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@scope" + (this.start ? " (" + this.start + ")" : "") + (this.end ? " to (" + this.end + ")" : "") + values; + }, + configurable: true, + enumerable: true, + }, + start: { + get: function () { + return this.__start; + } + }, + end: { + get: function () { + return this.__end; + } + } +}); + +//.CommonJS +exports.CSSScopeRule = CSSOM.CSSScopeRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSStartingStyleRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSStartingStyleRule.js new file mode 100644 index 0000000..98a15e6 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSStartingStyleRule.js @@ -0,0 +1,52 @@ +//.CommonJS +var CSSOM = { + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + CSSGroupingRule: require("./CSSGroupingRule").CSSGroupingRule +}; +///CommonJS + + +/** + * @constructor + * @see http://www.w3.org/TR/shadow-dom/#host-at-rule + */ +CSSOM.CSSStartingStyleRule = function CSSStartingStyleRule() { + CSSOM.CSSGroupingRule.call(this); +}; + +CSSOM.CSSStartingStyleRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSStartingStyleRule.prototype.constructor = CSSOM.CSSStartingStyleRule; + +Object.setPrototypeOf(CSSOM.CSSStartingStyleRule, CSSOM.CSSGroupingRule); + +Object.defineProperty(CSSOM.CSSStartingStyleRule.prototype, "type", { + value: 1002, + writable: false +}); + +//FIXME +//CSSOM.CSSStartingStyleRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; +//CSSOM.CSSStartingStyleRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; + +Object.defineProperty(CSSOM.CSSStartingStyleRule.prototype, "cssText", { + get: function() { + var values = ""; + var valuesArr = [" {"]; + if (this.cssRules.length) { + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + } + values = valuesArr.join("\n ") + "\n}"; + return "@starting-style" + values; + } +}); + + +//.CommonJS +exports.CSSStartingStyleRule = CSSOM.CSSStartingStyleRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSStyleDeclaration.js b/vanilla/node_modules/@acemir/cssom/lib/CSSStyleDeclaration.js new file mode 100644 index 0000000..b2ee05a --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSStyleDeclaration.js @@ -0,0 +1,164 @@ +//.CommonJS +var CSSOM = {}; +var regexPatterns = require("./regexPatterns").regexPatterns; +///CommonJS + +/** + * @constructor + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration + */ +CSSOM.CSSStyleDeclaration = function CSSStyleDeclaration(){ + this.length = 0; + this.parentRule = null; + + // NON-STANDARD + this._importants = {}; +}; + + +CSSOM.CSSStyleDeclaration.prototype = { + + constructor: CSSOM.CSSStyleDeclaration, + + /** + * + * @param {string} name + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue + * @return {string} the value of the property if it has been explicitly set for this declaration block. + * Returns the empty string if the property has not been set. + */ + getPropertyValue: function(name) { + return this[name] || ""; + }, + + /** + * + * @param {string} name + * @param {string} value + * @param {string} [priority=null] "important" or null + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty + */ + setProperty: function(name, value, priority, parseErrorHandler) + { + // NOTE: Check viability to add a validation for css values or use a dependency like csstree-validator + var basicStylePropertyValueValidationRegExp = regexPatterns.basicStylePropertyValueValidationRegExp + if (basicStylePropertyValueValidationRegExp.test(value)) { + parseErrorHandler && parseErrorHandler('Invalid CSSStyleDeclaration property (name = "' + name + '", value = "' + value + '")'); + } else if (this[name]) { + // Property already exist. Overwrite it. + var index = Array.prototype.indexOf.call(this, name); + if (index < 0) { + this[this.length] = name; + this.length++; + } + + // If the priority value of the incoming property is "important", + // or the value of the existing property is not "important", + // then remove the existing property and rewrite it. + if (priority || !this._importants[name]) { + this.removeProperty(name); + this[this.length] = name; + this.length++; + this[name] = value + ''; + this._importants[name] = priority; + } + } else { + // New property. + this[this.length] = name; + this.length++; + this[name] = value + ''; + this._importants[name] = priority; + } + }, + + /** + * + * @param {string} name + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty + * @return {string} the value of the property if it has been explicitly set for this declaration block. + * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. + */ + removeProperty: function(name) { + if (!(name in this)) { + return ""; + } + var index = Array.prototype.indexOf.call(this, name); + if (index < 0) { + return ""; + } + var prevValue = this[name]; + this[name] = ""; + + // That's what WebKit and Opera do + Array.prototype.splice.call(this, index, 1); + + // That's what Firefox does + //this[index] = "" + + return prevValue; + }, + + getPropertyCSSValue: function() { + //FIXME + }, + + /** + * + * @param {String} name + */ + getPropertyPriority: function(name) { + return this._importants[name] || ""; + }, + + + /** + * element.style.overflow = "auto" + * element.style.getPropertyShorthand("overflow-x") + * -> "overflow" + */ + getPropertyShorthand: function() { + //FIXME + }, + + isPropertyImplicit: function() { + //FIXME + }, + + // Doesn't work in IE < 9 + get cssText(){ + var properties = []; + for (var i=0, length=this.length; i < length; ++i) { + var name = this[i]; + var value = this.getPropertyValue(name); + var priority = this.getPropertyPriority(name); + if (priority) { + priority = " !" + priority; + } + properties[i] = name + ": " + value + priority + ";"; + } + return properties.join(" "); + }, + + set cssText(text){ + var i, name; + for (i = this.length; i--;) { + name = this[i]; + this[name] = ""; + } + Array.prototype.splice.call(this, 0, this.length); + this._importants = {}; + + var dummyRule = CSSOM.parse('#bogus{' + text + '}').cssRules[0].style; + var length = dummyRule.length; + for (i = 0; i < length; ++i) { + name = dummyRule[i]; + this.setProperty(dummyRule[i], dummyRule.getPropertyValue(name), dummyRule.getPropertyPriority(name)); + } + } +}; + + +//.CommonJS +exports.CSSStyleDeclaration = CSSOM.CSSStyleDeclaration; +CSSOM.parse = require('./parse').parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSStyleRule.js b/vanilla/node_modules/@acemir/cssom/lib/CSSStyleRule.js new file mode 100644 index 0000000..a7c81d0 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSStyleRule.js @@ -0,0 +1,109 @@ +//.CommonJS +var CSSOM = { + CSSStyleDeclaration: require("./CSSStyleDeclaration").CSSStyleDeclaration, + CSSRule: require("./CSSRule").CSSRule, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + CSSGroupingRule: require("./CSSGroupingRule").CSSGroupingRule, +}; +var regexPatterns = require("./regexPatterns").regexPatterns; +// Use cssstyle if available +try { + CSSOM.CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; +} catch (e) { + // ignore +} +///CommonJS + + +/** + * @constructor + * @see http://dev.w3.org/csswg/cssom/#cssstylerule + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleRule + */ +CSSOM.CSSStyleRule = function CSSStyleRule() { + CSSOM.CSSGroupingRule.call(this); + this.__selectorText = ""; + this.__style = new CSSOM.CSSStyleDeclaration(); + this.__style.parentRule = this; +}; + +CSSOM.CSSStyleRule.prototype = Object.create(CSSOM.CSSGroupingRule.prototype); +CSSOM.CSSStyleRule.prototype.constructor = CSSOM.CSSStyleRule; + +Object.setPrototypeOf(CSSOM.CSSStyleRule, CSSOM.CSSGroupingRule); + +Object.defineProperty(CSSOM.CSSStyleRule.prototype, "type", { + value: 1, + writable: false +}); + +Object.defineProperty(CSSOM.CSSStyleRule.prototype, "selectorText", { + get: function() { + return this.__selectorText; + }, + set: function(value) { + if (typeof value === "string") { + // Don't trim if the value ends with a hex escape sequence followed by space + // (e.g., ".\31 " where the space is part of the escape terminator) + var endsWithHexEscapeRegExp = regexPatterns.endsWithHexEscapeRegExp; + var endsWithEscape = endsWithHexEscapeRegExp.test(value); + var trimmedValue = endsWithEscape ? value.replace(/\s+$/, ' ').trimStart() : value.trim(); + + if (trimmedValue === '') { + return; + } + + // TODO: Setting invalid selectorText should be ignored + // There are some validations already on lib/parse.js + // but the same validations should be applied here. + // Check if we can move these validation logic to a shared function. + + this.__selectorText = trimmedValue; + } + }, + configurable: true +}); + +Object.defineProperty(CSSOM.CSSStyleRule.prototype, "style", { + get: function() { + return this.__style; + }, + set: function(value) { + if (typeof value === "string") { + this.__style.cssText = value; + } else { + this.__style = value; + } + }, + configurable: true +}); + +Object.defineProperty(CSSOM.CSSStyleRule.prototype, "cssText", { + get: function() { + var text; + if (this.selectorText) { + var values = ""; + if (this.cssRules.length) { + var valuesArr = [" {"]; + this.style.cssText && valuesArr.push(this.style.cssText); + valuesArr.push(this.cssRules.reduce(function(acc, rule){ + if (rule.cssText !== "") { + acc.push(rule.cssText); + } + return acc; + }, []).join("\n ")); + values = valuesArr.join("\n ") + "\n}"; + } else { + values = " {" + (this.style.cssText ? " " + this.style.cssText : "") + " }"; + } + text = this.selectorText + values; + } else { + text = ""; + } + return text; + } +}); + +//.CommonJS +exports.CSSStyleRule = CSSOM.CSSStyleRule; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/CSSStyleSheet.js b/vanilla/node_modules/@acemir/cssom/lib/CSSStyleSheet.js new file mode 100644 index 0000000..364607f --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/CSSStyleSheet.js @@ -0,0 +1,371 @@ +//.CommonJS +var CSSOM = { + MediaList: require("./MediaList").MediaList, + StyleSheet: require("./StyleSheet").StyleSheet, + CSSRuleList: require("./CSSRuleList").CSSRuleList, + CSSStyleRule: require("./CSSStyleRule").CSSStyleRule, +}; +var errorUtils = require("./errorUtils").errorUtils; +///CommonJS + + +/** + * @constructor + * @param {CSSStyleSheetInit} [opts] - CSSStyleSheetInit options. + * @param {string} [opts.baseURL] - The base URL of the stylesheet. + * @param {boolean} [opts.disabled] - The disabled attribute of the stylesheet. + * @param {MediaList | string} [opts.media] - The media attribute of the stylesheet. + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet + */ +CSSOM.CSSStyleSheet = function CSSStyleSheet(opts) { + CSSOM.StyleSheet.call(this); + this.__constructed = true; + this.__cssRules = new CSSOM.CSSRuleList(); + this.__ownerRule = null; + + if (opts && typeof opts === "object") { + if (opts.baseURL && typeof opts.baseURL === "string") { + this.__baseURL = opts.baseURL; + } + if (opts.media && typeof opts.media === "string") { + this.media.mediaText = opts.media; + } + if (typeof opts.disabled === "boolean") { + this.disabled = opts.disabled; + } + } +}; + + +CSSOM.CSSStyleSheet.prototype = Object.create(CSSOM.StyleSheet.prototype); +CSSOM.CSSStyleSheet.prototype.constructor = CSSOM.CSSStyleSheet; + +Object.setPrototypeOf(CSSOM.CSSStyleSheet, CSSOM.StyleSheet); + +Object.defineProperty(CSSOM.CSSStyleSheet.prototype, "cssRules", { + get: function() { + return this.__cssRules; + } +}); + +Object.defineProperty(CSSOM.CSSStyleSheet.prototype, "rules", { + get: function() { + return this.__cssRules; + } +}); + +Object.defineProperty(CSSOM.CSSStyleSheet.prototype, "ownerRule", { + get: function() { + return this.__ownerRule; + } +}); + +/** + * Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade. + * + * sheet = new Sheet("body {margin: 0}") + * sheet.toString() + * -> "body{margin:0;}" + * sheet.insertRule("img {border: none}", 0) + * -> 0 + * sheet.toString() + * -> "img{border:none;}body{margin:0;}" + * + * @param {string} rule + * @param {number} [index=0] + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-insertRule + * @return {number} The index within the style sheet's rule collection of the newly inserted rule. + */ +CSSOM.CSSStyleSheet.prototype.insertRule = function(rule, index) { + if (rule === undefined && index === undefined) { + errorUtils.throwMissingArguments(this, 'insertRule', this.constructor.name); + } + if (index === void 0) { + index = 0; + } + index = Number(index); + if (index < 0) { + index = 4294967296 + index; + } + if (index > this.cssRules.length) { + errorUtils.throwIndexError(this, 'insertRule', this.constructor.name, index, this.cssRules.length); + } + + var ruleToParse = String(rule); + var parseErrors = []; + var parsedSheet = CSSOM.parse(ruleToParse, undefined, function(err) { + parseErrors.push(err); + } ); + if (parsedSheet.cssRules.length !== 1) { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + var cssRule = parsedSheet.cssRules[0]; + + // Helper function to find the last index of a specific rule constructor + function findLastIndexOfConstructor(rules, constructorName) { + for (var i = rules.length - 1; i >= 0; i--) { + if (rules[i].constructor.name === constructorName) { + return i; + } + } + return -1; + } + + // Helper function to find the first index of a rule that's NOT of specified constructors + function findFirstNonConstructorIndex(rules, constructorNames) { + for (var i = 0; i < rules.length; i++) { + if (constructorNames.indexOf(rules[i].constructor.name) === -1) { + return i; + } + } + return rules.length; + } + + // Validate rule ordering based on CSS specification + if (cssRule.constructor.name === 'CSSImportRule') { + if (this.__constructed === true) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Can't insert @import rules into a constructed stylesheet.", + 'SyntaxError'); + } + // @import rules cannot be inserted after @layer rules that already exist + // They can only be inserted at the beginning or after other @import rules + var firstLayerIndex = findFirstNonConstructorIndex(this.cssRules, ['CSSImportRule']); + if (firstLayerIndex < this.cssRules.length && this.cssRules[firstLayerIndex].constructor.name === 'CSSLayerStatementRule' && index > firstLayerIndex) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + + // Also cannot insert after @namespace or other rules + var firstNonImportIndex = findFirstNonConstructorIndex(this.cssRules, ['CSSImportRule']); + if (index > firstNonImportIndex && firstNonImportIndex < this.cssRules.length && + this.cssRules[firstNonImportIndex].constructor.name !== 'CSSLayerStatementRule') { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + } else if (cssRule.constructor.name === 'CSSNamespaceRule') { + // @namespace rules can come after @layer and @import, but before any other rules + // They cannot come before @import rules + var firstImportIndex = -1; + for (var i = 0; i < this.cssRules.length; i++) { + if (this.cssRules[i].constructor.name === 'CSSImportRule') { + firstImportIndex = i; + break; + } + } + var firstNonImportNamespaceIndex = findFirstNonConstructorIndex(this.cssRules, [ + 'CSSLayerStatementRule', + 'CSSImportRule', + 'CSSNamespaceRule' + ]); + + // Cannot insert before @import rules + if (firstImportIndex !== -1 && index <= firstImportIndex) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + + // Cannot insert if there are already non-special rules + if (firstNonImportNamespaceIndex < this.cssRules.length) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'InvalidStateError'); + } + + // Cannot insert after other types of rules + if (index > firstNonImportNamespaceIndex) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + + + } else if (cssRule.constructor.name === 'CSSLayerStatementRule') { + // @layer statement rules can be inserted anywhere before @import and @namespace + // No additional restrictions beyond what's already handled + } else { + // Any other rule cannot be inserted before @import and @namespace + var firstNonSpecialRuleIndex = findFirstNonConstructorIndex(this.cssRules, [ + 'CSSLayerStatementRule', + 'CSSImportRule', + 'CSSNamespaceRule' + ]); + + if (index < firstNonSpecialRuleIndex) { + errorUtils.throwError(this, 'DOMException', + "Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.", + 'HierarchyRequestError'); + } + + if (parseErrors.filter(function(error) { return !error.isNested; }).length !== 0) { + errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError'); + } + } + + cssRule.__parentStyleSheet = this; + this.cssRules.splice(index, 0, cssRule); + return index; +}; + +CSSOM.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index) { + if (index === void 0) { + index = this.cssRules.length; + } + this.insertRule(selector + "{" + styleBlock + "}", index); + return -1; +}; + +/** + * Used to delete a rule from the style sheet. + * + * sheet = new Sheet("img{border:none} body{margin:0}") + * sheet.toString() + * -> "img{border:none;}body{margin:0;}" + * sheet.deleteRule(0) + * sheet.toString() + * -> "body{margin:0;}" + * + * @param {number} index within the style sheet's rule list of the rule to remove. + * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-deleteRule + */ +CSSOM.CSSStyleSheet.prototype.deleteRule = function(index) { + if (index === undefined) { + errorUtils.throwMissingArguments(this, 'deleteRule', this.constructor.name); + } + index = Number(index); + if (index < 0) { + index = 4294967296 + index; + } + if (index >= this.cssRules.length) { + errorUtils.throwIndexError(this, 'deleteRule', this.constructor.name, index, this.cssRules.length); + } + if (this.cssRules[index]) { + if (this.cssRules[index].constructor.name == "CSSNamespaceRule") { + var shouldContinue = this.cssRules.every(function (rule) { + return ['CSSImportRule','CSSLayerStatementRule','CSSNamespaceRule'].indexOf(rule.constructor.name) !== -1 + }); + if (!shouldContinue) { + errorUtils.throwError(this, 'DOMException', "Failed to execute 'deleteRule' on '" + this.constructor.name + "': Failed to delete rule.", "InvalidStateError"); + } + } + if (this.cssRules[index].constructor.name == "CSSImportRule") { + this.cssRules[index].styleSheet.__parentStyleSheet = null; + } + + this.cssRules[index].__parentStyleSheet = null; + } + this.cssRules.splice(index, 1); +}; + +CSSOM.CSSStyleSheet.prototype.removeRule = function(index) { + if (index === void 0) { + index = 0; + } + this.deleteRule(index); +}; + + +/** + * Replaces the rules of a {@link CSSStyleSheet} + * + * @returns a promise + * @see https://www.w3.org/TR/cssom-1/#dom-cssstylesheet-replace + */ +CSSOM.CSSStyleSheet.prototype.replace = function(text) { + var _Promise; + if (this.__globalObject && this.__globalObject['Promise']) { + _Promise = this.__globalObject['Promise']; + } else { + _Promise = Promise; + } + var _setTimeout; + if (this.__globalObject && this.__globalObject['setTimeout']) { + _setTimeout = this.__globalObject['setTimeout']; + } else { + _setTimeout = setTimeout; + } + var sheet = this; + return new _Promise(function (resolve, reject) { + // If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException. + if (!sheet.__constructed || sheet.__disallowModification) { + reject(errorUtils.createError(sheet, 'DOMException', + "Failed to execute 'replaceSync' on '" + sheet.constructor.name + "': Not allowed.", + 'NotAllowedError')); + } + // Set the disallow modification flag. + sheet.__disallowModification = true; + + // In parallel, do these steps: + _setTimeout(function() { + // Let rules be the result of running parse a stylesheet's contents from text. + var rules = new CSSOM.CSSRuleList(); + CSSOM.parse(text, { styleSheet: sheet, cssRules: rules }); + // If rules contains one or more @import rules, remove those rules from rules. + var i = 0; + while (i < rules.length) { + if (rules[i].constructor.name === 'CSSImportRule') { + rules.splice(i, 1); + } else { + i++; + } + } + // Set sheet's CSS rules to rules. + sheet.__cssRules.splice.apply(sheet.__cssRules, [0, sheet.__cssRules.length].concat(rules)); + // Unset sheet’s disallow modification flag. + delete sheet.__disallowModification; + // Resolve promise with sheet. + resolve(sheet); + }) + }); +} + +/** + * Synchronously replaces the rules of a {@link CSSStyleSheet} + * + * @see https://www.w3.org/TR/cssom-1/#dom-cssstylesheet-replacesync + */ +CSSOM.CSSStyleSheet.prototype.replaceSync = function(text) { + var sheet = this; + // If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException. + if (!sheet.__constructed || sheet.__disallowModification) { + errorUtils.throwError(sheet, 'DOMException', + "Failed to execute 'replaceSync' on '" + sheet.constructor.name + "': Not allowed.", + 'NotAllowedError'); + } + // Let rules be the result of running parse a stylesheet's contents from text. + var rules = new CSSOM.CSSRuleList(); + CSSOM.parse(text, { styleSheet: sheet, cssRules: rules }); + // If rules contains one or more @import rules, remove those rules from rules. + var i = 0; + while (i < rules.length) { + if (rules[i].constructor.name === 'CSSImportRule') { + rules.splice(i, 1); + } else { + i++; + } + } + // Set sheet's CSS rules to rules. + sheet.__cssRules.splice.apply(sheet.__cssRules, [0, sheet.__cssRules.length].concat(rules)); +} + +/** + * NON-STANDARD + * @return {string} serialize stylesheet + */ +CSSOM.CSSStyleSheet.prototype.toString = function() { + var result = ""; + var rules = this.cssRules; + for (var i=0; i 1000 ? '1000px' : 'auto'); + * } + */ +CSSOM.CSSValueExpression.prototype.parse = function() { + var token = this._token, + idx = this._idx; + + var character = '', + expression = '', + error = '', + info, + paren = []; + + + for (; ; ++idx) { + character = token.charAt(idx); + + // end of token + if (character === '') { + error = 'css expression error: unfinished expression!'; + break; + } + + switch(character) { + case '(': + paren.push(character); + expression += character; + break; + + case ')': + paren.pop(character); + expression += character; + break; + + case '/': + if ((info = this._parseJSComment(token, idx))) { // comment? + if (info.error) { + error = 'css expression error: unfinished comment in expression!'; + } else { + idx = info.idx; + // ignore the comment + } + } else if ((info = this._parseJSRexExp(token, idx))) { // regexp + idx = info.idx; + expression += info.text; + } else { // other + expression += character; + } + break; + + case "'": + case '"': + info = this._parseJSString(token, idx, character); + if (info) { // string + idx = info.idx; + expression += info.text; + } else { + expression += character; + } + break; + + default: + expression += character; + break; + } + + if (error) { + break; + } + + // end of expression + if (paren.length === 0) { + break; + } + } + + var ret; + if (error) { + ret = { + error: error + }; + } else { + ret = { + idx: idx, + expression: expression + }; + } + + return ret; +}; + + +/** + * + * @return {Object|false} + * - idx: + * - text: + * or + * - error: + * or + * false + * + */ +CSSOM.CSSValueExpression.prototype._parseJSComment = function(token, idx) { + var nextChar = token.charAt(idx + 1), + text; + + if (nextChar === '/' || nextChar === '*') { + var startIdx = idx, + endIdx, + commentEndChar; + + if (nextChar === '/') { // line comment + commentEndChar = '\n'; + } else if (nextChar === '*') { // block comment + commentEndChar = '*/'; + } + + endIdx = token.indexOf(commentEndChar, startIdx + 1 + 1); + if (endIdx !== -1) { + endIdx = endIdx + commentEndChar.length - 1; + text = token.substring(idx, endIdx + 1); + return { + idx: endIdx, + text: text + }; + } else { + var error = 'css expression error: unfinished comment in expression!'; + return { + error: error + }; + } + } else { + return false; + } +}; + + +/** + * + * @return {Object|false} + * - idx: + * - text: + * or + * false + * + */ +CSSOM.CSSValueExpression.prototype._parseJSString = function(token, idx, sep) { + var endIdx = this._findMatchedIdx(token, idx, sep), + text; + + if (endIdx === -1) { + return false; + } else { + text = token.substring(idx, endIdx + sep.length); + + return { + idx: endIdx, + text: text + }; + } +}; + + +/** + * parse regexp in css expression + * + * @return {Object|false} + * - idx: + * - regExp: + * or + * false + */ + +/* + +all legal RegExp + +/a/ +(/a/) +[/a/] +[12, /a/] + +!/a/ + ++/a/ +-/a/ +* /a/ +/ /a/ +%/a/ + +===/a/ +!==/a/ +==/a/ +!=/a/ +>/a/ +>=/a/ +>/a/ +>>>/a/ + +&&/a/ +||/a/ +?/a/ +=/a/ +,/a/ + + delete /a/ + in /a/ +instanceof /a/ + new /a/ + typeof /a/ + void /a/ + +*/ +CSSOM.CSSValueExpression.prototype._parseJSRexExp = function(token, idx) { + var before = token.substring(0, idx).replace(/\s+$/, ""), + legalRegx = [ + /^$/, + /\($/, + /\[$/, + /\!$/, + /\+$/, + /\-$/, + /\*$/, + /\/\s+/, + /\%$/, + /\=$/, + /\>$/, + /<$/, + /\&$/, + /\|$/, + /\^$/, + /\~$/, + /\?$/, + /\,$/, + /delete$/, + /in$/, + /instanceof$/, + /new$/, + /typeof$/, + /void$/ + ]; + + var isLegal = legalRegx.some(function(reg) { + return reg.test(before); + }); + + if (!isLegal) { + return false; + } else { + var sep = '/'; + + // same logic as string + return this._parseJSString(token, idx, sep); + } +}; + + +/** + * + * find next sep(same line) index in `token` + * + * @return {Number} + * + */ +CSSOM.CSSValueExpression.prototype._findMatchedIdx = function(token, idx, sep) { + var startIdx = idx, + endIdx; + + var NOT_FOUND = -1; + + while(true) { + endIdx = token.indexOf(sep, startIdx + 1); + + if (endIdx === -1) { // not found + endIdx = NOT_FOUND; + break; + } else { + var text = token.substring(idx + 1, endIdx), + matched = text.match(/\\+$/); + if (!matched || matched[0] % 2 === 0) { // not escaped + break; + } else { + startIdx = endIdx; + } + } + } + + // boundary must be in the same line(js sting or regexp) + var nextNewLineIdx = token.indexOf('\n', idx + 1); + if (nextNewLineIdx < endIdx) { + endIdx = NOT_FOUND; + } + + + return endIdx; +}; + + + + +//.CommonJS +exports.CSSValueExpression = CSSOM.CSSValueExpression; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/MatcherList.js b/vanilla/node_modules/@acemir/cssom/lib/MatcherList.js new file mode 100644 index 0000000..a791585 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/MatcherList.js @@ -0,0 +1,62 @@ +//.CommonJS +var CSSOM = {}; +///CommonJS + + +/** + * @constructor + * @see https://developer.mozilla.org/en/CSS/@-moz-document + */ +CSSOM.MatcherList = function MatcherList(){ + this.length = 0; +}; + +CSSOM.MatcherList.prototype = { + + constructor: CSSOM.MatcherList, + + /** + * @return {string} + */ + get matcherText() { + return Array.prototype.join.call(this, ", "); + }, + + /** + * @param {string} value + */ + set matcherText(value) { + // just a temporary solution, actually it may be wrong by just split the value with ',', because a url can include ','. + var values = value.split(","); + var length = this.length = values.length; + for (var i=0; i 1 ? "s" : "") + " required, but only " + + provided + " present."; + throwError(context, 'TypeError', message); +} + +/** + * Throws a DOMException for parse errors. + * + * @param {Object} context - The CSSOM object + * @param {string} methodName - The method name + * @param {string} objectName - The object name + * @param {string} rule - The rule that failed to parse + * @param {string} [name='SyntaxError'] - The DOMException name + */ +function throwParseError(context, methodName, objectName, rule, name) { + var message = "Failed to execute '" + methodName + "' on '" + objectName + "': " + + "Failed to parse the rule '" + rule + "'."; + throwError(context, 'DOMException', message, name || 'SyntaxError'); +} + +/** + * Throws a DOMException for index errors. + * + * @param {Object} context - The CSSOM object + * @param {string} methodName - The method name + * @param {string} objectName - The object name + * @param {number} index - The invalid index + * @param {number} maxIndex - The maximum valid index + * @param {string} [name='IndexSizeError'] - The DOMException name + */ +function throwIndexError(context, methodName, objectName, index, maxIndex, name) { + var message = "Failed to execute '" + methodName + "' on '" + objectName + "': " + + "The index provided (" + index + ") is larger than the maximum index (" + maxIndex + ")."; + throwError(context, 'DOMException', message, name || 'IndexSizeError'); +} + +var errorUtils = { + createError: createError, + getErrorConstructor: getErrorConstructor, + throwError: throwError, + throwMissingArguments: throwMissingArguments, + throwParseError: throwParseError, + throwIndexError: throwIndexError +}; + +//.CommonJS +exports.errorUtils = errorUtils; +///CommonJS \ No newline at end of file diff --git a/vanilla/node_modules/@acemir/cssom/lib/index.js b/vanilla/node_modules/@acemir/cssom/lib/index.js new file mode 100644 index 0000000..6138e29 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/index.js @@ -0,0 +1,42 @@ +'use strict'; + +exports.setup = require('./CSSOM').setup; + +require('./errorUtils'); +require("./regexPatterns") + +exports.CSSStyleDeclaration = require('./CSSStyleDeclaration').CSSStyleDeclaration; + +require('./cssstyleTryCatchBlock'); + +exports.CSSRule = require('./CSSRule').CSSRule; +exports.CSSRuleList = require('./CSSRuleList').CSSRuleList; +exports.CSSNestedDeclarations = require('./CSSNestedDeclarations').CSSNestedDeclarations; +exports.CSSGroupingRule = require('./CSSGroupingRule').CSSGroupingRule; +exports.CSSCounterStyleRule = require('./CSSCounterStyleRule').CSSCounterStyleRule; +exports.CSSPropertyRule = require('./CSSPropertyRule').CSSPropertyRule; +exports.CSSConditionRule = require('./CSSConditionRule').CSSConditionRule; +exports.CSSStyleRule = require('./CSSStyleRule').CSSStyleRule; +exports.MediaList = require('./MediaList').MediaList; +exports.CSSMediaRule = require('./CSSMediaRule').CSSMediaRule; +exports.CSSContainerRule = require('./CSSContainerRule').CSSContainerRule; +exports.CSSSupportsRule = require('./CSSSupportsRule').CSSSupportsRule; +exports.CSSImportRule = require('./CSSImportRule').CSSImportRule; +exports.CSSNamespaceRule = require('./CSSNamespaceRule').CSSNamespaceRule; +exports.CSSFontFaceRule = require('./CSSFontFaceRule').CSSFontFaceRule; +exports.CSSHostRule = require('./CSSHostRule').CSSHostRule; +exports.CSSStartingStyleRule = require('./CSSStartingStyleRule').CSSStartingStyleRule; +exports.StyleSheet = require('./StyleSheet').StyleSheet; +exports.CSSStyleSheet = require('./CSSStyleSheet').CSSStyleSheet; +exports.CSSKeyframesRule = require('./CSSKeyframesRule').CSSKeyframesRule; +exports.CSSKeyframeRule = require('./CSSKeyframeRule').CSSKeyframeRule; +exports.MatcherList = require('./MatcherList').MatcherList; +exports.CSSDocumentRule = require('./CSSDocumentRule').CSSDocumentRule; +exports.CSSValue = require('./CSSValue').CSSValue; +exports.CSSValueExpression = require('./CSSValueExpression').CSSValueExpression; +exports.CSSScopeRule = require('./CSSScopeRule').CSSScopeRule; +exports.CSSLayerBlockRule = require('./CSSLayerBlockRule').CSSLayerBlockRule; +exports.CSSLayerStatementRule = require('./CSSLayerStatementRule').CSSLayerStatementRule; +exports.CSSPageRule = require('./CSSPageRule').CSSPageRule; +exports.parse = require('./parse').parse; +exports.clone = require('./clone').clone; diff --git a/vanilla/node_modules/@acemir/cssom/lib/parse.js b/vanilla/node_modules/@acemir/cssom/lib/parse.js new file mode 100644 index 0000000..09d4ade --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/parse.js @@ -0,0 +1,3332 @@ +//.CommonJS +var CSSOM = {}; +var regexPatterns = require("./regexPatterns").regexPatterns; +///CommonJS + +/** + * Parses a CSS string and returns a `CSSStyleSheet` object representing the parsed stylesheet. + * + * @param {string} token - The CSS string to parse. + * @param {object} [opts] - Optional parsing options. + * @param {object} [opts.globalObject] - An optional global object to prioritize over the window object. Useful on jsdom webplatform tests. + * @param {Element | ProcessingInstruction} [opts.ownerNode] - The owner node of the stylesheet. + * @param {CSSRule} [opts.ownerRule] - The owner rule of the stylesheet. + * @param {CSSOM.CSSStyleSheet} [opts.styleSheet] - Reuse a style sheet instead of creating a new one (e.g. as `parentStyleSheet`) + * @param {CSSOM.CSSRuleList} [opts.cssRules] - Prepare all rules in this list instead of mutating the style sheet continually + * @param {function|boolean} [errorHandler] - Optional error handler function or `true` to use `console.error`. + * @returns {CSSOM.CSSStyleSheet} The parsed `CSSStyleSheet` object. + */ +CSSOM.parse = function parse(token, opts, errorHandler) { + errorHandler = errorHandler === true ? (console && console.error) : errorHandler; + + var i = 0; + + /** + "before-selector" or + "selector" or + "atRule" or + "atBlock" or + "conditionBlock" or + "before-name" or + "name" or + "before-value" or + "value" + */ + var state = "before-selector"; + + var index; + var buffer = ""; + var valueParenthesisDepth = 0; + var hasUnmatchedQuoteInSelector = false; // Track if current selector has unmatched quote + + var SIGNIFICANT_WHITESPACE = { + "name": true, + "before-name": true, + "selector": true, + "value": true, + "value-parenthesis": true, + "atRule": true, + "importRule-begin": true, + "importRule": true, + "namespaceRule-begin": true, + "namespaceRule": true, + "atBlock": true, + "containerBlock": true, + "conditionBlock": true, + "counterStyleBlock": true, + "propertyBlock": true, + 'documentRule-begin': true, + "scopeBlock": true, + "layerBlock": true, + "pageBlock": true + }; + + var styleSheet; + if (opts && opts.styleSheet) { + styleSheet = opts.styleSheet; + } else { + if (opts && opts.globalObject && opts.globalObject.CSSStyleSheet) { + styleSheet = new opts.globalObject.CSSStyleSheet(); + } else { + styleSheet = new CSSOM.CSSStyleSheet(); + } + styleSheet.__constructed = false; + } + + var topScope; + if (opts && opts.cssRules) { + topScope = { cssRules: opts.cssRules }; + } else { + topScope = styleSheet; + } + + if (opts && opts.ownerNode) { + styleSheet.__ownerNode = opts.ownerNode; + var ownerNodeMedia = opts.ownerNode.media || (opts.ownerNode.getAttribute && opts.ownerNode.getAttribute("media")); + if (ownerNodeMedia) { + styleSheet.media.mediaText = ownerNodeMedia; + } + var ownerNodeTitle = opts.ownerNode.title || (opts.ownerNode.getAttribute && opts.ownerNode.getAttribute("title")); + if (ownerNodeTitle) { + styleSheet.__title = ownerNodeTitle; + } + } + + if (opts && opts.ownerRule) { + styleSheet.__ownerRule = opts.ownerRule; + } + + // @type CSSStyleSheet|CSSMediaRule|CSSContainerRule|CSSSupportsRule|CSSFontFaceRule|CSSKeyframesRule|CSSDocumentRule + var currentScope = topScope; + + // @type CSSMediaRule|CSSContainerRule|CSSSupportsRule|CSSKeyframesRule|CSSDocumentRule + var parentRule; + + var ancestorRules = []; + var prevScope; + + var name, priority = "", styleRule, mediaRule, containerRule, counterStyleRule, propertyRule, supportsRule, importRule, fontFaceRule, keyframesRule, documentRule, hostRule, startingStyleRule, scopeRule, pageRule, layerBlockRule, layerStatementRule, nestedSelectorRule, namespaceRule; + + // Track defined namespace prefixes for validation + var definedNamespacePrefixes = {}; + + // Track which rules have been added + var ruleIdCounter = 0; + var addedToParent = {}; + var addedToTopScope = {}; + var addedToCurrentScope = {}; + + // Helper to get unique ID for tracking rules + function getRuleId(rule) { + if (!rule.__parseId) { + rule.__parseId = ++ruleIdCounter; + } + return rule.__parseId; + } + + // Cache last validation boundary position + // to avoid rescanning the entire token string for each at-rule + var lastValidationBoundary = 0; + + // Pre-compile validation regexes for common at-rules + var validationRegexCache = {}; + function getValidationRegex(atRuleKey) { + if (!validationRegexCache[atRuleKey]) { + var sourceRuleRegExp = atRuleKey === "@import" ? forwardImportRuleValidationRegExp : forwardRuleValidationRegExp; + validationRegexCache[atRuleKey] = new RegExp(atRuleKey + sourceRuleRegExp.source, sourceRuleRegExp.flags); + } + return validationRegexCache[atRuleKey]; + } + + // Import regex patterns from shared module + var atKeyframesRegExp = regexPatterns.atKeyframesRegExp; + var beforeRulePortionRegExp = regexPatterns.beforeRulePortionRegExp; + var beforeRuleValidationRegExp = regexPatterns.beforeRuleValidationRegExp; + var forwardRuleValidationRegExp = regexPatterns.forwardRuleValidationRegExp; + var forwardImportRuleValidationRegExp = regexPatterns.forwardImportRuleValidationRegExp; + + // Pre-compile regexBefore to avoid creating it on every validateAtRule call + var regexBefore = new RegExp(beforeRulePortionRegExp.source, beforeRulePortionRegExp.flags); + var forwardRuleClosingBraceRegExp = regexPatterns.forwardRuleClosingBraceRegExp; + var forwardRuleSemicolonAndOpeningBraceRegExp = regexPatterns.forwardRuleSemicolonAndOpeningBraceRegExp; + var cssCustomIdentifierRegExp = regexPatterns.cssCustomIdentifierRegExp; + var startsWithCombinatorRegExp = regexPatterns.startsWithCombinatorRegExp; + var atPageRuleSelectorRegExp = regexPatterns.atPageRuleSelectorRegExp; + var startsWithHexEscapeRegExp = regexPatterns.startsWithHexEscapeRegExp; + var identStartCharRegExp = regexPatterns.identStartCharRegExp; + var identCharRegExp = regexPatterns.identCharRegExp; + var specialCharsNeedEscapeRegExp = regexPatterns.specialCharsNeedEscapeRegExp; + var combinatorOrSeparatorRegExp = regexPatterns.combinatorOrSeparatorRegExp; + var afterHexEscapeSeparatorRegExp = regexPatterns.afterHexEscapeSeparatorRegExp; + var trailingSpaceSeparatorRegExp = regexPatterns.trailingSpaceSeparatorRegExp; + var endsWithHexEscapeRegExp = regexPatterns.endsWithHexEscapeRegExp; + var attributeSelectorContentRegExp = regexPatterns.attributeSelectorContentRegExp; + var pseudoElementRegExp = regexPatterns.pseudoElementRegExp; + var invalidCombinatorLtGtRegExp = regexPatterns.invalidCombinatorLtGtRegExp; + var invalidCombinatorDoubleGtRegExp = regexPatterns.invalidCombinatorDoubleGtRegExp; + var consecutiveCombinatorsRegExp = regexPatterns.consecutiveCombinatorsRegExp; + var invalidSlottedRegExp = regexPatterns.invalidSlottedRegExp; + var invalidPartRegExp = regexPatterns.invalidPartRegExp; + var invalidCueRegExp = regexPatterns.invalidCueRegExp; + var invalidCueRegionRegExp = regexPatterns.invalidCueRegionRegExp; + var invalidNestingPattern = regexPatterns.invalidNestingPattern; + var emptyPseudoClassRegExp = regexPatterns.emptyPseudoClassRegExp; + var whitespaceNormalizationRegExp = regexPatterns.whitespaceNormalizationRegExp; + var newlineRemovalRegExp = regexPatterns.newlineRemovalRegExp; + var whitespaceAndDotRegExp = regexPatterns.whitespaceAndDotRegExp; + var declarationOrOpenBraceRegExp = regexPatterns.declarationOrOpenBraceRegExp; + var ampersandRegExp = regexPatterns.ampersandRegExp; + var hexEscapeSequenceRegExp = regexPatterns.hexEscapeSequenceRegExp; + var attributeCaseFlagRegExp = regexPatterns.attributeCaseFlagRegExp; + var prependedAmpersandRegExp = regexPatterns.prependedAmpersandRegExp; + var openBraceGlobalRegExp = regexPatterns.openBraceGlobalRegExp; + var closeBraceGlobalRegExp = regexPatterns.closeBraceGlobalRegExp; + var scopePreludeSplitRegExp = regexPatterns.scopePreludeSplitRegExp; + var leadingWhitespaceRegExp = regexPatterns.leadingWhitespaceRegExp; + var doubleQuoteRegExp = regexPatterns.doubleQuoteRegExp; + var backslashRegExp = regexPatterns.backslashRegExp; + + /** + * Searches for the first occurrence of a CSS at-rule statement terminator (`;` or `}`) + * that is not inside a brace block within the given string. Mimics the behavior of a + * regular expression match for such terminators, including any trailing whitespace. + * @param {string} str - The string to search for at-rule statement terminators. + * @returns {object | null} {0: string, index: number} or null if no match is found. + */ + function atRulesStatemenRegExpES5Alternative(ruleSlice) { + for (var i = 0; i < ruleSlice.length; i++) { + var char = ruleSlice[i]; + + if (char === ';' || char === '}') { + // Simulate negative lookbehind: check if there is a { before this position + var sliceBefore = ruleSlice.substring(0, i); + var openBraceIndex = sliceBefore.indexOf('{'); + + if (openBraceIndex === -1) { + // No { found before, so we treat it as a valid match + var match = char; + var j = i + 1; + + while (j < ruleSlice.length && /\s/.test(ruleSlice[j])) { + match += ruleSlice[j]; + j++; + } + + var matchObj = [match]; + matchObj.index = i; + matchObj.input = ruleSlice; + return matchObj; + } + } + } + + return null; + } + + /** + * Finds the first balanced block (including nested braces) in the string, starting from fromIndex. + * Returns an object similar to RegExp.prototype.match output. + * @param {string} str - The string to search. + * @param {number} [fromIndex=0] - The index to start searching from. + * @returns {object|null} - { 0: matchedString, index: startIndex, input: str } or null if not found. + */ + function matchBalancedBlock(str, fromIndex) { + fromIndex = fromIndex || 0; + var openIndex = str.indexOf('{', fromIndex); + if (openIndex === -1) return null; + var depth = 0; + for (var i = openIndex; i < str.length; i++) { + if (str[i] === '{') { + depth++; + } else if (str[i] === '}') { + depth--; + if (depth === 0) { + var matchedString = str.slice(openIndex, i + 1); + return { + 0: matchedString, + index: openIndex, + input: str + }; + } + } + } + return null; + } + + /** + * Advances the index `i` to skip over a balanced block of curly braces in the given string. + * This is typically used to ignore the contents of a CSS rule block. + * + * @param {number} i - The current index in the string to start searching from. + * @param {string} str - The string containing the CSS code. + * @param {number} fromIndex - The index in the string where the balanced block search should begin. + * @returns {number} The updated index after skipping the balanced block. + */ + function ignoreBalancedBlock(i, str, fromIndex) { + var ruleClosingMatch = matchBalancedBlock(str, fromIndex); + if (ruleClosingMatch) { + var ignoreRange = ruleClosingMatch.index + ruleClosingMatch[0].length; + i += ignoreRange; + if (token.charAt(i) === '}') { + i -= 1; + } + } else { + i += str.length; + } + return i; + } + + /** + * Parses the scope prelude and extracts start and end selectors. + * @param {string} preludeContent - The scope prelude content (without @scope keyword) + * @returns {object} Object with startSelector and endSelector properties + */ + function parseScopePrelude(preludeContent) { + var parts = preludeContent.split(scopePreludeSplitRegExp); + + // Restore the parentheses that were consumed by the split + if (parts.length === 2) { + parts[0] = parts[0] + ')'; + parts[1] = '(' + parts[1]; + } + + var hasStart = parts[0] && + parts[0].charAt(0) === '(' && + parts[0].charAt(parts[0].length - 1) === ')'; + var hasEnd = parts[1] && + parts[1].charAt(0) === '(' && + parts[1].charAt(parts[1].length - 1) === ')'; + + // Handle case: @scope to () + var hasOnlyEnd = !hasStart && + !hasEnd && + parts[0].indexOf('to (') === 0 && + parts[0].charAt(parts[0].length - 1) === ')'; + + var startSelector = ''; + var endSelector = ''; + + if (hasStart) { + startSelector = parts[0].slice(1, -1).trim(); + } + if (hasEnd) { + endSelector = parts[1].slice(1, -1).trim(); + } + if (hasOnlyEnd) { + endSelector = parts[0].slice(4, -1).trim(); + } + + return { + startSelector: startSelector, + endSelector: endSelector, + hasStart: hasStart, + hasEnd: hasEnd, + hasOnlyEnd: hasOnlyEnd + }; + }; + + /** + * Checks if a selector contains pseudo-elements. + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if the selector contains pseudo-elements + */ + function hasPseudoElement(selector) { + // Match only double-colon (::) pseudo-elements + // Also match legacy single-colon pseudo-elements: :before, :after, :first-line, :first-letter + // These must NOT be followed by alphanumeric characters (to avoid matching :before-x or similar) + return pseudoElementRegExp.test(selector); + }; + + /** + * Validates balanced parentheses, brackets, and quotes in a selector. + * + * @param {string} selector - The CSS selector to validate + * @param {boolean} trackAttributes - Whether to track attribute selector context + * @param {boolean} useStack - Whether to use a stack for parentheses (needed for nested validation) + * @returns {boolean} True if the syntax is valid (all brackets, parentheses, and quotes are balanced) + */ + function validateBalancedSyntax(selector, trackAttributes, useStack) { + var parenDepth = 0; + var bracketDepth = 0; + var inSingleQuote = false; + var inDoubleQuote = false; + var inAttr = false; + var stack = useStack ? [] : null; + + for (var i = 0; i < selector.length; i++) { + var char = selector[i]; + + // Handle escape sequences - skip hex escapes or simple escapes + if (char === '\\') { + var escapeLen = getEscapeSequenceLength(selector, i); + if (escapeLen > 0) { + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + + if (inSingleQuote) { + if (char === "'") { + inSingleQuote = false; + } + } else if (inDoubleQuote) { + if (char === '"') { + inDoubleQuote = false; + } + } else if (trackAttributes && inAttr) { + if (char === "]") { + inAttr = false; + } else if (char === "'") { + inSingleQuote = true; + } else if (char === '"') { + inDoubleQuote = true; + } + } else { + if (trackAttributes && char === "[") { + inAttr = true; + } else if (char === "'") { + inSingleQuote = true; + } else if (char === '"') { + inDoubleQuote = true; + } else if (char === '(') { + if (useStack) { + stack.push("("); + } else { + parenDepth++; + } + } else if (char === ')') { + if (useStack) { + if (!stack.length || stack.pop() !== "(") { + return false; + } + } else { + parenDepth--; + if (parenDepth < 0) { + return false; + } + } + } else if (char === '[') { + bracketDepth++; + } else if (char === ']') { + bracketDepth--; + if (bracketDepth < 0) { + return false; + } + } + } + } + + // Check if everything is balanced + if (useStack) { + return stack.length === 0 && bracketDepth === 0 && !inSingleQuote && !inDoubleQuote && !inAttr; + } else { + return parenDepth === 0 && bracketDepth === 0 && !inSingleQuote && !inDoubleQuote; + } + }; + + /** + * Checks for basic syntax errors in selectors (mismatched parentheses, brackets, quotes). + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if there are syntax errors + */ + function hasBasicSyntaxError(selector) { + return !validateBalancedSyntax(selector, false, false); + }; + + /** + * Checks for invalid combinator patterns in selectors. + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if the selector contains invalid combinators + */ + function hasInvalidCombinators(selector) { + // Check for invalid combinator patterns: + // - <> (not a valid combinator) + // - >> (deep descendant combinator, deprecated and invalid) + // - Multiple consecutive combinators like >>, >~, etc. + if (invalidCombinatorLtGtRegExp.test(selector)) return true; + if (invalidCombinatorDoubleGtRegExp.test(selector)) return true; + // Check for other invalid consecutive combinator patterns + if (consecutiveCombinatorsRegExp.test(selector)) return true; + return false; + }; + + /** + * Checks for invalid pseudo-like syntax (function calls without proper pseudo prefix). + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if the selector contains invalid pseudo-like syntax + */ + function hasInvalidPseudoSyntax(selector) { + // Check for specific known pseudo-elements used without : or :: prefix + // Examples: slotted(div), part(name), cue(selector) + // These are ONLY valid as ::slotted(), ::part(), ::cue() + var invalidPatterns = [ + invalidSlottedRegExp, + invalidPartRegExp, + invalidCueRegExp, + invalidCueRegionRegExp + ]; + + for (var i = 0; i < invalidPatterns.length; i++) { + if (invalidPatterns[i].test(selector)) { + return true; + } + } + return false; + }; + + /** + * Checks for invalid nesting selector (&) usage. + * The & selector cannot be directly followed by a type selector without a delimiter. + * Valid: &.class, &#id, &[attr], &:hover, &::before, & div, &>div + * Invalid: &div, &span + * @param {string} selector - The CSS selector to check + * @returns {boolean} True if the selector contains invalid & usage + */ + function hasInvalidNestingSelector(selector) { + // Check for & followed directly by a letter (type selector) without any delimiter + // This regex matches & followed by a letter (start of type selector) that's not preceded by an escape + // We need to exclude valid cases like &.class, &#id, &[attr], &:pseudo, &::pseudo, & (with space), &> + return invalidNestingPattern.test(selector); + }; + + /** + * Checks if an at-rule can be nested based on parent chain validation. + * Used for at-rules like `@counter-style`, `@property` and `@font-face` rules that can only be nested inside + * `CSSScopeRule` or `CSSConditionRule` without `CSSStyleRule` in parent chain. + * @returns {boolean} `true` if nesting is allowed, `false` otherwise + */ + function canAtRuleBeNested() { + if (currentScope === topScope) { + return true; // Top-level is always allowed + } + + var hasStyleRuleInChain = false; + var hasValidParent = false; + + // Check currentScope + if (currentScope.constructor.name === 'CSSStyleRule') { + hasStyleRuleInChain = true; + } else if (currentScope instanceof CSSOM.CSSScopeRule || currentScope instanceof CSSOM.CSSConditionRule) { + hasValidParent = true; + } + + // Check ancestorRules for CSSStyleRule + if (!hasStyleRuleInChain) { + for (var j = 0; j < ancestorRules.length; j++) { + if (ancestorRules[j].constructor.name === 'CSSStyleRule') { + hasStyleRuleInChain = true; + break; + } + if (ancestorRules[j] instanceof CSSOM.CSSScopeRule || ancestorRules[j] instanceof CSSOM.CSSConditionRule) { + hasValidParent = true; + } + } + } + + // Allow nesting if we have a valid parent and no style rule in the chain + return hasValidParent && !hasStyleRuleInChain; + } + + function validateAtRule(atRuleKey, validCallback, cannotBeNested) { + var isValid = false; + // Use cached regex instead of creating new one each time + var ruleRegExp = getValidationRegex(atRuleKey); + // Only slice what we need for validation (max 100 chars) + // since we only check match at position 0 + var lookAheadLength = Math.min(100, token.length - i); + var ruleSlice = token.slice(i, i + lookAheadLength); + // Not all rules can be nested, if the rule cannot be nested and is in the root scope, do not perform the check + var shouldPerformCheck = cannotBeNested && currentScope !== topScope ? false : true; + // First, check if there is no invalid characters just after the at-rule + if (shouldPerformCheck && ruleSlice.search(ruleRegExp) === 0) { + // Only scan from the last known validation boundary + var searchStart = Math.max(0, lastValidationBoundary); + var beforeSlice = token.slice(searchStart, i); + + // Use pre-compiled regex instead of creating new one each time + var matches = beforeSlice.match(regexBefore); + var lastI = matches ? searchStart + beforeSlice.lastIndexOf(matches[matches.length - 1]) : searchStart; + var toCheckSlice = token.slice(lastI, i); + // Check if we don't have any invalid in the portion before the `at-rule` and the closest allowed character + var checkedSlice = toCheckSlice.search(beforeRuleValidationRegExp); + if (checkedSlice === 0) { + isValid = true; + // Update the validation boundary cache to this position + lastValidationBoundary = lastI; + } + } + + // Additional validation for @scope rule + if (isValid && atRuleKey === "@scope") { + var openBraceIndex = ruleSlice.indexOf('{'); + if (openBraceIndex !== -1) { + // Extract the rule prelude (everything between the at-rule and {) + var rulePrelude = ruleSlice.slice(0, openBraceIndex).trim(); + + // Skip past at-rule keyword and whitespace + var preludeContent = rulePrelude.slice("@scope".length).trim(); + + if (preludeContent.length > 0) { + // Parse the scope prelude + var parsedScopePrelude = parseScopePrelude(preludeContent); + var startSelector = parsedScopePrelude.startSelector; + var endSelector = parsedScopePrelude.endSelector; + var hasStart = parsedScopePrelude.hasStart; + var hasEnd = parsedScopePrelude.hasEnd; + var hasOnlyEnd = parsedScopePrelude.hasOnlyEnd; + + // Validation rules for @scope: + // 1. Empty selectors in parentheses are invalid: @scope () {} or @scope (.a) to () {} + if ((hasStart && startSelector === '') || (hasEnd && endSelector === '') || (hasOnlyEnd && endSelector === '')) { + isValid = false; + } + // 2. Pseudo-elements are invalid in scope selectors + else if ((startSelector && hasPseudoElement(startSelector)) || (endSelector && hasPseudoElement(endSelector))) { + isValid = false; + } + // 3. Basic syntax errors (mismatched parens, brackets, quotes) + else if ((startSelector && hasBasicSyntaxError(startSelector)) || (endSelector && hasBasicSyntaxError(endSelector))) { + isValid = false; + } + // 4. Invalid combinator patterns + else if ((startSelector && hasInvalidCombinators(startSelector)) || (endSelector && hasInvalidCombinators(endSelector))) { + isValid = false; + } + // 5. Invalid pseudo-like syntax (function without : or :: prefix) + else if ((startSelector && hasInvalidPseudoSyntax(startSelector)) || (endSelector && hasInvalidPseudoSyntax(endSelector))) { + isValid = false; + } + // 6. Invalid structure (no proper parentheses found when prelude is not empty) + else if (!hasStart && !hasOnlyEnd) { + isValid = false; + } + } + // Empty prelude (@scope {}) is valid + } + } + + if (isValid && atRuleKey === "@page") { + var openBraceIndex = ruleSlice.indexOf('{'); + if (openBraceIndex !== -1) { + // Extract the rule prelude (everything between the at-rule and {) + var rulePrelude = ruleSlice.slice(0, openBraceIndex).trim(); + + // Skip past at-rule keyword and whitespace + var preludeContent = rulePrelude.slice("@page".length).trim(); + + if (preludeContent.length > 0) { + var trimmedValue = preludeContent.trim(); + + // Empty selector is valid for @page + if (trimmedValue !== '') { + // Parse @page selectorText for page name and pseudo-pages + // Valid formats: + // - (empty - no name, no pseudo-page) + // - :left, :right, :first, :blank (pseudo-page only) + // - named (named page only) + // - named:first (named page with single pseudo-page) + // - named:first:left (named page with multiple pseudo-pages) + var match = trimmedValue.match(atPageRuleSelectorRegExp); + if (match) { + var pageName = match[1] || ''; + var pseudoPages = match[2] || ''; + + // Validate page name if present + if (pageName) { + if (!cssCustomIdentifierRegExp.test(pageName)) { + isValid = false; + } + } + + // Validate pseudo-pages if present + if (pseudoPages) { + var pseudos = pseudoPages.split(':').filter(function (p) { return p; }); + var validPseudos = ['left', 'right', 'first', 'blank']; + var allValid = true; + for (var j = 0; j < pseudos.length; j++) { + if (validPseudos.indexOf(pseudos[j].toLowerCase()) === -1) { + allValid = false; + break; + } + } + + if (!allValid) { + isValid = false; + } + } + } else { + isValid = false; + } + } + + } + } + } + + if (!isValid) { + // If it's invalid the browser will simply ignore the entire invalid block + // Use regex to find the closing brace of the invalid rule + + // Regex used above is not ES5 compliant. Using alternative. + // var ruleStatementMatch = ruleSlice.match(atRulesStatemenRegExp); // + var ruleStatementMatch = atRulesStatemenRegExpES5Alternative(ruleSlice); + + // If it's a statement inside a nested rule, ignore only the statement + if (ruleStatementMatch && currentScope !== topScope) { + var ignoreEnd = ruleStatementMatch[0].indexOf(";"); + i += ruleStatementMatch.index + ignoreEnd; + return; + } + + // Check if there's a semicolon before the invalid at-rule and the first opening brace + if (atRuleKey === "@layer") { + var ruleSemicolonAndOpeningBraceMatch = ruleSlice.match(forwardRuleSemicolonAndOpeningBraceRegExp); + if (ruleSemicolonAndOpeningBraceMatch && ruleSemicolonAndOpeningBraceMatch[1] === ";") { + // Ignore the rule block until the semicolon + i += ruleSemicolonAndOpeningBraceMatch.index + ruleSemicolonAndOpeningBraceMatch[0].length; + state = "before-selector"; + return; + } + } + + // Ignore the entire rule block (if it's a statement it should ignore the statement plus the next block) + i = ignoreBalancedBlock(i, ruleSlice); + state = "before-selector"; + } else { + validCallback.call(this); + } + } + + // Helper functions for looseSelectorValidator + // Defined outside to avoid recreation on every validation call + + /** + * Check if character is a valid identifier start + * @param {string} c - Character to check + * @returns {boolean} + */ + function isIdentStart(c) { + return /[a-zA-Z_\u00A0-\uFFFF]/.test(c); + } + + /** + * Check if character is a valid identifier character + * @param {string} c - Character to check + * @returns {boolean} + */ + function isIdentChar(c) { + return /[a-zA-Z0-9_\u00A0-\uFFFF\-]/.test(c); + } + + /** + * Helper function to validate CSS selector syntax without regex backtracking. + * Iteratively parses the selector string to identify valid components. + * + * Supports: + * - Escaped characters (e.g., .class\!, #id\@name) + * - Namespace selectors (ns|element, *|element, |element) + * - All standard CSS selectors (class, ID, type, attribute, pseudo, etc.) + * - Combinators (>, +, ~, whitespace) + * - Nesting selector (&) + * + * This approach eliminates exponential backtracking by using explicit character-by-character + * parsing instead of nested quantifiers in regex. + * + * @param {string} selector - The selector to validate + * @returns {boolean} - True if valid selector syntax + */ + function looseSelectorValidator(selector) { + if (!selector || selector.length === 0) { + return false; + } + + var i = 0; + var len = selector.length; + var hasMatchedComponent = false; + + // Helper: Skip escaped character (backslash + hex escape or any char) + function skipEscape() { + if (i < len && selector[i] === '\\') { + var escapeLen = getEscapeSequenceLength(selector, i); + if (escapeLen > 0) { + i += escapeLen; // Skip entire escape sequence + return true; + } + } + return false; + } + + // Helper: Parse identifier (with possible escapes) + function parseIdentifier() { + var start = i; + while (i < len) { + if (skipEscape()) { + continue; + } else if (isIdentChar(selector[i])) { + i++; + } else { + break; + } + } + return i > start; + } + + // Helper: Parse namespace prefix (optional) + function parseNamespace() { + var start = i; + + // Match: *| or identifier| or | + if (i < len && selector[i] === '*') { + i++; + } else if (i < len && (isIdentStart(selector[i]) || selector[i] === '\\')) { + parseIdentifier(); + } + + if (i < len && selector[i] === '|') { + i++; + return true; + } + + // Rollback if no pipe found + i = start; + return false; + } + + // Helper: Parse pseudo-class/element arguments (with balanced parens) + function parsePseudoArgs() { + if (i >= len || selector[i] !== '(') { + return false; + } + + i++; // Skip opening paren + var depth = 1; + var inString = false; + var stringChar = ''; + + while (i < len && depth > 0) { + var c = selector[i]; + + if (c === '\\' && i + 1 < len) { + i += 2; // Skip escaped character + } else if (!inString && (c === '"' || c === '\'')) { + inString = true; + stringChar = c; + i++; + } else if (inString && c === stringChar) { + inString = false; + i++; + } else if (!inString && c === '(') { + depth++; + i++; + } else if (!inString && c === ')') { + depth--; + i++; + } else { + i++; + } + } + + return depth === 0; + } + + // Main parsing loop + while (i < len) { + var matched = false; + var start = i; + + // Skip whitespace + while (i < len && /\s/.test(selector[i])) { + i++; + } + if (i > start) { + hasMatchedComponent = true; + continue; + } + + // Match combinators: >, +, ~ + if (i < len && /[>+~]/.test(selector[i])) { + i++; + hasMatchedComponent = true; + // Skip trailing whitespace + while (i < len && /\s/.test(selector[i])) { + i++; + } + continue; + } + + // Match nesting selector: & + if (i < len && selector[i] === '&') { + i++; + hasMatchedComponent = true; + matched = true; + } + // Match class selector: .identifier + else if (i < len && selector[i] === '.') { + i++; + if (parseIdentifier()) { + hasMatchedComponent = true; + matched = true; + } + } + // Match ID selector: #identifier + else if (i < len && selector[i] === '#') { + i++; + if (parseIdentifier()) { + hasMatchedComponent = true; + matched = true; + } + } + // Match pseudo-class/element: :identifier or ::identifier + else if (i < len && selector[i] === ':') { + i++; + if (i < len && selector[i] === ':') { + i++; // Pseudo-element + } + if (parseIdentifier()) { + parsePseudoArgs(); // Optional arguments + hasMatchedComponent = true; + matched = true; + } + } + // Match attribute selector: [...] + else if (i < len && selector[i] === '[') { + i++; + var depth = 1; + while (i < len && depth > 0) { + if (selector[i] === '\\') { + i += 2; + } else if (selector[i] === '\'') { + i++; + while (i < len && selector[i] !== '\'') { + if (selector[i] === '\\') i += 2; + else i++; + } + if (i < len) i++; // Skip closing quote + } else if (selector[i] === '"') { + i++; + while (i < len && selector[i] !== '"') { + if (selector[i] === '\\') i += 2; + else i++; + } + if (i < len) i++; // Skip closing quote + } else if (selector[i] === '[') { + depth++; + i++; + } else if (selector[i] === ']') { + depth--; + i++; + } else { + i++; + } + } + if (depth === 0) { + hasMatchedComponent = true; + matched = true; + } + } + // Match type selector with optional namespace: [namespace|]identifier + else if (i < len && (isIdentStart(selector[i]) || selector[i] === '\\' || selector[i] === '*' || selector[i] === '|')) { + parseNamespace(); // Optional namespace prefix + + if (i < len && selector[i] === '*') { + i++; // Universal selector + hasMatchedComponent = true; + matched = true; + } else if (i < len && (isIdentStart(selector[i]) || selector[i] === '\\')) { + if (parseIdentifier()) { + hasMatchedComponent = true; + matched = true; + } + } + } + + // If no match found, invalid selector + if (!matched && i === start) { + return false; + } + } + + return hasMatchedComponent; + } + + /** + * Validates a basic CSS selector, allowing for deeply nested balanced parentheses in pseudo-classes. + * This function replaces the previous basicSelectorRegExp. + * + * This function matches: + * - Type selectors (e.g., `div`, `span`) + * - Universal selector (`*`) + * - Namespace selectors (e.g., `*|div`, `custom|div`, `|div`) + * - ID selectors (e.g., `#header`, `#a\ b`, `#åèiöú`) + * - Class selectors (e.g., `.container`, `.a\ b`, `.åèiöú`) + * - Attribute selectors (e.g., `[type="text"]`) + * - Pseudo-classes and pseudo-elements (e.g., `:hover`, `::before`, `:nth-child(2)`) + * - Pseudo-classes with nested parentheses, including cases where parentheses are nested inside arguments, + * such as `:has(.sel:nth-child(3n))` + * - The parent selector (`&`) + * - Combinators (`>`, `+`, `~`) with optional whitespace + * - Whitespace (descendant combinator) + * + * Unicode and escape sequences are allowed in identifiers. + * + * @param {string} selector + * @returns {boolean} + */ + function basicSelectorValidator(selector) { + // Guard against extremely long selectors to prevent potential regex performance issues + // Reasonable selectors are typically under 1000 characters + if (selector.length > 10000) { + return false; + } + + // Validate balanced syntax with attribute tracking and stack-based parentheses matching + if (!validateBalancedSyntax(selector, true, true)) { + return false; + } + + // Check for invalid combinator patterns + if (hasInvalidCombinators(selector)) { + return false; + } + + // Check for invalid pseudo-like syntax + if (hasInvalidPseudoSyntax(selector)) { + return false; + } + + // Check for invalid nesting selector (&) usage + if (hasInvalidNestingSelector(selector)) { + return false; + } + + // Check for invalid pseudo-class usage with quoted strings + // Pseudo-classes like :lang(), :dir(), :nth-*() should not accept quoted strings + // Using iterative parsing instead of regex to avoid exponential backtracking + var noQuotesPseudos = ['lang', 'dir', 'nth-child', 'nth-last-child', 'nth-of-type', 'nth-last-of-type']; + + for (var idx = 0; idx < selector.length; idx++) { + // Look for pseudo-class/element start + if (selector[idx] === ':') { + var pseudoStart = idx; + idx++; + + // Skip second colon for pseudo-elements + if (idx < selector.length && selector[idx] === ':') { + idx++; + } + + // Extract pseudo name + var nameStart = idx; + while (idx < selector.length && /[a-zA-Z0-9\-]/.test(selector[idx])) { + idx++; + } + + if (idx === nameStart) { + continue; // No name found + } + + var pseudoName = selector.substring(nameStart, idx).toLowerCase(); + + // Check if this pseudo has arguments + if (idx < selector.length && selector[idx] === '(') { + idx++; + var contentStart = idx; + var depth = 1; + + // Find matching closing paren (handle nesting) + while (idx < selector.length && depth > 0) { + if (selector[idx] === '\\') { + idx += 2; // Skip escaped character + } else if (selector[idx] === '(') { + depth++; + idx++; + } else if (selector[idx] === ')') { + depth--; + idx++; + } else { + idx++; + } + } + + if (depth === 0) { + var pseudoContent = selector.substring(contentStart, idx - 1); + + // Check if this pseudo should not have quoted strings + for (var j = 0; j < noQuotesPseudos.length; j++) { + if (pseudoName === noQuotesPseudos[j] && /['"]/.test(pseudoContent)) { + return false; + } + } + } + } + } + } + + // Use the iterative validator to avoid regex backtracking issues + return looseSelectorValidator(selector); + } + + /** + * Regular expression to match CSS pseudo-classes with arguments. + * + * Matches patterns like `:pseudo-class(argument)`, capturing the pseudo-class name and its argument. + * + * Capture groups: + * 1. The pseudo-class name (letters and hyphens). + * 2. The argument inside the parentheses (can contain nested parentheses, quoted strings, and other characters.). + * + * Global flag (`g`) is used to find all matches in the input string. + * + * Example matches: + * - :nth-child(2n+1) + * - :has(.sel:nth-child(3n)) + * - :not(".foo, .bar") + * + * REPLACED WITH FUNCTION to avoid exponential backtracking. + */ + + /** + * Extract pseudo-classes with arguments from a selector using iterative parsing. + * Replaces the previous globalPseudoClassRegExp to avoid exponential backtracking. + * + * Handles: + * - Regular content without parentheses or quotes + * - Single-quoted strings + * - Double-quoted strings + * - Nested parentheses (arbitrary depth) + * + * @param {string} selector - The CSS selector to parse + * @returns {Array} Array of matches, each with: [fullMatch, pseudoName, pseudoArgs, startIndex] + */ + function extractPseudoClasses(selector) { + var matches = []; + + for (var i = 0; i < selector.length; i++) { + // Look for pseudo-class start (single or double colon) + if (selector[i] === ':') { + var pseudoStart = i; + i++; + + // Skip second colon for pseudo-elements (::) + if (i < selector.length && selector[i] === ':') { + i++; + } + + // Extract pseudo name + var nameStart = i; + while (i < selector.length && /[a-zA-Z\-]/.test(selector[i])) { + i++; + } + + if (i === nameStart) { + continue; // No name found + } + + var pseudoName = selector.substring(nameStart, i); + + // Check if this pseudo has arguments + if (i < selector.length && selector[i] === '(') { + i++; + var argsStart = i; + var depth = 1; + var inSingleQuote = false; + var inDoubleQuote = false; + + // Find matching closing paren (handle nesting and strings) + while (i < selector.length && depth > 0) { + var ch = selector[i]; + + if (ch === '\\') { + i += 2; // Skip escaped character + } else if (ch === "'" && !inDoubleQuote) { + inSingleQuote = !inSingleQuote; + i++; + } else if (ch === '"' && !inSingleQuote) { + inDoubleQuote = !inDoubleQuote; + i++; + } else if (ch === '(' && !inSingleQuote && !inDoubleQuote) { + depth++; + i++; + } else if (ch === ')' && !inSingleQuote && !inDoubleQuote) { + depth--; + i++; + } else { + i++; + } + } + + if (depth === 0) { + var pseudoArgs = selector.substring(argsStart, i - 1); + var fullMatch = selector.substring(pseudoStart, i); + + // Store match in same format as regex: [fullMatch, pseudoName, pseudoArgs, startIndex] + matches.push([fullMatch, pseudoName, pseudoArgs, pseudoStart]); + } + + // Move back one since loop will increment + i--; + } + } + } + + return matches; + } + + /** + * Parses a CSS selector string and splits it into parts, handling nested parentheses. + * + * This function is useful for splitting selectors that may contain nested function-like + * syntax (e.g., :not(.foo, .bar)), ensuring that commas inside parentheses do not split + * the selector. + * + * @param {string} selector - The CSS selector string to parse. + * @returns {string[]} An array of selector parts, split by top-level commas, with whitespace trimmed. + */ + function parseAndSplitNestedSelectors(selector) { + var depth = 0; // Track parenthesis nesting depth + var buffer = ""; // Accumulate characters for current selector part + var parts = []; // Array of split selector parts + var inSingleQuote = false; // Track if we're inside single quotes + var inDoubleQuote = false; // Track if we're inside double quotes + var i, char; + + for (i = 0; i < selector.length; i++) { + char = selector.charAt(i); + + // Handle escape sequences - skip them entirely + if (char === '\\' && i + 1 < selector.length) { + buffer += char; + i++; + buffer += selector.charAt(i); + continue; + } + + // Handle single quote strings + if (char === "'" && !inDoubleQuote) { + inSingleQuote = !inSingleQuote; + buffer += char; + } + // Handle double quote strings + else if (char === '"' && !inSingleQuote) { + inDoubleQuote = !inDoubleQuote; + buffer += char; + } + // Process characters outside of quoted strings + else if (!inSingleQuote && !inDoubleQuote) { + if (char === '(') { + // Entering a nested level (e.g., :is(...)) + depth++; + buffer += char; + } else if (char === ')') { + // Exiting a nested level + depth--; + buffer += char; + } else if (char === ',' && depth === 0) { + // Found a top-level comma separator - split here + // Note: escaped commas (\,) are already handled above + if (buffer.trim()) { + parts.push(buffer.trim()); + } + buffer = ""; + } else { + // Regular character - add to buffer + buffer += char; + } + } + // Characters inside quoted strings - add to buffer + else { + buffer += char; + } + } + + // Add any remaining content in buffer as the last part + var trimmed = buffer.trim(); + if (trimmed) { + // Preserve trailing space if selector ends with hex escape + var endsWithHexEscape = endsWithHexEscapeRegExp.test(buffer); + parts.push(endsWithHexEscape ? buffer.replace(leadingWhitespaceRegExp, '') : trimmed); + } + + return parts; + } + + /** + * Validates a CSS selector string, including handling of nested selectors within certain pseudo-classes. + * + * This function checks if the provided selector is valid according to the rules defined by + * `basicSelectorValidator`. For pseudo-classes that accept selector lists (such as :not, :is, :has, :where), + * it recursively validates each nested selector using the same validation logic. + * + * @param {string} selector - The CSS selector string to validate. + * @returns {boolean} Returns `true` if the selector is valid, otherwise `false`. + */ + + // Cache to store validated selectors (previously a ES6 Map, now an ES5-compliant object) + var validatedSelectorsCache = {}; + + // Only pseudo-classes that accept selector lists should recurse + var selectorListPseudoClasses = { + 'not': true, + 'is': true, + 'has': true, + 'where': true + }; + + function validateSelector(selector) { + if (validatedSelectorsCache.hasOwnProperty(selector)) { + return validatedSelectorsCache[selector]; + } + + // Use function-based parsing to extract pseudo-classes (avoids backtracking) + var pseudoClassMatches = extractPseudoClasses(selector); + + for (var j = 0; j < pseudoClassMatches.length; j++) { + var pseudoClass = pseudoClassMatches[j][1]; + if (selectorListPseudoClasses.hasOwnProperty(pseudoClass)) { + var nestedSelectors = parseAndSplitNestedSelectors(pseudoClassMatches[j][2]); + + // Check if ANY selector in the list contains & (nesting selector) + // If so, skip validation for the entire selector list since & will be replaced at runtime + var hasAmpersand = false; + for (var k = 0; k < nestedSelectors.length; k++) { + if (ampersandRegExp.test(nestedSelectors[k])) { + hasAmpersand = true; + break; + } + } + + // If any selector has &, skip validation for this entire pseudo-class + if (hasAmpersand) { + continue; + } + + // Otherwise, validate each selector normally + for (var i = 0; i < nestedSelectors.length; i++) { + var nestedSelector = nestedSelectors[i]; + if (!validatedSelectorsCache.hasOwnProperty(nestedSelector)) { + var nestedSelectorValidation = validateSelector(nestedSelector); + validatedSelectorsCache[nestedSelector] = nestedSelectorValidation; + if (!nestedSelectorValidation) { + validatedSelectorsCache[selector] = false; + return false; + } + } else if (!validatedSelectorsCache[nestedSelector]) { + validatedSelectorsCache[selector] = false; + return false; + } + } + } + } + + var basicSelectorValidation = basicSelectorValidator(selector); + validatedSelectorsCache[selector] = basicSelectorValidation; + + return basicSelectorValidation; + } + + /** + * Validates namespace selectors by checking if the namespace prefix is defined. + * + * @param {string} selector - The CSS selector to validate + * @returns {boolean} Returns true if the namespace is valid, false otherwise + */ + function validateNamespaceSelector(selector) { + // Check if selector contains a namespace prefix + // We need to ignore pipes inside attribute selectors + var pipeIndex = -1; + var inAttr = false; + var inSingleQuote = false; + var inDoubleQuote = false; + + for (var i = 0; i < selector.length; i++) { + var char = selector[i]; + + // Handle escape sequences - skip hex escapes or simple escapes + if (char === '\\') { + var escapeLen = getEscapeSequenceLength(selector, i); + if (escapeLen > 0) { + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + + if (inSingleQuote) { + if (char === "'") { + inSingleQuote = false; + } + } else if (inDoubleQuote) { + if (char === '"') { + inDoubleQuote = false; + } + } else if (inAttr) { + if (char === "]") { + inAttr = false; + } else if (char === "'") { + inSingleQuote = true; + } else if (char === '"') { + inDoubleQuote = true; + } + } else { + if (char === "[") { + inAttr = true; + } else if (char === "|" && !inAttr) { + // This is a namespace separator, not an attribute operator + pipeIndex = i; + break; + } + } + } + + if (pipeIndex === -1) { + return true; // No namespace, always valid + } + + var namespacePrefix = selector.substring(0, pipeIndex); + + // Universal namespace (*|) and default namespace (|) are always valid + if (namespacePrefix === '*' || namespacePrefix === '') { + return true; + } + + // Check if the custom namespace prefix is defined + return definedNamespacePrefixes.hasOwnProperty(namespacePrefix); + } + + /** + * Normalizes escape sequences in a selector to match browser behavior. + * Decodes escape sequences and re-encodes them in canonical form. + * + * @param {string} selector - The selector to normalize + * @returns {string} Normalized selector + */ + function normalizeSelectorEscapes(selector) { + var result = ''; + var i = 0; + var nextChar = ''; + + // Track context for identifier boundaries + var inIdentifier = false; + var inAttribute = false; + var attributeDepth = 0; + var needsEscapeForIdent = false; + var lastWasHexEscape = false; + + while (i < selector.length) { + var char = selector[i]; + + // Track attribute selector context + if (char === '[' && !inAttribute) { + inAttribute = true; + attributeDepth = 1; + result += char; + i++; + needsEscapeForIdent = false; + inIdentifier = false; + lastWasHexEscape = false; + continue; + } + + if (inAttribute) { + if (char === '[') attributeDepth++; + if (char === ']') { + attributeDepth--; + if (attributeDepth === 0) inAttribute = false; + } + // Don't normalize escapes inside attribute selectors + if (char === '\\' && i + 1 < selector.length) { + var escapeLen = getEscapeSequenceLength(selector, i); + result += selector.substr(i, escapeLen); + i += escapeLen; + } else { + result += char; + i++; + } + lastWasHexEscape = false; + continue; + } + + // Handle escape sequences + if (char === '\\') { + var escapeLen = getEscapeSequenceLength(selector, i); + if (escapeLen > 0) { + var escapeSeq = selector.substr(i, escapeLen); + var decoded = decodeEscapeSequence(escapeSeq); + var wasHexEscape = startsWithHexEscapeRegExp.test(escapeSeq); + var hadTerminatingSpace = wasHexEscape && escapeSeq[escapeLen - 1] === ' '; + nextChar = selector[i + escapeLen] || ''; + + // Check if this character needs escaping + var needsEscape = false; + var useHexEscape = false; + + if (needsEscapeForIdent) { + // At start of identifier (after . # or -) + // Digits must be escaped, letters/underscore/_/- don't need escaping + if (isDigit(decoded)) { + needsEscape = true; + useHexEscape = true; + } else if (decoded === '-') { + // Dash at identifier start: keep escaped if it's the only character, + // otherwise it can be decoded + var remainingSelector = selector.substring(i + escapeLen); + var hasMoreIdentChars = remainingSelector && identCharRegExp.test(remainingSelector[0]); + needsEscape = !hasMoreIdentChars; + } else if (!identStartCharRegExp.test(decoded)) { + needsEscape = true; + } + } else { + if (specialCharsNeedEscapeRegExp.test(decoded)) { + needsEscape = true; + } + } + + if (needsEscape) { + if (useHexEscape) { + // Use normalized hex escape + var codePoint = decoded.charCodeAt(0); + var hex = codePoint.toString(16); + result += '\\' + hex; + // Add space if next char could continue the hex sequence, + // or if at end of selector (to disambiguate the escape) + if (isHexDigit(nextChar) || !nextChar || afterHexEscapeSeparatorRegExp.test(nextChar)) { + result += ' '; + lastWasHexEscape = false; + } else { + lastWasHexEscape = true; + } + } else { + // Use simple character escape + result += '\\' + decoded; + lastWasHexEscape = false; + } + } else { + // No escape needed, use the character directly + // But if previous was hex escape (without terminating space) and this is alphanumeric, add space + if (lastWasHexEscape && !hadTerminatingSpace && isAlphanumeric(decoded)) { + result += ' '; + } + result += decoded; + // Preserve terminating space at end of selector (when followed by non-ident char) + if (hadTerminatingSpace && (!nextChar || afterHexEscapeSeparatorRegExp.test(nextChar))) { + result += ' '; + } + lastWasHexEscape = false; + } + + i += escapeLen; + // After processing escape, check if we're still needing ident validation + // Only stay in needsEscapeForIdent state if decoded was '-' + needsEscapeForIdent = needsEscapeForIdent && decoded === '-'; + inIdentifier = true; + continue; + } + } + + // Handle regular characters + if (char === '.' || char === '#') { + result += char; + needsEscapeForIdent = true; + inIdentifier = false; + lastWasHexEscape = false; + i++; + } else if (char === '-' && needsEscapeForIdent) { + // Dash after . or # - next char must be valid ident start or digit (which needs escaping) + result += char; + needsEscapeForIdent = true; + lastWasHexEscape = false; + i++; + } else if (isDigit(char) && needsEscapeForIdent) { + // Digit at identifier start must be hex escaped + var codePoint = char.charCodeAt(0); + var hex = codePoint.toString(16); + result += '\\' + hex; + nextChar = selector[i + 1] || ''; + // Add space if next char could continue the hex sequence, + // or if at end of selector (to disambiguate the escape) + if (isHexDigit(nextChar) || !nextChar || afterHexEscapeSeparatorRegExp.test(nextChar)) { + result += ' '; + lastWasHexEscape = false; + } else { + lastWasHexEscape = true; + } + needsEscapeForIdent = false; + inIdentifier = true; + i++; + } else if (char === ':' || combinatorOrSeparatorRegExp.test(char)) { + // Combinators, separators, and pseudo-class markers reset identifier state + // Preserve trailing space from hex escape + if (!(char === ' ' && lastWasHexEscape && result[result.length - 1] === ' ')) { + result += char; + } + needsEscapeForIdent = false; + inIdentifier = false; + lastWasHexEscape = false; + i++; + } else if (isLetter(char) && lastWasHexEscape) { + // Letter after hex escape needs a space separator + result += ' ' + char; + needsEscapeForIdent = false; + inIdentifier = true; + lastWasHexEscape = false; + i++; + } else if (char === ' ' && lastWasHexEscape) { + // Trailing space - keep it if at end or before non-ident char + nextChar = selector[i + 1] || ''; + if (!nextChar || trailingSpaceSeparatorRegExp.test(nextChar)) { + result += char; + } + needsEscapeForIdent = false; + inIdentifier = false; + lastWasHexEscape = false; + i++; + } else { + result += char; + needsEscapeForIdent = false; + inIdentifier = true; + lastWasHexEscape = false; + i++; + } + } + + return result; + } + + /** + * Helper function to decode all escape sequences in a string. + * + * @param {string} str - The string to decode + * @returns {string} The decoded string + */ + function decodeEscapeSequencesInString(str) { + var result = ''; + for (var i = 0; i < str.length; i++) { + if (str[i] === '\\' && i + 1 < str.length) { + // Get the escape sequence length + var escapeLen = getEscapeSequenceLength(str, i); + if (escapeLen > 0) { + var escapeSeq = str.substr(i, escapeLen); + var decoded = decodeEscapeSequence(escapeSeq); + result += decoded; + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + result += str[i]; + } + return result; + } + + /** + * Decodes a CSS escape sequence to its character value. + * + * @param {string} escapeSeq - The escape sequence (including backslash) + * @returns {string} The decoded character + */ + function decodeEscapeSequence(escapeSeq) { + if (escapeSeq.length < 2 || escapeSeq[0] !== '\\') { + return escapeSeq; + } + + var content = escapeSeq.substring(1); + + // Check if it's a hex escape + var hexMatch = content.match(hexEscapeSequenceRegExp); + if (hexMatch) { + var codePoint = parseInt(hexMatch[1], 16); + // Handle surrogate pairs for code points > 0xFFFF + if (codePoint > 0xFFFF) { + // Convert to surrogate pair + codePoint -= 0x10000; + var high = 0xD800 + (codePoint >> 10); + var low = 0xDC00 + (codePoint & 0x3FF); + return String.fromCharCode(high, low); + } + return String.fromCharCode(codePoint); + } + + // Simple escape - return the character after backslash + return content[0] || ''; + } + + /** + * Normalizes attribute selectors by ensuring values are properly quoted with double quotes. + * Examples: + * [attr=value] -> [attr="value"] + * [attr="value"] -> [attr="value"] (unchanged) + * [attr='value'] -> [attr="value"] (converted to double quotes) + * + * @param {string} selector - The selector to normalize + * @returns {string|null} Normalized selector, or null if invalid + */ + function normalizeAttributeSelectors(selector) { + var result = ''; + var i = 0; + + while (i < selector.length) { + // Look for attribute selector start + if (selector[i] === '[') { + result += '['; + i++; + + var attrContent = ''; + var depth = 1; + + // Find the closing bracket, handling nested brackets and escapes + while (i < selector.length && depth > 0) { + if (selector[i] === '\\' && i + 1 < selector.length) { + attrContent += selector.substring(i, i + 2); + i += 2; + continue; + } + if (selector[i] === '[') depth++; + if (selector[i] === ']') { + depth--; + if (depth === 0) break; + } + attrContent += selector[i]; + i++; + } + + // Normalize the attribute content + var normalized = normalizeAttributeContent(attrContent); + if (normalized === null) { + // Invalid attribute selector (e.g., unclosed quote) + return null; + } + result += normalized; + if (i < selector.length && selector[i] === ']') { + result += ']'; + i++; + } + } else { + result += selector[i]; + i++; + } + } + + return result; + } + + /** + * Processes a quoted attribute value by checking for proper closure and decoding escape sequences. + * @param {string} trimmedValue - The quoted value (with quotes) + * @param {string} quoteChar - The quote character ('"' or "'") + * @param {string} attrName - The attribute name + * @param {string} operator - The attribute operator + * @param {string} flag - Optional case-sensitivity flag + * @returns {string|null} Normalized attribute content, or null if invalid + */ + function processQuotedAttributeValue(trimmedValue, quoteChar, attrName, operator, flag) { + // Check if the closing quote is properly closed (not escaped) + if (trimmedValue.length < 2) { + return null; // Too short + } + // Find the actual closing quote (not escaped) + var i = 1; + var foundClose = false; + while (i < trimmedValue.length) { + if (trimmedValue[i] === '\\' && i + 1 < trimmedValue.length) { + // Skip escape sequence + var escapeLen = getEscapeSequenceLength(trimmedValue, i); + i += escapeLen; + continue; + } + if (trimmedValue[i] === quoteChar) { + // Found closing quote + foundClose = (i === trimmedValue.length - 1); + break; + } + i++; + } + if (!foundClose) { + return null; // Unclosed quote - invalid + } + // Extract inner value and decode escape sequences + var innerValue = trimmedValue.slice(1, -1); + var decodedValue = decodeEscapeSequencesInString(innerValue); + // If decoded value contains quotes, we need to escape them + var escapedValue = decodedValue.replace(doubleQuoteRegExp, '\\"'); + return attrName + operator + '"' + escapedValue + '"' + (flag ? ' ' + flag : ''); + } + + /** + * Normalizes the content inside an attribute selector. + * @param {string} content - The content between [ and ] + * @returns {string} Normalized content, or null if invalid + */ + function normalizeAttributeContent(content) { + // Match: attribute-name [operator] [value] [flag] + var match = content.match(attributeSelectorContentRegExp); + + if (!match) { + // No operator (e.g., [disabled]) or malformed - return as is + return content; + } + + var attrName = match[1]; + var operator = match[2]; + var valueAndFlag = match[3].trim(); // Trim here instead of in regex + + // Check if there's a case-sensitivity flag (i or s) at the end + var flagMatch = valueAndFlag.match(attributeCaseFlagRegExp); + var value = flagMatch ? flagMatch[1] : valueAndFlag; + var flag = flagMatch ? flagMatch[2] : ''; + + // Check for unclosed quotes - this makes the selector invalid + var trimmedValue = value.trim(); + var firstChar = trimmedValue[0]; + + if (firstChar === '"') { + return processQuotedAttributeValue(trimmedValue, '"', attrName, operator, flag); + } + + if (firstChar === "'") { + return processQuotedAttributeValue(trimmedValue, "'", attrName, operator, flag); + } + + // Check for unescaped special characters in unquoted values + // Escaped special characters are valid (e.g., \` is valid, but ` is not) + var hasUnescapedSpecialChar = false; + for (var i = 0; i < trimmedValue.length; i++) { + var char = trimmedValue[i]; + if (char === '\\' && i + 1 < trimmedValue.length) { + // Skip the entire escape sequence + var escapeLen = getEscapeSequenceLength(trimmedValue, i); + if (escapeLen > 0) { + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + // Check if this is an unescaped special character + if (specialCharsNeedEscapeRegExp.test(char)) { + hasUnescapedSpecialChar = true; + break; + } + } + + if (hasUnescapedSpecialChar) { + return null; // Unescaped special characters not allowed in unquoted attribute values + } + + // Decode escape sequences in the value before quoting + // Inside quotes, special characters don't need escaping + var decodedValue = decodeEscapeSequencesInString(trimmedValue); + + // If the decoded value contains double quotes, escape them for the output + // (since we're using double quotes as delimiters) + var escapedValue = decodedValue.replace(backslashRegExp, '\\\\').replace(doubleQuoteRegExp, '\\"'); + + // Unquoted value - add double quotes with decoded and re-escaped content + return attrName + operator + '"' + escapedValue + '"' + (flag ? ' ' + flag : ''); + } + + /** + * Processes a CSS selector text + * + * @param {string} selectorText - The CSS selector text to process + * @returns {string} The processed selector text with normalized whitespace and invalid selectors removed + */ + function processSelectorText(selectorText) { + // Normalize whitespace first + var normalized = selectorText.replace(whitespaceNormalizationRegExp, function (match, _, newline) { + if (newline) return " "; + return match; + }); + + // Normalize escape sequences to match browser behavior + normalized = normalizeSelectorEscapes(normalized); + + // Normalize attribute selectors (add quotes to unquoted values) + // Returns null if invalid (e.g., unclosed quotes) + normalized = normalizeAttributeSelectors(normalized); + if (normalized === null) { + return ''; // Invalid selector - return empty to trigger validation failure + } + + // Recursively process pseudo-classes to handle nesting + return processNestedPseudoClasses(normalized); + } + + /** + * Recursively processes pseudo-classes to filter invalid selectors + * + * @param {string} selectorText - The CSS selector text to process + * @param {number} depth - Current recursion depth (to prevent infinite loops) + * @returns {string} The processed selector text with invalid selectors removed + */ + function processNestedPseudoClasses(selectorText, depth) { + // Prevent infinite recursion + if (typeof depth === 'undefined') { + depth = 0; + } + if (depth > 10) { + return selectorText; + } + + var pseudoClassMatches = extractPseudoClasses(selectorText); + + // If no pseudo-classes found, return as-is + if (pseudoClassMatches.length === 0) { + return selectorText; + } + + // Build result by processing matches from right to left (to preserve positions) + var result = selectorText; + + for (var j = pseudoClassMatches.length - 1; j >= 0; j--) { + var pseudoClass = pseudoClassMatches[j][1]; + if (selectorListPseudoClasses.hasOwnProperty(pseudoClass)) { + var fullMatch = pseudoClassMatches[j][0]; + var pseudoArgs = pseudoClassMatches[j][2]; + var matchStart = pseudoClassMatches[j][3]; + + // Check if ANY selector contains & BEFORE processing + var nestedSelectorsRaw = parseAndSplitNestedSelectors(pseudoArgs); + var hasAmpersand = false; + for (var k = 0; k < nestedSelectorsRaw.length; k++) { + if (ampersandRegExp.test(nestedSelectorsRaw[k])) { + hasAmpersand = true; + break; + } + } + + // If & is present, skip all processing (keep everything unchanged) + if (hasAmpersand) { + continue; + } + + // Recursively process the arguments + var processedArgs = processNestedPseudoClasses(pseudoArgs, depth + 1); + var nestedSelectors = parseAndSplitNestedSelectors(processedArgs); + + // Filter out invalid selectors + var validSelectors = []; + for (var i = 0; i < nestedSelectors.length; i++) { + var nestedSelector = nestedSelectors[i]; + if (basicSelectorValidator(nestedSelector)) { + validSelectors.push(nestedSelector); + } + } + + // Reconstruct the pseudo-class with only valid selectors + var newArgs = validSelectors.join(', '); + var newPseudoClass = ':' + pseudoClass + '(' + newArgs + ')'; + + // Replace in the result string using position (processing right to left preserves positions) + result = result.substring(0, matchStart) + newPseudoClass + result.substring(matchStart + fullMatch.length); + } + } + + return result; + + return normalized; + } + + /** + * Checks if a selector contains newlines inside quoted strings. + * Uses iterative parsing to avoid regex backtracking issues. + * @param {string} selectorText - The selector to check + * @returns {boolean} True if newlines found inside quotes + */ + function hasNewlineInQuotedString(selectorText) { + for (var i = 0; i < selectorText.length; i++) { + var char = selectorText[i]; + + // Start of single-quoted string + if (char === "'") { + i++; + while (i < selectorText.length) { + if (selectorText[i] === '\\' && i + 1 < selectorText.length) { + // Skip escape sequence + i += 2; + continue; + } + if (selectorText[i] === "'") { + // End of string + break; + } + if (selectorText[i] === '\r' || selectorText[i] === '\n') { + return true; + } + i++; + } + } + // Start of double-quoted string + else if (char === '"') { + i++; + while (i < selectorText.length) { + if (selectorText[i] === '\\' && i + 1 < selectorText.length) { + // Skip escape sequence + i += 2; + continue; + } + if (selectorText[i] === '"') { + // End of string + break; + } + if (selectorText[i] === '\r' || selectorText[i] === '\n') { + return true; + } + i++; + } + } + } + return false; + } + + /** + * Checks if a given CSS selector text is valid by splitting it by commas + * and validating each individual selector using the `validateSelector` function. + * + * @param {string} selectorText - The CSS selector text to validate. Can contain multiple selectors separated by commas. + * @returns {boolean} Returns true if all selectors are valid, otherwise false. + */ + function isValidSelectorText(selectorText) { + // TODO: The same validations here needs to be reused in CSSStyleRule.selectorText setter + // TODO: Move these validation logic to a shared function to be reused in CSSStyleRule.selectorText setter + + // Check for empty or whitespace-only selector + if (!selectorText || selectorText.trim() === '') { + return false; + } + + // Check for empty selector lists in pseudo-classes (e.g., :is(), :not(), :where(), :has()) + // These are invalid after filtering out invalid selectors + if (emptyPseudoClassRegExp.test(selectorText)) { + return false; + } + + // Check for newlines inside single or double quotes + // Uses helper function to avoid regex security issues + if (hasNewlineInQuotedString(selectorText)) { + return false; + } + + // Split selectorText by commas and validate each part + var selectors = parseAndSplitNestedSelectors(selectorText); + for (var i = 0; i < selectors.length; i++) { + var selector = selectors[i].trim(); + if (!validateSelector(selector) || !validateNamespaceSelector(selector)) { + return false; + } + } + return true; + } + + function pushToAncestorRules(rule) { + ancestorRules.push(rule); + } + + function parseError(message, isNested) { + var lines = token.substring(0, i).split('\n'); + var lineCount = lines.length; + var charCount = lines.pop().length + 1; + var error = new Error(message + ' (line ' + lineCount + ', char ' + charCount + ')'); + error.line = lineCount; + /* jshint sub : true */ + error['char'] = charCount; + error.styleSheet = styleSheet; + error.isNested = !!isNested; + // Print the error but continue parsing the sheet + try { + throw error; + } catch (e) { + errorHandler && errorHandler(e); + } + }; + + /** + * Handles invalid selectors with unmatched quotes by skipping the entire rule block. + * @param {string} nextState - The parser state to transition to after skipping + */ + function handleUnmatchedQuoteInSelector(nextState) { + // parseError('Invalid selector with unmatched quote: ' + buffer.trim()); + // Skip this entire invalid rule including its block + var ruleClosingMatch = token.slice(i).match(forwardRuleClosingBraceRegExp); + if (ruleClosingMatch) { + i += ruleClosingMatch.index + ruleClosingMatch[0].length - 1; + } + styleRule = null; + buffer = ""; + hasUnmatchedQuoteInSelector = false; // Reset flag + state = nextState; + } + + // Helper functions to check character types + function isSelectorStartChar(char) { + return '.:#&*['.indexOf(char) !== -1; + } + + function isWhitespaceChar(char) { + return ' \t\n\r'.indexOf(char) !== -1; + } + + // Helper functions for character type checking (faster than regex for single chars) + function isDigit(char) { + var code = char.charCodeAt(0); + return code >= 0x0030 && code <= 0x0039; // 0-9 + } + + function isHexDigit(char) { + if (!char) return false; + var code = char.charCodeAt(0); + return (code >= 0x0030 && code <= 0x0039) || // 0-9 + (code >= 0x0041 && code <= 0x0046) || // A-F + (code >= 0x0061 && code <= 0x0066); // a-f + } + + function isLetter(char) { + if (!char) return false; + var code = char.charCodeAt(0); + return (code >= 0x0041 && code <= 0x005A) || // A-Z + (code >= 0x0061 && code <= 0x007A); // a-z + } + + function isAlphanumeric(char) { + var code = char.charCodeAt(0); + return (code >= 0x0030 && code <= 0x0039) || // 0-9 + (code >= 0x0041 && code <= 0x005A) || // A-Z + (code >= 0x0061 && code <= 0x007A); // a-z + } + + /** + * Get the length of an escape sequence starting at the given position. + * CSS escape sequences are: + * - Backslash followed by 1-6 hex digits, optionally followed by a whitespace (consumed) + * - Backslash followed by any non-hex character + * @param {string} str - The string to check + * @param {number} pos - Position of the backslash + * @returns {number} Number of characters in the escape sequence (including backslash) + */ + function getEscapeSequenceLength(str, pos) { + if (str[pos] !== '\\' || pos + 1 >= str.length) { + return 0; + } + + var nextChar = str[pos + 1]; + + // Check if it's a hex escape + if (isHexDigit(nextChar)) { + var hexLength = 1; + // Count up to 6 hex digits + while (hexLength < 6 && pos + 1 + hexLength < str.length && isHexDigit(str[pos + 1 + hexLength])) { + hexLength++; + } + // Check if followed by optional whitespace (which gets consumed) + if (pos + 1 + hexLength < str.length && isWhitespaceChar(str[pos + 1 + hexLength])) { + return 1 + hexLength + 1; // backslash + hex digits + whitespace + } + return 1 + hexLength; // backslash + hex digits + } + + // Simple escape: backslash + any character + return 2; + } + + /** + * Check if a string contains an unescaped occurrence of a specific character + * @param {string} str - The string to search + * @param {string} char - The character to look for + * @returns {boolean} True if the character appears unescaped + */ + function containsUnescaped(str, char) { + for (var i = 0; i < str.length; i++) { + if (str[i] === '\\') { + var escapeLen = getEscapeSequenceLength(str, i); + if (escapeLen > 0) { + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + if (str[i] === char) { + return true; + } + } + return false; + } + + var endingIndex = token.length - 1; + var initialEndingIndex = endingIndex; + + for (var character; (character = token.charAt(i)); i++) { + if (i === endingIndex) { + switch (state) { + case "importRule": + case "namespaceRule": + case "layerBlock": + if (character !== ";") { + token += ";"; + endingIndex += 1; + } + break; + case "value": + if (character !== "}") { + if (character === ";") { + token += "}" + } else { + token += ";"; + } + endingIndex += 1; + break; + } + case "name": + case "before-name": + if (character === "}") { + token += " " + } else { + token += "}" + } + endingIndex += 1 + break; + case "before-selector": + if (character !== "}" && currentScope !== styleSheet) { + token += "}" + endingIndex += 1 + break; + } + } + } + + // Handle escape sequences before processing special characters + // CSS escape sequences: \HHHHHH (1-6 hex digits) optionally followed by whitespace, or \ + any char + if (character === '\\' && i + 1 < token.length) { + var escapeLen = getEscapeSequenceLength(token, i); + if (escapeLen > 0) { + buffer += token.substr(i, escapeLen); + i += escapeLen - 1; // -1 because loop will increment + continue; + } + } + + switch (character) { + + case " ": + case "\t": + case "\r": + case "\n": + case "\f": + if (SIGNIFICANT_WHITESPACE[state]) { + buffer += character; + } + break; + + // String + case '"': + index = i + 1; + do { + index = token.indexOf('"', index) + 1; + if (!index) { + parseError('Unmatched "'); + // If we're parsing a selector, flag it as invalid + if (state === "selector" || state === "atRule") { + hasUnmatchedQuoteInSelector = true; + } + } + } while (token[index - 2] === '\\'); + if (index === 0) { + break; + } + buffer += token.slice(i, index); + i = index - 1; + switch (state) { + case 'before-value': + state = 'value'; + break; + case 'importRule-begin': + state = 'importRule'; + if (i === endingIndex) { + token += ';' + } + break; + case 'namespaceRule-begin': + state = 'namespaceRule'; + if (i === endingIndex) { + token += ';' + } + break; + } + break; + + case "'": + index = i + 1; + do { + index = token.indexOf("'", index) + 1; + if (!index) { + parseError("Unmatched '"); + // If we're parsing a selector, flag it as invalid + if (state === "selector" || state === "atRule") { + hasUnmatchedQuoteInSelector = true; + } + } + } while (token[index - 2] === '\\'); + if (index === 0) { + break; + } + buffer += token.slice(i, index); + i = index - 1; + switch (state) { + case 'before-value': + state = 'value'; + break; + case 'importRule-begin': + state = 'importRule'; + break; + case 'namespaceRule-begin': + state = 'namespaceRule'; + break; + } + break; + + // Comment + case "/": + if (token.charAt(i + 1) === "*") { + i += 2; + index = token.indexOf("*/", i); + if (index === -1) { + i = token.length - 1; + buffer = ""; + } else { + i = index + 1; + } + } else { + buffer += character; + } + if (state === "importRule-begin") { + buffer += " "; + state = "importRule"; + } + if (state === "namespaceRule-begin") { + buffer += " "; + state = "namespaceRule"; + } + break; + + // At-rule + case "@": + if (nestedSelectorRule) { + if (styleRule && styleRule.constructor.name === "CSSNestedDeclarations") { + currentScope.cssRules.push(styleRule); + } + // Only reset styleRule to parent if styleRule is not the nestedSelectorRule itself + // This preserves nested selectors when followed immediately by @-rules + if (styleRule !== nestedSelectorRule && nestedSelectorRule.parentRule && nestedSelectorRule.parentRule.constructor.name === "CSSStyleRule") { + styleRule = nestedSelectorRule.parentRule; + } + // Don't reset nestedSelectorRule here - preserve it through @-rules + } + if (token.indexOf("@-moz-document", i) === i) { + validateAtRule("@-moz-document", function () { + state = "documentRule-begin"; + documentRule = new CSSOM.CSSDocumentRule(); + documentRule.__starts = i; + i += "-moz-document".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@media", i) === i) { + validateAtRule("@media", function () { + state = "atBlock"; + mediaRule = new CSSOM.CSSMediaRule(); + mediaRule.__starts = i; + i += "media".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@container", i) === i) { + validateAtRule("@container", function () { + state = "containerBlock"; + containerRule = new CSSOM.CSSContainerRule(); + containerRule.__starts = i; + i += "container".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@counter-style", i) === i) { + buffer = ""; + // @counter-style can be nested only inside CSSScopeRule or CSSConditionRule + // and only if there's no CSSStyleRule in the parent chain + var cannotBeNested = !canAtRuleBeNested(); + validateAtRule("@counter-style", function () { + state = "counterStyleBlock" + counterStyleRule = new CSSOM.CSSCounterStyleRule(); + counterStyleRule.__starts = i; + i += "counter-style".length; + }, cannotBeNested); + break; + } else if (token.indexOf("@property", i) === i) { + buffer = ""; + // @property can be nested only inside CSSScopeRule or CSSConditionRule + // and only if there's no CSSStyleRule in the parent chain + var cannotBeNested = !canAtRuleBeNested(); + validateAtRule("@property", function () { + state = "propertyBlock" + propertyRule = new CSSOM.CSSPropertyRule(); + propertyRule.__starts = i; + i += "property".length; + }, cannotBeNested); + break; + } else if (token.indexOf("@scope", i) === i) { + validateAtRule("@scope", function () { + state = "scopeBlock"; + scopeRule = new CSSOM.CSSScopeRule(); + scopeRule.__starts = i; + i += "scope".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@layer", i) === i) { + validateAtRule("@layer", function () { + state = "layerBlock" + layerBlockRule = new CSSOM.CSSLayerBlockRule(); + layerBlockRule.__starts = i; + i += "layer".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@page", i) === i) { + validateAtRule("@page", function () { + state = "pageBlock" + pageRule = new CSSOM.CSSPageRule(); + pageRule.__starts = i; + i += "page".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@supports", i) === i) { + validateAtRule("@supports", function () { + state = "conditionBlock"; + supportsRule = new CSSOM.CSSSupportsRule(); + supportsRule.__starts = i; + i += "supports".length; + }); + buffer = ""; + break; + } else if (token.indexOf("@host", i) === i) { + validateAtRule("@host", function () { + state = "hostRule-begin"; + i += "host".length; + hostRule = new CSSOM.CSSHostRule(); + hostRule.__starts = i; + }); + buffer = ""; + break; + } else if (token.indexOf("@starting-style", i) === i) { + validateAtRule("@starting-style", function () { + state = "startingStyleRule-begin"; + i += "starting-style".length; + startingStyleRule = new CSSOM.CSSStartingStyleRule(); + startingStyleRule.__starts = i; + }); + buffer = ""; + break; + } else if (token.indexOf("@import", i) === i) { + buffer = ""; + validateAtRule("@import", function () { + state = "importRule-begin"; + i += "import".length; + buffer += "@import"; + }, true); + break; + } else if (token.indexOf("@namespace", i) === i) { + buffer = ""; + validateAtRule("@namespace", function () { + state = "namespaceRule-begin"; + i += "namespace".length; + buffer += "@namespace"; + }, true); + break; + } else if (token.indexOf("@font-face", i) === i) { + buffer = ""; + // @font-face can be nested only inside CSSScopeRule or CSSConditionRule + // and only if there's no CSSStyleRule in the parent chain + var cannotBeNested = !canAtRuleBeNested(); + validateAtRule("@font-face", function () { + state = "fontFaceRule-begin"; + i += "font-face".length; + fontFaceRule = new CSSOM.CSSFontFaceRule(); + fontFaceRule.__starts = i; + }, cannotBeNested); + break; + } else { + // Reset lastIndex before using global regex (shared instance) + atKeyframesRegExp.lastIndex = i; + var matchKeyframes = atKeyframesRegExp.exec(token); + if (matchKeyframes && matchKeyframes.index === i) { + state = "keyframesRule-begin"; + keyframesRule = new CSSOM.CSSKeyframesRule(); + keyframesRule.__starts = i; + keyframesRule._vendorPrefix = matchKeyframes[1]; // Will come out as undefined if no prefix was found + i += matchKeyframes[0].length - 1; + buffer = ""; + break; + } else if (state === "selector") { + state = "atRule"; + } + } + buffer += character; + break; + + case "{": + if (currentScope === topScope) { + nestedSelectorRule = null; + } + if (state === 'before-selector') { + parseError("Unexpected {"); + i = ignoreBalancedBlock(i, token.slice(i)); + break; + } + if (state === "selector" || state === "atRule") { + if (!nestedSelectorRule && containsUnescaped(buffer, ";")) { + var ruleClosingMatch = token.slice(i).match(forwardRuleClosingBraceRegExp); + if (ruleClosingMatch) { + styleRule = null; + buffer = ""; + state = "before-selector"; + i += ruleClosingMatch.index + ruleClosingMatch[0].length; + break; + } + } + + // Ensure styleRule exists before trying to set properties on it + if (!styleRule) { + styleRule = new CSSOM.CSSStyleRule(); + styleRule.__starts = i; + } + + // Check if tokenizer detected an unmatched quote BEFORE setting up the rule + if (hasUnmatchedQuoteInSelector) { + handleUnmatchedQuoteInSelector("before-selector"); + break; + } + + var originalParentRule = parentRule; + + if (parentRule) { + styleRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + } + + currentScope = parentRule = styleRule; + + var processedSelectorText = processSelectorText(buffer.trim()); + // In a nested selector, ensure each selector contains '&' at the beginning, except for selectors that already have '&' somewhere + if (originalParentRule && originalParentRule.constructor.name === "CSSStyleRule") { + styleRule.selectorText = parseAndSplitNestedSelectors(processedSelectorText).map(function (sel) { + // Add & at the beginning if there's no & in the selector, or if it starts with a combinator + return (sel.indexOf('&') === -1 || startsWithCombinatorRegExp.test(sel)) ? '& ' + sel : sel; + }).join(', '); + } else { + // Normalize comma spacing: split by commas and rejoin with ", " + styleRule.selectorText = parseAndSplitNestedSelectors(processedSelectorText).join(', '); + } + styleRule.style.__starts = i; + styleRule.__parentStyleSheet = styleSheet; + buffer = ""; + state = "before-name"; + } else if (state === "atBlock") { + mediaRule.media.mediaText = buffer.trim(); + + if (parentRule) { + mediaRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + // If entering @media from within a CSSStyleRule, set nestedSelectorRule + // so that & selectors and declarations work correctly inside + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + + currentScope = parentRule = mediaRule; + pushToAncestorRules(mediaRule); + mediaRule.__parentStyleSheet = styleSheet; + + // Don't reset styleRule to null if it's a nested CSSStyleRule that will contain this @-rule + if (!styleRule || styleRule.constructor.name !== "CSSStyleRule" || !styleRule.__parentRule) { + styleRule = null; // Reset styleRule when entering @-rule + } + + buffer = ""; + state = "before-selector"; + } else if (state === "containerBlock") { + containerRule.__conditionText = buffer.trim(); + + if (parentRule) { + containerRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + currentScope = parentRule = containerRule; + pushToAncestorRules(containerRule); + containerRule.__parentStyleSheet = styleSheet; + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + } else if (state === "counterStyleBlock") { + var counterStyleName = buffer.trim().replace(newlineRemovalRegExp, ""); + // Validate: name cannot be empty, contain whitespace, or contain dots + var isValidCounterStyleName = counterStyleName.length > 0 && !whitespaceAndDotRegExp.test(counterStyleName); + + if (isValidCounterStyleName) { + counterStyleRule.name = counterStyleName; + if (parentRule) { + counterStyleRule.__parentRule = parentRule; + } + counterStyleRule.__parentStyleSheet = styleSheet; + styleRule = counterStyleRule; + } + buffer = ""; + } else if (state === "propertyBlock") { + var propertyName = buffer.trim().replace(newlineRemovalRegExp, ""); + // Validate: name must start with -- (custom property) + var isValidPropertyName = propertyName.indexOf("--") === 0; + + if (isValidPropertyName) { + propertyRule.__name = propertyName; + if (parentRule) { + propertyRule.__parentRule = parentRule; + } + propertyRule.__parentStyleSheet = styleSheet; + styleRule = propertyRule; + } + buffer = ""; + } else if (state === "conditionBlock") { + supportsRule.__conditionText = buffer.trim(); + + if (parentRule) { + supportsRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + + currentScope = parentRule = supportsRule; + pushToAncestorRules(supportsRule); + supportsRule.__parentStyleSheet = styleSheet; + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + } else if (state === "scopeBlock") { + var parsedScopePrelude = parseScopePrelude(buffer.trim()); + + if (parsedScopePrelude.hasStart) { + scopeRule.__start = parsedScopePrelude.startSelector; + } + if (parsedScopePrelude.hasEnd) { + scopeRule.__end = parsedScopePrelude.endSelector; + } + if (parsedScopePrelude.hasOnlyEnd) { + scopeRule.__end = parsedScopePrelude.endSelector; + } + + if (parentRule) { + scopeRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + currentScope = parentRule = scopeRule; + pushToAncestorRules(scopeRule); + scopeRule.__parentStyleSheet = styleSheet; + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + } else if (state === "layerBlock") { + layerBlockRule.name = buffer.trim(); + + var isValidName = layerBlockRule.name.length === 0 || layerBlockRule.name.match(cssCustomIdentifierRegExp) !== null; + + if (isValidName) { + if (parentRule) { + layerBlockRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + + currentScope = parentRule = layerBlockRule; + pushToAncestorRules(layerBlockRule); + layerBlockRule.__parentStyleSheet = styleSheet; + } + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + } else if (state === "pageBlock") { + pageRule.selectorText = buffer.trim(); + + if (parentRule) { + pageRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + } + + currentScope = parentRule = pageRule; + pageRule.__parentStyleSheet = styleSheet; + styleRule = pageRule; + buffer = ""; + state = "before-name"; + } else if (state === "hostRule-begin") { + if (parentRule) { + pushToAncestorRules(parentRule); + } + + currentScope = parentRule = hostRule; + pushToAncestorRules(hostRule); + hostRule.__parentStyleSheet = styleSheet; + buffer = ""; + state = "before-selector"; + } else if (state === "startingStyleRule-begin") { + if (parentRule) { + startingStyleRule.__parentRule = parentRule; + pushToAncestorRules(parentRule); + if (parentRule.constructor.name === "CSSStyleRule" && !nestedSelectorRule) { + nestedSelectorRule = parentRule; + } + } + + currentScope = parentRule = startingStyleRule; + pushToAncestorRules(startingStyleRule); + startingStyleRule.__parentStyleSheet = styleSheet; + styleRule = null; // Reset styleRule when entering @-rule + buffer = ""; + state = "before-selector"; + + } else if (state === "fontFaceRule-begin") { + if (parentRule) { + fontFaceRule.__parentRule = parentRule; + } + fontFaceRule.__parentStyleSheet = styleSheet; + styleRule = fontFaceRule; + buffer = ""; + state = "before-name"; + } else if (state === "keyframesRule-begin") { + keyframesRule.name = buffer.trim(); + if (parentRule) { + pushToAncestorRules(parentRule); + keyframesRule.__parentRule = parentRule; + } + keyframesRule.__parentStyleSheet = styleSheet; + currentScope = parentRule = keyframesRule; + buffer = ""; + state = "keyframeRule-begin"; + } else if (state === "keyframeRule-begin") { + styleRule = new CSSOM.CSSKeyframeRule(); + styleRule.keyText = buffer.trim(); + styleRule.__starts = i; + buffer = ""; + state = "before-name"; + } else if (state === "documentRule-begin") { + // FIXME: what if this '{' is in the url text of the match function? + documentRule.matcher.matcherText = buffer.trim(); + if (parentRule) { + pushToAncestorRules(parentRule); + documentRule.__parentRule = parentRule; + } + currentScope = parentRule = documentRule; + pushToAncestorRules(documentRule); + documentRule.__parentStyleSheet = styleSheet; + buffer = ""; + state = "before-selector"; + } else if (state === "before-name" || state === "name") { + // @font-face and similar rules don't support nested selectors + // If we encounter a nested selector block inside them, skip it + if (styleRule.constructor.name === "CSSFontFaceRule" || + styleRule.constructor.name === "CSSKeyframeRule" || + (styleRule.constructor.name === "CSSPageRule" && parentRule === styleRule)) { + // Skip the nested block + var ruleClosingMatch = token.slice(i).match(forwardRuleClosingBraceRegExp); + if (ruleClosingMatch) { + i += ruleClosingMatch.index + ruleClosingMatch[0].length - 1; + buffer = ""; + state = "before-name"; + break; + } + } + + if (styleRule.constructor.name === "CSSNestedDeclarations") { + if (styleRule.style.length) { + parentRule.cssRules.push(styleRule); + styleRule.__parentRule = parentRule; + styleRule.__parentStyleSheet = styleSheet; + pushToAncestorRules(parentRule); + } else { + // If the styleRule is empty, we can assume that it's a nested selector + pushToAncestorRules(parentRule); + } + } else { + currentScope = parentRule = styleRule; + pushToAncestorRules(parentRule); + styleRule.__parentStyleSheet = styleSheet; + } + + styleRule = new CSSOM.CSSStyleRule(); + + // Check if tokenizer detected an unmatched quote BEFORE setting up the rule + if (hasUnmatchedQuoteInSelector) { + handleUnmatchedQuoteInSelector("before-name"); + break; + } + + var processedSelectorText = processSelectorText(buffer.trim()); + // In a nested selector, ensure each selector contains '&' at the beginning, except for selectors that already have '&' somewhere + if (parentRule.constructor.name === "CSSScopeRule" || (parentRule.constructor.name !== "CSSStyleRule" && parentRule.parentRule === null)) { + // Normalize comma spacing: split by commas and rejoin with ", " + styleRule.selectorText = parseAndSplitNestedSelectors(processedSelectorText).join(', '); + } else { + styleRule.selectorText = parseAndSplitNestedSelectors(processedSelectorText).map(function (sel) { + // Add & at the beginning if there's no & in the selector, or if it starts with a combinator + return (sel.indexOf('&') === -1 || startsWithCombinatorRegExp.test(sel)) ? '& ' + sel : sel; + }).join(', '); + } + styleRule.style.__starts = i - buffer.length; + styleRule.__parentRule = parentRule; + // Only set nestedSelectorRule if we're directly inside a CSSStyleRule or CSSScopeRule, + // not inside other grouping rules like @media/@supports + if (parentRule.constructor.name === "CSSStyleRule" || parentRule.constructor.name === "CSSScopeRule") { + nestedSelectorRule = styleRule; + } + + // Set __parentStyleSheet for the new nested styleRule + styleRule.__parentStyleSheet = styleSheet; + + // Update currentScope and parentRule to the new nested styleRule + // so that subsequent content (like @-rules) will be children of this rule + currentScope = parentRule = styleRule; + + buffer = ""; + state = "before-name"; + } + break; + + case ":": + if (state === "name") { + // It can be a nested selector, let's check + var openBraceBeforeMatch = token.slice(i).match(declarationOrOpenBraceRegExp); + var hasOpenBraceBefore = openBraceBeforeMatch && openBraceBeforeMatch[0] === '{'; + if (hasOpenBraceBefore) { + // Is a selector + buffer += character; + } else { + // Is a declaration + name = buffer.trim(); + buffer = ""; + state = "before-value"; + } + } else { + buffer += character; + } + break; + + case "(": + if (state === 'value') { + // ie css expression mode + if (buffer.trim() === 'expression') { + var info = (new CSSOM.CSSValueExpression(token, i)).parse(); + + if (info.error) { + parseError(info.error); + } else { + buffer += info.expression; + i = info.idx; + } + } else { + state = 'value-parenthesis'; + //always ensure this is reset to 1 on transition + //from value to value-parenthesis + valueParenthesisDepth = 1; + buffer += character; + } + } else if (state === 'value-parenthesis') { + valueParenthesisDepth++; + buffer += character; + } else { + buffer += character; + } + break; + + case ")": + if (state === 'value-parenthesis') { + valueParenthesisDepth--; + if (valueParenthesisDepth === 0) state = 'value'; + } + buffer += character; + break; + + case "!": + if (state === "value" && token.indexOf("!important", i) === i) { + priority = "important"; + i += "important".length; + } else { + buffer += character; + } + break; + + case ";": + switch (state) { + case "before-value": + case "before-name": + parseError("Unexpected ;"); + buffer = ""; + state = "before-name"; + break; + case "value": + styleRule.style.setProperty(name, buffer.trim(), priority, parseError); + priority = ""; + buffer = ""; + state = "before-name"; + break; + case "atRule": + buffer = ""; + state = "before-selector"; + break; + case "importRule": + var isValid = topScope.cssRules.length === 0 || topScope.cssRules.some(function (rule) { + return ['CSSImportRule', 'CSSLayerStatementRule'].indexOf(rule.constructor.name) !== -1 + }); + if (isValid) { + importRule = new CSSOM.CSSImportRule(); + if (opts && opts.globalObject && opts.globalObject.CSSStyleSheet) { + importRule.__styleSheet = new opts.globalObject.CSSStyleSheet(); + } + importRule.styleSheet.__constructed = false; + importRule.__parentStyleSheet = importRule.styleSheet.__parentStyleSheet = styleSheet; + importRule.parse(buffer + character); + topScope.cssRules.push(importRule); + } + buffer = ""; + state = "before-selector"; + break; + case "namespaceRule": + var isValid = topScope.cssRules.length === 0 || topScope.cssRules.every(function (rule) { + return ['CSSImportRule', 'CSSLayerStatementRule', 'CSSNamespaceRule'].indexOf(rule.constructor.name) !== -1 + }); + if (isValid) { + try { + // Validate namespace syntax before creating the rule + var testNamespaceRule = new CSSOM.CSSNamespaceRule(); + testNamespaceRule.parse(buffer + character); + + namespaceRule = testNamespaceRule; + namespaceRule.__parentStyleSheet = styleSheet; + topScope.cssRules.push(namespaceRule); + + // Track the namespace prefix for validation + if (namespaceRule.prefix) { + definedNamespacePrefixes[namespaceRule.prefix] = namespaceRule.namespaceURI; + } + } catch (e) { + parseError(e.message); + } + } + buffer = ""; + state = "before-selector"; + break; + case "layerBlock": + var nameListStr = buffer.trim().split(",").map(function (name) { + return name.trim(); + }); + var isInvalid = nameListStr.some(function (name) { + return name.trim().match(cssCustomIdentifierRegExp) === null; + }); + + // Check if there's a CSSStyleRule in the parent chain + var hasStyleRuleParent = false; + if (parentRule) { + var checkParent = parentRule; + while (checkParent) { + if (checkParent.constructor.name === "CSSStyleRule") { + hasStyleRuleParent = true; + break; + } + checkParent = checkParent.__parentRule; + } + } + + if (!isInvalid && !hasStyleRuleParent) { + layerStatementRule = new CSSOM.CSSLayerStatementRule(); + layerStatementRule.__parentStyleSheet = styleSheet; + layerStatementRule.__starts = layerBlockRule.__starts; + layerStatementRule.__ends = i; + layerStatementRule.nameList = nameListStr; + + // Add to parent rule if nested, otherwise to top scope + if (parentRule) { + layerStatementRule.__parentRule = parentRule; + parentRule.cssRules.push(layerStatementRule); + } else { + topScope.cssRules.push(layerStatementRule); + } + } + buffer = ""; + state = "before-selector"; + break; + default: + buffer += character; + break; + } + break; + + case "}": + if (state === "counterStyleBlock") { + // FIXME : Implement missing properties on CSSCounterStyleRule interface and update parse method + // For now it's just assigning entire rule text + if (counterStyleRule.name) { + // Only process if name was set (valid) + counterStyleRule.parse("@counter-style " + counterStyleRule.name + " { " + buffer + " }"); + counterStyleRule.__ends = i + 1; + // Add to parent's cssRules + if (counterStyleRule.__parentRule) { + counterStyleRule.__parentRule.cssRules.push(counterStyleRule); + } else { + topScope.cssRules.push(counterStyleRule); + } + } + // Restore currentScope to parent after closing this rule + if (counterStyleRule.__parentRule) { + currentScope = counterStyleRule.__parentRule; + } + styleRule = null; + buffer = ""; + state = "before-selector"; + break; + } + if (state === "propertyBlock") { + // Only process if name was set (valid) + if (propertyRule.__name) { + var parseSuccess = propertyRule.parse("@property " + propertyRule.__name + " { " + buffer + " }"); + // Only add the rule if parse was successful (syntax, inherits, and initial-value validation passed) + if (parseSuccess) { + propertyRule.__ends = i + 1; + // Add to parent's cssRules + if (propertyRule.__parentRule) { + propertyRule.__parentRule.cssRules.push(propertyRule); + } else { + topScope.cssRules.push(propertyRule); + } + } + } + // Restore currentScope to parent after closing this rule + if (propertyRule.__parentRule) { + currentScope = propertyRule.__parentRule; + } + styleRule = null; + buffer = ""; + state = "before-selector"; + break; + } + switch (state) { + case "value": + styleRule.style.setProperty(name, buffer.trim(), priority, parseError); + priority = ""; + /* falls through */ + case "before-value": + case "before-name": + case "name": + styleRule.__ends = i + 1; + + if (parentRule === styleRule) { + parentRule = ancestorRules.pop() + } + + if (parentRule) { + styleRule.__parentRule = parentRule; + } + styleRule.__parentStyleSheet = styleSheet; + + if (currentScope === styleRule) { + currentScope = parentRule || topScope; + } + + if (styleRule.constructor.name === "CSSStyleRule" && !isValidSelectorText(styleRule.selectorText)) { + if (styleRule === nestedSelectorRule) { + nestedSelectorRule = null; + } + parseError('Invalid CSSStyleRule (selectorText = "' + styleRule.selectorText + '")', styleRule.parentRule !== null); + } else { + if (styleRule.parentRule) { + styleRule.parentRule.cssRules.push(styleRule); + } else { + currentScope.cssRules.push(styleRule); + } + } + buffer = ""; + if (currentScope.constructor === CSSOM.CSSKeyframesRule) { + state = "keyframeRule-begin"; + } else { + state = "before-selector"; + } + + if (styleRule.constructor.name === "CSSNestedDeclarations") { + if (currentScope !== topScope) { + // Only set nestedSelectorRule if currentScope is CSSStyleRule or CSSScopeRule + // Not for other grouping rules like @media/@supports + if (currentScope.constructor.name === "CSSStyleRule" || currentScope.constructor.name === "CSSScopeRule") { + nestedSelectorRule = currentScope; + } + } + styleRule = null; + } else { + // Update nestedSelectorRule when closing a CSSStyleRule + if (styleRule === nestedSelectorRule) { + var selector = styleRule.selectorText && styleRule.selectorText.trim(); + // Check if this is proper nesting (&.class, &:pseudo) vs prepended & (& :is, & .class with space) + // Prepended & has pattern "& X" where X starts with : or . + var isPrependedAmpersand = selector && selector.match(prependedAmpersandRegExp); + + // Check if parent is a grouping rule that can contain nested selectors + var isGroupingRule = currentScope && currentScope instanceof CSSOM.CSSGroupingRule; + + if (!isPrependedAmpersand && isGroupingRule) { + // Proper nesting - set nestedSelectorRule to parent for more nested selectors + // But only if it's a CSSStyleRule or CSSScopeRule, not other grouping rules like @media + if (currentScope.constructor.name === "CSSStyleRule" || currentScope.constructor.name === "CSSScopeRule") { + nestedSelectorRule = currentScope; + } + // If currentScope is another type of grouping rule (like @media), keep nestedSelectorRule unchanged + } else { + // Prepended & or not nested in grouping rule - reset to prevent CSSNestedDeclarations + nestedSelectorRule = null; + } + } else if (nestedSelectorRule && currentScope instanceof CSSOM.CSSGroupingRule) { + // When closing a nested rule that's not the nestedSelectorRule itself, + // maintain nestedSelectorRule if we're still inside a grouping rule + // This ensures declarations after nested selectors inside @media/@supports etc. work correctly + } + styleRule = null; + break; + } + case "keyframeRule-begin": + case "before-selector": + case "selector": + // End of media/supports/document rule. + if (!parentRule) { + parseError("Unexpected }"); + + var hasPreviousStyleRule = currentScope.cssRules.length && currentScope.cssRules[currentScope.cssRules.length - 1].constructor.name === "CSSStyleRule"; + if (hasPreviousStyleRule) { + i = ignoreBalancedBlock(i, token.slice(i), 1); + } + + break; + } + + // Find the actual parent rule by popping from ancestor stack + while (ancestorRules.length > 0) { + parentRule = ancestorRules.pop(); + + // Skip if we popped the current scope itself (happens because we push both rule and parent) + if (parentRule === currentScope) { + continue; + } + + // Only process valid grouping rules + if (!(parentRule instanceof CSSOM.CSSGroupingRule && (parentRule.constructor.name !== 'CSSStyleRule' || parentRule.__parentRule))) { + continue; + } + + // Determine if we're closing a special nested selector context + var isClosingNestedSelectorContext = nestedSelectorRule && + (currentScope === nestedSelectorRule || nestedSelectorRule.__parentRule === currentScope); + + if (isClosingNestedSelectorContext) { + // Closing the nestedSelectorRule or its direct container + if (nestedSelectorRule.parentRule) { + // Add nestedSelectorRule to its parent and update scope + prevScope = nestedSelectorRule; + currentScope = nestedSelectorRule.parentRule; + // Use object lookup instead of O(n) indexOf + var scopeId = getRuleId(prevScope); + if (!addedToCurrentScope[scopeId]) { + currentScope.cssRules.push(prevScope); + addedToCurrentScope[scopeId] = true; + } + nestedSelectorRule = currentScope; + // Stop here to preserve context for sibling selectors + break; + } else { + // Top-level CSSStyleRule with nested grouping rule + prevScope = currentScope; + var actualParent = ancestorRules.length > 0 ? ancestorRules[ancestorRules.length - 1] : nestedSelectorRule; + if (actualParent !== prevScope) { + actualParent.cssRules.push(prevScope); + } + currentScope = actualParent; + parentRule = actualParent; + break; + } + } else { + // Regular case: add currentScope to parentRule + prevScope = currentScope; + if (parentRule !== prevScope) { + parentRule.cssRules.push(prevScope); + } + break; + } + } + + // If currentScope has a __parentRule and wasn't added yet, add it + if (ancestorRules.length === 0 && currentScope.__parentRule && currentScope.__parentRule.cssRules) { + // Use object lookup instead of O(n) findIndex + var parentId = getRuleId(currentScope); + if (!addedToParent[parentId]) { + currentScope.__parentRule.cssRules.push(currentScope); + addedToParent[parentId] = true; + } + } + + // Only handle top-level rule closing if we processed all ancestors + if (ancestorRules.length === 0 && currentScope.parentRule == null) { + currentScope.__ends = i + 1; + // Use object lookup instead of O(n) findIndex + var topId = getRuleId(currentScope); + if (currentScope !== topScope && !addedToTopScope[topId]) { + topScope.cssRules.push(currentScope); + addedToTopScope[topId] = true; + } + currentScope = topScope; + if (nestedSelectorRule === parentRule) { + // Check if this selector is really starting inside another selector + var nestedSelectorTokenToCurrentSelectorToken = token.slice(nestedSelectorRule.__starts, i + 1); + var openingBraceMatch = nestedSelectorTokenToCurrentSelectorToken.match(openBraceGlobalRegExp); + var closingBraceMatch = nestedSelectorTokenToCurrentSelectorToken.match(closeBraceGlobalRegExp); + var openingBraceLen = openingBraceMatch && openingBraceMatch.length; + var closingBraceLen = closingBraceMatch && closingBraceMatch.length; + + if (openingBraceLen === closingBraceLen) { + // If the number of opening and closing braces are equal, we can assume that the new selector is starting outside the nestedSelectorRule + nestedSelectorRule.__ends = i + 1; + nestedSelectorRule = null; + parentRule = null; + } + } else { + parentRule = null; + } + } else { + currentScope = parentRule; + } + + buffer = ""; + state = "before-selector"; + break; + } + break; + + default: + switch (state) { + case "before-selector": + state = "selector"; + if ((styleRule || scopeRule) && parentRule) { + // Assuming it's a declaration inside Nested Selector OR a Nested Declaration + // If Declaration inside Nested Selector let's keep the same styleRule + if (!isSelectorStartChar(character) && !isWhitespaceChar(character) && parentRule instanceof CSSOM.CSSGroupingRule) { + // parentRule.__parentRule = styleRule; + state = "before-name"; + if (styleRule !== parentRule) { + styleRule = new CSSOM.CSSNestedDeclarations(); + styleRule.__starts = i; + } + } + + } else if (nestedSelectorRule && parentRule && parentRule instanceof CSSOM.CSSGroupingRule) { + if (isSelectorStartChar(character)) { + // If starting with a selector character, create CSSStyleRule instead of CSSNestedDeclarations + styleRule = new CSSOM.CSSStyleRule(); + styleRule.__starts = i; + } else if (!isWhitespaceChar(character)) { + // Starting a declaration (not whitespace, not a selector) + state = "before-name"; + // Check if we should create CSSNestedDeclarations + // This happens if: parent has cssRules OR nestedSelectorRule exists (indicating CSSStyleRule in hierarchy) + if (parentRule.cssRules.length || nestedSelectorRule) { + currentScope = parentRule; + // Only set nestedSelectorRule if parentRule is CSSStyleRule or CSSScopeRule + if (parentRule.constructor.name === "CSSStyleRule" || parentRule.constructor.name === "CSSScopeRule") { + nestedSelectorRule = parentRule; + } + styleRule = new CSSOM.CSSNestedDeclarations(); + styleRule.__starts = i; + } else { + if (parentRule.constructor.name === "CSSStyleRule") { + styleRule = parentRule; + } else { + styleRule = new CSSOM.CSSStyleRule(); + styleRule.__starts = i; + } + } + } + } + break; + case "before-name": + state = "name"; + break; + case "before-value": + state = "value"; + break; + case "importRule-begin": + state = "importRule"; + break; + case "namespaceRule-begin": + state = "namespaceRule"; + break; + } + buffer += character; + break; + } + + // Auto-close all unclosed nested structures + // Check AFTER processing the character, at the ORIGINAL ending index + // Only add closing braces if CSS is incomplete (not at top scope) + if (i === initialEndingIndex && (currentScope !== topScope || ancestorRules.length > 0)) { + var needsClosing = ancestorRules.length; + if (currentScope !== topScope && ancestorRules.indexOf(currentScope) === -1) { + needsClosing += 1; + } + // Add closing braces for all unclosed structures + for (var closeIdx = 0; closeIdx < needsClosing; closeIdx++) { + token += "}"; + endingIndex += 1; + } + } + } + + if (buffer.trim() !== "") { + parseError("Unexpected end of input"); + } + + return styleSheet; +}; + + +//.CommonJS +exports.parse = CSSOM.parse; +// The following modules cannot be included sooner due to the mutual dependency with parse.js +CSSOM.CSSStyleSheet = require("./CSSStyleSheet").CSSStyleSheet; +CSSOM.CSSStyleRule = require("./CSSStyleRule").CSSStyleRule; +CSSOM.CSSNestedDeclarations = require("./CSSNestedDeclarations").CSSNestedDeclarations; +CSSOM.CSSImportRule = require("./CSSImportRule").CSSImportRule; +CSSOM.CSSNamespaceRule = require("./CSSNamespaceRule").CSSNamespaceRule; +CSSOM.CSSGroupingRule = require("./CSSGroupingRule").CSSGroupingRule; +CSSOM.CSSMediaRule = require("./CSSMediaRule").CSSMediaRule; +CSSOM.CSSCounterStyleRule = require("./CSSCounterStyleRule").CSSCounterStyleRule; +CSSOM.CSSPropertyRule = require("./CSSPropertyRule").CSSPropertyRule; +CSSOM.CSSContainerRule = require("./CSSContainerRule").CSSContainerRule; +CSSOM.CSSConditionRule = require("./CSSConditionRule").CSSConditionRule; +CSSOM.CSSSupportsRule = require("./CSSSupportsRule").CSSSupportsRule; +CSSOM.CSSFontFaceRule = require("./CSSFontFaceRule").CSSFontFaceRule; +CSSOM.CSSHostRule = require("./CSSHostRule").CSSHostRule; +CSSOM.CSSStartingStyleRule = require("./CSSStartingStyleRule").CSSStartingStyleRule; +CSSOM.CSSStyleDeclaration = require('./CSSStyleDeclaration').CSSStyleDeclaration; +CSSOM.CSSKeyframeRule = require('./CSSKeyframeRule').CSSKeyframeRule; +CSSOM.CSSKeyframesRule = require('./CSSKeyframesRule').CSSKeyframesRule; +CSSOM.CSSValueExpression = require('./CSSValueExpression').CSSValueExpression; +CSSOM.CSSDocumentRule = require('./CSSDocumentRule').CSSDocumentRule; +CSSOM.CSSScopeRule = require('./CSSScopeRule').CSSScopeRule; +CSSOM.CSSLayerBlockRule = require("./CSSLayerBlockRule").CSSLayerBlockRule; +CSSOM.CSSLayerStatementRule = require("./CSSLayerStatementRule").CSSLayerStatementRule; +CSSOM.CSSPageRule = require("./CSSPageRule").CSSPageRule; +// Use cssstyle if available +require("./cssstyleTryCatchBlock"); +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/lib/regexPatterns.js b/vanilla/node_modules/@acemir/cssom/lib/regexPatterns.js new file mode 100644 index 0000000..ec260a4 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/lib/regexPatterns.js @@ -0,0 +1,162 @@ +// Shared regex patterns for CSS parsing and validation +// These patterns are compiled once and reused across multiple files for better performance + +// Regex patterns for CSS parsing +var atKeyframesRegExp = /@(-(?:\w+-)+)?keyframes/g; // Match @keyframes and vendor-prefixed @keyframes +var beforeRulePortionRegExp = /{(?!.*{)|}(?!.*})|;(?!.*;)|\*\/(?!.*\*\/)/g; // Match the closest allowed character (a opening or closing brace, a semicolon or a comment ending) before the rule +var beforeRuleValidationRegExp = /^[\s{};]*(\*\/\s*)?$/; // Match that the portion before the rule is empty or contains only whitespace, semicolons, opening/closing braces, and optionally a comment ending (*/) followed by whitespace +var forwardRuleValidationRegExp = /(?:\s|\/\*|\{|\()/; // Match that the rule is followed by any whitespace, a opening comment, a condition opening parenthesis or a opening brace +var forwardImportRuleValidationRegExp = /(?:\s|\/\*|'|")/; // Match that the rule is followed by any whitespace, an opening comment, a single quote or double quote +var forwardRuleClosingBraceRegExp = /{[^{}]*}|}/; // Finds the next closing brace of a rule block +var forwardRuleSemicolonAndOpeningBraceRegExp = /^.*?({|;)/; // Finds the next semicolon or opening brace after the at-rule + +// Regex patterns for CSS selector validation and parsing +var cssCustomIdentifierRegExp = /^(-?[_a-zA-Z]+(\.[_a-zA-Z]+)*[_a-zA-Z0-9-]*)$/; // Validates a css custom identifier +var startsWithCombinatorRegExp = /^\s*[>+~]/; // Checks if a selector starts with a CSS combinator (>, +, ~) + +/** + * Parse `@page` selectorText for page name and pseudo-pages + * Valid formats: + * - (empty - no name, no pseudo-page) + * - `:left`, `:right`, `:first`, `:blank` (pseudo-page only) + * - `named` (named page only) + * - `named:first` (named page with single pseudo-page) + * - `named:first:left` (named page with multiple pseudo-pages) + */ +var atPageRuleSelectorRegExp = /^([^\s:]+)?((?::\w+)*)$/; // Validates @page rule selectors + +// Regex patterns for CSSImportRule parsing +var layerRegExp = /layer\(([^)]*)\)/; // Matches layer() function in @import +var layerRuleNameRegExp = /^(-?[_a-zA-Z]+(\.[_a-zA-Z]+)*[_a-zA-Z0-9-]*)$/; // Validates layer name (same as custom identifier) +var doubleOrMoreSpacesRegExp = /\s{2,}/g; // Matches two or more consecutive whitespace characters + + +// Regex patterns for CSS escape sequences and identifiers +var startsWithHexEscapeRegExp = /^\\[0-9a-fA-F]/; // Checks if escape sequence starts with hex escape +var identStartCharRegExp = /[a-zA-Z_\u00A0-\uFFFF]/; // Valid identifier start character +var identCharRegExp = /^[a-zA-Z0-9_\-\u00A0-\uFFFF\\]/; // Valid identifier character +var specialCharsNeedEscapeRegExp = /[!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~\s]/; // Characters that need escaping +var combinatorOrSeparatorRegExp = /[\s>+~,()]/; // Selector boundaries and combinators +var afterHexEscapeSeparatorRegExp = /[\s>+~,(){}\[\]]/; // Characters that separate after hex escape +var trailingSpaceSeparatorRegExp = /[\s>+~,(){}]/; // Characters that allow trailing space +var endsWithHexEscapeRegExp = /\\[0-9a-fA-F]{1,6}\s+$/; // Matches selector ending with hex escape + space(s) + +/** + * Regular expression to detect invalid characters in the value portion of a CSS style declaration. + * + * This regex matches a colon (:) that is not inside parentheses and not inside single or double quotes. + * It is used to ensure that the value part of a CSS property does not contain unexpected colons, + * which would indicate a malformed declaration (e.g., "color: foo:bar;" is invalid). + * + * The negative lookahead `(?![^(]*\))` ensures that the colon is not followed by a closing + * parenthesis without encountering an opening parenthesis, effectively ignoring colons inside + * function-like values (e.g., `url(data:image/png;base64,...)`). + * + * The lookahead `(?=(?:[^'"]|'[^']*'|"[^"]*")*$)` ensures that the colon is not inside single or double quotes, + * allowing colons within quoted strings (e.g., `content: ":";` or `background: url("foo:bar.png");`). + * + * Example: + * - `color: red;` // valid, does not match + * - `background: url(data:image/png;base64,...);` // valid, does not match + * - `content: ':';` // valid, does not match + * - `color: foo:bar;` // invalid, matches + */ +var basicStylePropertyValueValidationRegExp = /:(?![^(]*\))(?=(?:[^'"]|'[^']*'|"[^"]*")*$)/; + +// Attribute selector pattern: matches attribute-name operator value +// Operators: =, ~=, |=, ^=, $=, *= +// Rewritten to avoid ReDoS by using greedy match and trimming in JavaScript +var attributeSelectorContentRegExp = /^([^\s=~|^$*]+)\s*(~=|\|=|\^=|\$=|\*=|=)\s*(.+)$/; + +// Selector validation patterns +var pseudoElementRegExp = /::[a-zA-Z][\w-]*|:(before|after|first-line|first-letter)(?![a-zA-Z0-9_-])/; // Matches pseudo-elements +var invalidCombinatorLtGtRegExp = /<>/; // Invalid <> combinator +var invalidCombinatorDoubleGtRegExp = />>/; // Invalid >> combinator +var consecutiveCombinatorsRegExp = /[>+~]\s*[>+~]/; // Invalid consecutive combinators +var invalidSlottedRegExp = /(?:^|[\s>+~,\[])slotted\s*\(/i; // Invalid slotted() without :: +var invalidPartRegExp = /(?:^|[\s>+~,\[])part\s*\(/i; // Invalid part() without :: +var invalidCueRegExp = /(?:^|[\s>+~,\[])cue\s*\(/i; // Invalid cue() without :: +var invalidCueRegionRegExp = /(?:^|[\s>+~,\[])cue-region\s*\(/i; // Invalid cue-region() without :: +var invalidNestingPattern = /&(?![.\#\[:>\+~\s])[a-zA-Z]/; // Invalid & followed by type selector +var emptyPseudoClassRegExp = /:(?:is|not|where|has)\(\s*\)/; // Empty pseudo-class like :is() +var whitespaceNormalizationRegExp = /(['"])(?:\\.|[^\\])*?\1|(\r\n|\r|\n)/g; // Normalize newlines outside quotes +var newlineRemovalRegExp = /\n/g; // Remove all newlines +var whitespaceAndDotRegExp = /[\s.]/; // Matches whitespace or dot +var declarationOrOpenBraceRegExp = /[{;}]/; // Matches declaration separator or open brace +var ampersandRegExp = /&/; // Matches nesting selector +var hexEscapeSequenceRegExp = /^([0-9a-fA-F]{1,6})[ \t\r\n\f]?/; // Matches hex escape sequence (1-6 hex digits optionally followed by whitespace) +var attributeCaseFlagRegExp = /^(.+?)\s+([is])$/i; // Matches case-sensitivity flag at end of attribute value +var prependedAmpersandRegExp = /^&\s+[:\\.]/; // Matches prepended ampersand pattern (& followed by space and : or .) +var openBraceGlobalRegExp = /{/g; // Matches opening braces (global) +var closeBraceGlobalRegExp = /}/g; // Matches closing braces (global) +var scopePreludeSplitRegExp = /\s*\)\s*to\s+\(/; // Splits scope prelude by ") to (" +var leadingWhitespaceRegExp = /^\s+/; // Matches leading whitespace (used to implement a ES5-compliant alternative to trimStart()) +var doubleQuoteRegExp = /"/g; // Match all double quotes (for escaping in attribute values) +var backslashRegExp = /\\/g; // Match all backslashes (for escaping in attribute values) + +var regexPatterns = { + // Parsing patterns + atKeyframesRegExp: atKeyframesRegExp, + beforeRulePortionRegExp: beforeRulePortionRegExp, + beforeRuleValidationRegExp: beforeRuleValidationRegExp, + forwardRuleValidationRegExp: forwardRuleValidationRegExp, + forwardImportRuleValidationRegExp: forwardImportRuleValidationRegExp, + forwardRuleClosingBraceRegExp: forwardRuleClosingBraceRegExp, + forwardRuleSemicolonAndOpeningBraceRegExp: forwardRuleSemicolonAndOpeningBraceRegExp, + + // Selector validation patterns + cssCustomIdentifierRegExp: cssCustomIdentifierRegExp, + startsWithCombinatorRegExp: startsWithCombinatorRegExp, + atPageRuleSelectorRegExp: atPageRuleSelectorRegExp, + + // Parsing patterns used in CSSImportRule + layerRegExp: layerRegExp, + layerRuleNameRegExp: layerRuleNameRegExp, + doubleOrMoreSpacesRegExp: doubleOrMoreSpacesRegExp, + + // Escape sequence and identifier patterns + startsWithHexEscapeRegExp: startsWithHexEscapeRegExp, + identStartCharRegExp: identStartCharRegExp, + identCharRegExp: identCharRegExp, + specialCharsNeedEscapeRegExp: specialCharsNeedEscapeRegExp, + combinatorOrSeparatorRegExp: combinatorOrSeparatorRegExp, + afterHexEscapeSeparatorRegExp: afterHexEscapeSeparatorRegExp, + trailingSpaceSeparatorRegExp: trailingSpaceSeparatorRegExp, + endsWithHexEscapeRegExp: endsWithHexEscapeRegExp, + + // Basic style property value validation + basicStylePropertyValueValidationRegExp: basicStylePropertyValueValidationRegExp, + + // Attribute selector patterns + attributeSelectorContentRegExp: attributeSelectorContentRegExp, + + // Selector validation patterns + pseudoElementRegExp: pseudoElementRegExp, + invalidCombinatorLtGtRegExp: invalidCombinatorLtGtRegExp, + invalidCombinatorDoubleGtRegExp: invalidCombinatorDoubleGtRegExp, + consecutiveCombinatorsRegExp: consecutiveCombinatorsRegExp, + invalidSlottedRegExp: invalidSlottedRegExp, + invalidPartRegExp: invalidPartRegExp, + invalidCueRegExp: invalidCueRegExp, + invalidCueRegionRegExp: invalidCueRegionRegExp, + invalidNestingPattern: invalidNestingPattern, + emptyPseudoClassRegExp: emptyPseudoClassRegExp, + whitespaceNormalizationRegExp: whitespaceNormalizationRegExp, + newlineRemovalRegExp: newlineRemovalRegExp, + whitespaceAndDotRegExp: whitespaceAndDotRegExp, + declarationOrOpenBraceRegExp: declarationOrOpenBraceRegExp, + ampersandRegExp: ampersandRegExp, + hexEscapeSequenceRegExp: hexEscapeSequenceRegExp, + attributeCaseFlagRegExp: attributeCaseFlagRegExp, + prependedAmpersandRegExp: prependedAmpersandRegExp, + openBraceGlobalRegExp: openBraceGlobalRegExp, + closeBraceGlobalRegExp: closeBraceGlobalRegExp, + scopePreludeSplitRegExp: scopePreludeSplitRegExp, + leadingWhitespaceRegExp: leadingWhitespaceRegExp, + doubleQuoteRegExp: doubleQuoteRegExp, + backslashRegExp: backslashRegExp +}; + +//.CommonJS +exports.regexPatterns = regexPatterns; +///CommonJS diff --git a/vanilla/node_modules/@acemir/cssom/package.json b/vanilla/node_modules/@acemir/cssom/package.json new file mode 100644 index 0000000..0170d58 --- /dev/null +++ b/vanilla/node_modules/@acemir/cssom/package.json @@ -0,0 +1,32 @@ +{ + "name": "@acemir/cssom", + "description": "CSS Object Model implementation and CSS parser", + "keywords": [ + "CSS", + "CSSOM", + "parser", + "styleSheet" + ], + "version": "0.9.31", + "author": "Nikita Vasilyev ", + "contributors": [ + "Acemir Sousa Mendes " + ], + "repository": "acemir/CSSOM", + "files": [ + "lib/", + "build/" + ], + "browser": "./build/CSSOM.js", + "main": "./lib/index.js", + "license": "MIT", + "scripts": { + "build": "node build.js", + "release": "npm run build && changeset publish" + }, + "devDependencies": { + "@changesets/changelog-github": "^0.5.2", + "@changesets/cli": "^2.29.8", + "@changesets/get-release-plan": "^4.0.14" + } +} diff --git a/vanilla/node_modules/@asamuzakjp/css-color/LICENSE b/vanilla/node_modules/@asamuzakjp/css-color/LICENSE new file mode 100644 index 0000000..0004c52 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/css-color/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 asamuzaK (Kazz) + +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/vanilla/node_modules/@asamuzakjp/css-color/README.md b/vanilla/node_modules/@asamuzakjp/css-color/README.md new file mode 100644 index 0000000..715b6c3 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/css-color/README.md @@ -0,0 +1,316 @@ +# CSS color + +[![build](https://github.com/asamuzaK/cssColor/actions/workflows/node.js.yml/badge.svg)](https://github.com/asamuzaK/cssColor/actions/workflows/node.js.yml) +[![CodeQL](https://github.com/asamuzaK/cssColor/actions/workflows/github-code-scanning/codeql/badge.svg)](https://github.com/asamuzaK/cssColor/actions/workflows/github-code-scanning/codeql) +[![npm (scoped)](https://img.shields.io/npm/v/@asamuzakjp/css-color)](https://www.npmjs.com/package/@asamuzakjp/css-color) + +Resolve and convert CSS colors. + +## Install + +```console +npm i @asamuzakjp/css-color +``` + +## Usage + +```javascript +import { convert, resolve, utils } from '@asamuzakjp/css-color'; + +const resolvedValue = resolve( + 'color-mix(in oklab, lch(67.5345 42.5 258.2), color(srgb 0 0.5 0))' +); +// 'oklab(0.620754 -0.0931934 -0.00374881)' + +const convertedValue = convert.colorToHex('lab(46.2775% -47.5621 48.5837)'); +// '#008000' + +const result = utils.isColor('green'); +// true +``` + + + +### resolve(color, opt) + +resolves CSS color + +#### Parameters + +- `color` **[string][133]** color value + - system colors are not supported +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.currentColor` **[string][133]?** + - color to use for `currentcolor` keyword + - if omitted, it will be treated as a missing color, + i.e. `rgb(none none none / none)` + - `opt.customProperty` **[object][135]?** + - custom properties + - pair of `--` prefixed property name as a key and it's value, + e.g. + ```javascript + const opt = { + customProperty: { + '--some-color': '#008000', + '--some-length': '16px' + } + }; + ``` + - and/or `callback` function to get the value of the custom property, + e.g. + ```javascript + const node = document.getElementById('foo'); + const opt = { + customProperty: { + callback: node.style.getPropertyValue + } + }; + ``` + - `opt.dimension` **[object][135]?** + - dimension, e.g. for converting relative length to pixels + - pair of unit as a key and number in pixels as it's value, + e.g. suppose `1em === 12px`, `1rem === 16px` and `100vw === 1024px`, then + ```javascript + const opt = { + dimension: { + em: 12, + rem: 16, + vw: 10.24 + } + }; + ``` + - and/or `callback` function to get the value as a number in pixels, + e.g. + ```javascript + const opt = { + dimension: { + callback: unit => { + switch (unit) { + case 'em': + return 12; + case 'rem': + return 16; + case 'vw': + return 10.24; + default: + return; + } + } + } + }; + ``` + - `opt.format` **[string][133]?** + - output format, one of below + - `computedValue` (default), [computed value][139] of the color + - `specifiedValue`, [specified value][140] of the color + - `hex`, hex color notation, i.e. `#rrggbb` + - `hexAlpha`, hex color notation with alpha channel, i.e. `#rrggbbaa` + +Returns **[string][133]?** one of `rgba?()`, `#rrggbb(aa)?`, `color-name`, `color(color-space r g b / alpha)`, `color(color-space x y z / alpha)`, `(ok)?lab(l a b / alpha)`, `(ok)?lch(l c h / alpha)`, `'(empty-string)'`, `null` + +- in `computedValue`, values are numbers, however `rgb()` values are integers +- in `specifiedValue`, returns `empty string` for unknown and/or invalid color +- in `hex`, returns `null` for `transparent`, and also returns `null` if any of `r`, `g`, `b`, `alpha` is not a number +- in `hexAlpha`, returns `#00000000` for `transparent`, however returns `null` if any of `r`, `g`, `b`, `alpha` is not a number + +### convert + +Contains various color conversion functions. + +### convert.numberToHex(value) + +convert number to hex string + +#### Parameters + +- `value` **[number][134]** color value + +Returns **[string][133]** hex string: 00..ff + +### convert.colorToHex(value, opt) + +convert color to hex + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.alpha` **[boolean][136]?** return in #rrggbbaa notation + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[string][133]** #rrggbb(aa)? + +### convert.colorToHsl(value, opt) + +convert color to hsl + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[h, s, l, alpha] + +### convert.colorToHwb(value, opt) + +convert color to hwb + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[h, w, b, alpha] + +### convert.colorToLab(value, opt) + +convert color to lab + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[l, a, b, alpha] + +### convert.colorToLch(value, opt) + +convert color to lch + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[l, c, h, alpha] + +### convert.colorToOklab(value, opt) + +convert color to oklab + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[l, a, b, alpha] + +### convert.colorToOklch(value, opt) + +convert color to oklch + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[l, c, h, alpha] + +### convert.colorToRgb(value, opt) + +convert color to rgb + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[r, g, b, alpha] + +### convert.colorToXyz(value, opt) + +convert color to xyz + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + - `opt.d50` **[boolean][136]?** xyz in d50 white point + +Returns **[Array][137]<[number][134]>** \[x, y, z, alpha] + +### convert.colorToXyzD50(value, opt) + +convert color to xyz-d50 + +#### Parameters + +- `value` **[string][133]** color value +- `opt` **[object][135]?** options (optional, default `{}`) + - `opt.customProperty` **[object][135]?** + - custom properties, see `resolve()` function above + - `opt.dimension` **[object][135]?** + - dimension, see `resolve()` function above + +Returns **[Array][137]<[number][134]>** \[x, y, z, alpha] + +### utils + +Contains utility functions. + +### utils.isColor(color) + +is valid color type + +#### Parameters + +- `color` **[string][133]** color value + - system colors are not supported + +Returns **[boolean][136]** + +## Acknowledgments + +The following resources have been of great help in the development of the CSS color. + +- [csstools/postcss-plugins](https://github.com/csstools/postcss-plugins) +- [lru-cache](https://github.com/isaacs/node-lru-cache) + +--- + +Copyright (c) 2024 [asamuzaK (Kazz)](https://github.com/asamuzaK/) + +[133]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String +[134]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number +[135]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +[136]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean +[137]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array +[138]: https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code +[139]: https://developer.mozilla.org/en-US/docs/Web/CSS/computed_value +[140]: https://developer.mozilla.org/en-US/docs/Web/CSS/specified_value +[141]: https://www.npmjs.com/package/@csstools/css-calc diff --git a/vanilla/node_modules/@asamuzakjp/css-color/dist/browser/css-color.min.js b/vanilla/node_modules/@asamuzakjp/css-color/dist/browser/css-color.min.js new file mode 100644 index 0000000..3061ad6 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/css-color/dist/browser/css-color.min.js @@ -0,0 +1 @@ +class En extends Error{sourceStart;sourceEnd;parserState;constructor(t,n,r,s){super(t),this.name="ParseError",this.sourceStart=n,this.sourceEnd=r,this.parserState=s}}class At extends En{token;constructor(t,n,r,s,a){super(t,n,r,s),this.token=a}}const wt={UnexpectedNewLineInString:"Unexpected newline while consuming a string token.",UnexpectedEOFInString:"Unexpected EOF while consuming a string token.",UnexpectedEOFInComment:"Unexpected EOF while consuming a comment.",UnexpectedEOFInURL:"Unexpected EOF while consuming a url token.",UnexpectedEOFInEscapedCodePoint:"Unexpected EOF while consuming an escaped code point.",UnexpectedCharacterInURL:"Unexpected character while consuming a url token.",InvalidEscapeSequenceInURL:"Invalid escape sequence while consuming a url token.",InvalidEscapeSequenceAfterBackslash:'Invalid escape sequence after "\\"'};function $t(...e){let t="";for(let n=0;n=48&&e<=57}function Ko(e){return e>=65&&e<=90}function Zo(e){return e>=97&&e<=122}function Yt(e){return e>=48&&e<=57||e>=97&&e<=102||e>=65&&e<=70}function Jo(e){return Zo(e)||Ko(e)}function Xt(e){return Jo(e)||Qo(e)||e===95}function Lr(e){return Xt(e)||qe(e)||e===be}function Qo(e){return e===183||e===8204||e===8205||e===8255||e===8256||e===8204||192<=e&&e<=214||216<=e&&e<=246||248<=e&&e<=893||895<=e&&e<=8191||8304<=e&&e<=8591||11264<=e&&e<=12271||12289<=e&&e<=55295||63744<=e&&e<=64975||65008<=e&&e<=65533||e===0||!!Kt(e)||e>=65536}function ei(e){return e===11||e===127||0<=e&&e<=8||14<=e&&e<=31}function Jn(e){return e===jt||e===Vt||e===12}function Lt(e){return e===32||e===jt||e===9||e===Vt||e===12}function Kt(e){return e>=55296&&e<=57343}function Zt(e){return e.source.codePointAt(e.cursor)===92&&!Jn(e.source.codePointAt(e.cursor+1)??-1)}function Qn(e,t){return t.source.codePointAt(t.cursor)===be?t.source.codePointAt(t.cursor+1)===be||!!Xt(t.source.codePointAt(t.cursor+1)??-1)||t.source.codePointAt(t.cursor+1)===92&&!Jn(t.source.codePointAt(t.cursor+2)??-1):!!Xt(t.source.codePointAt(t.cursor)??-1)||Zt(t)}function js(e){return e.source.codePointAt(e.cursor)===qt||e.source.codePointAt(e.cursor)===be?!!qe(e.source.codePointAt(e.cursor+1)??-1)||e.source.codePointAt(e.cursor+1)===46&&qe(e.source.codePointAt(e.cursor+2)??-1):e.source.codePointAt(e.cursor)===46?qe(e.source.codePointAt(e.cursor+1)??-1):qe(e.source.codePointAt(e.cursor)??-1)}function ti(e){return e.source.codePointAt(e.cursor)===47&&e.source.codePointAt(e.cursor+1)===42}function ni(e){return e.source.codePointAt(e.cursor)===be&&e.source.codePointAt(e.cursor+1)===be&&e.source.codePointAt(e.cursor+2)===62}var g,F,er;function ri(e){switch(e){case g.OpenParen:return g.CloseParen;case g.CloseParen:return g.OpenParen;case g.OpenCurly:return g.CloseCurly;case g.CloseCurly:return g.OpenCurly;case g.OpenSquare:return g.CloseSquare;case g.CloseSquare:return g.OpenSquare;default:return null}}function si(e){switch(e[0]){case g.OpenParen:return[g.CloseParen,")",-1,-1,void 0];case g.CloseParen:return[g.OpenParen,"(",-1,-1,void 0];case g.OpenCurly:return[g.CloseCurly,"}",-1,-1,void 0];case g.CloseCurly:return[g.OpenCurly,"{",-1,-1,void 0];case g.OpenSquare:return[g.CloseSquare,"]",-1,-1,void 0];case g.CloseSquare:return[g.OpenSquare,"[",-1,-1,void 0];default:return null}}function ai(e,t){for(t.advanceCodePoint(2);;){const n=t.readCodePoint();if(n===void 0){const r=[g.Comment,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,void 0];return e.onParseError(new At(wt.UnexpectedEOFInComment,t.representationStart,t.representationEnd,["4.3.2. Consume comments","Unexpected EOF"],r)),r}if(n===42&&t.source.codePointAt(t.cursor)!==void 0&&t.source.codePointAt(t.cursor)===47){t.advanceCodePoint();break}}return[g.Comment,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,void 0]}function tr(e,t){const n=t.readCodePoint();if(n===void 0)return e.onParseError(new En(wt.UnexpectedEOFInEscapedCodePoint,t.representationStart,t.representationEnd,["4.3.7. Consume an escaped code point","Unexpected EOF"])),Pt;if(Yt(n)){const r=[n];let s;for(;(s=t.source.codePointAt(t.cursor))!==void 0&&Yt(s)&&r.length<6;)r.push(s),t.advanceCodePoint();Lt(t.source.codePointAt(t.cursor)??-1)&&(t.source.codePointAt(t.cursor)===Vt&&t.source.codePointAt(t.cursor+1)===jt&&t.advanceCodePoint(),t.advanceCodePoint());const a=parseInt(String.fromCodePoint(...r),16);return a===0||Kt(a)||a>1114111?Pt:a}return n===0||Kt(n)?Pt:n}function nr(e,t){const n=[];for(;;){const r=t.source.codePointAt(t.cursor)??-1;if(r===0||Kt(r))n.push(Pt),t.advanceCodePoint(+(r>65535)+1);else if(Lr(r))n.push(r),t.advanceCodePoint(+(r>65535)+1);else{if(!Zt(t))return n;t.advanceCodePoint(),n.push(tr(e,t))}}}function oi(e,t){t.advanceCodePoint();const n=t.source.codePointAt(t.cursor);if(n!==void 0&&(Lr(n)||Zt(t))){let r=er.Unrestricted;Qn(0,t)&&(r=er.ID);const s=nr(e,t);return[g.Hash,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:String.fromCodePoint(...s),type:r}]}return[g.Delim,"#",t.representationStart,t.representationEnd,{value:"#"}]}function ii(e,t){let n=F.Integer;for(t.source.codePointAt(t.cursor)!==qt&&t.source.codePointAt(t.cursor)!==be||t.advanceCodePoint();qe(t.source.codePointAt(t.cursor)??-1);)t.advanceCodePoint();if(t.source.codePointAt(t.cursor)===46&&qe(t.source.codePointAt(t.cursor+1)??-1))for(t.advanceCodePoint(2),n=F.Number;qe(t.source.codePointAt(t.cursor)??-1);)t.advanceCodePoint();if(t.source.codePointAt(t.cursor)===101||t.source.codePointAt(t.cursor)===69){if(qe(t.source.codePointAt(t.cursor+1)??-1))t.advanceCodePoint(2);else{if(t.source.codePointAt(t.cursor+1)!==be&&t.source.codePointAt(t.cursor+1)!==qt||!qe(t.source.codePointAt(t.cursor+2)??-1))return n;t.advanceCodePoint(3)}for(n=F.Number;qe(t.source.codePointAt(t.cursor)??-1);)t.advanceCodePoint()}return n}function Tr(e,t){let n;{const a=t.source.codePointAt(t.cursor);a===be?n="-":a===qt&&(n="+")}const r=ii(0,t),s=parseFloat(t.source.slice(t.representationStart,t.representationEnd+1));if(Qn(0,t)){const a=nr(e,t);return[g.Dimension,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:s,signCharacter:n,type:r,unit:String.fromCodePoint(...a)}]}return t.source.codePointAt(t.cursor)===37?(t.advanceCodePoint(),[g.Percentage,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:s,signCharacter:n}]):[g.Number,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:s,signCharacter:n,type:r}]}function li(e){for(;Lt(e.source.codePointAt(e.cursor)??-1);)e.advanceCodePoint();return[g.Whitespace,e.source.slice(e.representationStart,e.representationEnd+1),e.representationStart,e.representationEnd,void 0]}(function(e){e.Comment="comment",e.AtKeyword="at-keyword-token",e.BadString="bad-string-token",e.BadURL="bad-url-token",e.CDC="CDC-token",e.CDO="CDO-token",e.Colon="colon-token",e.Comma="comma-token",e.Delim="delim-token",e.Dimension="dimension-token",e.EOF="EOF-token",e.Function="function-token",e.Hash="hash-token",e.Ident="ident-token",e.Number="number-token",e.Percentage="percentage-token",e.Semicolon="semicolon-token",e.String="string-token",e.URL="url-token",e.Whitespace="whitespace-token",e.OpenParen="(-token",e.CloseParen=")-token",e.OpenSquare="[-token",e.CloseSquare="]-token",e.OpenCurly="{-token",e.CloseCurly="}-token",e.UnicodeRange="unicode-range-token"})(g||(g={})),(function(e){e.Integer="integer",e.Number="number"})(F||(F={})),(function(e){e.Unrestricted="unrestricted",e.ID="id"})(er||(er={}));class ci{cursor=0;source="";representationStart=0;representationEnd=-1;constructor(t){this.source=t}advanceCodePoint(t=1){this.cursor=this.cursor+t,this.representationEnd=this.cursor-1}readCodePoint(){const t=this.source.codePointAt(this.cursor);if(t!==void 0)return this.cursor=this.cursor+1,this.representationEnd=this.cursor-1,t}unreadCodePoint(t=1){this.cursor=this.cursor-t,this.representationEnd=this.cursor-1}resetRepresentation(){this.representationStart=this.cursor,this.representationEnd=-1}}function ui(e,t){let n="";const r=t.readCodePoint();for(;;){const s=t.readCodePoint();if(s===void 0){const a=[g.String,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:n}];return e.onParseError(new At(wt.UnexpectedEOFInString,t.representationStart,t.representationEnd,["4.3.5. Consume a string token","Unexpected EOF"],a)),a}if(Jn(s)){t.unreadCodePoint();const a=[g.BadString,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,void 0];return e.onParseError(new At(wt.UnexpectedNewLineInString,t.representationStart,t.source.codePointAt(t.cursor)===Vt&&t.source.codePointAt(t.cursor+1)===jt?t.representationEnd+2:t.representationEnd+1,["4.3.5. Consume a string token","Unexpected newline"],a)),a}if(s===r)return[g.String,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:n}];if(s!==92)s===0||Kt(s)?n+=String.fromCodePoint(Pt):n+=String.fromCodePoint(s);else{if(t.source.codePointAt(t.cursor)===void 0)continue;if(Jn(t.source.codePointAt(t.cursor)??-1)){t.source.codePointAt(t.cursor)===Vt&&t.source.codePointAt(t.cursor+1)===jt&&t.advanceCodePoint(),t.advanceCodePoint();continue}n+=String.fromCodePoint(tr(e,t))}}}function hi(e){return!(e.length!==3||e[0]!==117&&e[0]!==85||e[1]!==114&&e[1]!==82||e[2]!==108&&e[2]!==76)}function _r(e,t){for(;;){const n=t.source.codePointAt(t.cursor);if(n===void 0)return;if(n===41)return void t.advanceCodePoint();Zt(t)?(t.advanceCodePoint(),tr(e,t)):t.advanceCodePoint()}}function fi(e,t){for(;Lt(t.source.codePointAt(t.cursor)??-1);)t.advanceCodePoint();let n="";for(;;){if(t.source.codePointAt(t.cursor)===void 0){const s=[g.URL,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:n}];return e.onParseError(new At(wt.UnexpectedEOFInURL,t.representationStart,t.representationEnd,["4.3.6. Consume a url token","Unexpected EOF"],s)),s}if(t.source.codePointAt(t.cursor)===41)return t.advanceCodePoint(),[g.URL,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:n}];if(Lt(t.source.codePointAt(t.cursor)??-1)){for(t.advanceCodePoint();Lt(t.source.codePointAt(t.cursor)??-1);)t.advanceCodePoint();if(t.source.codePointAt(t.cursor)===void 0){const s=[g.URL,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:n}];return e.onParseError(new At(wt.UnexpectedEOFInURL,t.representationStart,t.representationEnd,["4.3.6. Consume a url token","Consume as much whitespace as possible","Unexpected EOF"],s)),s}return t.source.codePointAt(t.cursor)===41?(t.advanceCodePoint(),[g.URL,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:n}]):(_r(e,t),[g.BadURL,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,void 0])}const r=t.source.codePointAt(t.cursor);if(r===34||r===39||r===40||ei(r??-1)){_r(e,t);const s=[g.BadURL,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,void 0];return e.onParseError(new At(wt.UnexpectedCharacterInURL,t.representationStart,t.representationEnd,["4.3.6. Consume a url token",`Unexpected U+0022 QUOTATION MARK ("), U+0027 APOSTROPHE ('), U+0028 LEFT PARENTHESIS (() or non-printable code point`],s)),s}if(r===92){if(Zt(t)){t.advanceCodePoint(),n+=String.fromCodePoint(tr(e,t));continue}_r(e,t);const s=[g.BadURL,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,void 0];return e.onParseError(new At(wt.InvalidEscapeSequenceInURL,t.representationStart,t.representationEnd,["4.3.6. Consume a url token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"],s)),s}t.source.codePointAt(t.cursor)===0||Kt(t.source.codePointAt(t.cursor)??-1)?(n+=String.fromCodePoint(Pt),t.advanceCodePoint()):(n+=t.source[t.cursor],t.advanceCodePoint())}}function Wr(e,t){const n=nr(e,t);if(t.source.codePointAt(t.cursor)!==40)return[g.Ident,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:String.fromCodePoint(...n)}];if(hi(n)){t.advanceCodePoint();let r=0;for(;;){const s=Lt(t.source.codePointAt(t.cursor)??-1),a=Lt(t.source.codePointAt(t.cursor+1)??-1);if(s&&a){r+=1,t.advanceCodePoint(1);continue}const o=s?t.source.codePointAt(t.cursor+1):t.source.codePointAt(t.cursor);if(o===34||o===39)return r>0&&t.unreadCodePoint(r),[g.Function,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:String.fromCodePoint(...n)}];break}return fi(e,t)}return t.advanceCodePoint(),[g.Function,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{value:String.fromCodePoint(...n)}]}function pi(e){return!(e.source.codePointAt(e.cursor)!==117&&e.source.codePointAt(e.cursor)!==85||e.source.codePointAt(e.cursor+1)!==qt||e.source.codePointAt(e.cursor+2)!==63&&!Yt(e.source.codePointAt(e.cursor+2)??-1))}function di(e,t){t.advanceCodePoint(2);const n=[],r=[];let s;for(;(s=t.source.codePointAt(t.cursor))!==void 0&&n.length<6&&Yt(s);)n.push(s),t.advanceCodePoint();for(;(s=t.source.codePointAt(t.cursor))!==void 0&&n.length<6&&s===63;)r.length===0&&r.push(...n),n.push(48),r.push(70),t.advanceCodePoint();if(!r.length&&t.source.codePointAt(t.cursor)===be&&Yt(t.source.codePointAt(t.cursor+1)??-1))for(t.advanceCodePoint();(s=t.source.codePointAt(t.cursor))!==void 0&&r.length<6&&Yt(s);)r.push(s),t.advanceCodePoint();if(!r.length){const i=parseInt(String.fromCodePoint(...n),16);return[g.UnicodeRange,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{startOfRange:i,endOfRange:i}]}const a=parseInt(String.fromCodePoint(...n),16),o=parseInt(String.fromCodePoint(...r),16);return[g.UnicodeRange,t.source.slice(t.representationStart,t.representationEnd+1),t.representationStart,t.representationEnd,{startOfRange:a,endOfRange:o}]}function Nt(e,t){const n=qs(e),r=[];for(;!n.endOfFile();)r.push(n.nextToken());return r.push(n.nextToken()),r}function qs(e,t){const n=e.css.valueOf(),r=e.unicodeRangesAllowed??!1,s=new ci(n),a={onParseError:mi};return{nextToken:function(){s.resetRepresentation();const o=s.source.codePointAt(s.cursor);if(o===void 0)return[g.EOF,"",-1,-1,void 0];if(o===47&&ti(s))return ai(a,s);if(r&&(o===117||o===85)&&pi(s))return di(0,s);if(Xt(o))return Wr(a,s);if(qe(o))return Tr(a,s);switch(o){case 44:return s.advanceCodePoint(),[g.Comma,",",s.representationStart,s.representationEnd,void 0];case 58:return s.advanceCodePoint(),[g.Colon,":",s.representationStart,s.representationEnd,void 0];case 59:return s.advanceCodePoint(),[g.Semicolon,";",s.representationStart,s.representationEnd,void 0];case 40:return s.advanceCodePoint(),[g.OpenParen,"(",s.representationStart,s.representationEnd,void 0];case 41:return s.advanceCodePoint(),[g.CloseParen,")",s.representationStart,s.representationEnd,void 0];case 91:return s.advanceCodePoint(),[g.OpenSquare,"[",s.representationStart,s.representationEnd,void 0];case 93:return s.advanceCodePoint(),[g.CloseSquare,"]",s.representationStart,s.representationEnd,void 0];case 123:return s.advanceCodePoint(),[g.OpenCurly,"{",s.representationStart,s.representationEnd,void 0];case 125:return s.advanceCodePoint(),[g.CloseCurly,"}",s.representationStart,s.representationEnd,void 0];case 39:case 34:return ui(a,s);case 35:return oi(a,s);case qt:case 46:return js(s)?Tr(a,s):(s.advanceCodePoint(),[g.Delim,s.source[s.representationStart],s.representationStart,s.representationEnd,{value:s.source[s.representationStart]}]);case jt:case Vt:case 12:case 9:case 32:return li(s);case be:return js(s)?Tr(a,s):ni(s)?(s.advanceCodePoint(3),[g.CDC,"-->",s.representationStart,s.representationEnd,void 0]):Qn(0,s)?Wr(a,s):(s.advanceCodePoint(),[g.Delim,"-",s.representationStart,s.representationEnd,{value:"-"}]);case 60:return Xo(s)?(s.advanceCodePoint(4),[g.CDO," + +### matches(selector, node, opt) + +matches - equivalent to [Element.matches()][64] + +#### Parameters + +- `selector` **[string][59]** CSS selector +- `node` **[object][60]** Element node +- `opt` **[object][60]?** options + - `opt.noexcept` **[boolean][61]?** no exception + - `opt.warn` **[boolean][61]?** console warn e.g. unsupported pseudo-class + +Returns **[boolean][61]** `true` if matched, `false` otherwise + + +### closest(selector, node, opt) + +closest - equivalent to [Element.closest()][65] + +#### Parameters + +- `selector` **[string][59]** CSS selector +- `node` **[object][60]** Element node +- `opt` **[object][60]?** options + - `opt.noexcept` **[boolean][61]?** no exception + - `opt.warn` **[boolean][61]?** console warn e.g. unsupported pseudo-class + +Returns **[object][60]?** matched node + + +### querySelector(selector, node, opt) + +querySelector - equivalent to [Document.querySelector()][66], [DocumentFragment.querySelector()][67] and [Element.querySelector()][68] + +#### Parameters + +- `selector` **[string][59]** CSS selector +- `node` **[object][60]** Document, DocumentFragment or Element node +- `opt` **[object][60]?** options + - `opt.noexcept` **[boolean][61]?** no exception + - `opt.warn` **[boolean][61]?** console warn e.g. unsupported pseudo-class + +Returns **[object][60]?** matched node + + +### querySelectorAll(selector, node, opt) + +querySelectorAll - equivalent to [Document.querySelectorAll()][69], [DocumentFragment.querySelectorAll()][70] and [Element.querySelectorAll()][71] +**NOTE**: returns Array, not NodeList + +#### Parameters + +- `selector` **[string][59]** CSS selector +- `node` **[object][60]** Document, DocumentFragment or Element node +- `opt` **[object][60]?** options + - `opt.noexcept` **[boolean][61]?** no exception + - `opt.warn` **[boolean][61]?** console warn e.g. unsupported pseudo-class + +Returns **[Array][62]<([object][60] \| [undefined][63])>** array of matched nodes + + +## Monkey patch jsdom + +``` javascript +import { DOMSelector } from '@asamuzakjp/dom-selector'; +import { JSDOM } from 'jsdom'; + +const dom = new JSDOM('', { + runScripts: 'dangerously', + url: 'http://localhost/', + beforeParse: window => { + const domSelector = new DOMSelector(window); + + const matches = domSelector.matches.bind(domSelector); + window.Element.prototype.matches = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return matches(selector, this); + }; + + const closest = domSelector.closest.bind(domSelector); + window.Element.prototype.closest = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return closest(selector, this); + }; + + const querySelector = domSelector.querySelector.bind(domSelector); + window.Document.prototype.querySelector = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelector(selector, this); + }; + window.DocumentFragment.prototype.querySelector = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelector(selector, this); + }; + window.Element.prototype.querySelector = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelector(selector, this); + }; + + const querySelectorAll = domSelector.querySelectorAll.bind(domSelector); + window.Document.prototype.querySelectorAll = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelectorAll(selector, this); + }; + window.DocumentFragment.prototype.querySelectorAll = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelectorAll(selector, this); + }; + window.Element.prototype.querySelectorAll = function (...args) { + if (!args.length) { + throw new window.TypeError('1 argument required, but only 0 present.'); + } + const [selector] = args; + return querySelectorAll(selector, this); + }; + } +}); +``` + + +## Supported CSS selectors + +|Pattern|Supported|Note| +|:--------|:-------:|:--------| +|\*|✓| | +|E|✓| | +|ns\|E|✓| | +|\*\|E|✓| | +|\|E|✓| | +|E F|✓| | +|E > F|✓| | +|E + F|✓| | +|E ~ F|✓| | +|F \|\| E|Unsupported| | +|E.warning|✓| | +|E#myid|✓| | +|E\[foo\]|✓| | +|E\[foo="bar"\]|✓| | +|E\[foo="bar" i\]|✓| | +|E\[foo="bar" s\]|✓| | +|E\[foo~="bar"\]|✓| | +|E\[foo^="bar"\]|✓| | +|E\[foo$="bar"\]|✓| | +|E\[foo*="bar"\]|✓| | +|E\[foo\|="en"\]|✓| | +|E:is(s1, s2, …)|✓| | +|E:not(s1, s2, …)|✓| | +|E:where(s1, s2, …)|✓| | +|E:has(rs1, rs2, …)|✓| | +|E:defined|Partially supported|Matching with MathML is not yet supported.| +|E:dir(ltr)|✓| | +|E:lang(en)|✓| | +|E:any‑link|✓| | +|E:link|✓| | +|E:visited|✓|Returns `false` or `null` to prevent fingerprinting.| +|E:local‑link|✓| | +|E:target|✓| | +|E:target‑within|✓| | +|E:scope|✓| | +|E:hover|✓| | +|E:active|✓| | +|E:focus|✓| | +|E:focus‑visible|✓| | +|E:focus‑within|✓| | +|E:current|Unsupported| | +|E:current(s)|Unsupported| | +|E:past|Unsupported| | +|E:future|Unsupported| | +|E:open
E:closed|Partially supported|Matching with <select>, e.g. `select:open`, is not supported.| +|E:popover-open|✓| | +|E:enabled
E:disabled|✓| | +|E:read‑write
E:read‑only|✓| | +|E:placeholder‑shown|✓| | +|E:default|✓| | +|E:checked|✓| | +|E:indeterminate|✓| | +|E:blank|Unsupported| | +|E:valid
E:invalid|✓| | +|E:in-range
E:out-of-range|✓| | +|E:required
E:optional|✓| | +|E:user‑valid
E:user‑invalid|Unsupported| | +|E:root|✓| | +|E:empty|✓| | +|E:nth‑child(n [of S]?)|✓| | +|E:nth‑last‑child(n [of S]?)|✓| | +|E:first‑child|✓| | +|E:last‑child|✓| | +|E:only‑child|✓| | +|E:nth‑of‑type(n)|✓| | +|E:nth‑last‑of‑type(n)|✓| | +|E:first‑of‑type|✓| | +|E:last‑of‑type|✓| | +|E:only‑of‑type|✓| | +|E:nth‑col(n)|Unsupported| | +|E:nth‑last‑col(n)|Unsupported| | +|CE:state(v)|✓|*1| +|:host|✓| | +|:host(s)|✓| | +|:host(:state(v))|✓|*1| +|:host:has(rs1, rs2, ...)|✓| | +|:host(s):has(rs1, rs2, ...)|✓| | +|:host‑context(s)|✓| | +|:host‑context(s):has(rs1, rs2, ...)|✓| | +|&|✓|Only supports outermost `&`, i.e. equivalent to `:scope`| + +*1: `ElementInternals.states`, i.e. `CustomStateSet`, is not implemented in jsdom, so you need to apply a patch in the custom element constructor. + +``` javascript +class LabeledCheckbox extends window.HTMLElement { + #internals; + constructor() { + super(); + this.#internals = this.attachInternals(); + // patch CustomStateSet + if (!this.#internals.states) { + this.#internals.states = new Set(); + } + this.addEventListener('click', this._onClick.bind(this)); + } + get checked() { + return this.#internals.states.has('checked'); + } + set checked(flag) { + if (flag) { + this.#internals.states.add('checked'); + } else { + this.#internals.states.delete('checked'); + } + } + _onClick(event) { + this.checked = !this.checked; + } +} +``` + + +## Performance + +See [benchmark](https://github.com/asamuzaK/domSelector/actions/workflows/benchmark.yml) for the latest results. + + +## Acknowledgments + +The following resources have been of great help in the development of the DOM Selector. + +- [CSSTree](https://github.com/csstree/csstree) +- [selery](https://github.com/danburzo/selery) +- [jsdom](https://github.com/jsdom/jsdom) +- [nwsapi](https://github.com/dperini/nwsapi) + +--- +Copyright (c) 2023 [asamuzaK (Kazz)](https://github.com/asamuzaK/) + + +[1]: #matches +[2]: #parameters +[3]: #closest +[4]: #parameters-1 +[5]: #queryselector +[6]: #parameters-2 +[7]: #queryselectorall +[8]: #parameters-3 +[59]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String +[60]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +[61]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean +[62]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array +[63]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined +[64]: https://developer.mozilla.org/docs/Web/API/Element/matches +[65]: https://developer.mozilla.org/docs/Web/API/Element/closest +[66]: https://developer.mozilla.org/docs/Web/API/Document/querySelector +[67]: https://developer.mozilla.org/docs/Web/API/DocumentFragment/querySelector +[68]: https://developer.mozilla.org/docs/Web/API/Element/querySelector +[69]: https://developer.mozilla.org/docs/Web/API/Document/querySelectorAll +[70]: https://developer.mozilla.org/docs/Web/API/DocumentFragment/querySelectorAll +[71]: https://developer.mozilla.org/docs/Web/API/Element/querySelectorAll diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.cjs b/vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.cjs new file mode 100644 index 0000000..9505dd3 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.cjs @@ -0,0 +1,4622 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.js +var index_exports = {}; +__export(index_exports, { + DOMSelector: () => DOMSelector +}); +module.exports = __toCommonJS(index_exports); +var import_lru_cache = require("lru-cache"); + +// src/js/parser.js +var cssTree2 = __toESM(require("css-tree"), 1); + +// src/js/utility.js +var import_nwsapi = __toESM(require("@asamuzakjp/nwsapi"), 1); +var import_bidi_js = __toESM(require("bidi-js"), 1); +var cssTree = __toESM(require("css-tree"), 1); +var import_is_potential_custom_element_name = __toESM(require("is-potential-custom-element-name"), 1); + +// src/js/constant.js +var ATTR_SELECTOR = "AttributeSelector"; +var CLASS_SELECTOR = "ClassSelector"; +var COMBINATOR = "Combinator"; +var IDENT = "Identifier"; +var ID_SELECTOR = "IdSelector"; +var NOT_SUPPORTED_ERR = "NotSupportedError"; +var NTH = "Nth"; +var PS_CLASS_SELECTOR = "PseudoClassSelector"; +var PS_ELEMENT_SELECTOR = "PseudoElementSelector"; +var SELECTOR = "Selector"; +var STRING = "String"; +var SYNTAX_ERR = "SyntaxError"; +var TARGET_ALL = "all"; +var TARGET_FIRST = "first"; +var TARGET_LINEAL = "lineal"; +var TARGET_SELF = "self"; +var TYPE_SELECTOR = "TypeSelector"; +var BIT_01 = 1; +var BIT_02 = 2; +var BIT_04 = 4; +var BIT_08 = 8; +var BIT_16 = 16; +var BIT_32 = 32; +var BIT_FFFF = 65535; +var DUO = 2; +var HEX = 16; +var TYPE_FROM = 8; +var TYPE_TO = -1; +var ELEMENT_NODE = 1; +var TEXT_NODE = 3; +var DOCUMENT_NODE = 9; +var DOCUMENT_FRAGMENT_NODE = 11; +var DOCUMENT_POSITION_PRECEDING = 2; +var DOCUMENT_POSITION_CONTAINS = 8; +var SHOW_ALL = 4294967295; +var SHOW_CONTAINER = 1281; +var ALPHA_NUM = "[A-Z\\d]+"; +var CHILD_IDX = "(?:first|last|only)-(?:child|of-type)"; +var DIGIT = "(?:0|[1-9]\\d*)"; +var LANG_PART = `(?:-${ALPHA_NUM})*`; +var PSEUDO_CLASS = `(?:any-)?link|${CHILD_IDX}|checked|empty|indeterminate|read-(?:only|write)|target`; +var ANB = `[+-]?(?:${DIGIT}n?|n)|(?:[+-]?${DIGIT})?n\\s*[+-]\\s*${DIGIT}`; +var COMBO = "\\s?[\\s>~+]\\s?"; +var DESCEND = "\\s?[\\s>]\\s?"; +var SIBLING = "\\s?[+~]\\s?"; +var LOGIC_IS = `:is\\(\\s*[^)]+\\s*\\)`; +var N_TH = `nth-(?:last-)?(?:child|of-type)\\(\\s*(?:even|odd|${ANB})\\s*\\)`; +var SUB_TYPE = "\\[[^|\\]]+\\]|[#.:][\\w-]+"; +var SUB_TYPE_WO_PSEUDO = "\\[[^|\\]]+\\]|[#.][\\w-]+"; +var TAG_TYPE = "\\*|[A-Za-z][\\w-]*"; +var TAG_TYPE_I = "\\*|[A-Z][\\w-]*"; +var COMPOUND = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE})+)`; +var COMPOUND_L = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE}|${LOGIC_IS})+)`; +var COMPOUND_I = `(?:${TAG_TYPE_I}|(?:${TAG_TYPE_I})?(?:${SUB_TYPE})+)`; +var COMPOUND_WO_PSEUDO = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE_WO_PSEUDO})+)`; +var COMPLEX = `${COMPOUND}(?:${COMBO}${COMPOUND})*`; +var COMPLEX_L = `${COMPOUND_L}(?:${COMBO}${COMPOUND_L})*`; +var HAS_COMPOUND = `has\\([\\s>]?\\s*${COMPOUND_WO_PSEUDO}\\s*\\)`; +var LOGIC_COMPOUND = `(?:is|not)\\(\\s*${COMPOUND_L}(?:\\s*,\\s*${COMPOUND_L})*\\s*\\)`; +var LOGIC_COMPLEX = `(?:is|not)\\(\\s*${COMPLEX_L}(?:\\s*,\\s*${COMPLEX_L})*\\s*\\)`; +var FORM_PARTS = Object.freeze([ + "button", + "input", + "select", + "textarea" +]); +var INPUT_BUTTON = Object.freeze(["button", "reset", "submit"]); +var INPUT_CHECK = Object.freeze(["checkbox", "radio"]); +var INPUT_DATE = Object.freeze([ + "date", + "datetime-local", + "month", + "time", + "week" +]); +var INPUT_TEXT = Object.freeze([ + "email", + "password", + "search", + "tel", + "text", + "url" +]); +var INPUT_EDIT = Object.freeze([ + ...INPUT_DATE, + ...INPUT_TEXT, + "number" +]); +var INPUT_LTR = Object.freeze([ + ...INPUT_CHECK, + "color", + "date", + "image", + "number", + "range", + "time" +]); +var KEYS_LOGICAL = /* @__PURE__ */ new Set(["has", "is", "not", "where"]); + +// src/js/utility.js +var KEYS_DIR_AUTO = /* @__PURE__ */ new Set([...INPUT_BUTTON, ...INPUT_TEXT, "hidden"]); +var KEYS_DIR_LTR = new Set(INPUT_LTR); +var KEYS_INPUT_EDIT = new Set(INPUT_EDIT); +var KEYS_NODE_DIR_EXCLUDE = /* @__PURE__ */ new Set(["bdi", "script", "style", "textarea"]); +var KEYS_NODE_FOCUSABLE = /* @__PURE__ */ new Set(["button", "select", "textarea"]); +var KEYS_NODE_FOCUSABLE_SVG = /* @__PURE__ */ new Set([ + "clipPath", + "defs", + "desc", + "linearGradient", + "marker", + "mask", + "metadata", + "pattern", + "radialGradient", + "script", + "style", + "symbol", + "title" +]); +var REG_EXCLUDE_BASIC = /[|\\]|::|[^\u0021-\u007F\s]|\[\s*[\w$*=^|~-]+(?:(?:"[\w$*=^|~\s'-]+"|'[\w$*=^|~\s"-]+')?(?:\s+[\w$*=^|~-]+)+|"[^"\]]{1,255}|'[^'\]]{1,255})\s*\]|:(?:is|where)\(\s*\)/; +var REG_COMPLEX = new RegExp(`${COMPOUND_I}${COMBO}${COMPOUND_I}`, "i"); +var REG_DESCEND = new RegExp(`${COMPOUND_I}${DESCEND}${COMPOUND_I}`, "i"); +var REG_SIBLING = new RegExp(`${COMPOUND_I}${SIBLING}${COMPOUND_I}`, "i"); +var REG_LOGIC_COMPLEX = new RegExp( + `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPLEX})` +); +var REG_LOGIC_COMPOUND = new RegExp( + `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND})` +); +var REG_LOGIC_HAS_COMPOUND = new RegExp( + `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND}|${HAS_COMPOUND})` +); +var REG_END_WITH_HAS = new RegExp(`:${HAS_COMPOUND}$`); +var REG_WO_LOGICAL = new RegExp(`:(?!${PSEUDO_CLASS}|${N_TH})`); +var REG_IS_HTML = /^(?:application\/xhtml\+x|text\/ht)ml$/; +var REG_IS_XML = /^(?:application\/(?:[\w\-.]+\+)?|image\/[\w\-.]+\+|text\/)xml$/; +var getType = (o) => Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO); +var generateException = (msg, name, globalObject = globalThis) => { + return new globalObject.DOMException(msg, name); +}; +var findNestedHas = (leaf) => { + return leaf.name === "has"; +}; +var findLogicalWithNestedHas = (leaf) => { + if (KEYS_LOGICAL.has(leaf.name) && cssTree.find(leaf, findNestedHas)) { + return leaf; + } + return null; +}; +var filterNodesByAnB = (nodes, anb) => { + const { a, b, reverse } = anb; + const processedNodes = reverse ? [...nodes].reverse() : nodes; + const l = nodes.length; + const matched = []; + if (a === 0) { + if (b > 0 && b <= l) { + matched.push(processedNodes[b - 1]); + } + return matched; + } + let startIndex = b - 1; + if (a > 0) { + while (startIndex < 0) { + startIndex += a; + } + for (let i = startIndex; i < l; i += a) { + matched.push(processedNodes[i]); + } + } else if (startIndex >= 0) { + for (let i = startIndex; i >= 0; i += a) { + matched.push(processedNodes[i]); + } + return matched.reverse(); + } + return matched; +}; +var resolveContent = (node) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + let document; + let root; + let shadow; + switch (node.nodeType) { + case DOCUMENT_NODE: { + document = node; + root = node; + break; + } + case DOCUMENT_FRAGMENT_NODE: { + const { host, mode, ownerDocument } = node; + document = ownerDocument; + root = node; + shadow = host && (mode === "close" || mode === "open"); + break; + } + case ELEMENT_NODE: { + document = node.ownerDocument; + let refNode = node; + while (refNode) { + const { host, mode, nodeType, parentNode } = refNode; + if (nodeType === DOCUMENT_FRAGMENT_NODE) { + shadow = host && (mode === "close" || mode === "open"); + break; + } else if (parentNode) { + refNode = parentNode; + } else { + break; + } + } + root = refNode; + break; + } + default: { + throw new TypeError(`Unexpected node ${node.nodeName}`); + } + } + return [document, root, !!shadow]; +}; +var traverseNode = (node, walker, force = false) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (!walker) { + return null; + } + let refNode = walker.currentNode; + if (refNode === node) { + return refNode; + } else if (force || refNode.contains(node)) { + refNode = walker.nextNode(); + while (refNode) { + if (refNode === node) { + break; + } + refNode = walker.nextNode(); + } + return refNode; + } else { + if (refNode !== walker.root) { + let bool; + while (refNode) { + if (refNode === node) { + bool = true; + break; + } else if (refNode === walker.root || refNode.contains(node)) { + break; + } + refNode = walker.parentNode(); + } + if (bool) { + return refNode; + } + } + if (node.nodeType === ELEMENT_NODE) { + let bool; + while (refNode) { + if (refNode === node) { + bool = true; + break; + } + refNode = walker.nextNode(); + } + if (bool) { + return refNode; + } + } + } + return null; +}; +var isCustomElement = (node, opt = {}) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return false; + } + const { localName, ownerDocument } = node; + const { formAssociated } = opt; + const window = ownerDocument.defaultView; + let elmConstructor; + const attr = node.getAttribute("is"); + if (attr) { + elmConstructor = (0, import_is_potential_custom_element_name.default)(attr) && window.customElements.get(attr); + } else { + elmConstructor = (0, import_is_potential_custom_element_name.default)(localName) && window.customElements.get(localName); + } + if (elmConstructor) { + if (formAssociated) { + return !!elmConstructor.formAssociated; + } + return true; + } + return false; +}; +var getSlottedTextContent = (node) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (typeof node.assignedNodes !== "function") { + return null; + } + const nodes = node.assignedNodes(); + if (nodes.length) { + let text = ""; + const l = nodes.length; + for (let i = 0; i < l; i++) { + const item = nodes[i]; + text = item.textContent.trim(); + if (text) { + break; + } + } + return text; + } + return node.textContent.trim(); +}; +var getDirectionality = (node) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return null; + } + const { dir: dirAttr, localName, parentNode } = node; + const { getEmbeddingLevels } = (0, import_bidi_js.default)(); + if (dirAttr === "ltr" || dirAttr === "rtl") { + return dirAttr; + } else if (dirAttr === "auto") { + let text = ""; + switch (localName) { + case "input": { + if (!node.type || KEYS_DIR_AUTO.has(node.type)) { + text = node.value; + } else if (KEYS_DIR_LTR.has(node.type)) { + return "ltr"; + } + break; + } + case "slot": { + text = getSlottedTextContent(node); + break; + } + case "textarea": { + text = node.value; + break; + } + default: { + const items = [].slice.call(node.childNodes); + for (const item of items) { + const { + dir: itemDir, + localName: itemLocalName, + nodeType: itemNodeType, + textContent: itemTextContent + } = item; + if (itemNodeType === TEXT_NODE) { + text = itemTextContent.trim(); + } else if (itemNodeType === ELEMENT_NODE && !KEYS_NODE_DIR_EXCLUDE.has(itemLocalName) && (!itemDir || itemDir !== "ltr" && itemDir !== "rtl")) { + if (itemLocalName === "slot") { + text = getSlottedTextContent(item); + } else { + text = itemTextContent.trim(); + } + } + if (text) { + break; + } + } + } + } + if (text) { + const { + paragraphs: [{ level }] + } = getEmbeddingLevels(text); + if (level % 2 === 1) { + return "rtl"; + } + } else if (parentNode) { + const { nodeType: parentNodeType } = parentNode; + if (parentNodeType === ELEMENT_NODE) { + return getDirectionality(parentNode); + } + } + } else if (localName === "input" && node.type === "tel") { + return "ltr"; + } else if (localName === "bdi") { + const text = node.textContent.trim(); + if (text) { + const { + paragraphs: [{ level }] + } = getEmbeddingLevels(text); + if (level % 2 === 1) { + return "rtl"; + } + } + } else if (parentNode) { + if (localName === "slot") { + const text = getSlottedTextContent(node); + if (text) { + const { + paragraphs: [{ level }] + } = getEmbeddingLevels(text); + if (level % 2 === 1) { + return "rtl"; + } + return "ltr"; + } + } + const { nodeType: parentNodeType } = parentNode; + if (parentNodeType === ELEMENT_NODE) { + return getDirectionality(parentNode); + } + } + return "ltr"; +}; +var getLanguageAttribute = (node) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return null; + } + const { contentType } = node.ownerDocument; + const isHtml = REG_IS_HTML.test(contentType); + const isXml = REG_IS_XML.test(contentType); + let isShadow = false; + let current = node; + while (current) { + switch (current.nodeType) { + case ELEMENT_NODE: { + if (isHtml && current.hasAttribute("lang")) { + return current.getAttribute("lang"); + } else if (isXml && current.hasAttribute("xml:lang")) { + return current.getAttribute("xml:lang"); + } + break; + } + case DOCUMENT_FRAGMENT_NODE: { + if (current.host) { + isShadow = true; + } + break; + } + case DOCUMENT_NODE: + default: { + return null; + } + } + if (isShadow) { + current = current.host; + isShadow = false; + } else if (current.parentNode) { + current = current.parentNode; + } else { + break; + } + } + return null; +}; +var isContentEditable = (node) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return false; + } + if (typeof node.isContentEditable === "boolean") { + return node.isContentEditable; + } else if (node.ownerDocument.designMode === "on") { + return true; + } else { + let attr; + if (node.hasAttribute("contenteditable")) { + attr = node.getAttribute("contenteditable"); + } else { + attr = "inherit"; + } + switch (attr) { + case "": + case "true": { + return true; + } + case "plaintext-only": { + return true; + } + case "false": { + return false; + } + default: { + if (node?.parentNode?.nodeType === ELEMENT_NODE) { + return isContentEditable(node.parentNode); + } + return false; + } + } + } +}; +var isVisible = (node) => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + const window = node.ownerDocument.defaultView; + const { display, visibility } = window.getComputedStyle(node); + if (display !== "none" && visibility === "visible") { + return true; + } + return false; +}; +var isFocusVisible = (node) => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + const { localName, type } = node; + switch (localName) { + case "input": { + if (!type || KEYS_INPUT_EDIT.has(type)) { + return true; + } + return false; + } + case "textarea": { + return true; + } + default: { + return isContentEditable(node); + } + } +}; +var isFocusableArea = (node) => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + if (!node.isConnected) { + return false; + } + const window = node.ownerDocument.defaultView; + if (node instanceof window.HTMLElement) { + if (Number.isInteger(parseInt(node.getAttribute("tabindex")))) { + return true; + } + if (isContentEditable(node)) { + return true; + } + const { localName, parentNode } = node; + switch (localName) { + case "a": { + if (node.href || node.hasAttribute("href")) { + return true; + } + return false; + } + case "iframe": { + return true; + } + case "input": { + if (node.disabled || node.hasAttribute("disabled") || node.hidden || node.hasAttribute("hidden")) { + return false; + } + return true; + } + case "summary": { + if (parentNode.localName === "details") { + let child = parentNode.firstElementChild; + let bool = false; + while (child) { + if (child.localName === "summary") { + bool = child === node; + break; + } + child = child.nextElementSibling; + } + return bool; + } + return false; + } + default: { + if (KEYS_NODE_FOCUSABLE.has(localName) && !(node.disabled || node.hasAttribute("disabled"))) { + return true; + } + } + } + } else if (node instanceof window.SVGElement) { + if (Number.isInteger(parseInt(node.getAttributeNS(null, "tabindex")))) { + const ns = "http://www.w3.org/2000/svg"; + let bool; + let refNode = node; + while (refNode.namespaceURI === ns) { + bool = KEYS_NODE_FOCUSABLE_SVG.has(refNode.localName); + if (bool) { + break; + } + if (refNode?.parentNode?.namespaceURI === ns) { + refNode = refNode.parentNode; + } else { + break; + } + } + if (bool) { + return false; + } + return true; + } + if (node.localName === "a" && (node.href || node.hasAttributeNS(null, "href"))) { + return true; + } + } + return false; +}; +var getNamespaceURI = (ns, node) => { + if (typeof ns !== "string") { + throw new TypeError(`Unexpected type ${getType(ns)}`); + } else if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (!ns || node.nodeType !== ELEMENT_NODE) { + return null; + } + const { attributes } = node; + let res; + for (const attr of attributes) { + const { name, namespaceURI, prefix, value } = attr; + if (name === `xmlns:${ns}`) { + res = value; + } else if (prefix === ns) { + res = namespaceURI; + } + if (res) { + break; + } + } + return res ?? null; +}; +var isNamespaceDeclared = (ns = "", node = {}) => { + if (!ns || typeof ns !== "string" || node?.nodeType !== ELEMENT_NODE) { + return false; + } + if (node.lookupNamespaceURI(ns)) { + return true; + } + const root = node.ownerDocument.documentElement; + let parent = node; + let res; + while (parent) { + res = getNamespaceURI(ns, parent); + if (res || parent === root) { + break; + } + parent = parent.parentNode; + } + return !!res; +}; +var isPreceding = (nodeA, nodeB) => { + if (!nodeA?.nodeType) { + throw new TypeError(`Unexpected type ${getType(nodeA)}`); + } else if (!nodeB?.nodeType) { + throw new TypeError(`Unexpected type ${getType(nodeB)}`); + } + if (nodeA.nodeType !== ELEMENT_NODE || nodeB.nodeType !== ELEMENT_NODE) { + return false; + } + const posBit = nodeB.compareDocumentPosition(nodeA); + const res = posBit & DOCUMENT_POSITION_PRECEDING || posBit & DOCUMENT_POSITION_CONTAINS; + return !!res; +}; +var compareNodes = (a, b) => { + if (isPreceding(b, a)) { + return 1; + } + return -1; +}; +var sortNodes = (nodes = []) => { + const arr = [...nodes]; + if (arr.length > 1) { + arr.sort(compareNodes); + } + return arr; +}; +var initNwsapi = (window, document) => { + if (!window?.DOMException) { + throw new TypeError(`Unexpected global object ${getType(window)}`); + } + if (document?.nodeType !== DOCUMENT_NODE) { + document = window.document; + } + const nw = (0, import_nwsapi.default)({ + document, + DOMException: window.DOMException + }); + nw.configure({ + LOGERRORS: false + }); + return nw; +}; +var filterSelector = (selector, target) => { + const isQuerySelectorType = target === TARGET_FIRST || target === TARGET_ALL; + if (!selector || typeof selector !== "string" || /null|undefined/.test(selector)) { + return false; + } + if (selector.includes("[")) { + const index = selector.lastIndexOf("["); + const sel = selector.substring(index); + if (sel.indexOf("]") < 0) { + return false; + } + } + if (selector.includes("/") || REG_EXCLUDE_BASIC.test(selector)) { + return false; + } + if (selector.includes(":")) { + let complex = false; + if (target !== isQuerySelectorType) { + complex = REG_COMPLEX.test(selector); + } + if (isQuerySelectorType && REG_DESCEND.test(selector) && !REG_SIBLING.test(selector)) { + return false; + } else if (!isQuerySelectorType && /:has\(/.test(selector)) { + if (!complex || REG_LOGIC_HAS_COMPOUND.test(selector)) { + return false; + } + return REG_END_WITH_HAS.test(selector); + } else if (/:(?:is|not)\(/.test(selector)) { + if (complex) { + return !REG_LOGIC_COMPLEX.test(selector); + } else { + return !REG_LOGIC_COMPOUND.test(selector); + } + } else { + return !REG_WO_LOGICAL.test(selector); + } + } + return true; +}; + +// src/js/parser.js +var import_css_tree = require("css-tree"); +var AST_SORT_ORDER = /* @__PURE__ */ new Map([ + [PS_ELEMENT_SELECTOR, BIT_01], + [ID_SELECTOR, BIT_02], + [CLASS_SELECTOR, BIT_04], + [TYPE_SELECTOR, BIT_08], + [ATTR_SELECTOR, BIT_16], + [PS_CLASS_SELECTOR, BIT_32] +]); +var KEYS_PS_CLASS_STATE = /* @__PURE__ */ new Set([ + "checked", + "closed", + "disabled", + "empty", + "enabled", + "in-range", + "indeterminate", + "invalid", + "open", + "out-of-range", + "placeholder-shown", + "read-only", + "read-write", + "valid" +]); +var KEYS_SHADOW_HOST = /* @__PURE__ */ new Set(["host", "host-context"]); +var REG_EMPTY_PS_FUNC = /(?<=:(?:dir|has|host(?:-context)?|is|lang|not|nth-(?:last-)?(?:child|of-type)|where))\(\s+\)/g; +var REG_SHADOW_PS_ELEMENT = /^part|slotted$/; +var U_FFFD = "\uFFFD"; +var unescapeSelector = (selector = "") => { + if (typeof selector === "string" && selector.indexOf("\\", 0) >= 0) { + const arr = selector.split("\\"); + const selectorItems = [arr[0]]; + const l = arr.length; + for (let i = 1; i < l; i++) { + const item = arr[i]; + if (item === "" && i === l - 1) { + selectorItems.push(U_FFFD); + } else { + const hexExists = /^([\da-f]{1,6}\s?)/i.exec(item); + if (hexExists) { + const [, hex] = hexExists; + let str; + try { + const low = parseInt("D800", HEX); + const high = parseInt("DFFF", HEX); + const deci = parseInt(hex, HEX); + if (deci === 0 || deci >= low && deci <= high) { + str = U_FFFD; + } else { + str = String.fromCodePoint(deci); + } + } catch (e) { + str = U_FFFD; + } + let postStr = ""; + if (item.length > hex.length) { + postStr = item.substring(hex.length); + } + selectorItems.push(`${str}${postStr}`); + } else if (/^[\n\r\f]/.test(item)) { + selectorItems.push(`\\${item}`); + } else { + selectorItems.push(item); + } + } + } + return selectorItems.join(""); + } + return selector; +}; +var preprocess = (value) => { + if (typeof value !== "string") { + if (value === void 0 || value === null) { + return getType(value).toLowerCase(); + } else if (Array.isArray(value)) { + return value.join(","); + } else if (Object.hasOwn(value, "toString")) { + return value.toString(); + } else { + throw new DOMException(`Invalid selector ${value}`, SYNTAX_ERR); + } + } + let selector = value; + let index = 0; + while (index >= 0) { + index = selector.indexOf("#", index); + if (index < 0) { + break; + } + const preHash = selector.substring(0, index + 1); + let postHash = selector.substring(index + 1); + const codePoint = postHash.codePointAt(0); + if (codePoint > BIT_FFFF) { + const str = `\\${codePoint.toString(HEX)} `; + if (postHash.length === DUO) { + postHash = str; + } else { + postHash = `${str}${postHash.substring(DUO)}`; + } + } + selector = `${preHash}${postHash}`; + index++; + } + return selector.replace(/\f|\r\n?/g, "\n").replace(/[\0\uD800-\uDFFF]|\\$/g, U_FFFD).replace(/\x26/g, ":scope"); +}; +var parseSelector = (sel) => { + const selector = preprocess(sel); + if (/^$|^\s*>|,\s*$/.test(selector)) { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + try { + const ast = cssTree2.parse(selector, { + context: "selectorList", + parseCustomProperty: true + }); + return cssTree2.toPlainObject(ast); + } catch (e) { + const { message } = e; + if (/^(?:"\]"|Attribute selector [()\s,=~^$*|]+) is expected$/.test( + message + ) && !selector.endsWith("]")) { + const index = selector.lastIndexOf("["); + const selPart = selector.substring(index); + if (selPart.includes('"')) { + const quotes = selPart.match(/"/g).length; + if (quotes % 2) { + return parseSelector(`${selector}"]`); + } + return parseSelector(`${selector}]`); + } + return parseSelector(`${selector}]`); + } else if (message === '")" is expected') { + if (REG_EMPTY_PS_FUNC.test(selector)) { + return parseSelector(`${selector.replaceAll(REG_EMPTY_PS_FUNC, "()")}`); + } else if (!selector.endsWith(")")) { + return parseSelector(`${selector})`); + } else { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + } else { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + } +}; +var walkAST = (ast = {}) => { + const branches = /* @__PURE__ */ new Set(); + const info = { + hasForgivenPseudoFunc: false, + hasHasPseudoFunc: false, + hasLogicalPseudoFunc: false, + hasNotPseudoFunc: false, + hasNthChildOfSelector: false, + hasNestedSelector: false, + hasStatePseudoClass: false + }; + const opt = { + enter(node) { + switch (node.type) { + case CLASS_SELECTOR: { + if (/^-?\d/.test(node.name)) { + throw new DOMException( + `Invalid selector .${node.name}`, + SYNTAX_ERR + ); + } + break; + } + case ID_SELECTOR: { + if (/^-?\d/.test(node.name)) { + throw new DOMException( + `Invalid selector #${node.name}`, + SYNTAX_ERR + ); + } + break; + } + case PS_CLASS_SELECTOR: { + if (KEYS_LOGICAL.has(node.name)) { + info.hasNestedSelector = true; + info.hasLogicalPseudoFunc = true; + if (node.name === "has") { + info.hasHasPseudoFunc = true; + } else if (node.name === "not") { + info.hasNotPseudoFunc = true; + } else { + info.hasForgivenPseudoFunc = true; + } + } else if (KEYS_PS_CLASS_STATE.has(node.name)) { + info.hasStatePseudoClass = true; + } else if (KEYS_SHADOW_HOST.has(node.name) && Array.isArray(node.children) && node.children.length) { + info.hasNestedSelector = true; + } + break; + } + case PS_ELEMENT_SELECTOR: { + if (REG_SHADOW_PS_ELEMENT.test(node.name)) { + info.hasNestedSelector = true; + } + break; + } + case NTH: { + if (node.selector) { + info.hasNestedSelector = true; + info.hasNthChildOfSelector = true; + } + break; + } + case SELECTOR: { + branches.add(node.children); + break; + } + default: + } + } + }; + cssTree2.walk(ast, opt); + if (info.hasNestedSelector === true) { + cssTree2.findAll(ast, (node, item, list) => { + if (list) { + if (node.type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(node.name)) { + const itemList = list.filter((i) => { + const { name, type } = i; + return type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(name); + }); + for (const { children } of itemList) { + for (const { children: grandChildren } of children) { + for (const { children: greatGrandChildren } of grandChildren) { + if (branches.has(greatGrandChildren)) { + branches.delete(greatGrandChildren); + } + } + } + } + } else if (node.type === PS_CLASS_SELECTOR && KEYS_SHADOW_HOST.has(node.name) && Array.isArray(node.children) && node.children.length) { + const itemList = list.filter((i) => { + const { children, name, type } = i; + const res = type === PS_CLASS_SELECTOR && KEYS_SHADOW_HOST.has(name) && Array.isArray(children) && children.length; + return res; + }); + for (const { children } of itemList) { + for (const { children: grandChildren } of children) { + if (branches.has(grandChildren)) { + branches.delete(grandChildren); + } + } + } + } else if (node.type === PS_ELEMENT_SELECTOR && REG_SHADOW_PS_ELEMENT.test(node.name)) { + const itemList = list.filter((i) => { + const { name, type } = i; + const res = type === PS_ELEMENT_SELECTOR && REG_SHADOW_PS_ELEMENT.test(name); + return res; + }); + for (const { children } of itemList) { + for (const { children: grandChildren } of children) { + if (branches.has(grandChildren)) { + branches.delete(grandChildren); + } + } + } + } else if (node.type === NTH && node.selector) { + const itemList = list.filter((i) => { + const { selector, type } = i; + const res = type === NTH && selector; + return res; + }); + for (const { selector } of itemList) { + const { children } = selector; + for (const { children: grandChildren } of children) { + if (branches.has(grandChildren)) { + branches.delete(grandChildren); + } + } + } + } + } + }); + } + return { + info, + branches: [...branches] + }; +}; +var compareASTNodes = (a, b) => { + const bitA = AST_SORT_ORDER.get(a.type); + const bitB = AST_SORT_ORDER.get(b.type); + if (bitA === bitB) { + return 0; + } else if (bitA > bitB) { + return 1; + } else { + return -1; + } +}; +var sortAST = (asts) => { + const arr = [...asts]; + if (arr.length > 1) { + arr.sort(compareASTNodes); + } + return arr; +}; +var parseAstName = (selector) => { + let prefix; + let localName; + if (selector && typeof selector === "string") { + if (selector.indexOf("|") > -1) { + [prefix, localName] = selector.split("|"); + } else { + prefix = "*"; + localName = selector; + } + } else { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + return { + prefix, + localName + }; +}; + +// src/js/matcher.js +var KEYS_FORM_PS_DISABLED = /* @__PURE__ */ new Set([ + ...FORM_PARTS, + "fieldset", + "optgroup", + "option" +]); +var KEYS_INPUT_EDIT2 = new Set(INPUT_EDIT); +var REG_LANG_VALID = new RegExp(`^(?:\\*-)?${ALPHA_NUM}${LANG_PART}$`, "i"); +var REG_TAG_NAME = /[A-Z][\\w-]*/i; +var matchPseudoElementSelector = (astName, astType, opt = {}) => { + const { forgive, globalObject, warn } = opt; + if (astType !== PS_ELEMENT_SELECTOR) { + throw new TypeError(`Unexpected ast type ${getType(astType)}`); + } + switch (astName) { + case "after": + case "backdrop": + case "before": + case "cue": + case "cue-region": + case "first-letter": + case "first-line": + case "file-selector-button": + case "marker": + case "placeholder": + case "selection": + case "target-text": { + if (warn) { + throw generateException( + `Unsupported pseudo-element ::${astName}`, + NOT_SUPPORTED_ERR, + globalObject + ); + } + break; + } + case "part": + case "slotted": { + if (warn) { + throw generateException( + `Unsupported pseudo-element ::${astName}()`, + NOT_SUPPORTED_ERR, + globalObject + ); + } + break; + } + default: { + if (astName.startsWith("-webkit-")) { + if (warn) { + throw generateException( + `Unsupported pseudo-element ::${astName}`, + NOT_SUPPORTED_ERR, + globalObject + ); + } + } else if (!forgive) { + throw generateException( + `Unknown pseudo-element ::${astName}`, + SYNTAX_ERR, + globalObject + ); + } + } + } +}; +var matchDirectionPseudoClass = (ast, node) => { + const { name } = ast; + if (!name) { + const type = name === "" ? "(empty String)" : getType(name); + throw new TypeError(`Unexpected ast type ${type}`); + } + const dir = getDirectionality(node); + return name === dir; +}; +var matchLanguagePseudoClass = (ast, node) => { + const { name, type, value } = ast; + let langPattern; + if (type === STRING && value) { + langPattern = value; + } else if (type === IDENT && name) { + langPattern = unescapeSelector(name); + } + if (typeof langPattern !== "string") { + return false; + } + const elementLang = getLanguageAttribute(node); + if (elementLang === null) { + return false; + } + if (langPattern === "*") { + return elementLang !== ""; + } + if (!REG_LANG_VALID.test(langPattern)) { + return false; + } + let matcherRegex; + if (langPattern.indexOf("-") > -1) { + const [langMain, langSub, ...langRest] = langPattern.split("-"); + const extendedMain = langMain === "*" ? `${ALPHA_NUM}${LANG_PART}` : `${langMain}${LANG_PART}`; + const extendedSub = `-${langSub}${LANG_PART}`; + let extendedRest = ""; + for (let i = 0; i < langRest.length; i++) { + extendedRest += `-${langRest[i]}${LANG_PART}`; + } + matcherRegex = new RegExp( + `^${extendedMain}${extendedSub}${extendedRest}$`, + "i" + ); + } else { + matcherRegex = new RegExp(`^${langPattern}${LANG_PART}$`, "i"); + } + return matcherRegex.test(elementLang); +}; +var matchDisabledPseudoClass = (astName, node) => { + const { localName, parentNode } = node; + if (!KEYS_FORM_PS_DISABLED.has(localName) && !isCustomElement(node, { formAssociated: true })) { + return false; + } + let isDisabled = false; + if (node.disabled || node.hasAttribute("disabled")) { + isDisabled = true; + } else if (localName === "option") { + if (parentNode && parentNode.localName === "optgroup" && (parentNode.disabled || parentNode.hasAttribute("disabled"))) { + isDisabled = true; + } + } else if (localName !== "optgroup") { + let current = parentNode; + while (current) { + if (current.localName === "fieldset" && (current.disabled || current.hasAttribute("disabled"))) { + let legend; + let element = current.firstElementChild; + while (element) { + if (element.localName === "legend") { + legend = element; + break; + } + element = element.nextElementSibling; + } + if (!legend || !legend.contains(node)) { + isDisabled = true; + } + break; + } + current = current.parentNode; + } + } + if (astName === "disabled") { + return isDisabled; + } + return !isDisabled; +}; +var matchReadOnlyPseudoClass = (astName, node) => { + const { localName } = node; + let isReadOnly = false; + switch (localName) { + case "textarea": + case "input": { + const isEditableInput = !node.type || KEYS_INPUT_EDIT2.has(node.type); + if (localName === "textarea" || isEditableInput) { + isReadOnly = node.readOnly || node.hasAttribute("readonly") || node.disabled || node.hasAttribute("disabled"); + } else { + isReadOnly = true; + } + break; + } + default: { + isReadOnly = !isContentEditable(node); + } + } + if (astName === "read-only") { + return isReadOnly; + } + return !isReadOnly; +}; +var matchAttributeSelector = (ast, node, opt = {}) => { + const { + flags: astFlags, + matcher: astMatcher, + name: astName, + value: astValue + } = ast; + const { check, forgive, globalObject } = opt; + if (typeof astFlags === "string" && !/^[is]$/i.test(astFlags) && !forgive) { + const css = (0, import_css_tree.generate)(ast); + throw generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + globalObject + ); + } + const { attributes } = node; + if (!attributes || !attributes.length) { + return false; + } + const contentType = node.ownerDocument.contentType; + let caseInsensitive; + if (contentType === "text/html") { + if (typeof astFlags === "string" && /^s$/i.test(astFlags)) { + caseInsensitive = false; + } else { + caseInsensitive = true; + } + } else if (typeof astFlags === "string" && /^i$/i.test(astFlags)) { + caseInsensitive = true; + } else { + caseInsensitive = false; + } + let astAttrName = unescapeSelector(astName.name); + if (caseInsensitive) { + astAttrName = astAttrName.toLowerCase(); + } + const attrValues = /* @__PURE__ */ new Set(); + if (astAttrName.indexOf("|") > -1) { + const { prefix: astPrefix, localName: astLocalName } = parseAstName(astAttrName); + for (const item of attributes) { + let { name: itemName, value: itemValue } = item; + if (caseInsensitive) { + itemName = itemName.toLowerCase(); + itemValue = itemValue.toLowerCase(); + } + switch (astPrefix) { + case "": { + if (astLocalName === itemName) { + attrValues.add(itemValue); + } + break; + } + case "*": { + if (itemName.indexOf(":") > -1) { + const [, ...restItemName] = itemName.split(":"); + const itemLocalName = restItemName.join(":").replace(/^:/, ""); + if (itemLocalName === astLocalName) { + attrValues.add(itemValue); + } + } else if (astLocalName === itemName) { + attrValues.add(itemValue); + } + break; + } + default: { + if (!check) { + if (forgive) { + return false; + } + const css = (0, import_css_tree.generate)(ast); + throw generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + globalObject + ); + } + if (itemName.indexOf(":") > -1) { + const [itemPrefix, ...restItemName] = itemName.split(":"); + const itemLocalName = restItemName.join(":").replace(/^:/, ""); + if (itemPrefix === "xml" && itemLocalName === "lang") { + continue; + } else if (astPrefix === itemPrefix && astLocalName === itemLocalName) { + const namespaceDeclared = isNamespaceDeclared(astPrefix, node); + if (namespaceDeclared) { + attrValues.add(itemValue); + } + } + } + } + } + } + } else { + for (let { name: itemName, value: itemValue } of attributes) { + if (caseInsensitive) { + itemName = itemName.toLowerCase(); + itemValue = itemValue.toLowerCase(); + } + if (itemName.indexOf(":") > -1) { + const [itemPrefix, ...restItemName] = itemName.split(":"); + const itemLocalName = restItemName.join(":").replace(/^:/, ""); + if (!itemPrefix && astAttrName === `:${itemLocalName}`) { + attrValues.add(itemValue); + } else if (itemPrefix === "xml" && itemLocalName === "lang") { + continue; + } else if (astAttrName === itemLocalName) { + attrValues.add(itemValue); + } + } else if (astAttrName === itemName) { + attrValues.add(itemValue); + } + } + } + if (!attrValues.size) { + return false; + } + const { name: astIdentValue, value: astStringValue } = astValue ?? {}; + let attrValue; + if (astIdentValue) { + if (caseInsensitive) { + attrValue = astIdentValue.toLowerCase(); + } else { + attrValue = astIdentValue; + } + } else if (astStringValue) { + if (caseInsensitive) { + attrValue = astStringValue.toLowerCase(); + } else { + attrValue = astStringValue; + } + } else if (astStringValue === "") { + attrValue = astStringValue; + } + switch (astMatcher) { + case "=": { + return typeof attrValue === "string" && attrValues.has(attrValue); + } + case "~=": { + if (attrValue && typeof attrValue === "string") { + for (const value of attrValues) { + const item = new Set(value.split(/\s+/)); + if (item.has(attrValue)) { + return true; + } + } + } + return false; + } + case "|=": { + if (attrValue && typeof attrValue === "string") { + for (const value of attrValues) { + if (value === attrValue || value.startsWith(`${attrValue}-`)) { + return true; + } + } + } + return false; + } + case "^=": { + if (attrValue && typeof attrValue === "string") { + for (const value of attrValues) { + if (value.startsWith(`${attrValue}`)) { + return true; + } + } + } + return false; + } + case "$=": { + if (attrValue && typeof attrValue === "string") { + for (const value of attrValues) { + if (value.endsWith(`${attrValue}`)) { + return true; + } + } + } + return false; + } + case "*=": { + if (attrValue && typeof attrValue === "string") { + for (const value of attrValues) { + if (value.includes(`${attrValue}`)) { + return true; + } + } + } + return false; + } + case null: + default: { + return true; + } + } +}; +var matchTypeSelector = (ast, node, opt = {}) => { + const astName = unescapeSelector(ast.name); + const { localName, namespaceURI, prefix } = node; + const { check, forgive, globalObject } = opt; + let { prefix: astPrefix, localName: astLocalName } = parseAstName( + astName, + node + ); + if (node.ownerDocument.contentType === "text/html" && (!namespaceURI || namespaceURI === "http://www.w3.org/1999/xhtml") && REG_TAG_NAME.test(localName)) { + astPrefix = astPrefix.toLowerCase(); + astLocalName = astLocalName.toLowerCase(); + } + let nodePrefix; + let nodeLocalName; + if (localName.indexOf(":") > -1) { + [nodePrefix, nodeLocalName] = localName.split(":"); + } else { + nodePrefix = prefix || ""; + nodeLocalName = localName; + } + switch (astPrefix) { + case "": { + if (!nodePrefix && !namespaceURI && (astLocalName === "*" || astLocalName === nodeLocalName)) { + return true; + } + return false; + } + case "*": { + if (astLocalName === "*" || astLocalName === nodeLocalName) { + return true; + } + return false; + } + default: { + if (!check) { + if (forgive) { + return false; + } + const css = (0, import_css_tree.generate)(ast); + throw generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + globalObject + ); + } + const astNS = node.lookupNamespaceURI(astPrefix); + const nodeNS = node.lookupNamespaceURI(nodePrefix); + if (astNS === nodeNS && astPrefix === nodePrefix) { + if (astLocalName === "*" || astLocalName === nodeLocalName) { + return true; + } + return false; + } else if (!forgive && !astNS) { + throw generateException( + `Undeclared namespace ${astPrefix}`, + SYNTAX_ERR, + globalObject + ); + } + return false; + } + } +}; + +// src/js/finder.js +var DIR_NEXT = "next"; +var DIR_PREV = "prev"; +var KEYS_FORM = /* @__PURE__ */ new Set([...FORM_PARTS, "fieldset", "form"]); +var KEYS_FORM_PS_VALID = /* @__PURE__ */ new Set([...FORM_PARTS, "form"]); +var KEYS_INPUT_CHECK = new Set(INPUT_CHECK); +var KEYS_INPUT_PLACEHOLDER = /* @__PURE__ */ new Set([...INPUT_TEXT, "number"]); +var KEYS_INPUT_RANGE = /* @__PURE__ */ new Set([...INPUT_DATE, "number", "range"]); +var KEYS_INPUT_REQUIRED = /* @__PURE__ */ new Set([...INPUT_CHECK, ...INPUT_EDIT, "file"]); +var KEYS_INPUT_RESET = /* @__PURE__ */ new Set(["button", "reset"]); +var KEYS_INPUT_SUBMIT = /* @__PURE__ */ new Set(["image", "submit"]); +var KEYS_MODIFIER = /* @__PURE__ */ new Set([ + "Alt", + "AltGraph", + "CapsLock", + "Control", + "Fn", + "FnLock", + "Hyper", + "Meta", + "NumLock", + "ScrollLock", + "Shift", + "Super", + "Symbol", + "SymbolLock" +]); +var KEYS_PS_UNCACHE = /* @__PURE__ */ new Set([ + "any-link", + "defined", + "dir", + "link", + "scope" +]); +var KEYS_PS_NTH_OF_TYPE = /* @__PURE__ */ new Set([ + "first-of-type", + "last-of-type", + "only-of-type" +]); +var Finder = class { + /* private fields */ + #ast; + #astCache; + #check; + #descendant; + #document; + #documentCache; + #documentURL; + #event; + #eventHandlers; + #focus; + #invalidate; + #invalidateResults; + #lastFocusVisible; + #node; + #nodeWalker; + #nodes; + #noexcept; + #pseudoElement; + #results; + #root; + #rootWalker; + #scoped; + #selector; + #shadow; + #verifyShadowHost; + #walkers; + #warn; + #window; + /** + * constructor + * @param {object} window - The window object. + */ + constructor(window) { + this.#window = window; + this.#astCache = /* @__PURE__ */ new WeakMap(); + this.#documentCache = /* @__PURE__ */ new WeakMap(); + this.#event = null; + this.#focus = null; + this.#lastFocusVisible = null; + this.#eventHandlers = /* @__PURE__ */ new Set([ + { + keys: ["focus", "focusin"], + handler: this._handleFocusEvent + }, + { + keys: ["keydown", "keyup"], + handler: this._handleKeyboardEvent + }, + { + keys: ["mouseover", "mousedown", "mouseup", "click", "mouseout"], + handler: this._handleMouseEvent + } + ]); + this._registerEventListeners(); + this.clearResults(true); + } + /** + * Handles errors. + * @param {Error} e - The error object. + * @param {object} [opt] - Options. + * @param {boolean} [opt.noexcept] - If true, exceptions are not thrown. + * @throws {Error} Throws an error. + * @returns {void} + */ + onError = (e, opt = {}) => { + const noexcept = opt.noexcept ?? this.#noexcept; + if (noexcept) { + return; + } + const isDOMException = e instanceof DOMException || e instanceof this.#window.DOMException; + if (isDOMException) { + if (e.name === NOT_SUPPORTED_ERR) { + if (this.#warn) { + console.warn(e.message); + } + return; + } + throw new this.#window.DOMException(e.message, e.name); + } + if (e.name in this.#window) { + throw new this.#window[e.name](e.message, { cause: e }); + } + throw e; + }; + /** + * Sets up the finder. + * @param {string} selector - The CSS selector. + * @param {object} node - Document, DocumentFragment, or Element. + * @param {object} [opt] - Options. + * @param {boolean} [opt.check] - Indicates if running in internal check(). + * @param {boolean} [opt.noexcept] - If true, exceptions are not thrown. + * @param {boolean} [opt.warn] - If true, console warnings are enabled. + * @returns {object} The finder instance. + */ + setup = (selector, node, opt = {}) => { + const { check, noexcept, warn } = opt; + this.#check = !!check; + this.#noexcept = !!noexcept; + this.#warn = !!warn; + [this.#document, this.#root, this.#shadow] = resolveContent(node); + this.#documentURL = null; + this.#node = node; + this.#scoped = this.#node !== this.#root && this.#node.nodeType === ELEMENT_NODE; + this.#selector = selector; + [this.#ast, this.#nodes] = this._correspond(selector); + this.#pseudoElement = []; + this.#walkers = /* @__PURE__ */ new WeakMap(); + this.#nodeWalker = null; + this.#rootWalker = null; + this.#verifyShadowHost = null; + this.clearResults(); + return this; + }; + /** + * Clear cached results. + * @param {boolean} all - clear all results + * @returns {void} + */ + clearResults = (all = false) => { + this.#invalidateResults = /* @__PURE__ */ new WeakMap(); + if (all) { + this.#results = /* @__PURE__ */ new WeakMap(); + } + }; + /** + * Handles focus events. + * @private + * @param {Event} evt - The event object. + * @returns {void} + */ + _handleFocusEvent = (evt) => { + this.#focus = evt; + }; + /** + * Handles keyboard events. + * @private + * @param {Event} evt - The event object. + * @returns {void} + */ + _handleKeyboardEvent = (evt) => { + const { key } = evt; + if (!KEYS_MODIFIER.has(key)) { + this.#event = evt; + } + }; + /** + * Handles mouse events. + * @private + * @param {Event} evt - The event object. + * @returns {void} + */ + _handleMouseEvent = (evt) => { + this.#event = evt; + }; + /** + * Registers event listeners. + * @private + * @returns {Array.} An array of return values from addEventListener. + */ + _registerEventListeners = () => { + const opt = { + capture: true, + passive: true + }; + const func = []; + for (const eventHandler of this.#eventHandlers) { + const { keys, handler } = eventHandler; + const l = keys.length; + for (let i = 0; i < l; i++) { + const key = keys[i]; + func.push(this.#window.addEventListener(key, handler, opt)); + } + } + return func; + }; + /** + * Processes selector branches into the internal AST structure. + * @private + * @param {Array.>} branches - The branches from walkAST. + * @param {string} selector - The original selector for error reporting. + * @returns {{ast: Array, descendant: boolean}} + * An object with the AST, descendant flag. + */ + _processSelectorBranches = (branches, selector) => { + let descendant = false; + const ast = []; + const l = branches.length; + for (let i = 0; i < l; i++) { + const items = [...branches[i]]; + const branch = []; + let item = items.shift(); + if (item && item.type !== COMBINATOR) { + const leaves = /* @__PURE__ */ new Set(); + while (item) { + if (item.type === COMBINATOR) { + const [nextItem] = items; + if (!nextItem || nextItem.type === COMBINATOR) { + const msg = `Invalid selector ${selector}`; + this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + return { ast: [], descendant: false, invalidate: false }; + } + if (item.name === " " || item.name === ">") { + descendant = true; + } + branch.push({ combo: item, leaves: sortAST(leaves) }); + leaves.clear(); + } else { + if (item.name && typeof item.name === "string") { + const unescapedName = unescapeSelector(item.name); + if (unescapedName !== item.name) { + item.name = unescapedName; + } + if (/[|:]/.test(unescapedName)) { + item.namespace = true; + } + } + leaves.add(item); + } + if (items.length) { + item = items.shift(); + } else { + branch.push({ combo: null, leaves: sortAST(leaves) }); + leaves.clear(); + break; + } + } + } + ast.push({ branch, dir: null, filtered: false, find: false }); + } + return { ast, descendant }; + }; + /** + * Corresponds AST and nodes. + * @private + * @param {string} selector - The CSS selector. + * @returns {Array.>} An array with the AST and nodes. + */ + _correspond = (selector) => { + const nodes = []; + this.#descendant = false; + this.#invalidate = false; + let ast; + if (this.#documentCache.has(this.#document)) { + const cachedItem = this.#documentCache.get(this.#document); + if (cachedItem && cachedItem.has(`${selector}`)) { + const item = cachedItem.get(`${selector}`); + ast = item.ast; + this.#descendant = item.descendant; + this.#invalidate = item.invalidate; + } + } + if (ast) { + const l = ast.length; + for (let i = 0; i < l; i++) { + ast[i].dir = null; + ast[i].filtered = false; + ast[i].find = false; + nodes[i] = []; + } + } else { + let cssAst; + try { + cssAst = parseSelector(selector); + } catch (e) { + return this.onError(e); + } + const { branches, info } = walkAST(cssAst); + const { + hasHasPseudoFunc, + hasLogicalPseudoFunc, + hasNthChildOfSelector, + hasStatePseudoClass + } = info; + this.#invalidate = hasHasPseudoFunc || hasStatePseudoClass || !!(hasLogicalPseudoFunc && hasNthChildOfSelector); + const processed = this._processSelectorBranches(branches, selector); + ast = processed.ast; + this.#descendant = processed.descendant; + let cachedItem; + if (this.#documentCache.has(this.#document)) { + cachedItem = this.#documentCache.get(this.#document); + } else { + cachedItem = /* @__PURE__ */ new Map(); + } + cachedItem.set(`${selector}`, { + ast, + descendant: this.#descendant, + invalidate: this.#invalidate + }); + this.#documentCache.set(this.#document, cachedItem); + for (let i = 0; i < ast.length; i++) { + nodes[i] = []; + } + } + return [ast, nodes]; + }; + /** + * Creates a TreeWalker. + * @private + * @param {object} node - The Document, DocumentFragment, or Element node. + * @param {object} [opt] - Options. + * @param {boolean} [opt.force] - Force creation of a new TreeWalker. + * @param {number} [opt.whatToShow] - The NodeFilter whatToShow value. + * @returns {object} The TreeWalker object. + */ + _createTreeWalker = (node, opt = {}) => { + const { force = false, whatToShow = SHOW_CONTAINER } = opt; + if (force) { + return this.#document.createTreeWalker(node, whatToShow); + } else if (this.#walkers.has(node)) { + return this.#walkers.get(node); + } + const walker = this.#document.createTreeWalker(node, whatToShow); + this.#walkers.set(node, walker); + return walker; + }; + /** + * Gets selector branches from cache or parses them. + * @private + * @param {object} selector - The AST. + * @returns {Array.>} The selector branches. + */ + _getSelectorBranches = (selector) => { + if (this.#astCache.has(selector)) { + return this.#astCache.get(selector); + } + const { branches } = walkAST(selector); + this.#astCache.set(selector, branches); + return branches; + }; + /** + * Gets the children of a node, optionally filtered by a selector. + * @private + * @param {object} parentNode - The parent element. + * @param {Array.>} selectorBranches - The selector branches. + * @param {object} [opt] - Options. + * @returns {Array.} An array of child nodes. + */ + _getFilteredChildren = (parentNode, selectorBranches, opt = {}) => { + const children = []; + const walker = this._createTreeWalker(parentNode, { force: true }); + let childNode = walker.firstChild(); + while (childNode) { + if (selectorBranches) { + if (isVisible(childNode)) { + let isMatch = false; + const l = selectorBranches.length; + for (let i = 0; i < l; i++) { + const leaves = selectorBranches[i]; + if (this._matchLeaves(leaves, childNode, opt)) { + isMatch = true; + break; + } + } + if (isMatch) { + children.push(childNode); + } + } + } else { + children.push(childNode); + } + childNode = walker.nextSibling(); + } + return children; + }; + /** + * Collects nth-child nodes. + * @private + * @param {object} anb - An+B options. + * @param {number} anb.a - The 'a' value. + * @param {number} anb.b - The 'b' value. + * @param {boolean} [anb.reverse] - If true, reverses the order. + * @param {object} [anb.selector] - The AST. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _collectNthChild = (anb, node, opt = {}) => { + const { a, b, selector } = anb; + const { parentNode } = node; + if (!parentNode) { + const matchedNode = /* @__PURE__ */ new Set(); + if (node === this.#root && a * 1 + b * 1 === 1) { + if (selector) { + const selectorBranches2 = this._getSelectorBranches(selector); + const l = selectorBranches2.length; + for (let i = 0; i < l; i++) { + const leaves = selectorBranches2[i]; + if (this._matchLeaves(leaves, node, opt)) { + matchedNode.add(node); + break; + } + } + } else { + matchedNode.add(node); + } + } + return matchedNode; + } + const selectorBranches = selector ? this._getSelectorBranches(selector) : null; + const children = this._getFilteredChildren( + parentNode, + selectorBranches, + opt + ); + const matchedNodes = filterNodesByAnB(children, anb); + return new Set(matchedNodes); + }; + /** + * Collects nth-of-type nodes. + * @private + * @param {object} anb - An+B options. + * @param {number} anb.a - The 'a' value. + * @param {number} anb.b - The 'b' value. + * @param {boolean} [anb.reverse] - If true, reverses the order. + * @param {object} node - The Element node. + * @returns {Set.} A collection of matched nodes. + */ + _collectNthOfType = (anb, node) => { + const { parentNode } = node; + if (!parentNode) { + if (node === this.#root && anb.a * 1 + anb.b * 1 === 1) { + return /* @__PURE__ */ new Set([node]); + } + return /* @__PURE__ */ new Set(); + } + const typedSiblings = []; + const walker = this._createTreeWalker(parentNode, { force: true }); + let sibling = walker.firstChild(); + while (sibling) { + if (sibling.localName === node.localName && sibling.namespaceURI === node.namespaceURI && sibling.prefix === node.prefix) { + typedSiblings.push(sibling); + } + sibling = walker.nextSibling(); + } + const matchedNodes = filterNodesByAnB(typedSiblings, anb); + return new Set(matchedNodes); + }; + /** + * Matches An+B. + * @private + * @param {object} ast - The AST. + * @param {object} node - The Element node. + * @param {string} nthName - The name of the nth pseudo-class. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchAnPlusB = (ast, node, nthName, opt = {}) => { + const { + nth: { a, b, name: nthIdentName }, + selector + } = ast; + const anbMap = /* @__PURE__ */ new Map(); + if (nthIdentName) { + if (nthIdentName === "even") { + anbMap.set("a", 2); + anbMap.set("b", 0); + } else if (nthIdentName === "odd") { + anbMap.set("a", 2); + anbMap.set("b", 1); + } + if (nthName.indexOf("last") > -1) { + anbMap.set("reverse", true); + } + } else { + if (typeof a === "string" && /-?\d+/.test(a)) { + anbMap.set("a", a * 1); + } else { + anbMap.set("a", 0); + } + if (typeof b === "string" && /-?\d+/.test(b)) { + anbMap.set("b", b * 1); + } else { + anbMap.set("b", 0); + } + if (nthName.indexOf("last") > -1) { + anbMap.set("reverse", true); + } + } + if (nthName === "nth-child" || nthName === "nth-last-child") { + if (selector) { + anbMap.set("selector", selector); + } + const anb = Object.fromEntries(anbMap); + const nodes = this._collectNthChild(anb, node, opt); + return nodes; + } else if (nthName === "nth-of-type" || nthName === "nth-last-of-type") { + const anb = Object.fromEntries(anbMap); + const nodes = this._collectNthOfType(anb, node); + return nodes; + } + return /* @__PURE__ */ new Set(); + }; + /** + * Matches the :has() pseudo-class function. + * @private + * @param {Array.} astLeaves - The AST leaves. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {boolean} The result. + */ + _matchHasPseudoFunc = (astLeaves, node, opt = {}) => { + if (Array.isArray(astLeaves) && astLeaves.length) { + const leaves = [...astLeaves]; + const [leaf] = leaves; + const { type: leafType } = leaf; + let combo; + if (leafType === COMBINATOR) { + combo = leaves.shift(); + } else { + combo = { + name: " ", + type: COMBINATOR + }; + } + const twigLeaves = []; + while (leaves.length) { + const [item] = leaves; + const { type: itemType } = item; + if (itemType === COMBINATOR) { + break; + } else { + twigLeaves.push(leaves.shift()); + } + } + const twig = { + combo, + leaves: twigLeaves + }; + opt.dir = DIR_NEXT; + const nodes = this._matchCombinator(twig, node, opt); + if (nodes.size) { + if (leaves.length) { + let bool = false; + for (const nextNode of nodes) { + bool = this._matchHasPseudoFunc(leaves, nextNode, opt); + if (bool) { + break; + } + } + return bool; + } + return true; + } + } + return false; + }; + /** + * Evaluates the :has() pseudo-class. + * @private + * @param {object} astData - The AST data. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {?object} The matched node. + */ + _evaluateHasPseudo = (astData, node, opt) => { + const { branches } = astData; + let bool = false; + const l = branches.length; + for (let i = 0; i < l; i++) { + const leaves = branches[i]; + bool = this._matchHasPseudoFunc(leaves, node, opt); + if (bool) { + break; + } + } + if (!bool) { + return null; + } + if ((opt.isShadowRoot || this.#shadow) && node.nodeType === DOCUMENT_FRAGMENT_NODE) { + return this.#verifyShadowHost ? node : null; + } + return node; + }; + /** + * Matches logical pseudo-class functions. + * @private + * @param {object} astData - The AST data. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {?object} The matched node. + */ + _matchLogicalPseudoFunc = (astData, node, opt = {}) => { + const { astName, branches, twigBranches } = astData; + if (astName === "has") { + return this._evaluateHasPseudo(astData, node, opt); + } + const isShadowRoot = (opt.isShadowRoot || this.#shadow) && node.nodeType === DOCUMENT_FRAGMENT_NODE; + if (isShadowRoot) { + let invalid = false; + for (const branch of branches) { + if (branch.length > 1) { + invalid = true; + break; + } else if (astName === "not") { + const [{ type: childAstType }] = branch; + if (childAstType !== PS_CLASS_SELECTOR) { + invalid = true; + break; + } + } + } + if (invalid) { + return null; + } + } + opt.forgive = astName === "is" || astName === "where"; + const l = twigBranches.length; + let bool; + for (let i = 0; i < l; i++) { + const branch = twigBranches[i]; + const lastIndex = branch.length - 1; + const { leaves } = branch[lastIndex]; + bool = this._matchLeaves(leaves, node, opt); + if (bool && lastIndex > 0) { + let nextNodes = /* @__PURE__ */ new Set([node]); + for (let j = lastIndex - 1; j >= 0; j--) { + const twig = branch[j]; + const arr = []; + opt.dir = DIR_PREV; + for (const nextNode of nextNodes) { + const m = this._matchCombinator(twig, nextNode, opt); + if (m.size) { + arr.push(...m); + } + } + if (arr.length) { + if (j === 0) { + bool = true; + } else { + nextNodes = new Set(arr); + } + } else { + bool = false; + break; + } + } + } + if (bool) { + break; + } + } + if (astName === "not") { + if (bool) { + return null; + } + return node; + } else if (bool) { + return node; + } + return null; + }; + /** + * match pseudo-class selector + * @private + * @see https://html.spec.whatwg.org/#pseudo-classes + * @param {object} ast - AST + * @param {object} node - Element node + * @param {object} [opt] - options + * @returns {Set.} - collection of matched nodes + */ + _matchPseudoClassSelector(ast, node, opt = {}) { + const { children: astChildren, name: astName } = ast; + const { localName, parentNode } = node; + const { forgive, warn = this.#warn } = opt; + const matched = /* @__PURE__ */ new Set(); + if (Array.isArray(astChildren) && KEYS_LOGICAL.has(astName)) { + if (!astChildren.length && astName !== "is" && astName !== "where") { + const css = (0, import_css_tree.generate)(ast); + const msg = `Invalid selector ${css}`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + let astData; + if (this.#astCache.has(ast)) { + astData = this.#astCache.get(ast); + } else { + const { branches } = walkAST(ast); + if (astName === "has") { + let forgiven = false; + const l = astChildren.length; + for (let i = 0; i < l; i++) { + const child = astChildren[i]; + const item = (0, import_css_tree.find)(child, findLogicalWithNestedHas); + if (item) { + const itemName = item.name; + if (itemName === "is" || itemName === "where") { + forgiven = true; + break; + } else { + const css = (0, import_css_tree.generate)(ast); + const msg = `Invalid selector ${css}`; + return this.onError( + generateException(msg, SYNTAX_ERR, this.#window) + ); + } + } + } + if (forgiven) { + return matched; + } + astData = { + astName, + branches + }; + } else { + const twigBranches = []; + const l = branches.length; + for (let i = 0; i < l; i++) { + const [...leaves] = branches[i]; + const branch = []; + const leavesSet = /* @__PURE__ */ new Set(); + let item = leaves.shift(); + while (item) { + if (item.type === COMBINATOR) { + branch.push({ + combo: item, + leaves: [...leavesSet] + }); + leavesSet.clear(); + } else if (item) { + leavesSet.add(item); + } + if (leaves.length) { + item = leaves.shift(); + } else { + branch.push({ + combo: null, + leaves: [...leavesSet] + }); + leavesSet.clear(); + break; + } + } + twigBranches.push(branch); + } + astData = { + astName, + branches, + twigBranches + }; + this.#astCache.set(ast, astData); + } + } + const res = this._matchLogicalPseudoFunc(astData, node, opt); + if (res) { + matched.add(res); + } + } else if (Array.isArray(astChildren)) { + if (/^nth-(?:last-)?(?:child|of-type)$/.test(astName)) { + if (astChildren.length !== 1) { + const css = (0, import_css_tree.generate)(ast); + return this.onError( + generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + this.#window + ) + ); + } + const [branch] = astChildren; + const nodes = this._matchAnPlusB(branch, node, astName, opt); + return nodes; + } else { + switch (astName) { + // :dir() + case "dir": { + if (astChildren.length !== 1) { + const css = (0, import_css_tree.generate)(ast); + return this.onError( + generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + this.#window + ) + ); + } + const [astChild] = astChildren; + const res = matchDirectionPseudoClass(astChild, node); + if (res) { + matched.add(node); + } + break; + } + // :lang() + case "lang": { + if (!astChildren.length) { + const css = (0, import_css_tree.generate)(ast); + return this.onError( + generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + this.#window + ) + ); + } + let bool; + for (const astChild of astChildren) { + bool = matchLanguagePseudoClass(astChild, node); + if (bool) { + break; + } + } + if (bool) { + matched.add(node); + } + break; + } + // :state() + case "state": { + if (isCustomElement(node)) { + const [{ value: stateValue }] = astChildren; + if (stateValue) { + if (node[stateValue]) { + matched.add(node); + } else { + for (const i in node) { + const prop = node[i]; + if (prop instanceof this.#window.ElementInternals) { + if (prop?.states?.has(stateValue)) { + matched.add(node); + } + break; + } + } + } + } + } + break; + } + case "current": + case "heading": + case "nth-col": + case "nth-last-col": { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-class :${astName}()`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + // Ignore :host() and :host-context(). + case "host": + case "host-context": { + break; + } + // Deprecated in CSS Selectors 3. + case "contains": { + if (warn) { + this.onError( + generateException( + `Unknown pseudo-class :${astName}()`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + default: { + if (!forgive) { + this.onError( + generateException( + `Unknown pseudo-class :${astName}()`, + SYNTAX_ERR, + this.#window + ) + ); + } + } + } + } + } else if (KEYS_PS_NTH_OF_TYPE.has(astName)) { + if (node === this.#root) { + matched.add(node); + } else if (parentNode) { + switch (astName) { + case "first-of-type": { + const [node1] = this._collectNthOfType( + { + a: 0, + b: 1 + }, + node + ); + if (node1) { + matched.add(node1); + } + break; + } + case "last-of-type": { + const [node1] = this._collectNthOfType( + { + a: 0, + b: 1, + reverse: true + }, + node + ); + if (node1) { + matched.add(node1); + } + break; + } + // 'only-of-type' is handled by default. + default: { + const [node1] = this._collectNthOfType( + { + a: 0, + b: 1 + }, + node + ); + if (node1 === node) { + const [node2] = this._collectNthOfType( + { + a: 0, + b: 1, + reverse: true + }, + node + ); + if (node2 === node) { + matched.add(node); + } + } + } + } + } + } else { + switch (astName) { + case "disabled": + case "enabled": { + const isMatch = matchDisabledPseudoClass(astName, node); + if (isMatch) { + matched.add(node); + } + break; + } + case "read-only": + case "read-write": { + const isMatch = matchReadOnlyPseudoClass(astName, node); + if (isMatch) { + matched.add(node); + } + break; + } + case "any-link": + case "link": { + if ((localName === "a" || localName === "area") && node.hasAttribute("href")) { + matched.add(node); + } + break; + } + case "local-link": { + if ((localName === "a" || localName === "area") && node.hasAttribute("href")) { + if (!this.#documentURL) { + this.#documentURL = new URL(this.#document.URL); + } + const { href, origin, pathname } = this.#documentURL; + const attrURL = new URL(node.getAttribute("href"), href); + if (attrURL.origin === origin && attrURL.pathname === pathname) { + matched.add(node); + } + } + break; + } + case "visited": { + break; + } + case "hover": { + const { target, type } = this.#event ?? {}; + if (/^(?:click|mouse(?:down|over|up))$/.test(type) && node.contains(target)) { + matched.add(node); + } + break; + } + case "active": { + const { buttons, target, type } = this.#event ?? {}; + if (type === "mousedown" && buttons & 1 && node.contains(target)) { + matched.add(node); + } + break; + } + case "target": { + if (!this.#documentURL) { + this.#documentURL = new URL(this.#document.URL); + } + const { hash } = this.#documentURL; + if (node.id && hash === `#${node.id}` && this.#document.contains(node)) { + matched.add(node); + } + break; + } + case "target-within": { + if (!this.#documentURL) { + this.#documentURL = new URL(this.#document.URL); + } + const { hash } = this.#documentURL; + if (hash) { + const id = hash.replace(/^#/, ""); + let current = this.#document.getElementById(id); + while (current) { + if (current === node) { + matched.add(node); + break; + } + current = current.parentNode; + } + } + break; + } + case "scope": { + if (this.#node.nodeType === ELEMENT_NODE) { + if (!this.#shadow && node === this.#node) { + matched.add(node); + } + } else if (node === this.#document.documentElement) { + matched.add(node); + } + break; + } + case "focus": { + const activeElement = this.#document.activeElement; + if (node === activeElement && isFocusableArea(node)) { + matched.add(node); + } else if (activeElement.shadowRoot) { + const activeShadowElement = activeElement.shadowRoot.activeElement; + let current = activeShadowElement; + while (current) { + if (current.nodeType === DOCUMENT_FRAGMENT_NODE) { + const { host } = current; + if (host === activeElement) { + if (isFocusableArea(node)) { + matched.add(node); + } else { + matched.add(host); + } + } + break; + } else { + current = current.parentNode; + } + } + } + break; + } + case "focus-visible": { + if (node === this.#document.activeElement && isFocusableArea(node)) { + let bool; + if (isFocusVisible(node)) { + bool = true; + } else if (this.#focus) { + const { relatedTarget, target: focusTarget } = this.#focus; + if (focusTarget === node) { + if (isFocusVisible(relatedTarget)) { + bool = true; + } else if (this.#event) { + const { + altKey: eventAltKey, + ctrlKey: eventCtrlKey, + key: eventKey, + metaKey: eventMetaKey, + target: eventTarget, + type: eventType + } = this.#event; + if (eventTarget === relatedTarget) { + if (this.#lastFocusVisible === null) { + bool = true; + } else if (focusTarget === this.#lastFocusVisible) { + bool = true; + } + } else if (eventKey === "Tab") { + if (eventType === "keydown" && eventTarget !== node || eventType === "keyup" && eventTarget === node) { + if (eventTarget === focusTarget) { + if (this.#lastFocusVisible === null) { + bool = true; + } else if (eventTarget === this.#lastFocusVisible && relatedTarget === null) { + bool = true; + } + } else { + bool = true; + } + } + } else if (eventKey) { + if ((eventType === "keydown" || eventType === "keyup") && !eventAltKey && !eventCtrlKey && !eventMetaKey && eventTarget === node) { + bool = true; + } + } + } else if (relatedTarget === null || relatedTarget === this.#lastFocusVisible) { + bool = true; + } + } + } + if (bool) { + this.#lastFocusVisible = node; + matched.add(node); + } else if (this.#lastFocusVisible === node) { + this.#lastFocusVisible = null; + } + } + break; + } + case "focus-within": { + const activeElement = this.#document.activeElement; + if (node.contains(activeElement) && isFocusableArea(activeElement)) { + matched.add(node); + } else if (activeElement.shadowRoot) { + const activeShadowElement = activeElement.shadowRoot.activeElement; + if (node.contains(activeShadowElement)) { + matched.add(node); + } else { + let current = activeShadowElement; + while (current) { + if (current.nodeType === DOCUMENT_FRAGMENT_NODE) { + const { host } = current; + if (host === activeElement && node.contains(host)) { + matched.add(node); + } + break; + } else { + current = current.parentNode; + } + } + } + } + break; + } + case "open": + case "closed": { + if (localName === "details" || localName === "dialog") { + if (node.hasAttribute("open")) { + if (astName === "open") { + matched.add(node); + } + } else if (astName === "closed") { + matched.add(node); + } + } + break; + } + case "placeholder-shown": { + let placeholder; + if (node.placeholder) { + placeholder = node.placeholder; + } else if (node.hasAttribute("placeholder")) { + placeholder = node.getAttribute("placeholder"); + } + if (typeof placeholder === "string" && !/[\r\n]/.test(placeholder)) { + let targetNode; + if (localName === "textarea") { + targetNode = node; + } else if (localName === "input") { + if (node.hasAttribute("type")) { + if (KEYS_INPUT_PLACEHOLDER.has(node.getAttribute("type"))) { + targetNode = node; + } + } else { + targetNode = node; + } + } + if (targetNode && node.value === "") { + matched.add(node); + } + } + break; + } + case "checked": { + const attrType = node.getAttribute("type"); + if (node.checked && localName === "input" && (attrType === "checkbox" || attrType === "radio") || node.selected && localName === "option") { + matched.add(node); + } + break; + } + case "indeterminate": { + if (node.indeterminate && localName === "input" && node.type === "checkbox" || localName === "progress" && !node.hasAttribute("value")) { + matched.add(node); + } else if (localName === "input" && node.type === "radio" && !node.hasAttribute("checked")) { + const nodeName = node.name; + let parent = node.parentNode; + while (parent) { + if (parent.localName === "form") { + break; + } + parent = parent.parentNode; + } + if (!parent) { + parent = this.#document.documentElement; + } + const walker = this._createTreeWalker(parent); + let refNode = traverseNode(parent, walker); + refNode = walker.firstChild(); + let checked; + while (refNode) { + if (refNode.localName === "input" && refNode.getAttribute("type") === "radio") { + if (refNode.hasAttribute("name")) { + if (refNode.getAttribute("name") === nodeName) { + checked = !!refNode.checked; + } + } else { + checked = !!refNode.checked; + } + if (checked) { + break; + } + } + refNode = walker.nextNode(); + } + if (!checked) { + matched.add(node); + } + } + break; + } + case "default": { + const attrType = node.getAttribute("type"); + if (localName === "button" && !(node.hasAttribute("type") && KEYS_INPUT_RESET.has(attrType)) || localName === "input" && node.hasAttribute("type") && KEYS_INPUT_SUBMIT.has(attrType)) { + let form = node.parentNode; + while (form) { + if (form.localName === "form") { + break; + } + form = form.parentNode; + } + if (form) { + const walker = this._createTreeWalker(form); + let refNode = traverseNode(form, walker); + refNode = walker.firstChild(); + while (refNode) { + const nodeName = refNode.localName; + const nodeAttrType = refNode.getAttribute("type"); + let m; + if (nodeName === "button") { + m = !(refNode.hasAttribute("type") && KEYS_INPUT_RESET.has(nodeAttrType)); + } else if (nodeName === "input") { + m = refNode.hasAttribute("type") && KEYS_INPUT_SUBMIT.has(nodeAttrType); + } + if (m) { + if (refNode === node) { + matched.add(node); + } + break; + } + refNode = walker.nextNode(); + } + } + } else if (localName === "input" && node.hasAttribute("type") && node.hasAttribute("checked") && KEYS_INPUT_CHECK.has(attrType)) { + matched.add(node); + } else if (localName === "option" && node.hasAttribute("selected")) { + matched.add(node); + } + break; + } + case "valid": + case "invalid": { + if (KEYS_FORM_PS_VALID.has(localName)) { + let valid; + if (node.checkValidity()) { + if (node.maxLength >= 0) { + if (node.maxLength >= node.value.length) { + valid = true; + } + } else { + valid = true; + } + } + if (valid) { + if (astName === "valid") { + matched.add(node); + } + } else if (astName === "invalid") { + matched.add(node); + } + } else if (localName === "fieldset") { + const walker = this._createTreeWalker(node); + let refNode = traverseNode(node, walker); + refNode = walker.firstChild(); + let valid; + if (!refNode) { + valid = true; + } else { + while (refNode) { + if (KEYS_FORM_PS_VALID.has(refNode.localName)) { + if (refNode.checkValidity()) { + if (refNode.maxLength >= 0) { + valid = refNode.maxLength >= refNode.value.length; + } else { + valid = true; + } + } else { + valid = false; + } + if (!valid) { + break; + } + } + refNode = walker.nextNode(); + } + } + if (valid) { + if (astName === "valid") { + matched.add(node); + } + } else if (astName === "invalid") { + matched.add(node); + } + } + break; + } + case "in-range": + case "out-of-range": { + const attrType = node.getAttribute("type"); + if (localName === "input" && !(node.readonly || node.hasAttribute("readonly")) && !(node.disabled || node.hasAttribute("disabled")) && KEYS_INPUT_RANGE.has(attrType)) { + const flowed = node.validity.rangeUnderflow || node.validity.rangeOverflow; + if (astName === "out-of-range" && flowed) { + matched.add(node); + } else if (astName === "in-range" && !flowed && (node.hasAttribute("min") || node.hasAttribute("max") || attrType === "range")) { + matched.add(node); + } + } + break; + } + case "required": + case "optional": { + let required; + let optional; + if (localName === "select" || localName === "textarea") { + if (node.required || node.hasAttribute("required")) { + required = true; + } else { + optional = true; + } + } else if (localName === "input") { + if (node.hasAttribute("type")) { + const attrType = node.getAttribute("type"); + if (KEYS_INPUT_REQUIRED.has(attrType)) { + if (node.required || node.hasAttribute("required")) { + required = true; + } else { + optional = true; + } + } else { + optional = true; + } + } else if (node.required || node.hasAttribute("required")) { + required = true; + } else { + optional = true; + } + } + if (astName === "required" && required) { + matched.add(node); + } else if (astName === "optional" && optional) { + matched.add(node); + } + break; + } + case "root": { + if (node === this.#document.documentElement) { + matched.add(node); + } + break; + } + case "empty": { + if (node.hasChildNodes()) { + const walker = this._createTreeWalker(node, { + force: true, + whatToShow: SHOW_ALL + }); + let refNode = walker.firstChild(); + let bool; + while (refNode) { + bool = refNode.nodeType !== ELEMENT_NODE && refNode.nodeType !== TEXT_NODE; + if (!bool) { + break; + } + refNode = walker.nextSibling(); + } + if (bool) { + matched.add(node); + } + } else { + matched.add(node); + } + break; + } + case "first-child": { + if (parentNode && node === parentNode.firstElementChild || node === this.#root) { + matched.add(node); + } + break; + } + case "last-child": { + if (parentNode && node === parentNode.lastElementChild || node === this.#root) { + matched.add(node); + } + break; + } + case "only-child": { + if (parentNode && node === parentNode.firstElementChild && node === parentNode.lastElementChild || node === this.#root) { + matched.add(node); + } + break; + } + case "defined": { + if (node.hasAttribute("is") || localName.includes("-")) { + if (isCustomElement(node)) { + matched.add(node); + } + } else if (node instanceof this.#window.HTMLElement || node instanceof this.#window.SVGElement) { + matched.add(node); + } + break; + } + case "popover-open": { + if (node.popover && isVisible(node)) { + matched.add(node); + } + break; + } + // Ignore :host. + case "host": { + break; + } + // Legacy pseudo-elements. + case "after": + case "before": + case "first-letter": + case "first-line": { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-element ::${astName}`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + // Not supported. + case "autofill": + case "blank": + case "buffering": + case "current": + case "fullscreen": + case "future": + case "has-slotted": + case "heading": + case "modal": + case "muted": + case "past": + case "paused": + case "picture-in-picture": + case "playing": + case "seeking": + case "stalled": + case "user-invalid": + case "user-valid": + case "volume-locked": + case "-webkit-autofill": { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-class :${astName}`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + default: { + if (astName.startsWith("-webkit-")) { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-class :${astName}`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + } else if (!forgive) { + this.onError( + generateException( + `Unknown pseudo-class :${astName}`, + SYNTAX_ERR, + this.#window + ) + ); + } + } + } + } + return matched; + } + /** + * Evaluates the :host() pseudo-class. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} host - The host element. + * @param {object} ast - The original AST for error reporting. + * @returns {boolean} True if matched. + */ + _evaluateHostPseudo = (leaves, host, ast) => { + const l = leaves.length; + for (let i = 0; i < l; i++) { + const leaf = leaves[i]; + if (leaf.type === COMBINATOR) { + const css = (0, import_css_tree.generate)(ast); + const msg = `Invalid selector ${css}`; + this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + return false; + } + if (!this._matchSelector(leaf, host).has(host)) { + return false; + } + } + return true; + }; + /** + * Evaluates the :host-context() pseudo-class. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} host - The host element. + * @param {object} ast - The original AST for error reporting. + * @returns {boolean} True if matched. + */ + _evaluateHostContextPseudo = (leaves, host, ast) => { + let parent = host; + while (parent) { + let bool; + const l = leaves.length; + for (let i = 0; i < l; i++) { + const leaf = leaves[i]; + if (leaf.type === COMBINATOR) { + const css = (0, import_css_tree.generate)(ast); + const msg = `Invalid selector ${css}`; + this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + return false; + } + bool = this._matchSelector(leaf, parent).has(parent); + if (!bool) { + break; + } + } + if (bool) { + return true; + } + parent = parent.parentNode; + } + return false; + }; + /** + * Matches shadow host pseudo-classes. + * @private + * @param {object} ast - The AST. + * @param {object} node - The DocumentFragment node. + * @returns {?object} The matched node. + */ + _matchShadowHostPseudoClass = (ast, node) => { + const { children: astChildren, name: astName } = ast; + if (!Array.isArray(astChildren)) { + if (astName === "host") { + return node; + } + const msg = `Invalid selector :${astName}`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + if (astName !== "host" && astName !== "host-context") { + const msg = `Invalid selector :${astName}()`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + if (astChildren.length !== 1) { + const css = (0, import_css_tree.generate)(ast); + const msg = `Invalid selector ${css}`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + const { host } = node; + const { branches } = walkAST(astChildren[0]); + const [branch] = branches; + const [...leaves] = branch; + let isMatch = false; + if (astName === "host") { + isMatch = this._evaluateHostPseudo(leaves, host, ast); + } else { + isMatch = this._evaluateHostContextPseudo(leaves, host, ast); + } + return isMatch ? node : null; + }; + /** + * Matches a selector for element nodes. + * @private + * @param {object} ast - The AST. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchSelectorForElement = (ast, node, opt = {}) => { + const { type: astType } = ast; + const astName = unescapeSelector(ast.name); + const matched = /* @__PURE__ */ new Set(); + switch (astType) { + case ATTR_SELECTOR: { + if (matchAttributeSelector(ast, node, opt)) { + matched.add(node); + } + break; + } + case ID_SELECTOR: { + if (node.id === astName) { + matched.add(node); + } + break; + } + case CLASS_SELECTOR: { + if (node.classList.contains(astName)) { + matched.add(node); + } + break; + } + case PS_CLASS_SELECTOR: { + return this._matchPseudoClassSelector(ast, node, opt); + } + case TYPE_SELECTOR: { + if (matchTypeSelector(ast, node, opt)) { + matched.add(node); + } + break; + } + // PS_ELEMENT_SELECTOR is handled by default. + default: { + try { + if (opt.check) { + const css = (0, import_css_tree.generate)(ast); + this.#pseudoElement.push(css); + matched.add(node); + } else { + matchPseudoElementSelector(astName, astType, opt); + } + } catch (e) { + this.onError(e); + } + } + } + return matched; + }; + /** + * Matches a selector for a shadow root. + * @private + * @param {object} ast - The AST. + * @param {object} node - The DocumentFragment node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchSelectorForShadowRoot = (ast, node, opt = {}) => { + const { name: astName } = ast; + if (KEYS_LOGICAL.has(astName)) { + opt.isShadowRoot = true; + return this._matchPseudoClassSelector(ast, node, opt); + } + const matched = /* @__PURE__ */ new Set(); + if (astName === "host" || astName === "host-context") { + const res = this._matchShadowHostPseudoClass(ast, node, opt); + if (res) { + this.#verifyShadowHost = true; + matched.add(res); + } + } + return matched; + }; + /** + * Matches a selector. + * @private + * @param {object} ast - The AST. + * @param {object} node - The Document, DocumentFragment, or Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchSelector = (ast, node, opt = {}) => { + if (node.nodeType === ELEMENT_NODE) { + return this._matchSelectorForElement(ast, node, opt); + } + if (this.#shadow && node.nodeType === DOCUMENT_FRAGMENT_NODE && ast.type === PS_CLASS_SELECTOR) { + return this._matchSelectorForShadowRoot(ast, node, opt); + } + return /* @__PURE__ */ new Set(); + }; + /** + * Matches leaves. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} node - The node. + * @param {object} [opt] - Options. + * @returns {boolean} The result. + */ + _matchLeaves = (leaves, node, opt = {}) => { + const results = this.#invalidate ? this.#invalidateResults : this.#results; + let result = results.get(leaves); + if (result && result.has(node)) { + const { matched } = result.get(node); + return matched; + } + let cacheable = true; + if (node.nodeType === ELEMENT_NODE && KEYS_FORM.has(node.localName)) { + cacheable = false; + } + let bool; + const l = leaves.length; + for (let i = 0; i < l; i++) { + const leaf = leaves[i]; + switch (leaf.type) { + case ATTR_SELECTOR: + case ID_SELECTOR: { + cacheable = false; + break; + } + case PS_CLASS_SELECTOR: { + if (KEYS_PS_UNCACHE.has(leaf.name)) { + cacheable = false; + } + break; + } + default: { + } + } + bool = this._matchSelector(leaf, node, opt).has(node); + if (!bool) { + break; + } + } + if (cacheable) { + if (!result) { + result = /* @__PURE__ */ new WeakMap(); + } + result.set(node, { + matched: bool + }); + results.set(leaves, result); + } + return bool; + }; + /** + * Traverses all descendant nodes and collects matches. + * @private + * @param {object} baseNode - The base Element node or Element.shadowRoot. + * @param {Array.} leaves - The AST leaves. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _traverseAllDescendants = (baseNode, leaves, opt = {}) => { + const walker = this._createTreeWalker(baseNode); + traverseNode(baseNode, walker); + let currentNode = walker.firstChild(); + const nodes = /* @__PURE__ */ new Set(); + while (currentNode) { + if (this._matchLeaves(leaves, currentNode, opt)) { + nodes.add(currentNode); + } + currentNode = walker.nextNode(); + } + return nodes; + }; + /** + * Finds descendant nodes. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} baseNode - The base Element node or Element.shadowRoot. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _findDescendantNodes = (leaves, baseNode, opt = {}) => { + const [leaf, ...filterLeaves] = leaves; + const { type: leafType } = leaf; + switch (leafType) { + case ID_SELECTOR: { + const canUseGetElementById = !this.#shadow && baseNode.nodeType === ELEMENT_NODE && this.#root.nodeType !== ELEMENT_NODE; + if (canUseGetElementById) { + const leafName = unescapeSelector(leaf.name); + const nodes = /* @__PURE__ */ new Set(); + const foundNode = this.#root.getElementById(leafName); + if (foundNode && foundNode !== baseNode && baseNode.contains(foundNode)) { + const isCompoundSelector = filterLeaves.length > 0; + if (!isCompoundSelector || this._matchLeaves(filterLeaves, foundNode, opt)) { + nodes.add(foundNode); + } + } + return nodes; + } + return this._traverseAllDescendants(baseNode, leaves, opt); + } + case PS_ELEMENT_SELECTOR: { + const leafName = unescapeSelector(leaf.name); + matchPseudoElementSelector(leafName, leafType, opt); + return /* @__PURE__ */ new Set(); + } + default: { + return this._traverseAllDescendants(baseNode, leaves, opt); + } + } + }; + /** + * Matches the descendant combinator ' '. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchDescendantCombinator = (twig, node, opt = {}) => { + const { leaves } = twig; + const { parentNode } = node; + const { dir } = opt; + if (dir === DIR_NEXT) { + return this._findDescendantNodes(leaves, node, opt); + } + const ancestors = []; + let refNode = parentNode; + while (refNode) { + if (this._matchLeaves(leaves, refNode, opt)) { + ancestors.push(refNode); + } + refNode = refNode.parentNode; + } + if (ancestors.length) { + return new Set(ancestors.reverse()); + } + return /* @__PURE__ */ new Set(); + }; + /** + * Matches the child combinator '>'. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchChildCombinator = (twig, node, opt = {}) => { + const { leaves } = twig; + const { dir } = opt; + const { parentNode } = node; + const matched = /* @__PURE__ */ new Set(); + if (dir === DIR_NEXT) { + let refNode = node.firstElementChild; + while (refNode) { + if (this._matchLeaves(leaves, refNode, opt)) { + matched.add(refNode); + } + refNode = refNode.nextElementSibling; + } + } else { + if (parentNode && this._matchLeaves(leaves, parentNode, opt)) { + matched.add(parentNode); + } + } + return matched; + }; + /** + * Matches the adjacent sibling combinator '+'. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchAdjacentSiblingCombinator = (twig, node, opt = {}) => { + const { leaves } = twig; + const { dir } = opt; + const matched = /* @__PURE__ */ new Set(); + const refNode = dir === DIR_NEXT ? node.nextElementSibling : node.previousElementSibling; + if (refNode && this._matchLeaves(leaves, refNode, opt)) { + matched.add(refNode); + } + return matched; + }; + /** + * Matches the general sibling combinator '~'. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchGeneralSiblingCombinator = (twig, node, opt = {}) => { + const { leaves } = twig; + const { dir } = opt; + const matched = /* @__PURE__ */ new Set(); + let refNode = dir === DIR_NEXT ? node.nextElementSibling : node.previousElementSibling; + while (refNode) { + if (this._matchLeaves(leaves, refNode, opt)) { + matched.add(refNode); + } + refNode = dir === DIR_NEXT ? refNode.nextElementSibling : refNode.previousElementSibling; + } + return matched; + }; + /** + * Matches a combinator. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchCombinator = (twig, node, opt = {}) => { + const { + combo: { name: comboName } + } = twig; + switch (comboName) { + case "+": { + return this._matchAdjacentSiblingCombinator(twig, node, opt); + } + case "~": { + return this._matchGeneralSiblingCombinator(twig, node, opt); + } + case ">": { + return this._matchChildCombinator(twig, node, opt); + } + case " ": + default: { + return this._matchDescendantCombinator(twig, node, opt); + } + } + }; + /** + * Traverses with a TreeWalker and collects nodes matching the leaves. + * @private + * @param {TreeWalker} walker - The TreeWalker instance to use. + * @param {Array} leaves - The AST leaves to match against. + * @param {object} options - Traversal options. + * @param {Node} options.startNode - The node to start traversal from. + * @param {string} options.targetType - The type of target ('all' or 'first'). + * @param {Node} [options.boundaryNode] - The node to stop traversal at. + * @param {boolean} [options.force] - Force traversal to the next node. + * @returns {Array.} An array of matched nodes. + */ + _traverseAndCollectNodes = (walker, leaves, options) => { + const { boundaryNode, force, startNode, targetType } = options; + const collectedNodes = []; + let currentNode = traverseNode(startNode, walker, !!force); + if (!currentNode) { + return []; + } + if (currentNode.nodeType !== ELEMENT_NODE) { + currentNode = walker.nextNode(); + } else if (currentNode === startNode && currentNode !== this.#root) { + currentNode = walker.nextNode(); + } + const matchOpt = { + warn: this.#warn + }; + while (currentNode) { + if (boundaryNode) { + if (currentNode === boundaryNode) { + break; + } else if (targetType === TARGET_ALL && !boundaryNode.contains(currentNode)) { + break; + } + } + if (this._matchLeaves(leaves, currentNode, matchOpt) && currentNode !== this.#node) { + collectedNodes.push(currentNode); + if (targetType !== TARGET_ALL) { + break; + } + } + currentNode = walker.nextNode(); + } + return collectedNodes; + }; + /** + * Finds matched node(s) preceding this.#node. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} node - The node to start from. + * @param {object} opt - Options. + * @param {boolean} [opt.force] - If true, traverses only to the next node. + * @param {string} [opt.targetType] - The target type. + * @returns {Array.} A collection of matched nodes. + */ + _findPrecede = (leaves, node, opt = {}) => { + const { force, targetType } = opt; + if (!this.#rootWalker) { + this.#rootWalker = this._createTreeWalker(this.#root); + } + return this._traverseAndCollectNodes(this.#rootWalker, leaves, { + force, + targetType, + boundaryNode: this.#node, + startNode: node + }); + }; + /** + * Finds matched node(s) in #nodeWalker. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} node - The node to start from. + * @param {object} opt - Options. + * @param {boolean} [opt.precede] - If true, finds preceding nodes. + * @returns {Array.} A collection of matched nodes. + */ + _findNodeWalker = (leaves, node, opt = {}) => { + const { precede, ...traversalOpts } = opt; + if (precede) { + const precedeNodes = this._findPrecede(leaves, this.#root, opt); + if (precedeNodes.length) { + return precedeNodes; + } + } + if (!this.#nodeWalker) { + this.#nodeWalker = this._createTreeWalker(this.#node); + } + return this._traverseAndCollectNodes(this.#nodeWalker, leaves, { + startNode: node, + ...traversalOpts + }); + }; + /** + * Matches the node itself. + * @private + * @param {Array} leaves - The AST leaves. + * @param {boolean} check - Indicates if running in internal check(). + * @returns {Array} An array containing [nodes, filtered, pseudoElement]. + */ + _matchSelf = (leaves, check = false) => { + const options = { check, warn: this.#warn }; + const matched = this._matchLeaves(leaves, this.#node, options); + const nodes = matched ? [this.#node] : []; + return [nodes, matched, this.#pseudoElement]; + }; + /** + * Finds lineal nodes (self and ancestors). + * @private + * @param {Array} leaves - The AST leaves. + * @param {object} opt - Options. + * @returns {Array} An array containing [nodes, filtered]. + */ + _findLineal = (leaves, opt) => { + const { complex } = opt; + const nodes = []; + const options = { warn: this.#warn }; + const selfMatched = this._matchLeaves(leaves, this.#node, options); + if (selfMatched) { + nodes.push(this.#node); + } + if (!selfMatched || complex) { + let currentNode = this.#node.parentNode; + while (currentNode) { + if (this._matchLeaves(leaves, currentNode, options)) { + nodes.push(currentNode); + } + currentNode = currentNode.parentNode; + } + } + const filtered = nodes.length > 0; + return [nodes, filtered]; + }; + /** + * Finds entry nodes for pseudo-element selectors. + * @private + * @param {object} leaf - The pseudo-element leaf from the AST. + * @param {Array.} filterLeaves - Leaves for compound selectors. + * @param {string} targetType - The type of target to find. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForPseudoElement = (leaf, filterLeaves, targetType) => { + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF && this.#check) { + const css = (0, import_css_tree.generate)(leaf); + this.#pseudoElement.push(css); + if (filterLeaves.length) { + [nodes, filtered] = this._matchSelf(filterLeaves, this.#check); + } else { + nodes.push(this.#node); + filtered = true; + } + } else { + matchPseudoElementSelector(leaf.name, leaf.type, { warn: this.#warn }); + } + return { nodes, filtered, pending: false }; + }; + /** + * Finds entry nodes for ID selectors. + * @private + * @param {object} twig - The current twig from the AST branch. + * @param {string} targetType - The type of target to find. + * @param {object} opt - Additional options for finding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForId = (twig, targetType, opt) => { + const { leaves } = twig; + const [leaf, ...filterLeaves] = leaves; + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else if (targetType === TARGET_FIRST && this.#root.nodeType !== ELEMENT_NODE) { + const node = this.#root.getElementById(leaf.name); + if (node) { + if (filterLeaves.length) { + if (this._matchLeaves(filterLeaves, node, { warn: this.#warn })) { + nodes.push(node); + filtered = true; + } + } else { + nodes.push(node); + filtered = true; + } + } + } else { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } + return { nodes, filtered, pending: false }; + }; + /** + * Finds entry nodes for class selectors. + * @private + * @param {Array.} leaves - The AST leaves for the selector. + * @param {string} targetType - The type of target to find. + * @param {object} opt - Additional options for finding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForClass = (leaves, targetType, opt) => { + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } + return { nodes, filtered, pending: false }; + }; + /** + * Finds entry nodes for type selectors. + * @private + * @param {Array.} leaves - The AST leaves for the selector. + * @param {string} targetType - The type of target to find. + * @param {object} opt - Additional options for finding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForType = (leaves, targetType, opt) => { + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } + return { nodes, filtered, pending: false }; + }; + /** + * Finds entry nodes for other selector types (default case). + * @private + * @param {object} twig - The current twig from the AST branch. + * @param {string} targetType - The type of target to find. + * @param {object} opt - Additional options for finding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForOther = (twig, targetType, opt) => { + const { leaves } = twig; + const [leaf, ...filterLeaves] = leaves; + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + let pending = false; + if (targetType !== TARGET_LINEAL && /host(?:-context)?/.test(leaf.name)) { + let shadowRoot = null; + if (this.#shadow && this.#node.nodeType === DOCUMENT_FRAGMENT_NODE) { + shadowRoot = this._matchShadowHostPseudoClass(leaf, this.#node); + } else if (filterLeaves.length && this.#node.nodeType === ELEMENT_NODE) { + shadowRoot = this._matchShadowHostPseudoClass( + leaf, + this.#node.shadowRoot + ); + } + if (shadowRoot) { + let bool = true; + const l = filterLeaves.length; + for (let i = 0; i < l; i++) { + const filterLeaf = filterLeaves[i]; + switch (filterLeaf.name) { + case "host": + case "host-context": { + const matchedNode = this._matchShadowHostPseudoClass( + filterLeaf, + shadowRoot + ); + bool = matchedNode === shadowRoot; + break; + } + case "has": { + bool = this._matchPseudoClassSelector( + filterLeaf, + shadowRoot, + {} + ).has(shadowRoot); + break; + } + default: { + bool = false; + } + } + if (!bool) { + break; + } + } + if (bool) { + nodes.push(shadowRoot); + filtered = true; + } + } + } else if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else if (targetType === TARGET_FIRST) { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } else { + pending = true; + } + return { nodes, filtered, pending }; + }; + /** + * Finds entry nodes. + * @private + * @param {object} twig - The twig object. + * @param {string} targetType - The target type. + * @param {object} [opt] - Options. + * @param {boolean} [opt.complex] - If true, the selector is complex. + * @param {string} [opt.dir] - The find direction. + * @returns {object} An object with nodes and their state. + */ + _findEntryNodes = (twig, targetType, opt = {}) => { + const { leaves } = twig; + const [leaf, ...filterLeaves] = leaves; + const { complex = false, dir = DIR_PREV } = opt; + const precede = dir === DIR_NEXT && this.#node.nodeType === ELEMENT_NODE && this.#node !== this.#root; + let result; + switch (leaf.type) { + case PS_ELEMENT_SELECTOR: { + result = this._findEntryNodesForPseudoElement( + leaf, + filterLeaves, + targetType + ); + break; + } + case ID_SELECTOR: { + result = this._findEntryNodesForId(twig, targetType, { + complex, + precede + }); + break; + } + case CLASS_SELECTOR: { + result = this._findEntryNodesForClass(leaves, targetType, { + complex, + precede + }); + break; + } + case TYPE_SELECTOR: { + result = this._findEntryNodesForType(leaves, targetType, { + complex, + precede + }); + break; + } + default: { + result = this._findEntryNodesForOther(twig, targetType, { + complex, + precede + }); + } + } + return { + compound: filterLeaves.length > 0, + filtered: result.filtered, + nodes: result.nodes, + pending: result.pending + }; + }; + /** + * Determines the direction and starting twig for a selector branch. + * @private + * @param {Array.} branch - The AST branch. + * @param {string} targetType - The type of target to find. + * @returns {object} An object with the direction and starting twig. + */ + _determineTraversalStrategy = (branch, targetType) => { + const branchLen = branch.length; + const firstTwig = branch[0]; + const lastTwig = branch[branchLen - 1]; + if (branchLen === 1) { + return { dir: DIR_PREV, twig: firstTwig }; + } + const { + leaves: [{ name: firstName, type: firstType }] + } = firstTwig; + const { + leaves: [{ name: lastName, type: lastType }] + } = lastTwig; + const { combo: firstCombo } = firstTwig; + if (this.#selector.includes(":scope") || lastType === PS_ELEMENT_SELECTOR || lastType === ID_SELECTOR) { + return { dir: DIR_PREV, twig: lastTwig }; + } + if (firstType === ID_SELECTOR) { + return { dir: DIR_NEXT, twig: firstTwig }; + } + if (firstName === "*" && firstType === TYPE_SELECTOR) { + return { dir: DIR_PREV, twig: lastTwig }; + } + if (lastName === "*" && lastType === TYPE_SELECTOR) { + return { dir: DIR_NEXT, twig: firstTwig }; + } + if (branchLen === 2) { + if (targetType === TARGET_FIRST) { + return { dir: DIR_PREV, twig: lastTwig }; + } + const { name: comboName } = firstCombo; + if (comboName === "+" || comboName === "~") { + return { dir: DIR_PREV, twig: lastTwig }; + } + } else if (branchLen > 2 && this.#scoped && targetType === TARGET_FIRST) { + if (lastType === TYPE_SELECTOR) { + return { dir: DIR_PREV, twig: lastTwig }; + } + let isChildOrDescendant = false; + for (const { combo } of branch) { + if (combo) { + const { name: comboName } = combo; + isChildOrDescendant = comboName === ">" || comboName === " "; + if (!isChildOrDescendant) { + break; + } + } + } + if (isChildOrDescendant) { + return { dir: DIR_PREV, twig: lastTwig }; + } + } + return { dir: DIR_NEXT, twig: firstTwig }; + }; + /** + * Processes pending items not resolved with a direct strategy. + * @private + * @param {Set.} pendingItems - The set of pending items. + */ + _processPendingItems = (pendingItems) => { + if (!pendingItems.size) { + return; + } + if (!this.#rootWalker) { + this.#rootWalker = this._createTreeWalker(this.#root); + } + const walker = this.#rootWalker; + let node = this.#root; + if (this.#scoped) { + node = this.#node; + } + let nextNode = traverseNode(node, walker); + while (nextNode) { + const isWithinScope = this.#node.nodeType !== ELEMENT_NODE || nextNode === this.#node || this.#node.contains(nextNode); + if (isWithinScope) { + for (const pendingItem of pendingItems) { + const { leaves } = pendingItem.get("twig"); + if (this._matchLeaves(leaves, nextNode, { warn: this.#warn })) { + const index = pendingItem.get("index"); + this.#ast[index].filtered = true; + this.#ast[index].find = true; + this.#nodes[index].push(nextNode); + } + } + } else if (this.#scoped) { + break; + } + nextNode = walker.nextNode(); + } + }; + /** + * Collects nodes. + * @private + * @param {string} targetType - The target type. + * @returns {Array.>} An array containing the AST and nodes. + */ + _collectNodes = (targetType) => { + const ast = this.#ast.values(); + if (targetType === TARGET_ALL || targetType === TARGET_FIRST) { + const pendingItems = /* @__PURE__ */ new Set(); + let i = 0; + for (const { branch } of ast) { + const complex = branch.length > 1; + const { dir, twig } = this._determineTraversalStrategy( + branch, + targetType + ); + const { compound, filtered, nodes, pending } = this._findEntryNodes( + twig, + targetType, + { complex, dir } + ); + if (nodes.length) { + this.#ast[i].find = true; + this.#nodes[i] = nodes; + } else if (pending) { + pendingItems.add( + /* @__PURE__ */ new Map([ + ["index", i], + ["twig", twig] + ]) + ); + } + this.#ast[i].dir = dir; + this.#ast[i].filtered = filtered || !compound; + i++; + } + this._processPendingItems(pendingItems); + } else { + let i = 0; + for (const { branch } of ast) { + const twig = branch[branch.length - 1]; + const complex = branch.length > 1; + const dir = DIR_PREV; + const { compound, filtered, nodes } = this._findEntryNodes( + twig, + targetType, + { complex, dir } + ); + if (nodes.length) { + this.#ast[i].find = true; + this.#nodes[i] = nodes; + } + this.#ast[i].dir = dir; + this.#ast[i].filtered = filtered || !compound; + i++; + } + } + return [this.#ast, this.#nodes]; + }; + /** + * Gets combined nodes. + * @private + * @param {object} twig - The twig object. + * @param {object} nodes - A collection of nodes. + * @param {string} dir - The direction. + * @returns {Array.} A collection of matched nodes. + */ + _getCombinedNodes = (twig, nodes, dir) => { + const arr = []; + const options = { + dir, + warn: this.#warn + }; + for (const node of nodes) { + const matched = this._matchCombinator(twig, node, options); + if (matched.size) { + arr.push(...matched); + } + } + return arr; + }; + /** + * Matches a node in the 'next' direction. + * @private + * @param {Array} branch - The branch. + * @param {Set.} nodes - A collection of Element nodes. + * @param {object} opt - Options. + * @param {object} opt.combo - The combo object. + * @param {number} opt.index - The index. + * @returns {?object} The matched node. + */ + _matchNodeNext = (branch, nodes, opt) => { + const { combo, index } = opt; + const { combo: nextCombo, leaves } = branch[index]; + const twig = { + combo, + leaves + }; + const nextNodes = new Set(this._getCombinedNodes(twig, nodes, DIR_NEXT)); + if (nextNodes.size) { + if (index === branch.length - 1) { + const [nextNode] = sortNodes(nextNodes); + return nextNode; + } + return this._matchNodeNext(branch, nextNodes, { + combo: nextCombo, + index: index + 1 + }); + } + return null; + }; + /** + * Matches a node in the 'previous' direction. + * @private + * @param {Array} branch - The branch. + * @param {object} node - The Element node. + * @param {object} opt - Options. + * @param {number} opt.index - The index. + * @returns {?object} The node. + */ + _matchNodePrev = (branch, node, opt) => { + const { index } = opt; + const twig = branch[index]; + const nodes = /* @__PURE__ */ new Set([node]); + const nextNodes = new Set(this._getCombinedNodes(twig, nodes, DIR_PREV)); + if (nextNodes.size) { + if (index === 0) { + return node; + } + let matched; + for (const nextNode of nextNodes) { + matched = this._matchNodePrev(branch, nextNode, { + index: index - 1 + }); + if (matched) { + break; + } + } + if (matched) { + return node; + } + } + return null; + }; + /** + * Processes a complex selector branch to find all matching nodes. + * @private + * @param {Array} branch - The selector branch from the AST. + * @param {Array} entryNodes - The initial set of nodes to start from. + * @param {string} dir - The direction of traversal ('next' or 'prev'). + * @returns {Set.} A set of all matched nodes. + */ + _processComplexBranchAll = (branch, entryNodes, dir) => { + const matchedNodes = /* @__PURE__ */ new Set(); + const branchLen = branch.length; + const lastIndex = branchLen - 1; + if (dir === DIR_NEXT) { + const { combo: firstCombo } = branch[0]; + for (const node of entryNodes) { + let combo = firstCombo; + let nextNodes = /* @__PURE__ */ new Set([node]); + for (let j = 1; j < branchLen; j++) { + const { combo: nextCombo, leaves } = branch[j]; + const twig = { combo, leaves }; + const nodesArr = this._getCombinedNodes(twig, nextNodes, dir); + if (nodesArr.length) { + if (j === lastIndex) { + for (const nextNode of nodesArr) { + matchedNodes.add(nextNode); + } + } + combo = nextCombo; + nextNodes = new Set(nodesArr); + } else { + nextNodes.clear(); + break; + } + } + } + } else { + for (const node of entryNodes) { + let nextNodes = /* @__PURE__ */ new Set([node]); + for (let j = lastIndex - 1; j >= 0; j--) { + const twig = branch[j]; + const nodesArr = this._getCombinedNodes(twig, nextNodes, dir); + if (nodesArr.length) { + if (j === 0) { + matchedNodes.add(node); + } + nextNodes = new Set(nodesArr); + } else { + nextNodes.clear(); + break; + } + } + } + } + return matchedNodes; + }; + /** + * Processes a complex selector branch to find the first matching node. + * @private + * @param {Array} branch - The selector branch from the AST. + * @param {Array} entryNodes - The initial set of nodes to start from. + * @param {string} dir - The direction of traversal ('next' or 'prev'). + * @param {string} targetType - The type of search (e.g., 'first'). + * @returns {?object} The first matched node, or null. + */ + _processComplexBranchFirst = (branch, entryNodes, dir, targetType) => { + const branchLen = branch.length; + const lastIndex = branchLen - 1; + if (dir === DIR_NEXT) { + const { combo: entryCombo } = branch[0]; + for (const node of entryNodes) { + const matchedNode = this._matchNodeNext(branch, /* @__PURE__ */ new Set([node]), { + combo: entryCombo, + index: 1 + }); + if (matchedNode) { + if (this.#node.nodeType === ELEMENT_NODE) { + if (matchedNode !== this.#node && this.#node.contains(matchedNode)) { + return matchedNode; + } + } else { + return matchedNode; + } + } + } + const { leaves: entryLeaves } = branch[0]; + const [entryNode] = entryNodes; + if (this.#node.contains(entryNode)) { + let [refNode] = this._findNodeWalker(entryLeaves, entryNode, { + targetType + }); + while (refNode) { + const matchedNode = this._matchNodeNext(branch, /* @__PURE__ */ new Set([refNode]), { + combo: entryCombo, + index: 1 + }); + if (matchedNode) { + if (this.#node.nodeType === ELEMENT_NODE) { + if (matchedNode !== this.#node && this.#node.contains(matchedNode)) { + return matchedNode; + } + } else { + return matchedNode; + } + } + [refNode] = this._findNodeWalker(entryLeaves, refNode, { + targetType, + force: true + }); + } + } + } else { + for (const node of entryNodes) { + const matchedNode = this._matchNodePrev(branch, node, { + index: lastIndex - 1 + }); + if (matchedNode) { + return matchedNode; + } + } + if (targetType === TARGET_FIRST) { + const { leaves: entryLeaves } = branch[lastIndex]; + const [entryNode] = entryNodes; + let [refNode] = this._findNodeWalker(entryLeaves, entryNode, { + targetType + }); + while (refNode) { + const matchedNode = this._matchNodePrev(branch, refNode, { + index: lastIndex - 1 + }); + if (matchedNode) { + return refNode; + } + [refNode] = this._findNodeWalker(entryLeaves, refNode, { + targetType, + force: true + }); + } + } + } + return null; + }; + /** + * Finds matched nodes. + * @param {string} targetType - The target type. + * @returns {Set.} A collection of matched nodes. + */ + find = (targetType) => { + const [[...branches], collectedNodes] = this._collectNodes(targetType); + const l = branches.length; + let sort = l > 1 && targetType === TARGET_ALL && this.#selector.includes(":scope"); + let nodes = /* @__PURE__ */ new Set(); + for (let i = 0; i < l; i++) { + const { branch, dir, find: find3 } = branches[i]; + if (!branch.length || !find3) { + continue; + } + const entryNodes = collectedNodes[i]; + const lastIndex = branch.length - 1; + if (lastIndex === 0) { + if ((targetType === TARGET_ALL || targetType === TARGET_FIRST) && this.#node.nodeType === ELEMENT_NODE) { + for (const node of entryNodes) { + if (node !== this.#node && this.#node.contains(node)) { + nodes.add(node); + if (targetType === TARGET_FIRST) { + break; + } + } + } + } else if (targetType === TARGET_ALL) { + if (nodes.size) { + for (const node of entryNodes) { + nodes.add(node); + } + sort = true; + } else { + nodes = new Set(entryNodes); + } + } else { + if (entryNodes.length) { + nodes.add(entryNodes[0]); + } + } + } else { + if (targetType === TARGET_ALL) { + const newNodes = this._processComplexBranchAll( + branch, + entryNodes, + dir + ); + if (nodes.size) { + for (const newNode of newNodes) { + nodes.add(newNode); + } + sort = true; + } else { + nodes = newNodes; + } + } else { + const matchedNode = this._processComplexBranchFirst( + branch, + entryNodes, + dir, + targetType + ); + if (matchedNode) { + nodes.add(matchedNode); + } + } + } + } + if (this.#check) { + const match = !!nodes.size; + let pseudoElement; + if (this.#pseudoElement.length) { + pseudoElement = this.#pseudoElement.join(""); + } else { + pseudoElement = null; + } + return { match, pseudoElement }; + } + if (targetType === TARGET_FIRST || targetType === TARGET_ALL) { + nodes.delete(this.#node); + } + if ((sort || targetType === TARGET_FIRST) && nodes.size > 1) { + return new Set(sortNodes(nodes)); + } + return nodes; + }; +}; + +// src/index.js +var MAX_CACHE = 1024; +var DOMSelector = class { + /* private fields */ + #window; + #document; + #finder; + #idlUtils; + #nwsapi; + #cache; + /** + * Creates an instance of DOMSelector. + * @param {Window} window - The window object. + * @param {Document} document - The document object. + * @param {object} [opt] - Options. + */ + constructor(window, document, opt = {}) { + const { idlUtils } = opt; + this.#window = window; + this.#document = document ?? window.document; + this.#finder = new Finder(window); + this.#idlUtils = idlUtils; + this.#nwsapi = initNwsapi(window, document); + this.#cache = new import_lru_cache.LRUCache({ + max: MAX_CACHE + }); + } + /** + * Clears the internal cache of finder results. + * @returns {void} + */ + clear = () => { + this.#finder.clearResults(true); + }; + /** + * Checks if an element matches a CSS selector. + * @param {string} selector - The CSS selector to check against. + * @param {Element} node - The element node to check. + * @param {object} [opt] - Optional parameters. + * @returns {CheckResult} An object containing the check result. + */ + check = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } else if (node.nodeType !== ELEMENT_NODE) { + const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`); + return this.#finder.onError(e, opt); + } + const document = node.ownerDocument; + if (document === this.#document && document.contentType === "text/html" && document.documentElement && node.parentNode) { + const cacheKey = `check_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_SELF); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const match = this.#nwsapi.match(selector, n); + return { + match, + pseudoElement: null + }; + } catch (e) { + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + opt.check = true; + opt.noexept = true; + opt.warn = false; + this.#finder.setup(selector, node, opt); + res = this.#finder.find(TARGET_SELF); + } catch (e) { + this.#finder.onError(e, opt); + } + return res; + }; + /** + * Returns true if the element matches the selector. + * @param {string} selector - The CSS selector to match against. + * @param {Element} node - The element node to test. + * @param {object} [opt] - Optional parameters. + * @returns {boolean} `true` if the element matches, or `false` otherwise. + */ + matches = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } else if (node.nodeType !== ELEMENT_NODE) { + const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`); + return this.#finder.onError(e, opt); + } + const document = node.ownerDocument; + if (document === this.#document && document.contentType === "text/html" && document.documentElement && node.parentNode) { + const cacheKey = `matches_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_SELF); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const res2 = this.#nwsapi.match(selector, n); + return res2; + } catch (e) { + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + this.#finder.setup(selector, node, opt); + const nodes = this.#finder.find(TARGET_SELF); + res = nodes.size; + } catch (e) { + this.#finder.onError(e, opt); + } + return !!res; + }; + /** + * Traverses up the DOM tree to find the first node that matches the selector. + * @param {string} selector - The CSS selector to match against. + * @param {Element} node - The element from which to start traversing. + * @param {object} [opt] - Optional parameters. + * @returns {?Element} The first matching ancestor element, or `null`. + */ + closest = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } else if (node.nodeType !== ELEMENT_NODE) { + const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`); + return this.#finder.onError(e, opt); + } + const document = node.ownerDocument; + if (document === this.#document && document.contentType === "text/html" && document.documentElement && node.parentNode) { + const cacheKey = `closest_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_LINEAL); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const res2 = this.#nwsapi.closest(selector, n); + return res2; + } catch (e) { + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + this.#finder.setup(selector, node, opt); + const nodes = this.#finder.find(TARGET_LINEAL); + if (nodes.size) { + let refNode = node; + while (refNode) { + if (nodes.has(refNode)) { + res = refNode; + break; + } + refNode = refNode.parentNode; + } + } + } catch (e) { + this.#finder.onError(e, opt); + } + return res ?? null; + }; + /** + * Returns the first element within the subtree that matches the selector. + * @param {string} selector - The CSS selector to match. + * @param {Document|DocumentFragment|Element} node - The node to find within. + * @param {object} [opt] - Optional parameters. + * @returns {?Element} The first matching element, or `null`. + */ + querySelector = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + this.#finder.setup(selector, node, opt); + const nodes = this.#finder.find(TARGET_FIRST); + if (nodes.size) { + [res] = [...nodes]; + } + } catch (e) { + this.#finder.onError(e, opt); + } + return res ?? null; + }; + /** + * Returns an array of elements within the subtree that match the selector. + * Note: This method returns an Array, not a NodeList. + * @param {string} selector - The CSS selector to match. + * @param {Document|DocumentFragment|Element} node - The node to find within. + * @param {object} [opt] - Optional parameters. + * @returns {Array} An array of elements, or an empty array. + */ + querySelectorAll = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } + const document = node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument; + if (document === this.#document && document.contentType === "text/html" && document.documentElement && (node.nodeType !== DOCUMENT_FRAGMENT_NODE || !node.host)) { + const cacheKey = `querySelectorAll_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_ALL); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const res2 = this.#nwsapi.select(selector, n); + return res2; + } catch (e) { + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + this.#finder.setup(selector, node, opt); + const nodes = this.#finder.find(TARGET_ALL); + if (nodes.size) { + res = [...nodes]; + } + } catch (e) { + this.#finder.onError(e, opt); + } + return res ?? []; + }; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + DOMSelector +}); +/*! + * DOM Selector - A CSS selector engine. + * @license MIT + * @copyright asamuzaK (Kazz) + * @see {@link https://github.com/asamuzaK/domSelector/blob/main/LICENSE} + */ +//# sourceMappingURL=index.cjs.map \ No newline at end of file diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.cjs.map b/vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.cjs.map new file mode 100644 index 0000000..e8327b1 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.cjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/index.js","../../src/js/parser.js","../../src/js/utility.js","../../src/js/constant.js","../../src/js/matcher.js","../../src/js/finder.js"],"sourcesContent":["/*!\n * DOM Selector - A CSS selector engine.\n * @license MIT\n * @copyright asamuzaK (Kazz)\n * @see {@link https://github.com/asamuzaK/domSelector/blob/main/LICENSE}\n */\n\n/* import */\nimport { LRUCache } from 'lru-cache';\nimport { Finder } from './js/finder.js';\nimport { filterSelector, getType, initNwsapi } from './js/utility.js';\n\n/* constants */\nimport {\n DOCUMENT_NODE,\n DOCUMENT_FRAGMENT_NODE,\n ELEMENT_NODE,\n TARGET_ALL,\n TARGET_FIRST,\n TARGET_LINEAL,\n TARGET_SELF\n} from './js/constant.js';\nconst MAX_CACHE = 1024;\n\n/**\n * @typedef {object} CheckResult\n * @property {boolean} match - The match result.\n * @property {string?} pseudoElement - The pseudo-element, if any.\n */\n\n/* DOMSelector */\nexport class DOMSelector {\n /* private fields */\n #window;\n #document;\n #finder;\n #idlUtils;\n #nwsapi;\n #cache;\n\n /**\n * Creates an instance of DOMSelector.\n * @param {Window} window - The window object.\n * @param {Document} document - The document object.\n * @param {object} [opt] - Options.\n */\n constructor(window, document, opt = {}) {\n const { idlUtils } = opt;\n this.#window = window;\n this.#document = document ?? window.document;\n this.#finder = new Finder(window);\n this.#idlUtils = idlUtils;\n this.#nwsapi = initNwsapi(window, document);\n this.#cache = new LRUCache({\n max: MAX_CACHE\n });\n }\n\n /**\n * Clears the internal cache of finder results.\n * @returns {void}\n */\n clear = () => {\n this.#finder.clearResults(true);\n };\n\n /**\n * Checks if an element matches a CSS selector.\n * @param {string} selector - The CSS selector to check against.\n * @param {Element} node - The element node to check.\n * @param {object} [opt] - Optional parameters.\n * @returns {CheckResult} An object containing the check result.\n */\n check = (selector, node, opt = {}) => {\n if (!node?.nodeType) {\n const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);\n return this.#finder.onError(e, opt);\n } else if (node.nodeType !== ELEMENT_NODE) {\n const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`);\n return this.#finder.onError(e, opt);\n }\n const document = node.ownerDocument;\n if (\n document === this.#document &&\n document.contentType === 'text/html' &&\n document.documentElement &&\n node.parentNode\n ) {\n const cacheKey = `check_${selector}`;\n let filterMatches = false;\n if (this.#cache.has(cacheKey)) {\n filterMatches = this.#cache.get(cacheKey);\n } else {\n filterMatches = filterSelector(selector, TARGET_SELF);\n this.#cache.set(cacheKey, filterMatches);\n }\n if (filterMatches) {\n try {\n const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node;\n const match = this.#nwsapi.match(selector, n);\n return {\n match,\n pseudoElement: null\n };\n } catch (e) {\n // fall through\n }\n }\n }\n let res;\n try {\n if (this.#idlUtils) {\n node = this.#idlUtils.wrapperForImpl(node);\n }\n opt.check = true;\n opt.noexept = true;\n opt.warn = false;\n this.#finder.setup(selector, node, opt);\n res = this.#finder.find(TARGET_SELF);\n } catch (e) {\n this.#finder.onError(e, opt);\n }\n return res;\n };\n\n /**\n * Returns true if the element matches the selector.\n * @param {string} selector - The CSS selector to match against.\n * @param {Element} node - The element node to test.\n * @param {object} [opt] - Optional parameters.\n * @returns {boolean} `true` if the element matches, or `false` otherwise.\n */\n matches = (selector, node, opt = {}) => {\n if (!node?.nodeType) {\n const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);\n return this.#finder.onError(e, opt);\n } else if (node.nodeType !== ELEMENT_NODE) {\n const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`);\n return this.#finder.onError(e, opt);\n }\n const document = node.ownerDocument;\n if (\n document === this.#document &&\n document.contentType === 'text/html' &&\n document.documentElement &&\n node.parentNode\n ) {\n const cacheKey = `matches_${selector}`;\n let filterMatches = false;\n if (this.#cache.has(cacheKey)) {\n filterMatches = this.#cache.get(cacheKey);\n } else {\n filterMatches = filterSelector(selector, TARGET_SELF);\n this.#cache.set(cacheKey, filterMatches);\n }\n if (filterMatches) {\n try {\n const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node;\n const res = this.#nwsapi.match(selector, n);\n return res;\n } catch (e) {\n // fall through\n }\n }\n }\n let res;\n try {\n if (this.#idlUtils) {\n node = this.#idlUtils.wrapperForImpl(node);\n }\n this.#finder.setup(selector, node, opt);\n const nodes = this.#finder.find(TARGET_SELF);\n res = nodes.size;\n } catch (e) {\n this.#finder.onError(e, opt);\n }\n return !!res;\n };\n\n /**\n * Traverses up the DOM tree to find the first node that matches the selector.\n * @param {string} selector - The CSS selector to match against.\n * @param {Element} node - The element from which to start traversing.\n * @param {object} [opt] - Optional parameters.\n * @returns {?Element} The first matching ancestor element, or `null`.\n */\n closest = (selector, node, opt = {}) => {\n if (!node?.nodeType) {\n const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);\n return this.#finder.onError(e, opt);\n } else if (node.nodeType !== ELEMENT_NODE) {\n const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`);\n return this.#finder.onError(e, opt);\n }\n const document = node.ownerDocument;\n if (\n document === this.#document &&\n document.contentType === 'text/html' &&\n document.documentElement &&\n node.parentNode\n ) {\n const cacheKey = `closest_${selector}`;\n let filterMatches = false;\n if (this.#cache.has(cacheKey)) {\n filterMatches = this.#cache.get(cacheKey);\n } else {\n filterMatches = filterSelector(selector, TARGET_LINEAL);\n this.#cache.set(cacheKey, filterMatches);\n }\n if (filterMatches) {\n try {\n const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node;\n const res = this.#nwsapi.closest(selector, n);\n return res;\n } catch (e) {\n // fall through\n }\n }\n }\n let res;\n try {\n if (this.#idlUtils) {\n node = this.#idlUtils.wrapperForImpl(node);\n }\n this.#finder.setup(selector, node, opt);\n const nodes = this.#finder.find(TARGET_LINEAL);\n if (nodes.size) {\n let refNode = node;\n while (refNode) {\n if (nodes.has(refNode)) {\n res = refNode;\n break;\n }\n refNode = refNode.parentNode;\n }\n }\n } catch (e) {\n this.#finder.onError(e, opt);\n }\n return res ?? null;\n };\n\n /**\n * Returns the first element within the subtree that matches the selector.\n * @param {string} selector - The CSS selector to match.\n * @param {Document|DocumentFragment|Element} node - The node to find within.\n * @param {object} [opt] - Optional parameters.\n * @returns {?Element} The first matching element, or `null`.\n */\n querySelector = (selector, node, opt = {}) => {\n if (!node?.nodeType) {\n const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);\n return this.#finder.onError(e, opt);\n }\n /*\n const document =\n node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument;\n if (\n document === this.#document &&\n document.contentType === 'text/html' &&\n document.documentElement &&\n (node.nodeType !== DOCUMENT_FRAGMENT_NODE || !node.host)\n ) {\n const cacheKey = `querySelector_${selector}`;\n let filterMatches = false;\n if (this.#cache.has(cacheKey)) {\n filterMatches = this.#cache.get(cacheKey);\n } else {\n filterMatches = filterSelector(selector, TARGET_FIRST);\n this.#cache.set(cacheKey, filterMatches);\n }\n if (filterMatches) {\n try {\n const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node;\n const res = this.#nwsapi.first(selector, n);\n return res;\n } catch (e) {\n // fall through\n }\n }\n }\n */\n let res;\n try {\n if (this.#idlUtils) {\n node = this.#idlUtils.wrapperForImpl(node);\n }\n this.#finder.setup(selector, node, opt);\n const nodes = this.#finder.find(TARGET_FIRST);\n if (nodes.size) {\n [res] = [...nodes];\n }\n } catch (e) {\n this.#finder.onError(e, opt);\n }\n return res ?? null;\n };\n\n /**\n * Returns an array of elements within the subtree that match the selector.\n * Note: This method returns an Array, not a NodeList.\n * @param {string} selector - The CSS selector to match.\n * @param {Document|DocumentFragment|Element} node - The node to find within.\n * @param {object} [opt] - Optional parameters.\n * @returns {Array} An array of elements, or an empty array.\n */\n querySelectorAll = (selector, node, opt = {}) => {\n if (!node?.nodeType) {\n const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);\n return this.#finder.onError(e, opt);\n }\n const document =\n node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument;\n if (\n document === this.#document &&\n document.contentType === 'text/html' &&\n document.documentElement &&\n (node.nodeType !== DOCUMENT_FRAGMENT_NODE || !node.host)\n ) {\n const cacheKey = `querySelectorAll_${selector}`;\n let filterMatches = false;\n if (this.#cache.has(cacheKey)) {\n filterMatches = this.#cache.get(cacheKey);\n } else {\n filterMatches = filterSelector(selector, TARGET_ALL);\n this.#cache.set(cacheKey, filterMatches);\n }\n if (filterMatches) {\n try {\n const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node;\n const res = this.#nwsapi.select(selector, n);\n return res;\n } catch (e) {\n // fall through\n }\n }\n }\n let res;\n try {\n if (this.#idlUtils) {\n node = this.#idlUtils.wrapperForImpl(node);\n }\n this.#finder.setup(selector, node, opt);\n const nodes = this.#finder.find(TARGET_ALL);\n if (nodes.size) {\n res = [...nodes];\n }\n } catch (e) {\n this.#finder.onError(e, opt);\n }\n return res ?? [];\n };\n}\n","/**\n * parser.js\n */\n\n/* import */\nimport * as cssTree from 'css-tree';\nimport { getType } from './utility.js';\n\n/* constants */\nimport {\n ATTR_SELECTOR,\n BIT_01,\n BIT_02,\n BIT_04,\n BIT_08,\n BIT_16,\n BIT_32,\n BIT_FFFF,\n CLASS_SELECTOR,\n DUO,\n HEX,\n ID_SELECTOR,\n KEYS_LOGICAL,\n NTH,\n PS_CLASS_SELECTOR,\n PS_ELEMENT_SELECTOR,\n SELECTOR,\n SYNTAX_ERR,\n TYPE_SELECTOR\n} from './constant.js';\nconst AST_SORT_ORDER = new Map([\n [PS_ELEMENT_SELECTOR, BIT_01],\n [ID_SELECTOR, BIT_02],\n [CLASS_SELECTOR, BIT_04],\n [TYPE_SELECTOR, BIT_08],\n [ATTR_SELECTOR, BIT_16],\n [PS_CLASS_SELECTOR, BIT_32]\n]);\nconst KEYS_PS_CLASS_STATE = new Set([\n 'checked',\n 'closed',\n 'disabled',\n 'empty',\n 'enabled',\n 'in-range',\n 'indeterminate',\n 'invalid',\n 'open',\n 'out-of-range',\n 'placeholder-shown',\n 'read-only',\n 'read-write',\n 'valid'\n]);\nconst KEYS_SHADOW_HOST = new Set(['host', 'host-context']);\nconst REG_EMPTY_PS_FUNC =\n /(?<=:(?:dir|has|host(?:-context)?|is|lang|not|nth-(?:last-)?(?:child|of-type)|where))\\(\\s+\\)/g;\nconst REG_SHADOW_PS_ELEMENT = /^part|slotted$/;\nconst U_FFFD = '\\uFFFD';\n\n/**\n * Unescapes a CSS selector string.\n * @param {string} selector - The CSS selector to unescape.\n * @returns {string} The unescaped selector string.\n */\nexport const unescapeSelector = (selector = '') => {\n if (typeof selector === 'string' && selector.indexOf('\\\\', 0) >= 0) {\n const arr = selector.split('\\\\');\n const selectorItems = [arr[0]];\n const l = arr.length;\n for (let i = 1; i < l; i++) {\n const item = arr[i];\n if (item === '' && i === l - 1) {\n selectorItems.push(U_FFFD);\n } else {\n const hexExists = /^([\\da-f]{1,6}\\s?)/i.exec(item);\n if (hexExists) {\n const [, hex] = hexExists;\n let str;\n try {\n const low = parseInt('D800', HEX);\n const high = parseInt('DFFF', HEX);\n const deci = parseInt(hex, HEX);\n if (deci === 0 || (deci >= low && deci <= high)) {\n str = U_FFFD;\n } else {\n str = String.fromCodePoint(deci);\n }\n } catch (e) {\n str = U_FFFD;\n }\n let postStr = '';\n if (item.length > hex.length) {\n postStr = item.substring(hex.length);\n }\n selectorItems.push(`${str}${postStr}`);\n // whitespace\n } else if (/^[\\n\\r\\f]/.test(item)) {\n selectorItems.push(`\\\\${item}`);\n } else {\n selectorItems.push(item);\n }\n }\n }\n return selectorItems.join('');\n }\n return selector;\n};\n\n/**\n * Preprocesses a selector string according to the specification.\n * @see https://drafts.csswg.org/css-syntax-3/#input-preprocessing\n * @param {string} value - The value to preprocess.\n * @returns {string} The preprocessed selector string.\n */\nexport const preprocess = value => {\n // Non-string values will be converted to string.\n if (typeof value !== 'string') {\n if (value === undefined || value === null) {\n return getType(value).toLowerCase();\n } else if (Array.isArray(value)) {\n return value.join(',');\n } else if (Object.hasOwn(value, 'toString')) {\n return value.toString();\n } else {\n throw new DOMException(`Invalid selector ${value}`, SYNTAX_ERR);\n }\n }\n let selector = value;\n let index = 0;\n while (index >= 0) {\n // @see https://drafts.csswg.org/selectors/#id-selectors\n index = selector.indexOf('#', index);\n if (index < 0) {\n break;\n }\n const preHash = selector.substring(0, index + 1);\n let postHash = selector.substring(index + 1);\n const codePoint = postHash.codePointAt(0);\n if (codePoint > BIT_FFFF) {\n const str = `\\\\${codePoint.toString(HEX)} `;\n if (postHash.length === DUO) {\n postHash = str;\n } else {\n postHash = `${str}${postHash.substring(DUO)}`;\n }\n }\n selector = `${preHash}${postHash}`;\n index++;\n }\n return selector\n .replace(/\\f|\\r\\n?/g, '\\n')\n .replace(/[\\0\\uD800-\\uDFFF]|\\\\$/g, U_FFFD)\n .replace(/\\x26/g, ':scope');\n};\n\n/**\n * Creates an Abstract Syntax Tree (AST) from a CSS selector string.\n * @param {string} sel - The CSS selector string.\n * @returns {object} The parsed AST object.\n */\nexport const parseSelector = sel => {\n const selector = preprocess(sel);\n // invalid selectors\n if (/^$|^\\s*>|,\\s*$/.test(selector)) {\n throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);\n }\n try {\n const ast = cssTree.parse(selector, {\n context: 'selectorList',\n parseCustomProperty: true\n });\n return cssTree.toPlainObject(ast);\n } catch (e) {\n const { message } = e;\n if (\n /^(?:\"\\]\"|Attribute selector [()\\s,=~^$*|]+) is expected$/.test(\n message\n ) &&\n !selector.endsWith(']')\n ) {\n const index = selector.lastIndexOf('[');\n const selPart = selector.substring(index);\n if (selPart.includes('\"')) {\n const quotes = selPart.match(/\"/g).length;\n if (quotes % 2) {\n return parseSelector(`${selector}\"]`);\n }\n return parseSelector(`${selector}]`);\n }\n return parseSelector(`${selector}]`);\n } else if (message === '\")\" is expected') {\n // workaround for https://github.com/csstree/csstree/issues/283\n if (REG_EMPTY_PS_FUNC.test(selector)) {\n return parseSelector(`${selector.replaceAll(REG_EMPTY_PS_FUNC, '()')}`);\n } else if (!selector.endsWith(')')) {\n return parseSelector(`${selector})`);\n } else {\n throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);\n }\n } else {\n throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);\n }\n }\n};\n\n/**\n * Walks the provided AST to collect selector branches and gather information\n * about its contents.\n * @param {object} ast - The AST to traverse.\n * @returns {{branches: Array, info: object}} An object containing the selector branches and info.\n */\nexport const walkAST = (ast = {}) => {\n const branches = new Set();\n const info = {\n hasForgivenPseudoFunc: false,\n hasHasPseudoFunc: false,\n hasLogicalPseudoFunc: false,\n hasNotPseudoFunc: false,\n hasNthChildOfSelector: false,\n hasNestedSelector: false,\n hasStatePseudoClass: false\n };\n const opt = {\n enter(node) {\n switch (node.type) {\n case CLASS_SELECTOR: {\n if (/^-?\\d/.test(node.name)) {\n throw new DOMException(\n `Invalid selector .${node.name}`,\n SYNTAX_ERR\n );\n }\n break;\n }\n case ID_SELECTOR: {\n if (/^-?\\d/.test(node.name)) {\n throw new DOMException(\n `Invalid selector #${node.name}`,\n SYNTAX_ERR\n );\n }\n break;\n }\n case PS_CLASS_SELECTOR: {\n if (KEYS_LOGICAL.has(node.name)) {\n info.hasNestedSelector = true;\n info.hasLogicalPseudoFunc = true;\n if (node.name === 'has') {\n info.hasHasPseudoFunc = true;\n } else if (node.name === 'not') {\n info.hasNotPseudoFunc = true;\n } else {\n info.hasForgivenPseudoFunc = true;\n }\n } else if (KEYS_PS_CLASS_STATE.has(node.name)) {\n info.hasStatePseudoClass = true;\n } else if (\n KEYS_SHADOW_HOST.has(node.name) &&\n Array.isArray(node.children) &&\n node.children.length\n ) {\n info.hasNestedSelector = true;\n }\n break;\n }\n case PS_ELEMENT_SELECTOR: {\n if (REG_SHADOW_PS_ELEMENT.test(node.name)) {\n info.hasNestedSelector = true;\n }\n break;\n }\n case NTH: {\n if (node.selector) {\n info.hasNestedSelector = true;\n info.hasNthChildOfSelector = true;\n }\n break;\n }\n case SELECTOR: {\n branches.add(node.children);\n break;\n }\n default:\n }\n }\n };\n cssTree.walk(ast, opt);\n if (info.hasNestedSelector === true) {\n cssTree.findAll(ast, (node, item, list) => {\n if (list) {\n if (node.type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(node.name)) {\n const itemList = list.filter(i => {\n const { name, type } = i;\n return type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(name);\n });\n for (const { children } of itemList) {\n // SelectorList\n for (const { children: grandChildren } of children) {\n // Selector\n for (const { children: greatGrandChildren } of grandChildren) {\n if (branches.has(greatGrandChildren)) {\n branches.delete(greatGrandChildren);\n }\n }\n }\n }\n } else if (\n node.type === PS_CLASS_SELECTOR &&\n KEYS_SHADOW_HOST.has(node.name) &&\n Array.isArray(node.children) &&\n node.children.length\n ) {\n const itemList = list.filter(i => {\n const { children, name, type } = i;\n const res =\n type === PS_CLASS_SELECTOR &&\n KEYS_SHADOW_HOST.has(name) &&\n Array.isArray(children) &&\n children.length;\n return res;\n });\n for (const { children } of itemList) {\n // Selector\n for (const { children: grandChildren } of children) {\n if (branches.has(grandChildren)) {\n branches.delete(grandChildren);\n }\n }\n }\n } else if (\n node.type === PS_ELEMENT_SELECTOR &&\n REG_SHADOW_PS_ELEMENT.test(node.name)\n ) {\n const itemList = list.filter(i => {\n const { name, type } = i;\n const res =\n type === PS_ELEMENT_SELECTOR && REG_SHADOW_PS_ELEMENT.test(name);\n return res;\n });\n for (const { children } of itemList) {\n // Selector\n for (const { children: grandChildren } of children) {\n if (branches.has(grandChildren)) {\n branches.delete(grandChildren);\n }\n }\n }\n } else if (node.type === NTH && node.selector) {\n const itemList = list.filter(i => {\n const { selector, type } = i;\n const res = type === NTH && selector;\n return res;\n });\n for (const { selector } of itemList) {\n const { children } = selector;\n // Selector\n for (const { children: grandChildren } of children) {\n if (branches.has(grandChildren)) {\n branches.delete(grandChildren);\n }\n }\n }\n }\n }\n });\n }\n return {\n info,\n branches: [...branches]\n };\n};\n\n/**\n * Comparison function for sorting AST nodes based on specificity.\n * @param {object} a - The first AST node.\n * @param {object} b - The second AST node.\n * @returns {number} -1, 0 or 1, depending on the sort order.\n */\nexport const compareASTNodes = (a, b) => {\n const bitA = AST_SORT_ORDER.get(a.type);\n const bitB = AST_SORT_ORDER.get(b.type);\n if (bitA === bitB) {\n return 0;\n } else if (bitA > bitB) {\n return 1;\n } else {\n return -1;\n }\n};\n\n/**\n * Sorts a collection of AST nodes based on CSS specificity rules.\n * @param {Array} asts - A collection of AST nodes to sort.\n * @returns {Array} A new array containing the sorted AST nodes.\n */\nexport const sortAST = asts => {\n const arr = [...asts];\n if (arr.length > 1) {\n arr.sort(compareASTNodes);\n }\n return arr;\n};\n\n/**\n * Parses a type selector's name, which may include a namespace prefix.\n * @param {string} selector - The type selector name (e.g., 'ns|E' or 'E').\n * @returns {{prefix: string, localName: string}} An object with `prefix` and\n * `localName` properties.\n */\nexport const parseAstName = selector => {\n let prefix;\n let localName;\n if (selector && typeof selector === 'string') {\n if (selector.indexOf('|') > -1) {\n [prefix, localName] = selector.split('|');\n } else {\n prefix = '*';\n localName = selector;\n }\n } else {\n throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);\n }\n return {\n prefix,\n localName\n };\n};\n\n/* Re-exported from css-tree. */\nexport { find as findAST, generate as generateCSS } from 'css-tree';\n","/**\n * utility.js\n */\n\n/* import */\nimport nwsapi from '@asamuzakjp/nwsapi';\nimport bidiFactory from 'bidi-js';\nimport * as cssTree from 'css-tree';\nimport isCustomElementName from 'is-potential-custom-element-name';\n\n/* constants */\nimport {\n ATRULE,\n COMBO,\n COMPOUND_I,\n DESCEND,\n DOCUMENT_FRAGMENT_NODE,\n DOCUMENT_NODE,\n DOCUMENT_POSITION_CONTAINS,\n DOCUMENT_POSITION_PRECEDING,\n ELEMENT_NODE,\n HAS_COMPOUND,\n INPUT_BUTTON,\n INPUT_EDIT,\n INPUT_LTR,\n INPUT_TEXT,\n KEYS_LOGICAL,\n LOGIC_COMPLEX,\n LOGIC_COMPOUND,\n N_TH,\n PSEUDO_CLASS,\n RULE,\n SCOPE,\n SELECTOR_LIST,\n SIBLING,\n TARGET_ALL,\n TARGET_FIRST,\n TEXT_NODE,\n TYPE_FROM,\n TYPE_TO\n} from './constant.js';\nconst KEYS_DIR_AUTO = new Set([...INPUT_BUTTON, ...INPUT_TEXT, 'hidden']);\nconst KEYS_DIR_LTR = new Set(INPUT_LTR);\nconst KEYS_INPUT_EDIT = new Set(INPUT_EDIT);\nconst KEYS_NODE_DIR_EXCLUDE = new Set(['bdi', 'script', 'style', 'textarea']);\nconst KEYS_NODE_FOCUSABLE = new Set(['button', 'select', 'textarea']);\nconst KEYS_NODE_FOCUSABLE_SVG = new Set([\n 'clipPath',\n 'defs',\n 'desc',\n 'linearGradient',\n 'marker',\n 'mask',\n 'metadata',\n 'pattern',\n 'radialGradient',\n 'script',\n 'style',\n 'symbol',\n 'title'\n]);\nconst REG_EXCLUDE_BASIC =\n /[|\\\\]|::|[^\\u0021-\\u007F\\s]|\\[\\s*[\\w$*=^|~-]+(?:(?:\"[\\w$*=^|~\\s'-]+\"|'[\\w$*=^|~\\s\"-]+')?(?:\\s+[\\w$*=^|~-]+)+|\"[^\"\\]]{1,255}|'[^'\\]]{1,255})\\s*\\]|:(?:is|where)\\(\\s*\\)/;\nconst REG_COMPLEX = new RegExp(`${COMPOUND_I}${COMBO}${COMPOUND_I}`, 'i');\nconst REG_DESCEND = new RegExp(`${COMPOUND_I}${DESCEND}${COMPOUND_I}`, 'i');\nconst REG_SIBLING = new RegExp(`${COMPOUND_I}${SIBLING}${COMPOUND_I}`, 'i');\nconst REG_LOGIC_COMPLEX = new RegExp(\n `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPLEX})`\n);\nconst REG_LOGIC_COMPOUND = new RegExp(\n `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND})`\n);\nconst REG_LOGIC_HAS_COMPOUND = new RegExp(\n `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND}|${HAS_COMPOUND})`\n);\nconst REG_END_WITH_HAS = new RegExp(`:${HAS_COMPOUND}$`);\nconst REG_WO_LOGICAL = new RegExp(`:(?!${PSEUDO_CLASS}|${N_TH})`);\nconst REG_IS_HTML = /^(?:application\\/xhtml\\+x|text\\/ht)ml$/;\nconst REG_IS_XML =\n /^(?:application\\/(?:[\\w\\-.]+\\+)?|image\\/[\\w\\-.]+\\+|text\\/)xml$/;\n\n/**\n * Manages state for extracting nested selectors from a CSS AST.\n */\nclass SelectorExtractor {\n constructor() {\n this.selectors = [];\n this.isScoped = false;\n }\n\n /**\n * Walker enter function.\n * @param {object} node - The AST node.\n */\n enter(node) {\n switch (node.type) {\n case ATRULE: {\n if (node.name === 'scope') {\n this.isScoped = true;\n }\n break;\n }\n case SCOPE: {\n const { children, type } = node.root;\n const arr = [];\n if (type === SELECTOR_LIST) {\n for (const child of children) {\n const selector = cssTree.generate(child);\n arr.push(selector);\n }\n this.selectors.push(arr);\n }\n break;\n }\n case RULE: {\n const { children, type } = node.prelude;\n const arr = [];\n if (type === SELECTOR_LIST) {\n let hasAmp = false;\n for (const child of children) {\n const selector = cssTree.generate(child);\n if (this.isScoped && !hasAmp) {\n hasAmp = /\\x26/.test(selector);\n }\n arr.push(selector);\n }\n if (this.isScoped) {\n if (hasAmp) {\n this.selectors.push(arr);\n /* FIXME:\n } else {\n this.selectors = arr;\n this.isScoped = false;\n */\n }\n } else {\n this.selectors.push(arr);\n }\n }\n }\n }\n }\n\n /**\n * Walker leave function.\n * @param {object} node - The AST node.\n */\n leave(node) {\n if (node.type === ATRULE) {\n if (node.name === 'scope') {\n this.isScoped = false;\n }\n }\n }\n}\n\n/**\n * Get type of an object.\n * @param {object} o - Object to check.\n * @returns {string} - Type of the object.\n */\nexport const getType = o =>\n Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO);\n\n/**\n * Verify array contents.\n * @param {Array} arr - The array.\n * @param {string} type - Expected type, e.g. 'String'.\n * @throws {TypeError} - Throws if array or its items are of unexpected type.\n * @returns {Array} - The verified array.\n */\nexport const verifyArray = (arr, type) => {\n if (!Array.isArray(arr)) {\n throw new TypeError(`Unexpected type ${getType(arr)}`);\n }\n if (typeof type !== 'string') {\n throw new TypeError(`Unexpected type ${getType(type)}`);\n }\n for (const item of arr) {\n if (getType(item) !== type) {\n throw new TypeError(`Unexpected type ${getType(item)}`);\n }\n }\n return arr;\n};\n\n/**\n * Generate a DOMException.\n * @param {string} msg - The error message.\n * @param {string} name - The error name.\n * @param {object} globalObject - The global object (e.g., window).\n * @returns {DOMException} The generated DOMException object.\n */\nexport const generateException = (msg, name, globalObject = globalThis) => {\n return new globalObject.DOMException(msg, name);\n};\n\n/**\n * Find a nested :has() pseudo-class.\n * @param {object} leaf - The AST leaf to check.\n * @returns {?object} The leaf if it's :has, otherwise null.\n */\nexport const findNestedHas = leaf => {\n return leaf.name === 'has';\n};\n\n/**\n * Find a logical pseudo-class that contains a nested :has().\n * @param {object} leaf - The AST leaf to check.\n * @returns {?object} The leaf if it matches, otherwise null.\n */\nexport const findLogicalWithNestedHas = leaf => {\n if (KEYS_LOGICAL.has(leaf.name) && cssTree.find(leaf, findNestedHas)) {\n return leaf;\n }\n return null;\n};\n\n/**\n * Filter a list of nodes based on An+B logic\n * @param {Array.} nodes - array of nodes to filter\n * @param {object} anb - An+B options\n * @param {number} anb.a - a\n * @param {number} anb.b - b\n * @param {boolean} [anb.reverse] - reverse order\n * @returns {Array.} - array of matched nodes\n */\nexport const filterNodesByAnB = (nodes, anb) => {\n const { a, b, reverse } = anb;\n const processedNodes = reverse ? [...nodes].reverse() : nodes;\n const l = nodes.length;\n const matched = [];\n if (a === 0) {\n if (b > 0 && b <= l) {\n matched.push(processedNodes[b - 1]);\n }\n return matched;\n }\n let startIndex = b - 1;\n if (a > 0) {\n while (startIndex < 0) {\n startIndex += a;\n }\n for (let i = startIndex; i < l; i += a) {\n matched.push(processedNodes[i]);\n }\n } else if (startIndex >= 0) {\n for (let i = startIndex; i >= 0; i += a) {\n matched.push(processedNodes[i]);\n }\n return matched.reverse();\n }\n return matched;\n};\n\n/**\n * Resolve content document, root node, and check if it's in a shadow DOM.\n * @param {object} node - Document, DocumentFragment, or Element node.\n * @returns {Array.} - [document, root, isInShadow].\n */\nexport const resolveContent = node => {\n if (!node?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(node)}`);\n }\n let document;\n let root;\n let shadow;\n switch (node.nodeType) {\n case DOCUMENT_NODE: {\n document = node;\n root = node;\n break;\n }\n case DOCUMENT_FRAGMENT_NODE: {\n const { host, mode, ownerDocument } = node;\n document = ownerDocument;\n root = node;\n shadow = host && (mode === 'close' || mode === 'open');\n break;\n }\n case ELEMENT_NODE: {\n document = node.ownerDocument;\n let refNode = node;\n while (refNode) {\n const { host, mode, nodeType, parentNode } = refNode;\n if (nodeType === DOCUMENT_FRAGMENT_NODE) {\n shadow = host && (mode === 'close' || mode === 'open');\n break;\n } else if (parentNode) {\n refNode = parentNode;\n } else {\n break;\n }\n }\n root = refNode;\n break;\n }\n default: {\n throw new TypeError(`Unexpected node ${node.nodeName}`);\n }\n }\n return [document, root, !!shadow];\n};\n\n/**\n * Traverse node tree with a TreeWalker.\n * @param {object} node - The target node.\n * @param {object} walker - The TreeWalker instance.\n * @param {boolean} [force] - Traverse only to the next node.\n * @returns {?object} - The current node if found, otherwise null.\n */\nexport const traverseNode = (node, walker, force = false) => {\n if (!node?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(node)}`);\n }\n if (!walker) {\n return null;\n }\n let refNode = walker.currentNode;\n if (refNode === node) {\n return refNode;\n } else if (force || refNode.contains(node)) {\n refNode = walker.nextNode();\n while (refNode) {\n if (refNode === node) {\n break;\n }\n refNode = walker.nextNode();\n }\n return refNode;\n } else {\n if (refNode !== walker.root) {\n let bool;\n while (refNode) {\n if (refNode === node) {\n bool = true;\n break;\n } else if (refNode === walker.root || refNode.contains(node)) {\n break;\n }\n refNode = walker.parentNode();\n }\n if (bool) {\n return refNode;\n }\n }\n if (node.nodeType === ELEMENT_NODE) {\n let bool;\n while (refNode) {\n if (refNode === node) {\n bool = true;\n break;\n }\n refNode = walker.nextNode();\n }\n if (bool) {\n return refNode;\n }\n }\n }\n return null;\n};\n\n/**\n * Check if a node is a custom element.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {boolean} - True if it's a custom element.\n */\nexport const isCustomElement = (node, opt = {}) => {\n if (!node?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(node)}`);\n }\n if (node.nodeType !== ELEMENT_NODE) {\n return false;\n }\n const { localName, ownerDocument } = node;\n const { formAssociated } = opt;\n const window = ownerDocument.defaultView;\n let elmConstructor;\n const attr = node.getAttribute('is');\n if (attr) {\n elmConstructor =\n isCustomElementName(attr) && window.customElements.get(attr);\n } else {\n elmConstructor =\n isCustomElementName(localName) && window.customElements.get(localName);\n }\n if (elmConstructor) {\n if (formAssociated) {\n return !!elmConstructor.formAssociated;\n }\n return true;\n }\n return false;\n};\n\n/**\n * Get slotted text content.\n * @param {object} node - The Element node (likely a ).\n * @returns {?string} - The text content.\n */\nexport const getSlottedTextContent = node => {\n if (!node?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(node)}`);\n }\n if (typeof node.assignedNodes !== 'function') {\n return null;\n }\n const nodes = node.assignedNodes();\n if (nodes.length) {\n let text = '';\n const l = nodes.length;\n for (let i = 0; i < l; i++) {\n const item = nodes[i];\n text = item.textContent.trim();\n if (text) {\n break;\n }\n }\n return text;\n }\n return node.textContent.trim();\n};\n\n/**\n * Get directionality of a node.\n * @see https://html.spec.whatwg.org/multipage/dom.html#the-dir-attribute\n * @param {object} node - The Element node.\n * @returns {?string} - 'ltr' or 'rtl'.\n */\nexport const getDirectionality = node => {\n if (!node?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(node)}`);\n }\n if (node.nodeType !== ELEMENT_NODE) {\n return null;\n }\n const { dir: dirAttr, localName, parentNode } = node;\n const { getEmbeddingLevels } = bidiFactory();\n if (dirAttr === 'ltr' || dirAttr === 'rtl') {\n return dirAttr;\n } else if (dirAttr === 'auto') {\n let text = '';\n switch (localName) {\n case 'input': {\n if (!node.type || KEYS_DIR_AUTO.has(node.type)) {\n text = node.value;\n } else if (KEYS_DIR_LTR.has(node.type)) {\n return 'ltr';\n }\n break;\n }\n case 'slot': {\n text = getSlottedTextContent(node);\n break;\n }\n case 'textarea': {\n text = node.value;\n break;\n }\n default: {\n const items = [].slice.call(node.childNodes);\n for (const item of items) {\n const {\n dir: itemDir,\n localName: itemLocalName,\n nodeType: itemNodeType,\n textContent: itemTextContent\n } = item;\n if (itemNodeType === TEXT_NODE) {\n text = itemTextContent.trim();\n } else if (\n itemNodeType === ELEMENT_NODE &&\n !KEYS_NODE_DIR_EXCLUDE.has(itemLocalName) &&\n (!itemDir || (itemDir !== 'ltr' && itemDir !== 'rtl'))\n ) {\n if (itemLocalName === 'slot') {\n text = getSlottedTextContent(item);\n } else {\n text = itemTextContent.trim();\n }\n }\n if (text) {\n break;\n }\n }\n }\n }\n if (text) {\n const {\n paragraphs: [{ level }]\n } = getEmbeddingLevels(text);\n if (level % 2 === 1) {\n return 'rtl';\n }\n } else if (parentNode) {\n const { nodeType: parentNodeType } = parentNode;\n if (parentNodeType === ELEMENT_NODE) {\n return getDirectionality(parentNode);\n }\n }\n } else if (localName === 'input' && node.type === 'tel') {\n return 'ltr';\n } else if (localName === 'bdi') {\n const text = node.textContent.trim();\n if (text) {\n const {\n paragraphs: [{ level }]\n } = getEmbeddingLevels(text);\n if (level % 2 === 1) {\n return 'rtl';\n }\n }\n } else if (parentNode) {\n if (localName === 'slot') {\n const text = getSlottedTextContent(node);\n if (text) {\n const {\n paragraphs: [{ level }]\n } = getEmbeddingLevels(text);\n if (level % 2 === 1) {\n return 'rtl';\n }\n return 'ltr';\n }\n }\n const { nodeType: parentNodeType } = parentNode;\n if (parentNodeType === ELEMENT_NODE) {\n return getDirectionality(parentNode);\n }\n }\n return 'ltr';\n};\n\n/**\n * Traverses up the DOM tree to find the language attribute for a node.\n * It checks for 'lang' in HTML and 'xml:lang' in XML contexts.\n * @param {object} node - The starting element node.\n * @returns {string|null} The language attribute value, or null if not found.\n */\nexport const getLanguageAttribute = node => {\n if (!node?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(node)}`);\n }\n if (node.nodeType !== ELEMENT_NODE) {\n return null;\n }\n const { contentType } = node.ownerDocument;\n const isHtml = REG_IS_HTML.test(contentType);\n const isXml = REG_IS_XML.test(contentType);\n let isShadow = false;\n // Traverse up from the current node to the root.\n let current = node;\n while (current) {\n // Check if the current node is an element.\n switch (current.nodeType) {\n case ELEMENT_NODE: {\n // Check for and return the language attribute if present.\n if (isHtml && current.hasAttribute('lang')) {\n return current.getAttribute('lang');\n } else if (isXml && current.hasAttribute('xml:lang')) {\n return current.getAttribute('xml:lang');\n }\n break;\n }\n case DOCUMENT_FRAGMENT_NODE: {\n // Continue traversal if the current node is a shadow root.\n if (current.host) {\n isShadow = true;\n }\n break;\n }\n case DOCUMENT_NODE:\n default: {\n // Stop if we reach the root document node.\n return null;\n }\n }\n if (isShadow) {\n current = current.host;\n isShadow = false;\n } else if (current.parentNode) {\n current = current.parentNode;\n } else {\n break;\n }\n }\n // No language attribute was found in the hierarchy.\n return null;\n};\n\n/**\n * Check if content is editable.\n * NOTE: Not implemented in jsdom https://github.com/jsdom/jsdom/issues/1670\n * @param {object} node - The Element node.\n * @returns {boolean} - True if content is editable.\n */\nexport const isContentEditable = node => {\n if (!node?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(node)}`);\n }\n if (node.nodeType !== ELEMENT_NODE) {\n return false;\n }\n if (typeof node.isContentEditable === 'boolean') {\n return node.isContentEditable;\n } else if (node.ownerDocument.designMode === 'on') {\n return true;\n } else {\n let attr;\n if (node.hasAttribute('contenteditable')) {\n attr = node.getAttribute('contenteditable');\n } else {\n attr = 'inherit';\n }\n switch (attr) {\n case '':\n case 'true': {\n return true;\n }\n case 'plaintext-only': {\n // FIXME:\n // @see https://github.com/w3c/editing/issues/470\n // @see https://github.com/whatwg/html/issues/10651\n return true;\n }\n case 'false': {\n return false;\n }\n default: {\n if (node?.parentNode?.nodeType === ELEMENT_NODE) {\n return isContentEditable(node.parentNode);\n }\n return false;\n }\n }\n }\n};\n\n/**\n * Check if a node is visible.\n * @param {object} node - The Element node.\n * @returns {boolean} - True if the node is visible.\n */\nexport const isVisible = node => {\n if (node?.nodeType !== ELEMENT_NODE) {\n return false;\n }\n const window = node.ownerDocument.defaultView;\n const { display, visibility } = window.getComputedStyle(node);\n if (display !== 'none' && visibility === 'visible') {\n return true;\n }\n return false;\n};\n\n/**\n * Check if focus is visible on the node.\n * @param {object} node - The Element node.\n * @returns {boolean} - True if focus is visible.\n */\nexport const isFocusVisible = node => {\n if (node?.nodeType !== ELEMENT_NODE) {\n return false;\n }\n const { localName, type } = node;\n switch (localName) {\n case 'input': {\n if (!type || KEYS_INPUT_EDIT.has(type)) {\n return true;\n }\n return false;\n }\n case 'textarea': {\n return true;\n }\n default: {\n return isContentEditable(node);\n }\n }\n};\n\n/**\n * Check if an area is focusable.\n * @param {object} node - The Element node.\n * @returns {boolean} - True if the area is focusable.\n */\nexport const isFocusableArea = node => {\n if (node?.nodeType !== ELEMENT_NODE) {\n return false;\n }\n if (!node.isConnected) {\n return false;\n }\n const window = node.ownerDocument.defaultView;\n if (node instanceof window.HTMLElement) {\n if (Number.isInteger(parseInt(node.getAttribute('tabindex')))) {\n return true;\n }\n if (isContentEditable(node)) {\n return true;\n }\n const { localName, parentNode } = node;\n switch (localName) {\n case 'a': {\n if (node.href || node.hasAttribute('href')) {\n return true;\n }\n return false;\n }\n case 'iframe': {\n return true;\n }\n case 'input': {\n if (\n node.disabled ||\n node.hasAttribute('disabled') ||\n node.hidden ||\n node.hasAttribute('hidden')\n ) {\n return false;\n }\n return true;\n }\n case 'summary': {\n if (parentNode.localName === 'details') {\n let child = parentNode.firstElementChild;\n let bool = false;\n while (child) {\n if (child.localName === 'summary') {\n bool = child === node;\n break;\n }\n child = child.nextElementSibling;\n }\n return bool;\n }\n return false;\n }\n default: {\n if (\n KEYS_NODE_FOCUSABLE.has(localName) &&\n !(node.disabled || node.hasAttribute('disabled'))\n ) {\n return true;\n }\n }\n }\n } else if (node instanceof window.SVGElement) {\n if (Number.isInteger(parseInt(node.getAttributeNS(null, 'tabindex')))) {\n const ns = 'http://www.w3.org/2000/svg';\n let bool;\n let refNode = node;\n while (refNode.namespaceURI === ns) {\n bool = KEYS_NODE_FOCUSABLE_SVG.has(refNode.localName);\n if (bool) {\n break;\n }\n if (refNode?.parentNode?.namespaceURI === ns) {\n refNode = refNode.parentNode;\n } else {\n break;\n }\n }\n if (bool) {\n return false;\n }\n return true;\n }\n if (\n node.localName === 'a' &&\n (node.href || node.hasAttributeNS(null, 'href'))\n ) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Check if a node is focusable.\n * NOTE: Not applied, needs fix in jsdom itself.\n * @see https://github.com/whatwg/html/pull/8392\n * @see https://phabricator.services.mozilla.com/D156219\n * @see https://github.com/jsdom/jsdom/issues/3029\n * @see https://github.com/jsdom/jsdom/issues/3464\n * @param {object} node - The Element node.\n * @returns {boolean} - True if the node is focusable.\n */\nexport const isFocusable = node => {\n if (node?.nodeType !== ELEMENT_NODE) {\n return false;\n }\n const window = node.ownerDocument.defaultView;\n let refNode = node;\n let res = true;\n while (refNode) {\n if (refNode.disabled || refNode.hasAttribute('disabled')) {\n res = false;\n break;\n }\n if (refNode.hidden || refNode.hasAttribute('hidden')) {\n res = false;\n }\n const { contentVisibility, display, visibility } =\n window.getComputedStyle(refNode);\n if (\n display === 'none' ||\n visibility !== 'visible' ||\n (contentVisibility === 'hidden' && refNode !== node)\n ) {\n res = false;\n } else {\n res = true;\n }\n if (res && refNode?.parentNode?.nodeType === ELEMENT_NODE) {\n refNode = refNode.parentNode;\n } else {\n break;\n }\n }\n return res;\n};\n\n/**\n * Get namespace URI.\n * @param {string} ns - The namespace prefix.\n * @param {object} node - The Element node.\n * @returns {?string} - The namespace URI.\n */\nexport const getNamespaceURI = (ns, node) => {\n if (typeof ns !== 'string') {\n throw new TypeError(`Unexpected type ${getType(ns)}`);\n } else if (!node?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(node)}`);\n }\n if (!ns || node.nodeType !== ELEMENT_NODE) {\n return null;\n }\n const { attributes } = node;\n let res;\n for (const attr of attributes) {\n const { name, namespaceURI, prefix, value } = attr;\n if (name === `xmlns:${ns}`) {\n res = value;\n } else if (prefix === ns) {\n res = namespaceURI;\n }\n if (res) {\n break;\n }\n }\n return res ?? null;\n};\n\n/**\n * Check if a namespace is declared.\n * @param {string} ns - The namespace.\n * @param {object} node - The Element node.\n * @returns {boolean} - True if the namespace is declared.\n */\nexport const isNamespaceDeclared = (ns = '', node = {}) => {\n if (!ns || typeof ns !== 'string' || node?.nodeType !== ELEMENT_NODE) {\n return false;\n }\n if (node.lookupNamespaceURI(ns)) {\n return true;\n }\n const root = node.ownerDocument.documentElement;\n let parent = node;\n let res;\n while (parent) {\n res = getNamespaceURI(ns, parent);\n if (res || parent === root) {\n break;\n }\n parent = parent.parentNode;\n }\n return !!res;\n};\n\n/**\n * Check if nodeA precedes and/or contains nodeB.\n * @param {object} nodeA - The first Element node.\n * @param {object} nodeB - The second Element node.\n * @returns {boolean} - True if nodeA precedes nodeB.\n */\nexport const isPreceding = (nodeA, nodeB) => {\n if (!nodeA?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(nodeA)}`);\n } else if (!nodeB?.nodeType) {\n throw new TypeError(`Unexpected type ${getType(nodeB)}`);\n }\n if (nodeA.nodeType !== ELEMENT_NODE || nodeB.nodeType !== ELEMENT_NODE) {\n return false;\n }\n const posBit = nodeB.compareDocumentPosition(nodeA);\n const res =\n posBit & DOCUMENT_POSITION_PRECEDING || posBit & DOCUMENT_POSITION_CONTAINS;\n return !!res;\n};\n\n/**\n * Comparison function for sorting nodes based on document position.\n * @param {object} a - The first node.\n * @param {object} b - The second node.\n * @returns {number} - Sort order.\n */\nexport const compareNodes = (a, b) => {\n if (isPreceding(b, a)) {\n return 1;\n }\n return -1;\n};\n\n/**\n * Sort a collection of nodes.\n * @param {Array.|Set.} nodes - Collection of nodes.\n * @returns {Array.} - Collection of sorted nodes.\n */\nexport const sortNodes = (nodes = []) => {\n const arr = [...nodes];\n if (arr.length > 1) {\n arr.sort(compareNodes);\n }\n return arr;\n};\n\n/**\n * Concat an array of nested selectors into an equivalent single selector.\n * @param {Array.>} selectors - [parents, children, ...].\n * @returns {string} - The concatenated selector.\n */\nexport const concatNestedSelectors = selectors => {\n if (!Array.isArray(selectors)) {\n throw new TypeError(`Unexpected type ${getType(selectors)}`);\n }\n let selector = '';\n if (selectors.length) {\n const revSelectors = selectors.toReversed();\n let child = verifyArray(revSelectors.shift(), 'String');\n if (child.length === 1) {\n [child] = child;\n }\n while (revSelectors.length) {\n const parentArr = verifyArray(revSelectors.shift(), 'String');\n if (!parentArr.length) {\n continue;\n }\n let parent;\n if (parentArr.length === 1) {\n [parent] = parentArr;\n if (!/^[>~+]/.test(parent) && /[\\s>~+]/.test(parent)) {\n parent = `:is(${parent})`;\n }\n } else {\n parent = `:is(${parentArr.join(', ')})`;\n }\n if (selector.includes('\\x26')) {\n selector = selector.replace(/\\x26/g, parent);\n }\n if (Array.isArray(child)) {\n const items = [];\n for (let item of child) {\n if (item.includes('\\x26')) {\n if (/^[>~+]/.test(item)) {\n item = `${parent} ${item.replace(/\\x26/g, parent)} ${selector}`;\n } else {\n item = `${item.replace(/\\x26/g, parent)} ${selector}`;\n }\n } else {\n item = `${parent} ${item} ${selector}`;\n }\n items.push(item.trim());\n }\n selector = items.join(', ');\n } else if (revSelectors.length) {\n selector = `${child} ${selector}`;\n } else {\n if (child.includes('\\x26')) {\n if (/^[>~+]/.test(child)) {\n selector = `${parent} ${child.replace(/\\x26/g, parent)} ${selector}`;\n } else {\n selector = `${child.replace(/\\x26/g, parent)} ${selector}`;\n }\n } else {\n selector = `${parent} ${child} ${selector}`;\n }\n }\n selector = selector.trim();\n if (revSelectors.length) {\n child = parentArr.length > 1 ? parentArr : parent;\n } else {\n break;\n }\n }\n selector = selector.replace(/\\x26/g, ':scope').trim();\n }\n return selector;\n};\n\n/**\n * Extract nested selectors from CSSRule.cssText.\n * @param {string} css - CSSRule.cssText.\n * @returns {Array.>} - Array of nested selectors.\n */\nexport const extractNestedSelectors = css => {\n const ast = cssTree.parse(css, {\n context: 'rule'\n });\n const extractor = new SelectorExtractor();\n cssTree.walk(ast, {\n enter: extractor.enter.bind(extractor),\n leave: extractor.leave.bind(extractor)\n });\n return extractor.selectors;\n};\n\n/**\n * Initialize nwsapi.\n * @param {object} window - The Window object.\n * @param {object} document - The Document object.\n * @returns {object} - The nwsapi instance.\n */\nexport const initNwsapi = (window, document) => {\n if (!window?.DOMException) {\n throw new TypeError(`Unexpected global object ${getType(window)}`);\n }\n if (document?.nodeType !== DOCUMENT_NODE) {\n document = window.document;\n }\n const nw = nwsapi({\n document,\n DOMException: window.DOMException\n });\n nw.configure({\n LOGERRORS: false\n });\n return nw;\n};\n\n/**\n * Filter a selector for use with nwsapi.\n * @param {string} selector - The selector string.\n * @param {string} target - The target type.\n * @returns {boolean} - True if the selector is valid for nwsapi.\n */\nexport const filterSelector = (selector, target) => {\n const isQuerySelectorType = target === TARGET_FIRST || target === TARGET_ALL;\n if (\n !selector ||\n typeof selector !== 'string' ||\n /null|undefined/.test(selector)\n ) {\n return false;\n }\n // Exclude missing close square bracket.\n if (selector.includes('[')) {\n const index = selector.lastIndexOf('[');\n const sel = selector.substring(index);\n if (sel.indexOf(']') < 0) {\n return false;\n }\n }\n // Exclude various complex or unsupported selectors.\n // - selectors containing '/'\n // - namespaced selectors\n // - escaped selectors\n // - pseudo-element selectors\n // - selectors containing non-ASCII\n // - selectors containing control character other than whitespace\n // - attribute selectors with case flag, e.g. [attr i]\n // - attribute selectors with unclosed quotes\n // - empty :is() or :where()\n if (selector.includes('/') || REG_EXCLUDE_BASIC.test(selector)) {\n return false;\n }\n // Include pseudo-classes that are known to work correctly.\n if (selector.includes(':')) {\n let complex = false;\n if (target !== isQuerySelectorType) {\n complex = REG_COMPLEX.test(selector);\n }\n if (\n isQuerySelectorType &&\n REG_DESCEND.test(selector) &&\n !REG_SIBLING.test(selector)\n ) {\n return false;\n } else if (!isQuerySelectorType && /:has\\(/.test(selector)) {\n if (!complex || REG_LOGIC_HAS_COMPOUND.test(selector)) {\n return false;\n }\n return REG_END_WITH_HAS.test(selector);\n } else if (/:(?:is|not)\\(/.test(selector)) {\n if (complex) {\n return !REG_LOGIC_COMPLEX.test(selector);\n } else {\n return !REG_LOGIC_COMPOUND.test(selector);\n }\n } else {\n return !REG_WO_LOGICAL.test(selector);\n }\n }\n return true;\n};\n","/**\n * constant.js\n */\n\n/* string */\nexport const ATRULE = 'Atrule';\nexport const ATTR_SELECTOR = 'AttributeSelector';\nexport const CLASS_SELECTOR = 'ClassSelector';\nexport const COMBINATOR = 'Combinator';\nexport const IDENT = 'Identifier';\nexport const ID_SELECTOR = 'IdSelector';\nexport const NOT_SUPPORTED_ERR = 'NotSupportedError';\nexport const NTH = 'Nth';\nexport const OPERATOR = 'Operator';\nexport const PS_CLASS_SELECTOR = 'PseudoClassSelector';\nexport const PS_ELEMENT_SELECTOR = 'PseudoElementSelector';\nexport const RULE = 'Rule';\nexport const SCOPE = 'Scope';\nexport const SELECTOR = 'Selector';\nexport const SELECTOR_LIST = 'SelectorList';\nexport const STRING = 'String';\nexport const SYNTAX_ERR = 'SyntaxError';\nexport const TARGET_ALL = 'all';\nexport const TARGET_FIRST = 'first';\nexport const TARGET_LINEAL = 'lineal';\nexport const TARGET_SELF = 'self';\nexport const TYPE_SELECTOR = 'TypeSelector';\n\n/* numeric */\nexport const BIT_01 = 1;\nexport const BIT_02 = 2;\nexport const BIT_04 = 4;\nexport const BIT_08 = 8;\nexport const BIT_16 = 0x10;\nexport const BIT_32 = 0x20;\nexport const BIT_FFFF = 0xffff;\nexport const DUO = 2;\nexport const HEX = 16;\nexport const TYPE_FROM = 8;\nexport const TYPE_TO = -1;\n\n/* Node */\nexport const ELEMENT_NODE = 1;\nexport const TEXT_NODE = 3;\nexport const DOCUMENT_NODE = 9;\nexport const DOCUMENT_FRAGMENT_NODE = 11;\nexport const DOCUMENT_POSITION_PRECEDING = 2;\nexport const DOCUMENT_POSITION_CONTAINS = 8;\nexport const DOCUMENT_POSITION_CONTAINED_BY = 0x10;\n\n/* NodeFilter */\nexport const SHOW_ALL = 0xffffffff;\nexport const SHOW_CONTAINER = 0x501;\nexport const SHOW_DOCUMENT = 0x100;\nexport const SHOW_DOCUMENT_FRAGMENT = 0x400;\nexport const SHOW_ELEMENT = 1;\n\n/* selectors */\nexport const ALPHA_NUM = '[A-Z\\\\d]+';\nexport const CHILD_IDX = '(?:first|last|only)-(?:child|of-type)';\nexport const DIGIT = '(?:0|[1-9]\\\\d*)';\nexport const LANG_PART = `(?:-${ALPHA_NUM})*`;\nexport const PSEUDO_CLASS = `(?:any-)?link|${CHILD_IDX}|checked|empty|indeterminate|read-(?:only|write)|target`;\nexport const ANB = `[+-]?(?:${DIGIT}n?|n)|(?:[+-]?${DIGIT})?n\\\\s*[+-]\\\\s*${DIGIT}`;\n// combinators\nexport const COMBO = '\\\\s?[\\\\s>~+]\\\\s?';\nexport const DESCEND = '\\\\s?[\\\\s>]\\\\s?';\nexport const SIBLING = '\\\\s?[+~]\\\\s?';\n// LOGIC_IS: :is()\nexport const LOGIC_IS = `:is\\\\(\\\\s*[^)]+\\\\s*\\\\)`;\n// N_TH: excludes An+B with selector list, e.g. :nth-child(2n+1 of .foo)\nexport const N_TH = `nth-(?:last-)?(?:child|of-type)\\\\(\\\\s*(?:even|odd|${ANB})\\\\s*\\\\)`;\n// SUB_TYPE: attr, id, class, pseudo-class, note that [foo|=bar] is excluded\nexport const SUB_TYPE = '\\\\[[^|\\\\]]+\\\\]|[#.:][\\\\w-]+';\nexport const SUB_TYPE_WO_PSEUDO = '\\\\[[^|\\\\]]+\\\\]|[#.][\\\\w-]+';\n// TAG_TYPE: *, tag\nexport const TAG_TYPE = '\\\\*|[A-Za-z][\\\\w-]*';\nexport const TAG_TYPE_I = '\\\\*|[A-Z][\\\\w-]*';\nexport const COMPOUND = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE})+)`;\nexport const COMPOUND_L = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE}|${LOGIC_IS})+)`;\nexport const COMPOUND_I = `(?:${TAG_TYPE_I}|(?:${TAG_TYPE_I})?(?:${SUB_TYPE})+)`;\nexport const COMPOUND_WO_PSEUDO = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE_WO_PSEUDO})+)`;\nexport const COMPLEX = `${COMPOUND}(?:${COMBO}${COMPOUND})*`;\nexport const COMPLEX_L = `${COMPOUND_L}(?:${COMBO}${COMPOUND_L})*`;\nexport const HAS_COMPOUND = `has\\\\([\\\\s>]?\\\\s*${COMPOUND_WO_PSEUDO}\\\\s*\\\\)`;\nexport const LOGIC_COMPOUND = `(?:is|not)\\\\(\\\\s*${COMPOUND_L}(?:\\\\s*,\\\\s*${COMPOUND_L})*\\\\s*\\\\)`;\nexport const LOGIC_COMPLEX = `(?:is|not)\\\\(\\\\s*${COMPLEX_L}(?:\\\\s*,\\\\s*${COMPLEX_L})*\\\\s*\\\\)`;\n\n/* forms and input types */\nexport const FORM_PARTS = Object.freeze([\n 'button',\n 'input',\n 'select',\n 'textarea'\n]);\nexport const INPUT_BUTTON = Object.freeze(['button', 'reset', 'submit']);\nexport const INPUT_CHECK = Object.freeze(['checkbox', 'radio']);\nexport const INPUT_DATE = Object.freeze([\n 'date',\n 'datetime-local',\n 'month',\n 'time',\n 'week'\n]);\nexport const INPUT_TEXT = Object.freeze([\n 'email',\n 'password',\n 'search',\n 'tel',\n 'text',\n 'url'\n]);\nexport const INPUT_EDIT = Object.freeze([\n ...INPUT_DATE,\n ...INPUT_TEXT,\n 'number'\n]);\nexport const INPUT_LTR = Object.freeze([\n ...INPUT_CHECK,\n 'color',\n 'date',\n 'image',\n 'number',\n 'range',\n 'time'\n]);\n\n/* logical combination pseudo-classes */\nexport const KEYS_LOGICAL = new Set(['has', 'is', 'not', 'where']);\n","/**\n * matcher.js\n */\n\n/* import */\nimport { generateCSS, parseAstName, unescapeSelector } from './parser.js';\nimport {\n generateException,\n getDirectionality,\n getLanguageAttribute,\n getType,\n isContentEditable,\n isCustomElement,\n isNamespaceDeclared\n} from './utility.js';\n\n/* constants */\nimport {\n ALPHA_NUM,\n FORM_PARTS,\n IDENT,\n INPUT_EDIT,\n LANG_PART,\n NOT_SUPPORTED_ERR,\n PS_ELEMENT_SELECTOR,\n STRING,\n SYNTAX_ERR\n} from './constant.js';\nconst KEYS_FORM_PS_DISABLED = new Set([\n ...FORM_PARTS,\n 'fieldset',\n 'optgroup',\n 'option'\n]);\nconst KEYS_INPUT_EDIT = new Set(INPUT_EDIT);\nconst REG_LANG_VALID = new RegExp(`^(?:\\\\*-)?${ALPHA_NUM}${LANG_PART}$`, 'i');\nconst REG_TAG_NAME = /[A-Z][\\\\w-]*/i;\n\n/**\n * Validates a pseudo-element selector.\n * @param {string} astName - The name of the pseudo-element from the AST.\n * @param {string} astType - The type of the selector from the AST.\n * @param {object} [opt] - Optional parameters.\n * @param {boolean} [opt.forgive] - If true, ignores unknown pseudo-elements.\n * @param {boolean} [opt.warn] - If true, throws an error for unsupported ones.\n * @throws {DOMException} If the selector is invalid or unsupported.\n * @returns {void}\n */\nexport const matchPseudoElementSelector = (astName, astType, opt = {}) => {\n const { forgive, globalObject, warn } = opt;\n if (astType !== PS_ELEMENT_SELECTOR) {\n // Ensure the AST node is a pseudo-element selector.\n throw new TypeError(`Unexpected ast type ${getType(astType)}`);\n }\n switch (astName) {\n case 'after':\n case 'backdrop':\n case 'before':\n case 'cue':\n case 'cue-region':\n case 'first-letter':\n case 'first-line':\n case 'file-selector-button':\n case 'marker':\n case 'placeholder':\n case 'selection':\n case 'target-text': {\n // Warn if the pseudo-element is known but unsupported.\n if (warn) {\n throw generateException(\n `Unsupported pseudo-element ::${astName}`,\n NOT_SUPPORTED_ERR,\n globalObject\n );\n }\n break;\n }\n case 'part':\n case 'slotted': {\n // Warn if the functional pseudo-element is known but unsupported.\n if (warn) {\n throw generateException(\n `Unsupported pseudo-element ::${astName}()`,\n NOT_SUPPORTED_ERR,\n globalObject\n );\n }\n break;\n }\n default: {\n // Handle vendor-prefixed or unknown pseudo-elements.\n if (astName.startsWith('-webkit-')) {\n if (warn) {\n throw generateException(\n `Unsupported pseudo-element ::${astName}`,\n NOT_SUPPORTED_ERR,\n globalObject\n );\n }\n // Throw an error for unknown pseudo-elements if not forgiven.\n } else if (!forgive) {\n throw generateException(\n `Unknown pseudo-element ::${astName}`,\n SYNTAX_ERR,\n globalObject\n );\n }\n }\n }\n};\n\n/**\n * Matches the :dir() pseudo-class against an element's directionality.\n * @param {object} ast - The AST object for the pseudo-class.\n * @param {object} node - The element node to match against.\n * @throws {TypeError} If the AST does not contain a valid direction value.\n * @returns {boolean} - True if the directionality matches, otherwise false.\n */\nexport const matchDirectionPseudoClass = (ast, node) => {\n const { name } = ast;\n // The :dir() pseudo-class requires a direction argument (e.g., \"ltr\").\n if (!name) {\n const type = name === '' ? '(empty String)' : getType(name);\n throw new TypeError(`Unexpected ast type ${type}`);\n }\n // Get the computed directionality of the element.\n const dir = getDirectionality(node);\n // Compare the expected direction with the element's actual direction.\n return name === dir;\n};\n\n/**\n * Matches the :lang() pseudo-class against an element's language.\n * @see https://datatracker.ietf.org/doc/html/rfc4647#section-3.3.1\n * @param {object} ast - The AST object for the pseudo-class.\n * @param {object} node - The element node to match against.\n * @returns {boolean} - True if the language matches, otherwise false.\n */\nexport const matchLanguagePseudoClass = (ast, node) => {\n const { name, type, value } = ast;\n let langPattern;\n // Determine the language pattern from the AST.\n if (type === STRING && value) {\n langPattern = value;\n } else if (type === IDENT && name) {\n langPattern = unescapeSelector(name);\n }\n // If no valid language pattern is provided, it cannot match.\n if (typeof langPattern !== 'string') {\n return false;\n }\n // Get the effective language attribute for the current node.\n const elementLang = getLanguageAttribute(node);\n // If the element has no language, it cannot match a specific pattern.\n if (elementLang === null) {\n return false;\n }\n // Handle the universal selector '*' for :lang.\n if (langPattern === '*') {\n // It matches any language unless attribute is not empty.\n return elementLang !== '';\n }\n // Validate the provided language pattern structure.\n if (!REG_LANG_VALID.test(langPattern)) {\n return false;\n }\n // Build a regex for extended language range matching.\n let matcherRegex;\n if (langPattern.indexOf('-') > -1) {\n // Handle complex patterns with wildcards and sub-tags (e.g., '*-US').\n const [langMain, langSub, ...langRest] = langPattern.split('-');\n const extendedMain =\n langMain === '*' ? `${ALPHA_NUM}${LANG_PART}` : `${langMain}${LANG_PART}`;\n const extendedSub = `-${langSub}${LANG_PART}`;\n let extendedRest = '';\n // Use a standard for loop for performance as per the rules.\n for (let i = 0; i < langRest.length; i++) {\n extendedRest += `-${langRest[i]}${LANG_PART}`;\n }\n matcherRegex = new RegExp(\n `^${extendedMain}${extendedSub}${extendedRest}$`,\n 'i'\n );\n } else {\n // Handle simple language patterns (e.g., 'en').\n matcherRegex = new RegExp(`^${langPattern}${LANG_PART}$`, 'i');\n }\n // Test the element's language against the constructed regex.\n return matcherRegex.test(elementLang);\n};\n\n/**\n * Matches the :disabled and :enabled pseudo-classes.\n * @param {string} astName - pseudo-class name\n * @param {object} node - Element node\n * @returns {boolean} - True if matched\n */\nexport const matchDisabledPseudoClass = (astName, node) => {\n const { localName, parentNode } = node;\n if (\n !KEYS_FORM_PS_DISABLED.has(localName) &&\n !isCustomElement(node, { formAssociated: true })\n ) {\n return false;\n }\n let isDisabled = false;\n if (node.disabled || node.hasAttribute('disabled')) {\n isDisabled = true;\n } else if (localName === 'option') {\n if (\n parentNode &&\n parentNode.localName === 'optgroup' &&\n (parentNode.disabled || parentNode.hasAttribute('disabled'))\n ) {\n isDisabled = true;\n }\n } else if (localName !== 'optgroup') {\n let current = parentNode;\n while (current) {\n if (\n current.localName === 'fieldset' &&\n (current.disabled || current.hasAttribute('disabled'))\n ) {\n // The first in a disabled
is not disabled.\n let legend;\n let element = current.firstElementChild;\n while (element) {\n if (element.localName === 'legend') {\n legend = element;\n break;\n }\n element = element.nextElementSibling;\n }\n if (!legend || !legend.contains(node)) {\n isDisabled = true;\n }\n // Found the containing fieldset, stop searching up.\n break;\n }\n current = current.parentNode;\n }\n }\n if (astName === 'disabled') {\n return isDisabled;\n }\n return !isDisabled;\n};\n\n/**\n * Match the :read-only and :read-write pseudo-classes\n * @param {string} astName - pseudo-class name\n * @param {object} node - Element node\n * @returns {boolean} - True if matched\n */\nexport const matchReadOnlyPseudoClass = (astName, node) => {\n const { localName } = node;\n let isReadOnly = false;\n switch (localName) {\n case 'textarea':\n case 'input': {\n const isEditableInput = !node.type || KEYS_INPUT_EDIT.has(node.type);\n if (localName === 'textarea' || isEditableInput) {\n isReadOnly =\n node.readOnly ||\n node.hasAttribute('readonly') ||\n node.disabled ||\n node.hasAttribute('disabled');\n } else {\n // Non-editable input types are always read-only\n isReadOnly = true;\n }\n break;\n }\n default: {\n isReadOnly = !isContentEditable(node);\n }\n }\n if (astName === 'read-only') {\n return isReadOnly;\n }\n return !isReadOnly;\n};\n\n/**\n * Matches an attribute selector against an element.\n * This function handles various attribute matchers like '=', '~=', '^=', etc.,\n * and considers namespaces and case sensitivity based on document type.\n * @param {object} ast - The AST for the attribute selector.\n * @param {object} node - The element node to match against.\n * @param {object} [opt] - Optional parameters.\n * @param {boolean} [opt.check] - True if running in an internal check.\n * @param {boolean} [opt.forgive] - True to forgive certain syntax errors.\n * @returns {boolean} - True if the attribute selector matches, otherwise false.\n */\nexport const matchAttributeSelector = (ast, node, opt = {}) => {\n const {\n flags: astFlags,\n matcher: astMatcher,\n name: astName,\n value: astValue\n } = ast;\n const { check, forgive, globalObject } = opt;\n // Validate selector flags ('i' or 's').\n if (typeof astFlags === 'string' && !/^[is]$/i.test(astFlags) && !forgive) {\n const css = generateCSS(ast);\n throw generateException(\n `Invalid selector ${css}`,\n SYNTAX_ERR,\n globalObject\n );\n }\n const { attributes } = node;\n // An element with no attributes cannot match.\n if (!attributes || !attributes.length) {\n return false;\n }\n // Determine case sensitivity based on document type and flags.\n const contentType = node.ownerDocument.contentType;\n let caseInsensitive;\n if (contentType === 'text/html') {\n if (typeof astFlags === 'string' && /^s$/i.test(astFlags)) {\n caseInsensitive = false;\n } else {\n caseInsensitive = true;\n }\n } else if (typeof astFlags === 'string' && /^i$/i.test(astFlags)) {\n caseInsensitive = true;\n } else {\n caseInsensitive = false;\n }\n // Prepare the attribute name from the selector for matching.\n let astAttrName = unescapeSelector(astName.name);\n if (caseInsensitive) {\n astAttrName = astAttrName.toLowerCase();\n }\n // A set to store the values of attributes whose names match.\n const attrValues = new Set();\n // Handle namespaced attribute names (e.g., [*|attr], [ns|attr]).\n if (astAttrName.indexOf('|') > -1) {\n const { prefix: astPrefix, localName: astLocalName } =\n parseAstName(astAttrName);\n for (const item of attributes) {\n let { name: itemName, value: itemValue } = item;\n if (caseInsensitive) {\n itemName = itemName.toLowerCase();\n itemValue = itemValue.toLowerCase();\n }\n switch (astPrefix) {\n case '': {\n if (astLocalName === itemName) {\n attrValues.add(itemValue);\n }\n break;\n }\n case '*': {\n if (itemName.indexOf(':') > -1) {\n const [, ...restItemName] = itemName.split(':');\n const itemLocalName = restItemName.join(':').replace(/^:/, '');\n if (itemLocalName === astLocalName) {\n attrValues.add(itemValue);\n }\n } else if (astLocalName === itemName) {\n attrValues.add(itemValue);\n }\n break;\n }\n default: {\n if (!check) {\n if (forgive) {\n return false;\n }\n const css = generateCSS(ast);\n throw generateException(\n `Invalid selector ${css}`,\n SYNTAX_ERR,\n globalObject\n );\n }\n if (itemName.indexOf(':') > -1) {\n const [itemPrefix, ...restItemName] = itemName.split(':');\n const itemLocalName = restItemName.join(':').replace(/^:/, '');\n // Ignore the 'xml:lang' attribute.\n if (itemPrefix === 'xml' && itemLocalName === 'lang') {\n continue;\n } else if (\n astPrefix === itemPrefix &&\n astLocalName === itemLocalName\n ) {\n const namespaceDeclared = isNamespaceDeclared(astPrefix, node);\n if (namespaceDeclared) {\n attrValues.add(itemValue);\n }\n }\n }\n }\n }\n }\n // Handle non-namespaced attribute names.\n } else {\n for (let { name: itemName, value: itemValue } of attributes) {\n if (caseInsensitive) {\n itemName = itemName.toLowerCase();\n itemValue = itemValue.toLowerCase();\n }\n if (itemName.indexOf(':') > -1) {\n const [itemPrefix, ...restItemName] = itemName.split(':');\n const itemLocalName = restItemName.join(':').replace(/^:/, '');\n // The attribute is starting with ':'.\n if (!itemPrefix && astAttrName === `:${itemLocalName}`) {\n attrValues.add(itemValue);\n // Ignore the 'xml:lang' attribute.\n } else if (itemPrefix === 'xml' && itemLocalName === 'lang') {\n continue;\n } else if (astAttrName === itemLocalName) {\n attrValues.add(itemValue);\n }\n } else if (astAttrName === itemName) {\n attrValues.add(itemValue);\n }\n }\n }\n if (!attrValues.size) {\n return false;\n }\n // Prepare the value from the selector's RHS for comparison.\n const { name: astIdentValue, value: astStringValue } = astValue ?? {};\n let attrValue;\n if (astIdentValue) {\n if (caseInsensitive) {\n attrValue = astIdentValue.toLowerCase();\n } else {\n attrValue = astIdentValue;\n }\n } else if (astStringValue) {\n if (caseInsensitive) {\n attrValue = astStringValue.toLowerCase();\n } else {\n attrValue = astStringValue;\n }\n } else if (astStringValue === '') {\n attrValue = astStringValue;\n }\n // Perform the final match based on the specified matcher.\n switch (astMatcher) {\n case '=': {\n return typeof attrValue === 'string' && attrValues.has(attrValue);\n }\n case '~=': {\n if (attrValue && typeof attrValue === 'string') {\n for (const value of attrValues) {\n const item = new Set(value.split(/\\s+/));\n if (item.has(attrValue)) {\n return true;\n }\n }\n }\n return false;\n }\n case '|=': {\n if (attrValue && typeof attrValue === 'string') {\n for (const value of attrValues) {\n if (value === attrValue || value.startsWith(`${attrValue}-`)) {\n return true;\n }\n }\n }\n return false;\n }\n case '^=': {\n if (attrValue && typeof attrValue === 'string') {\n for (const value of attrValues) {\n if (value.startsWith(`${attrValue}`)) {\n return true;\n }\n }\n }\n return false;\n }\n case '$=': {\n if (attrValue && typeof attrValue === 'string') {\n for (const value of attrValues) {\n if (value.endsWith(`${attrValue}`)) {\n return true;\n }\n }\n }\n return false;\n }\n case '*=': {\n if (attrValue && typeof attrValue === 'string') {\n for (const value of attrValues) {\n if (value.includes(`${attrValue}`)) {\n return true;\n }\n }\n }\n return false;\n }\n case null:\n default: {\n // This case handles attribute existence checks (e.g., '[disabled]').\n return true;\n }\n }\n};\n\n/**\n * match type selector\n * @param {object} ast - AST\n * @param {object} node - Element node\n * @param {object} [opt] - options\n * @param {boolean} [opt.check] - running in internal check()\n * @param {boolean} [opt.forgive] - forgive undeclared namespace\n * @returns {boolean} - result\n */\nexport const matchTypeSelector = (ast, node, opt = {}) => {\n const astName = unescapeSelector(ast.name);\n const { localName, namespaceURI, prefix } = node;\n const { check, forgive, globalObject } = opt;\n let { prefix: astPrefix, localName: astLocalName } = parseAstName(\n astName,\n node\n );\n if (\n node.ownerDocument.contentType === 'text/html' &&\n (!namespaceURI || namespaceURI === 'http://www.w3.org/1999/xhtml') &&\n REG_TAG_NAME.test(localName)\n ) {\n astPrefix = astPrefix.toLowerCase();\n astLocalName = astLocalName.toLowerCase();\n }\n let nodePrefix;\n let nodeLocalName;\n // just in case that the namespaced content is parsed as text/html\n if (localName.indexOf(':') > -1) {\n [nodePrefix, nodeLocalName] = localName.split(':');\n } else {\n nodePrefix = prefix || '';\n nodeLocalName = localName;\n }\n switch (astPrefix) {\n case '': {\n if (\n !nodePrefix &&\n !namespaceURI &&\n (astLocalName === '*' || astLocalName === nodeLocalName)\n ) {\n return true;\n }\n return false;\n }\n case '*': {\n if (astLocalName === '*' || astLocalName === nodeLocalName) {\n return true;\n }\n return false;\n }\n default: {\n if (!check) {\n if (forgive) {\n return false;\n }\n const css = generateCSS(ast);\n throw generateException(\n `Invalid selector ${css}`,\n SYNTAX_ERR,\n globalObject\n );\n }\n const astNS = node.lookupNamespaceURI(astPrefix);\n const nodeNS = node.lookupNamespaceURI(nodePrefix);\n if (astNS === nodeNS && astPrefix === nodePrefix) {\n if (astLocalName === '*' || astLocalName === nodeLocalName) {\n return true;\n }\n return false;\n } else if (!forgive && !astNS) {\n throw generateException(\n `Undeclared namespace ${astPrefix}`,\n SYNTAX_ERR,\n globalObject\n );\n }\n return false;\n }\n }\n};\n","/**\n * finder.js\n */\n\n/* import */\nimport {\n matchAttributeSelector,\n matchDirectionPseudoClass,\n matchDisabledPseudoClass,\n matchLanguagePseudoClass,\n matchPseudoElementSelector,\n matchReadOnlyPseudoClass,\n matchTypeSelector\n} from './matcher.js';\nimport {\n findAST,\n generateCSS,\n parseSelector,\n sortAST,\n unescapeSelector,\n walkAST\n} from './parser.js';\nimport {\n filterNodesByAnB,\n findLogicalWithNestedHas,\n generateException,\n isCustomElement,\n isFocusVisible,\n isFocusableArea,\n isVisible,\n resolveContent,\n sortNodes,\n traverseNode\n} from './utility.js';\n\n/* constants */\nimport {\n ATTR_SELECTOR,\n CLASS_SELECTOR,\n COMBINATOR,\n DOCUMENT_FRAGMENT_NODE,\n ELEMENT_NODE,\n FORM_PARTS,\n ID_SELECTOR,\n INPUT_CHECK,\n INPUT_DATE,\n INPUT_EDIT,\n INPUT_TEXT,\n KEYS_LOGICAL,\n NOT_SUPPORTED_ERR,\n PS_CLASS_SELECTOR,\n PS_ELEMENT_SELECTOR,\n SHOW_ALL,\n SHOW_CONTAINER,\n SYNTAX_ERR,\n TARGET_ALL,\n TARGET_FIRST,\n TARGET_LINEAL,\n TARGET_SELF,\n TEXT_NODE,\n TYPE_SELECTOR\n} from './constant.js';\nconst DIR_NEXT = 'next';\nconst DIR_PREV = 'prev';\nconst KEYS_FORM = new Set([...FORM_PARTS, 'fieldset', 'form']);\nconst KEYS_FORM_PS_VALID = new Set([...FORM_PARTS, 'form']);\nconst KEYS_INPUT_CHECK = new Set(INPUT_CHECK);\nconst KEYS_INPUT_PLACEHOLDER = new Set([...INPUT_TEXT, 'number']);\nconst KEYS_INPUT_RANGE = new Set([...INPUT_DATE, 'number', 'range']);\nconst KEYS_INPUT_REQUIRED = new Set([...INPUT_CHECK, ...INPUT_EDIT, 'file']);\nconst KEYS_INPUT_RESET = new Set(['button', 'reset']);\nconst KEYS_INPUT_SUBMIT = new Set(['image', 'submit']);\nconst KEYS_MODIFIER = new Set([\n 'Alt',\n 'AltGraph',\n 'CapsLock',\n 'Control',\n 'Fn',\n 'FnLock',\n 'Hyper',\n 'Meta',\n 'NumLock',\n 'ScrollLock',\n 'Shift',\n 'Super',\n 'Symbol',\n 'SymbolLock'\n]);\nconst KEYS_PS_UNCACHE = new Set([\n 'any-link',\n 'defined',\n 'dir',\n 'link',\n 'scope'\n]);\nconst KEYS_PS_NTH_OF_TYPE = new Set([\n 'first-of-type',\n 'last-of-type',\n 'only-of-type'\n]);\n\n/**\n * Finder\n * NOTE: #ast[i] corresponds to #nodes[i]\n */\nexport class Finder {\n /* private fields */\n #ast;\n #astCache;\n #check;\n #descendant;\n #document;\n #documentCache;\n #documentURL;\n #event;\n #eventHandlers;\n #focus;\n #invalidate;\n #invalidateResults;\n #lastFocusVisible;\n #node;\n #nodeWalker;\n #nodes;\n #noexcept;\n #pseudoElement;\n #results;\n #root;\n #rootWalker;\n #scoped;\n #selector;\n #shadow;\n #verifyShadowHost;\n #walkers;\n #warn;\n #window;\n\n /**\n * constructor\n * @param {object} window - The window object.\n */\n constructor(window) {\n this.#window = window;\n this.#astCache = new WeakMap();\n this.#documentCache = new WeakMap();\n this.#event = null;\n this.#focus = null;\n this.#lastFocusVisible = null;\n this.#eventHandlers = new Set([\n {\n keys: ['focus', 'focusin'],\n handler: this._handleFocusEvent\n },\n {\n keys: ['keydown', 'keyup'],\n handler: this._handleKeyboardEvent\n },\n {\n keys: ['mouseover', 'mousedown', 'mouseup', 'click', 'mouseout'],\n handler: this._handleMouseEvent\n }\n ]);\n this._registerEventListeners();\n this.clearResults(true);\n }\n\n /**\n * Handles errors.\n * @param {Error} e - The error object.\n * @param {object} [opt] - Options.\n * @param {boolean} [opt.noexcept] - If true, exceptions are not thrown.\n * @throws {Error} Throws an error.\n * @returns {void}\n */\n onError = (e, opt = {}) => {\n const noexcept = opt.noexcept ?? this.#noexcept;\n if (noexcept) {\n return;\n }\n const isDOMException =\n e instanceof DOMException || e instanceof this.#window.DOMException;\n if (isDOMException) {\n if (e.name === NOT_SUPPORTED_ERR) {\n if (this.#warn) {\n console.warn(e.message);\n }\n return;\n }\n throw new this.#window.DOMException(e.message, e.name);\n }\n if (e.name in this.#window) {\n throw new this.#window[e.name](e.message, { cause: e });\n }\n throw e;\n };\n\n /**\n * Sets up the finder.\n * @param {string} selector - The CSS selector.\n * @param {object} node - Document, DocumentFragment, or Element.\n * @param {object} [opt] - Options.\n * @param {boolean} [opt.check] - Indicates if running in internal check().\n * @param {boolean} [opt.noexcept] - If true, exceptions are not thrown.\n * @param {boolean} [opt.warn] - If true, console warnings are enabled.\n * @returns {object} The finder instance.\n */\n setup = (selector, node, opt = {}) => {\n const { check, noexcept, warn } = opt;\n this.#check = !!check;\n this.#noexcept = !!noexcept;\n this.#warn = !!warn;\n [this.#document, this.#root, this.#shadow] = resolveContent(node);\n this.#documentURL = null;\n this.#node = node;\n this.#scoped =\n this.#node !== this.#root && this.#node.nodeType === ELEMENT_NODE;\n this.#selector = selector;\n [this.#ast, this.#nodes] = this._correspond(selector);\n this.#pseudoElement = [];\n this.#walkers = new WeakMap();\n this.#nodeWalker = null;\n this.#rootWalker = null;\n this.#verifyShadowHost = null;\n this.clearResults();\n return this;\n };\n\n /**\n * Clear cached results.\n * @param {boolean} all - clear all results\n * @returns {void}\n */\n clearResults = (all = false) => {\n this.#invalidateResults = new WeakMap();\n if (all) {\n this.#results = new WeakMap();\n }\n };\n\n /**\n * Handles focus events.\n * @private\n * @param {Event} evt - The event object.\n * @returns {void}\n */\n _handleFocusEvent = evt => {\n this.#focus = evt;\n };\n\n /**\n * Handles keyboard events.\n * @private\n * @param {Event} evt - The event object.\n * @returns {void}\n */\n _handleKeyboardEvent = evt => {\n const { key } = evt;\n if (!KEYS_MODIFIER.has(key)) {\n this.#event = evt;\n }\n };\n\n /**\n * Handles mouse events.\n * @private\n * @param {Event} evt - The event object.\n * @returns {void}\n */\n _handleMouseEvent = evt => {\n this.#event = evt;\n };\n\n /**\n * Registers event listeners.\n * @private\n * @returns {Array.} An array of return values from addEventListener.\n */\n _registerEventListeners = () => {\n const opt = {\n capture: true,\n passive: true\n };\n const func = [];\n for (const eventHandler of this.#eventHandlers) {\n const { keys, handler } = eventHandler;\n const l = keys.length;\n for (let i = 0; i < l; i++) {\n const key = keys[i];\n func.push(this.#window.addEventListener(key, handler, opt));\n }\n }\n return func;\n };\n\n /**\n * Processes selector branches into the internal AST structure.\n * @private\n * @param {Array.>} branches - The branches from walkAST.\n * @param {string} selector - The original selector for error reporting.\n * @returns {{ast: Array, descendant: boolean}}\n * An object with the AST, descendant flag.\n */\n _processSelectorBranches = (branches, selector) => {\n let descendant = false;\n const ast = [];\n const l = branches.length;\n for (let i = 0; i < l; i++) {\n const items = [...branches[i]];\n const branch = [];\n let item = items.shift();\n if (item && item.type !== COMBINATOR) {\n const leaves = new Set();\n while (item) {\n if (item.type === COMBINATOR) {\n const [nextItem] = items;\n if (!nextItem || nextItem.type === COMBINATOR) {\n const msg = `Invalid selector ${selector}`;\n this.onError(generateException(msg, SYNTAX_ERR, this.#window));\n // Stop processing on invalid selector.\n return { ast: [], descendant: false, invalidate: false };\n }\n if (item.name === ' ' || item.name === '>') {\n descendant = true;\n }\n branch.push({ combo: item, leaves: sortAST(leaves) });\n leaves.clear();\n } else {\n if (item.name && typeof item.name === 'string') {\n const unescapedName = unescapeSelector(item.name);\n if (unescapedName !== item.name) {\n item.name = unescapedName;\n }\n if (/[|:]/.test(unescapedName)) {\n item.namespace = true;\n }\n }\n leaves.add(item);\n }\n if (items.length) {\n item = items.shift();\n } else {\n branch.push({ combo: null, leaves: sortAST(leaves) });\n leaves.clear();\n break;\n }\n }\n }\n ast.push({ branch, dir: null, filtered: false, find: false });\n }\n return { ast, descendant };\n };\n\n /**\n * Corresponds AST and nodes.\n * @private\n * @param {string} selector - The CSS selector.\n * @returns {Array.>} An array with the AST and nodes.\n */\n _correspond = selector => {\n const nodes = [];\n this.#descendant = false;\n this.#invalidate = false;\n let ast;\n if (this.#documentCache.has(this.#document)) {\n const cachedItem = this.#documentCache.get(this.#document);\n if (cachedItem && cachedItem.has(`${selector}`)) {\n const item = cachedItem.get(`${selector}`);\n ast = item.ast;\n this.#descendant = item.descendant;\n this.#invalidate = item.invalidate;\n }\n }\n if (ast) {\n const l = ast.length;\n for (let i = 0; i < l; i++) {\n ast[i].dir = null;\n ast[i].filtered = false;\n ast[i].find = false;\n nodes[i] = [];\n }\n } else {\n let cssAst;\n try {\n cssAst = parseSelector(selector);\n } catch (e) {\n return this.onError(e);\n }\n const { branches, info } = walkAST(cssAst);\n const {\n hasHasPseudoFunc,\n hasLogicalPseudoFunc,\n hasNthChildOfSelector,\n hasStatePseudoClass\n } = info;\n this.#invalidate =\n hasHasPseudoFunc ||\n hasStatePseudoClass ||\n !!(hasLogicalPseudoFunc && hasNthChildOfSelector);\n const processed = this._processSelectorBranches(branches, selector);\n ast = processed.ast;\n this.#descendant = processed.descendant;\n let cachedItem;\n if (this.#documentCache.has(this.#document)) {\n cachedItem = this.#documentCache.get(this.#document);\n } else {\n cachedItem = new Map();\n }\n cachedItem.set(`${selector}`, {\n ast,\n descendant: this.#descendant,\n invalidate: this.#invalidate\n });\n this.#documentCache.set(this.#document, cachedItem);\n // Initialize nodes array for each branch.\n for (let i = 0; i < ast.length; i++) {\n nodes[i] = [];\n }\n }\n return [ast, nodes];\n };\n\n /**\n * Creates a TreeWalker.\n * @private\n * @param {object} node - The Document, DocumentFragment, or Element node.\n * @param {object} [opt] - Options.\n * @param {boolean} [opt.force] - Force creation of a new TreeWalker.\n * @param {number} [opt.whatToShow] - The NodeFilter whatToShow value.\n * @returns {object} The TreeWalker object.\n */\n _createTreeWalker = (node, opt = {}) => {\n const { force = false, whatToShow = SHOW_CONTAINER } = opt;\n if (force) {\n return this.#document.createTreeWalker(node, whatToShow);\n } else if (this.#walkers.has(node)) {\n return this.#walkers.get(node);\n }\n const walker = this.#document.createTreeWalker(node, whatToShow);\n this.#walkers.set(node, walker);\n return walker;\n };\n\n /**\n * Gets selector branches from cache or parses them.\n * @private\n * @param {object} selector - The AST.\n * @returns {Array.>} The selector branches.\n */\n _getSelectorBranches = selector => {\n if (this.#astCache.has(selector)) {\n return this.#astCache.get(selector);\n }\n const { branches } = walkAST(selector);\n this.#astCache.set(selector, branches);\n return branches;\n };\n\n /**\n * Gets the children of a node, optionally filtered by a selector.\n * @private\n * @param {object} parentNode - The parent element.\n * @param {Array.>} selectorBranches - The selector branches.\n * @param {object} [opt] - Options.\n * @returns {Array.} An array of child nodes.\n */\n _getFilteredChildren = (parentNode, selectorBranches, opt = {}) => {\n const children = [];\n const walker = this._createTreeWalker(parentNode, { force: true });\n let childNode = walker.firstChild();\n while (childNode) {\n if (selectorBranches) {\n if (isVisible(childNode)) {\n let isMatch = false;\n const l = selectorBranches.length;\n for (let i = 0; i < l; i++) {\n const leaves = selectorBranches[i];\n if (this._matchLeaves(leaves, childNode, opt)) {\n isMatch = true;\n break;\n }\n }\n if (isMatch) {\n children.push(childNode);\n }\n }\n } else {\n children.push(childNode);\n }\n childNode = walker.nextSibling();\n }\n return children;\n };\n\n /**\n * Collects nth-child nodes.\n * @private\n * @param {object} anb - An+B options.\n * @param {number} anb.a - The 'a' value.\n * @param {number} anb.b - The 'b' value.\n * @param {boolean} [anb.reverse] - If true, reverses the order.\n * @param {object} [anb.selector] - The AST.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _collectNthChild = (anb, node, opt = {}) => {\n const { a, b, selector } = anb;\n const { parentNode } = node;\n if (!parentNode) {\n const matchedNode = new Set();\n if (node === this.#root && a * 1 + b * 1 === 1) {\n if (selector) {\n const selectorBranches = this._getSelectorBranches(selector);\n const l = selectorBranches.length;\n for (let i = 0; i < l; i++) {\n const leaves = selectorBranches[i];\n if (this._matchLeaves(leaves, node, opt)) {\n matchedNode.add(node);\n break;\n }\n }\n } else {\n matchedNode.add(node);\n }\n }\n return matchedNode;\n }\n const selectorBranches = selector\n ? this._getSelectorBranches(selector)\n : null;\n const children = this._getFilteredChildren(\n parentNode,\n selectorBranches,\n opt\n );\n const matchedNodes = filterNodesByAnB(children, anb);\n return new Set(matchedNodes);\n };\n\n /**\n * Collects nth-of-type nodes.\n * @private\n * @param {object} anb - An+B options.\n * @param {number} anb.a - The 'a' value.\n * @param {number} anb.b - The 'b' value.\n * @param {boolean} [anb.reverse] - If true, reverses the order.\n * @param {object} node - The Element node.\n * @returns {Set.} A collection of matched nodes.\n */\n _collectNthOfType = (anb, node) => {\n const { parentNode } = node;\n if (!parentNode) {\n if (node === this.#root && anb.a * 1 + anb.b * 1 === 1) {\n return new Set([node]);\n }\n return new Set();\n }\n const typedSiblings = [];\n const walker = this._createTreeWalker(parentNode, { force: true });\n let sibling = walker.firstChild();\n while (sibling) {\n if (\n sibling.localName === node.localName &&\n sibling.namespaceURI === node.namespaceURI &&\n sibling.prefix === node.prefix\n ) {\n typedSiblings.push(sibling);\n }\n sibling = walker.nextSibling();\n }\n const matchedNodes = filterNodesByAnB(typedSiblings, anb);\n return new Set(matchedNodes);\n };\n\n /**\n * Matches An+B.\n * @private\n * @param {object} ast - The AST.\n * @param {object} node - The Element node.\n * @param {string} nthName - The name of the nth pseudo-class.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _matchAnPlusB = (ast, node, nthName, opt = {}) => {\n const {\n nth: { a, b, name: nthIdentName },\n selector\n } = ast;\n const anbMap = new Map();\n if (nthIdentName) {\n if (nthIdentName === 'even') {\n anbMap.set('a', 2);\n anbMap.set('b', 0);\n } else if (nthIdentName === 'odd') {\n anbMap.set('a', 2);\n anbMap.set('b', 1);\n }\n if (nthName.indexOf('last') > -1) {\n anbMap.set('reverse', true);\n }\n } else {\n if (typeof a === 'string' && /-?\\d+/.test(a)) {\n anbMap.set('a', a * 1);\n } else {\n anbMap.set('a', 0);\n }\n if (typeof b === 'string' && /-?\\d+/.test(b)) {\n anbMap.set('b', b * 1);\n } else {\n anbMap.set('b', 0);\n }\n if (nthName.indexOf('last') > -1) {\n anbMap.set('reverse', true);\n }\n }\n if (nthName === 'nth-child' || nthName === 'nth-last-child') {\n if (selector) {\n anbMap.set('selector', selector);\n }\n const anb = Object.fromEntries(anbMap);\n const nodes = this._collectNthChild(anb, node, opt);\n return nodes;\n } else if (nthName === 'nth-of-type' || nthName === 'nth-last-of-type') {\n const anb = Object.fromEntries(anbMap);\n const nodes = this._collectNthOfType(anb, node);\n return nodes;\n }\n return new Set();\n };\n\n /**\n * Matches the :has() pseudo-class function.\n * @private\n * @param {Array.} astLeaves - The AST leaves.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {boolean} The result.\n */\n _matchHasPseudoFunc = (astLeaves, node, opt = {}) => {\n if (Array.isArray(astLeaves) && astLeaves.length) {\n // Prepare a copy to avoid astLeaves being consumed.\n const leaves = [...astLeaves];\n const [leaf] = leaves;\n const { type: leafType } = leaf;\n let combo;\n if (leafType === COMBINATOR) {\n combo = leaves.shift();\n } else {\n combo = {\n name: ' ',\n type: COMBINATOR\n };\n }\n const twigLeaves = [];\n while (leaves.length) {\n const [item] = leaves;\n const { type: itemType } = item;\n if (itemType === COMBINATOR) {\n break;\n } else {\n twigLeaves.push(leaves.shift());\n }\n }\n const twig = {\n combo,\n leaves: twigLeaves\n };\n opt.dir = DIR_NEXT;\n const nodes = this._matchCombinator(twig, node, opt);\n if (nodes.size) {\n if (leaves.length) {\n let bool = false;\n for (const nextNode of nodes) {\n bool = this._matchHasPseudoFunc(leaves, nextNode, opt);\n if (bool) {\n break;\n }\n }\n return bool;\n }\n return true;\n }\n }\n return false;\n };\n\n /**\n * Evaluates the :has() pseudo-class.\n * @private\n * @param {object} astData - The AST data.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {?object} The matched node.\n */\n _evaluateHasPseudo = (astData, node, opt) => {\n const { branches } = astData;\n let bool = false;\n const l = branches.length;\n for (let i = 0; i < l; i++) {\n const leaves = branches[i];\n bool = this._matchHasPseudoFunc(leaves, node, opt);\n if (bool) {\n break;\n }\n }\n if (!bool) {\n return null;\n }\n if (\n (opt.isShadowRoot || this.#shadow) &&\n node.nodeType === DOCUMENT_FRAGMENT_NODE\n ) {\n return this.#verifyShadowHost ? node : null;\n }\n return node;\n };\n\n /**\n * Matches logical pseudo-class functions.\n * @private\n * @param {object} astData - The AST data.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {?object} The matched node.\n */\n _matchLogicalPseudoFunc = (astData, node, opt = {}) => {\n const { astName, branches, twigBranches } = astData;\n // Handle :has().\n if (astName === 'has') {\n return this._evaluateHasPseudo(astData, node, opt);\n }\n // Handle :is(), :not(), :where().\n const isShadowRoot =\n (opt.isShadowRoot || this.#shadow) &&\n node.nodeType === DOCUMENT_FRAGMENT_NODE;\n // Check for invalid shadow root.\n if (isShadowRoot) {\n let invalid = false;\n for (const branch of branches) {\n if (branch.length > 1) {\n invalid = true;\n break;\n } else if (astName === 'not') {\n const [{ type: childAstType }] = branch;\n if (childAstType !== PS_CLASS_SELECTOR) {\n invalid = true;\n break;\n }\n }\n }\n if (invalid) {\n return null;\n }\n }\n opt.forgive = astName === 'is' || astName === 'where';\n const l = twigBranches.length;\n let bool;\n for (let i = 0; i < l; i++) {\n const branch = twigBranches[i];\n const lastIndex = branch.length - 1;\n const { leaves } = branch[lastIndex];\n bool = this._matchLeaves(leaves, node, opt);\n if (bool && lastIndex > 0) {\n let nextNodes = new Set([node]);\n for (let j = lastIndex - 1; j >= 0; j--) {\n const twig = branch[j];\n const arr = [];\n opt.dir = DIR_PREV;\n for (const nextNode of nextNodes) {\n const m = this._matchCombinator(twig, nextNode, opt);\n if (m.size) {\n arr.push(...m);\n }\n }\n if (arr.length) {\n if (j === 0) {\n bool = true;\n } else {\n nextNodes = new Set(arr);\n }\n } else {\n bool = false;\n break;\n }\n }\n }\n if (bool) {\n break;\n }\n }\n if (astName === 'not') {\n if (bool) {\n return null;\n }\n return node;\n } else if (bool) {\n return node;\n }\n return null;\n };\n\n /**\n * match pseudo-class selector\n * @private\n * @see https://html.spec.whatwg.org/#pseudo-classes\n * @param {object} ast - AST\n * @param {object} node - Element node\n * @param {object} [opt] - options\n * @returns {Set.} - collection of matched nodes\n */\n _matchPseudoClassSelector(ast, node, opt = {}) {\n const { children: astChildren, name: astName } = ast;\n const { localName, parentNode } = node;\n const { forgive, warn = this.#warn } = opt;\n const matched = new Set();\n // :has(), :is(), :not(), :where()\n if (Array.isArray(astChildren) && KEYS_LOGICAL.has(astName)) {\n if (!astChildren.length && astName !== 'is' && astName !== 'where') {\n const css = generateCSS(ast);\n const msg = `Invalid selector ${css}`;\n return this.onError(generateException(msg, SYNTAX_ERR, this.#window));\n }\n let astData;\n if (this.#astCache.has(ast)) {\n astData = this.#astCache.get(ast);\n } else {\n const { branches } = walkAST(ast);\n if (astName === 'has') {\n // Check for nested :has().\n let forgiven = false;\n const l = astChildren.length;\n for (let i = 0; i < l; i++) {\n const child = astChildren[i];\n const item = findAST(child, findLogicalWithNestedHas);\n if (item) {\n const itemName = item.name;\n if (itemName === 'is' || itemName === 'where') {\n forgiven = true;\n break;\n } else {\n const css = generateCSS(ast);\n const msg = `Invalid selector ${css}`;\n return this.onError(\n generateException(msg, SYNTAX_ERR, this.#window)\n );\n }\n }\n }\n if (forgiven) {\n return matched;\n }\n astData = {\n astName,\n branches\n };\n } else {\n const twigBranches = [];\n const l = branches.length;\n for (let i = 0; i < l; i++) {\n const [...leaves] = branches[i];\n const branch = [];\n const leavesSet = new Set();\n let item = leaves.shift();\n while (item) {\n if (item.type === COMBINATOR) {\n branch.push({\n combo: item,\n leaves: [...leavesSet]\n });\n leavesSet.clear();\n } else if (item) {\n leavesSet.add(item);\n }\n if (leaves.length) {\n item = leaves.shift();\n } else {\n branch.push({\n combo: null,\n leaves: [...leavesSet]\n });\n leavesSet.clear();\n break;\n }\n }\n twigBranches.push(branch);\n }\n astData = {\n astName,\n branches,\n twigBranches\n };\n this.#astCache.set(ast, astData);\n }\n }\n const res = this._matchLogicalPseudoFunc(astData, node, opt);\n if (res) {\n matched.add(res);\n }\n } else if (Array.isArray(astChildren)) {\n // :nth-child(), :nth-last-child(), nth-of-type(), :nth-last-of-type()\n if (/^nth-(?:last-)?(?:child|of-type)$/.test(astName)) {\n if (astChildren.length !== 1) {\n const css = generateCSS(ast);\n return this.onError(\n generateException(\n `Invalid selector ${css}`,\n SYNTAX_ERR,\n this.#window\n )\n );\n }\n const [branch] = astChildren;\n const nodes = this._matchAnPlusB(branch, node, astName, opt);\n return nodes;\n } else {\n switch (astName) {\n // :dir()\n case 'dir': {\n if (astChildren.length !== 1) {\n const css = generateCSS(ast);\n return this.onError(\n generateException(\n `Invalid selector ${css}`,\n SYNTAX_ERR,\n this.#window\n )\n );\n }\n const [astChild] = astChildren;\n const res = matchDirectionPseudoClass(astChild, node);\n if (res) {\n matched.add(node);\n }\n break;\n }\n // :lang()\n case 'lang': {\n if (!astChildren.length) {\n const css = generateCSS(ast);\n return this.onError(\n generateException(\n `Invalid selector ${css}`,\n SYNTAX_ERR,\n this.#window\n )\n );\n }\n let bool;\n for (const astChild of astChildren) {\n bool = matchLanguagePseudoClass(astChild, node);\n if (bool) {\n break;\n }\n }\n if (bool) {\n matched.add(node);\n }\n break;\n }\n // :state()\n case 'state': {\n if (isCustomElement(node)) {\n const [{ value: stateValue }] = astChildren;\n if (stateValue) {\n if (node[stateValue]) {\n matched.add(node);\n } else {\n for (const i in node) {\n const prop = node[i];\n if (prop instanceof this.#window.ElementInternals) {\n if (prop?.states?.has(stateValue)) {\n matched.add(node);\n }\n break;\n }\n }\n }\n }\n }\n break;\n }\n case 'current':\n case 'heading':\n case 'nth-col':\n case 'nth-last-col': {\n if (warn) {\n this.onError(\n generateException(\n `Unsupported pseudo-class :${astName}()`,\n NOT_SUPPORTED_ERR,\n this.#window\n )\n );\n }\n break;\n }\n // Ignore :host() and :host-context().\n case 'host':\n case 'host-context': {\n break;\n }\n // Deprecated in CSS Selectors 3.\n case 'contains': {\n if (warn) {\n this.onError(\n generateException(\n `Unknown pseudo-class :${astName}()`,\n NOT_SUPPORTED_ERR,\n this.#window\n )\n );\n }\n break;\n }\n default: {\n if (!forgive) {\n this.onError(\n generateException(\n `Unknown pseudo-class :${astName}()`,\n SYNTAX_ERR,\n this.#window\n )\n );\n }\n }\n }\n }\n } else if (KEYS_PS_NTH_OF_TYPE.has(astName)) {\n if (node === this.#root) {\n matched.add(node);\n } else if (parentNode) {\n switch (astName) {\n case 'first-of-type': {\n const [node1] = this._collectNthOfType(\n {\n a: 0,\n b: 1\n },\n node\n );\n if (node1) {\n matched.add(node1);\n }\n break;\n }\n case 'last-of-type': {\n const [node1] = this._collectNthOfType(\n {\n a: 0,\n b: 1,\n reverse: true\n },\n node\n );\n if (node1) {\n matched.add(node1);\n }\n break;\n }\n // 'only-of-type' is handled by default.\n default: {\n const [node1] = this._collectNthOfType(\n {\n a: 0,\n b: 1\n },\n node\n );\n if (node1 === node) {\n const [node2] = this._collectNthOfType(\n {\n a: 0,\n b: 1,\n reverse: true\n },\n node\n );\n if (node2 === node) {\n matched.add(node);\n }\n }\n }\n }\n }\n } else {\n switch (astName) {\n case 'disabled':\n case 'enabled': {\n const isMatch = matchDisabledPseudoClass(astName, node);\n if (isMatch) {\n matched.add(node);\n }\n break;\n }\n case 'read-only':\n case 'read-write': {\n const isMatch = matchReadOnlyPseudoClass(astName, node);\n if (isMatch) {\n matched.add(node);\n }\n break;\n }\n case 'any-link':\n case 'link': {\n if (\n (localName === 'a' || localName === 'area') &&\n node.hasAttribute('href')\n ) {\n matched.add(node);\n }\n break;\n }\n case 'local-link': {\n if (\n (localName === 'a' || localName === 'area') &&\n node.hasAttribute('href')\n ) {\n if (!this.#documentURL) {\n this.#documentURL = new URL(this.#document.URL);\n }\n const { href, origin, pathname } = this.#documentURL;\n const attrURL = new URL(node.getAttribute('href'), href);\n if (attrURL.origin === origin && attrURL.pathname === pathname) {\n matched.add(node);\n }\n }\n break;\n }\n case 'visited': {\n // prevent fingerprinting\n break;\n }\n case 'hover': {\n const { target, type } = this.#event ?? {};\n if (\n /^(?:click|mouse(?:down|over|up))$/.test(type) &&\n node.contains(target)\n ) {\n matched.add(node);\n }\n break;\n }\n case 'active': {\n const { buttons, target, type } = this.#event ?? {};\n if (type === 'mousedown' && buttons & 1 && node.contains(target)) {\n matched.add(node);\n }\n break;\n }\n case 'target': {\n if (!this.#documentURL) {\n this.#documentURL = new URL(this.#document.URL);\n }\n const { hash } = this.#documentURL;\n if (\n node.id &&\n hash === `#${node.id}` &&\n this.#document.contains(node)\n ) {\n matched.add(node);\n }\n break;\n }\n case 'target-within': {\n if (!this.#documentURL) {\n this.#documentURL = new URL(this.#document.URL);\n }\n const { hash } = this.#documentURL;\n if (hash) {\n const id = hash.replace(/^#/, '');\n let current = this.#document.getElementById(id);\n while (current) {\n if (current === node) {\n matched.add(node);\n break;\n }\n current = current.parentNode;\n }\n }\n break;\n }\n case 'scope': {\n if (this.#node.nodeType === ELEMENT_NODE) {\n if (!this.#shadow && node === this.#node) {\n matched.add(node);\n }\n } else if (node === this.#document.documentElement) {\n matched.add(node);\n }\n break;\n }\n case 'focus': {\n const activeElement = this.#document.activeElement;\n if (node === activeElement && isFocusableArea(node)) {\n matched.add(node);\n } else if (activeElement.shadowRoot) {\n const activeShadowElement = activeElement.shadowRoot.activeElement;\n let current = activeShadowElement;\n while (current) {\n if (current.nodeType === DOCUMENT_FRAGMENT_NODE) {\n const { host } = current;\n if (host === activeElement) {\n if (isFocusableArea(node)) {\n matched.add(node);\n } else {\n matched.add(host);\n }\n }\n break;\n } else {\n current = current.parentNode;\n }\n }\n }\n break;\n }\n case 'focus-visible': {\n if (node === this.#document.activeElement && isFocusableArea(node)) {\n let bool;\n if (isFocusVisible(node)) {\n bool = true;\n } else if (this.#focus) {\n const { relatedTarget, target: focusTarget } = this.#focus;\n if (focusTarget === node) {\n if (isFocusVisible(relatedTarget)) {\n bool = true;\n } else if (this.#event) {\n const {\n altKey: eventAltKey,\n ctrlKey: eventCtrlKey,\n key: eventKey,\n metaKey: eventMetaKey,\n target: eventTarget,\n type: eventType\n } = this.#event;\n // this.#event is irrelevant if eventTarget === relatedTarget\n if (eventTarget === relatedTarget) {\n if (this.#lastFocusVisible === null) {\n bool = true;\n } else if (focusTarget === this.#lastFocusVisible) {\n bool = true;\n }\n } else if (eventKey === 'Tab') {\n if (\n (eventType === 'keydown' && eventTarget !== node) ||\n (eventType === 'keyup' && eventTarget === node)\n ) {\n if (eventTarget === focusTarget) {\n if (this.#lastFocusVisible === null) {\n bool = true;\n } else if (\n eventTarget === this.#lastFocusVisible &&\n relatedTarget === null\n ) {\n bool = true;\n }\n } else {\n bool = true;\n }\n }\n } else if (eventKey) {\n if (\n (eventType === 'keydown' || eventType === 'keyup') &&\n !eventAltKey &&\n !eventCtrlKey &&\n !eventMetaKey &&\n eventTarget === node\n ) {\n bool = true;\n }\n }\n } else if (\n relatedTarget === null ||\n relatedTarget === this.#lastFocusVisible\n ) {\n bool = true;\n }\n }\n }\n if (bool) {\n this.#lastFocusVisible = node;\n matched.add(node);\n } else if (this.#lastFocusVisible === node) {\n this.#lastFocusVisible = null;\n }\n }\n break;\n }\n case 'focus-within': {\n const activeElement = this.#document.activeElement;\n if (node.contains(activeElement) && isFocusableArea(activeElement)) {\n matched.add(node);\n } else if (activeElement.shadowRoot) {\n const activeShadowElement = activeElement.shadowRoot.activeElement;\n if (node.contains(activeShadowElement)) {\n matched.add(node);\n } else {\n let current = activeShadowElement;\n while (current) {\n if (current.nodeType === DOCUMENT_FRAGMENT_NODE) {\n const { host } = current;\n if (host === activeElement && node.contains(host)) {\n matched.add(node);\n }\n break;\n } else {\n current = current.parentNode;\n }\n }\n }\n }\n break;\n }\n case 'open':\n case 'closed': {\n if (localName === 'details' || localName === 'dialog') {\n if (node.hasAttribute('open')) {\n if (astName === 'open') {\n matched.add(node);\n }\n } else if (astName === 'closed') {\n matched.add(node);\n }\n }\n break;\n }\n case 'placeholder-shown': {\n let placeholder;\n if (node.placeholder) {\n placeholder = node.placeholder;\n } else if (node.hasAttribute('placeholder')) {\n placeholder = node.getAttribute('placeholder');\n }\n if (typeof placeholder === 'string' && !/[\\r\\n]/.test(placeholder)) {\n let targetNode;\n if (localName === 'textarea') {\n targetNode = node;\n } else if (localName === 'input') {\n if (node.hasAttribute('type')) {\n if (KEYS_INPUT_PLACEHOLDER.has(node.getAttribute('type'))) {\n targetNode = node;\n }\n } else {\n targetNode = node;\n }\n }\n if (targetNode && node.value === '') {\n matched.add(node);\n }\n }\n break;\n }\n case 'checked': {\n const attrType = node.getAttribute('type');\n if (\n (node.checked &&\n localName === 'input' &&\n (attrType === 'checkbox' || attrType === 'radio')) ||\n (node.selected && localName === 'option')\n ) {\n matched.add(node);\n }\n break;\n }\n case 'indeterminate': {\n if (\n (node.indeterminate &&\n localName === 'input' &&\n node.type === 'checkbox') ||\n (localName === 'progress' && !node.hasAttribute('value'))\n ) {\n matched.add(node);\n } else if (\n localName === 'input' &&\n node.type === 'radio' &&\n !node.hasAttribute('checked')\n ) {\n const nodeName = node.name;\n let parent = node.parentNode;\n while (parent) {\n if (parent.localName === 'form') {\n break;\n }\n parent = parent.parentNode;\n }\n if (!parent) {\n parent = this.#document.documentElement;\n }\n const walker = this._createTreeWalker(parent);\n let refNode = traverseNode(parent, walker);\n refNode = walker.firstChild();\n let checked;\n while (refNode) {\n if (\n refNode.localName === 'input' &&\n refNode.getAttribute('type') === 'radio'\n ) {\n if (refNode.hasAttribute('name')) {\n if (refNode.getAttribute('name') === nodeName) {\n checked = !!refNode.checked;\n }\n } else {\n checked = !!refNode.checked;\n }\n if (checked) {\n break;\n }\n }\n refNode = walker.nextNode();\n }\n if (!checked) {\n matched.add(node);\n }\n }\n break;\n }\n case 'default': {\n // button[type=\"submit\"], input[type=\"submit\"], input[type=\"image\"]\n const attrType = node.getAttribute('type');\n if (\n (localName === 'button' &&\n !(node.hasAttribute('type') && KEYS_INPUT_RESET.has(attrType))) ||\n (localName === 'input' &&\n node.hasAttribute('type') &&\n KEYS_INPUT_SUBMIT.has(attrType))\n ) {\n let form = node.parentNode;\n while (form) {\n if (form.localName === 'form') {\n break;\n }\n form = form.parentNode;\n }\n if (form) {\n const walker = this._createTreeWalker(form);\n let refNode = traverseNode(form, walker);\n refNode = walker.firstChild();\n while (refNode) {\n const nodeName = refNode.localName;\n const nodeAttrType = refNode.getAttribute('type');\n let m;\n if (nodeName === 'button') {\n m = !(\n refNode.hasAttribute('type') &&\n KEYS_INPUT_RESET.has(nodeAttrType)\n );\n } else if (nodeName === 'input') {\n m =\n refNode.hasAttribute('type') &&\n KEYS_INPUT_SUBMIT.has(nodeAttrType);\n }\n if (m) {\n if (refNode === node) {\n matched.add(node);\n }\n break;\n }\n refNode = walker.nextNode();\n }\n }\n // input[type=\"checkbox\"], input[type=\"radio\"]\n } else if (\n localName === 'input' &&\n node.hasAttribute('type') &&\n node.hasAttribute('checked') &&\n KEYS_INPUT_CHECK.has(attrType)\n ) {\n matched.add(node);\n // option\n } else if (localName === 'option' && node.hasAttribute('selected')) {\n matched.add(node);\n }\n break;\n }\n case 'valid':\n case 'invalid': {\n if (KEYS_FORM_PS_VALID.has(localName)) {\n let valid;\n if (node.checkValidity()) {\n if (node.maxLength >= 0) {\n if (node.maxLength >= node.value.length) {\n valid = true;\n }\n } else {\n valid = true;\n }\n }\n if (valid) {\n if (astName === 'valid') {\n matched.add(node);\n }\n } else if (astName === 'invalid') {\n matched.add(node);\n }\n } else if (localName === 'fieldset') {\n const walker = this._createTreeWalker(node);\n let refNode = traverseNode(node, walker);\n refNode = walker.firstChild();\n let valid;\n if (!refNode) {\n valid = true;\n } else {\n while (refNode) {\n if (KEYS_FORM_PS_VALID.has(refNode.localName)) {\n if (refNode.checkValidity()) {\n if (refNode.maxLength >= 0) {\n valid = refNode.maxLength >= refNode.value.length;\n } else {\n valid = true;\n }\n } else {\n valid = false;\n }\n if (!valid) {\n break;\n }\n }\n refNode = walker.nextNode();\n }\n }\n if (valid) {\n if (astName === 'valid') {\n matched.add(node);\n }\n } else if (astName === 'invalid') {\n matched.add(node);\n }\n }\n break;\n }\n case 'in-range':\n case 'out-of-range': {\n const attrType = node.getAttribute('type');\n if (\n localName === 'input' &&\n !(node.readonly || node.hasAttribute('readonly')) &&\n !(node.disabled || node.hasAttribute('disabled')) &&\n KEYS_INPUT_RANGE.has(attrType)\n ) {\n const flowed =\n node.validity.rangeUnderflow || node.validity.rangeOverflow;\n if (astName === 'out-of-range' && flowed) {\n matched.add(node);\n } else if (\n astName === 'in-range' &&\n !flowed &&\n (node.hasAttribute('min') ||\n node.hasAttribute('max') ||\n attrType === 'range')\n ) {\n matched.add(node);\n }\n }\n break;\n }\n case 'required':\n case 'optional': {\n let required;\n let optional;\n if (localName === 'select' || localName === 'textarea') {\n if (node.required || node.hasAttribute('required')) {\n required = true;\n } else {\n optional = true;\n }\n } else if (localName === 'input') {\n if (node.hasAttribute('type')) {\n const attrType = node.getAttribute('type');\n if (KEYS_INPUT_REQUIRED.has(attrType)) {\n if (node.required || node.hasAttribute('required')) {\n required = true;\n } else {\n optional = true;\n }\n } else {\n optional = true;\n }\n } else if (node.required || node.hasAttribute('required')) {\n required = true;\n } else {\n optional = true;\n }\n }\n if (astName === 'required' && required) {\n matched.add(node);\n } else if (astName === 'optional' && optional) {\n matched.add(node);\n }\n break;\n }\n case 'root': {\n if (node === this.#document.documentElement) {\n matched.add(node);\n }\n break;\n }\n case 'empty': {\n if (node.hasChildNodes()) {\n const walker = this._createTreeWalker(node, {\n force: true,\n whatToShow: SHOW_ALL\n });\n let refNode = walker.firstChild();\n let bool;\n while (refNode) {\n bool =\n refNode.nodeType !== ELEMENT_NODE &&\n refNode.nodeType !== TEXT_NODE;\n if (!bool) {\n break;\n }\n refNode = walker.nextSibling();\n }\n if (bool) {\n matched.add(node);\n }\n } else {\n matched.add(node);\n }\n break;\n }\n case 'first-child': {\n if (\n (parentNode && node === parentNode.firstElementChild) ||\n node === this.#root\n ) {\n matched.add(node);\n }\n break;\n }\n case 'last-child': {\n if (\n (parentNode && node === parentNode.lastElementChild) ||\n node === this.#root\n ) {\n matched.add(node);\n }\n break;\n }\n case 'only-child': {\n if (\n (parentNode &&\n node === parentNode.firstElementChild &&\n node === parentNode.lastElementChild) ||\n node === this.#root\n ) {\n matched.add(node);\n }\n break;\n }\n case 'defined': {\n if (node.hasAttribute('is') || localName.includes('-')) {\n if (isCustomElement(node)) {\n matched.add(node);\n }\n // NOTE: MathMLElement is not implemented in jsdom.\n } else if (\n node instanceof this.#window.HTMLElement ||\n node instanceof this.#window.SVGElement\n ) {\n matched.add(node);\n }\n break;\n }\n case 'popover-open': {\n if (node.popover && isVisible(node)) {\n matched.add(node);\n }\n break;\n }\n // Ignore :host.\n case 'host': {\n break;\n }\n // Legacy pseudo-elements.\n case 'after':\n case 'before':\n case 'first-letter':\n case 'first-line': {\n if (warn) {\n this.onError(\n generateException(\n `Unsupported pseudo-element ::${astName}`,\n NOT_SUPPORTED_ERR,\n this.#window\n )\n );\n }\n break;\n }\n // Not supported.\n case 'autofill':\n case 'blank':\n case 'buffering':\n case 'current':\n case 'fullscreen':\n case 'future':\n case 'has-slotted':\n case 'heading':\n case 'modal':\n case 'muted':\n case 'past':\n case 'paused':\n case 'picture-in-picture':\n case 'playing':\n case 'seeking':\n case 'stalled':\n case 'user-invalid':\n case 'user-valid':\n case 'volume-locked':\n case '-webkit-autofill': {\n if (warn) {\n this.onError(\n generateException(\n `Unsupported pseudo-class :${astName}`,\n NOT_SUPPORTED_ERR,\n this.#window\n )\n );\n }\n break;\n }\n default: {\n if (astName.startsWith('-webkit-')) {\n if (warn) {\n this.onError(\n generateException(\n `Unsupported pseudo-class :${astName}`,\n NOT_SUPPORTED_ERR,\n this.#window\n )\n );\n }\n } else if (!forgive) {\n this.onError(\n generateException(\n `Unknown pseudo-class :${astName}`,\n SYNTAX_ERR,\n this.#window\n )\n );\n }\n }\n }\n }\n return matched;\n }\n\n /**\n * Evaluates the :host() pseudo-class.\n * @private\n * @param {Array.} leaves - The AST leaves.\n * @param {object} host - The host element.\n * @param {object} ast - The original AST for error reporting.\n * @returns {boolean} True if matched.\n */\n _evaluateHostPseudo = (leaves, host, ast) => {\n const l = leaves.length;\n for (let i = 0; i < l; i++) {\n const leaf = leaves[i];\n if (leaf.type === COMBINATOR) {\n const css = generateCSS(ast);\n const msg = `Invalid selector ${css}`;\n this.onError(generateException(msg, SYNTAX_ERR, this.#window));\n return false;\n }\n if (!this._matchSelector(leaf, host).has(host)) {\n return false;\n }\n }\n return true;\n };\n\n /**\n * Evaluates the :host-context() pseudo-class.\n * @private\n * @param {Array.} leaves - The AST leaves.\n * @param {object} host - The host element.\n * @param {object} ast - The original AST for error reporting.\n * @returns {boolean} True if matched.\n */\n _evaluateHostContextPseudo = (leaves, host, ast) => {\n let parent = host;\n while (parent) {\n let bool;\n const l = leaves.length;\n for (let i = 0; i < l; i++) {\n const leaf = leaves[i];\n if (leaf.type === COMBINATOR) {\n const css = generateCSS(ast);\n const msg = `Invalid selector ${css}`;\n this.onError(generateException(msg, SYNTAX_ERR, this.#window));\n return false;\n }\n bool = this._matchSelector(leaf, parent).has(parent);\n if (!bool) {\n break;\n }\n }\n if (bool) {\n return true;\n }\n parent = parent.parentNode;\n }\n return false;\n };\n\n /**\n * Matches shadow host pseudo-classes.\n * @private\n * @param {object} ast - The AST.\n * @param {object} node - The DocumentFragment node.\n * @returns {?object} The matched node.\n */\n _matchShadowHostPseudoClass = (ast, node) => {\n const { children: astChildren, name: astName } = ast;\n // Handle simple pseudo-class (no arguments).\n if (!Array.isArray(astChildren)) {\n if (astName === 'host') {\n return node;\n }\n const msg = `Invalid selector :${astName}`;\n return this.onError(generateException(msg, SYNTAX_ERR, this.#window));\n }\n // Handle functional pseudo-class like :host(...).\n if (astName !== 'host' && astName !== 'host-context') {\n const msg = `Invalid selector :${astName}()`;\n return this.onError(generateException(msg, SYNTAX_ERR, this.#window));\n }\n if (astChildren.length !== 1) {\n const css = generateCSS(ast);\n const msg = `Invalid selector ${css}`;\n return this.onError(generateException(msg, SYNTAX_ERR, this.#window));\n }\n const { host } = node;\n const { branches } = walkAST(astChildren[0]);\n const [branch] = branches;\n const [...leaves] = branch;\n let isMatch = false;\n if (astName === 'host') {\n isMatch = this._evaluateHostPseudo(leaves, host, ast);\n // astName === 'host-context'.\n } else {\n isMatch = this._evaluateHostContextPseudo(leaves, host, ast);\n }\n return isMatch ? node : null;\n };\n\n /**\n * Matches a selector for element nodes.\n * @private\n * @param {object} ast - The AST.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _matchSelectorForElement = (ast, node, opt = {}) => {\n const { type: astType } = ast;\n const astName = unescapeSelector(ast.name);\n const matched = new Set();\n switch (astType) {\n case ATTR_SELECTOR: {\n if (matchAttributeSelector(ast, node, opt)) {\n matched.add(node);\n }\n break;\n }\n case ID_SELECTOR: {\n if (node.id === astName) {\n matched.add(node);\n }\n break;\n }\n case CLASS_SELECTOR: {\n if (node.classList.contains(astName)) {\n matched.add(node);\n }\n break;\n }\n case PS_CLASS_SELECTOR: {\n return this._matchPseudoClassSelector(ast, node, opt);\n }\n case TYPE_SELECTOR: {\n if (matchTypeSelector(ast, node, opt)) {\n matched.add(node);\n }\n break;\n }\n // PS_ELEMENT_SELECTOR is handled by default.\n default: {\n try {\n if (opt.check) {\n const css = generateCSS(ast);\n this.#pseudoElement.push(css);\n matched.add(node);\n } else {\n matchPseudoElementSelector(astName, astType, opt);\n }\n } catch (e) {\n this.onError(e);\n }\n }\n }\n return matched;\n };\n\n /**\n * Matches a selector for a shadow root.\n * @private\n * @param {object} ast - The AST.\n * @param {object} node - The DocumentFragment node.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _matchSelectorForShadowRoot = (ast, node, opt = {}) => {\n const { name: astName } = ast;\n if (KEYS_LOGICAL.has(astName)) {\n opt.isShadowRoot = true;\n return this._matchPseudoClassSelector(ast, node, opt);\n }\n const matched = new Set();\n if (astName === 'host' || astName === 'host-context') {\n const res = this._matchShadowHostPseudoClass(ast, node, opt);\n if (res) {\n this.#verifyShadowHost = true;\n matched.add(res);\n }\n }\n return matched;\n };\n\n /**\n * Matches a selector.\n * @private\n * @param {object} ast - The AST.\n * @param {object} node - The Document, DocumentFragment, or Element node.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _matchSelector = (ast, node, opt = {}) => {\n if (node.nodeType === ELEMENT_NODE) {\n return this._matchSelectorForElement(ast, node, opt);\n }\n if (\n this.#shadow &&\n node.nodeType === DOCUMENT_FRAGMENT_NODE &&\n ast.type === PS_CLASS_SELECTOR\n ) {\n return this._matchSelectorForShadowRoot(ast, node, opt);\n }\n return new Set();\n };\n\n /**\n * Matches leaves.\n * @private\n * @param {Array.} leaves - The AST leaves.\n * @param {object} node - The node.\n * @param {object} [opt] - Options.\n * @returns {boolean} The result.\n */\n _matchLeaves = (leaves, node, opt = {}) => {\n const results = this.#invalidate ? this.#invalidateResults : this.#results;\n let result = results.get(leaves);\n if (result && result.has(node)) {\n const { matched } = result.get(node);\n return matched;\n }\n let cacheable = true;\n if (node.nodeType === ELEMENT_NODE && KEYS_FORM.has(node.localName)) {\n cacheable = false;\n }\n let bool;\n const l = leaves.length;\n for (let i = 0; i < l; i++) {\n const leaf = leaves[i];\n switch (leaf.type) {\n case ATTR_SELECTOR:\n case ID_SELECTOR: {\n cacheable = false;\n break;\n }\n case PS_CLASS_SELECTOR: {\n if (KEYS_PS_UNCACHE.has(leaf.name)) {\n cacheable = false;\n }\n break;\n }\n default: {\n // No action needed for other types.\n }\n }\n bool = this._matchSelector(leaf, node, opt).has(node);\n if (!bool) {\n break;\n }\n }\n if (cacheable) {\n if (!result) {\n result = new WeakMap();\n }\n result.set(node, {\n matched: bool\n });\n results.set(leaves, result);\n }\n return bool;\n };\n\n /**\n * Traverses all descendant nodes and collects matches.\n * @private\n * @param {object} baseNode - The base Element node or Element.shadowRoot.\n * @param {Array.} leaves - The AST leaves.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _traverseAllDescendants = (baseNode, leaves, opt = {}) => {\n const walker = this._createTreeWalker(baseNode);\n traverseNode(baseNode, walker);\n let currentNode = walker.firstChild();\n const nodes = new Set();\n while (currentNode) {\n if (this._matchLeaves(leaves, currentNode, opt)) {\n nodes.add(currentNode);\n }\n currentNode = walker.nextNode();\n }\n return nodes;\n };\n\n /**\n * Finds descendant nodes.\n * @private\n * @param {Array.} leaves - The AST leaves.\n * @param {object} baseNode - The base Element node or Element.shadowRoot.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _findDescendantNodes = (leaves, baseNode, opt = {}) => {\n const [leaf, ...filterLeaves] = leaves;\n const { type: leafType } = leaf;\n switch (leafType) {\n case ID_SELECTOR: {\n const canUseGetElementById =\n !this.#shadow &&\n baseNode.nodeType === ELEMENT_NODE &&\n this.#root.nodeType !== ELEMENT_NODE;\n if (canUseGetElementById) {\n const leafName = unescapeSelector(leaf.name);\n const nodes = new Set();\n const foundNode = this.#root.getElementById(leafName);\n if (\n foundNode &&\n foundNode !== baseNode &&\n baseNode.contains(foundNode)\n ) {\n const isCompoundSelector = filterLeaves.length > 0;\n if (\n !isCompoundSelector ||\n this._matchLeaves(filterLeaves, foundNode, opt)\n ) {\n nodes.add(foundNode);\n }\n }\n return nodes;\n }\n // Fallback to default traversal if fast path is not applicable.\n return this._traverseAllDescendants(baseNode, leaves, opt);\n }\n case PS_ELEMENT_SELECTOR: {\n const leafName = unescapeSelector(leaf.name);\n matchPseudoElementSelector(leafName, leafType, opt);\n return new Set();\n }\n default: {\n return this._traverseAllDescendants(baseNode, leaves, opt);\n }\n }\n };\n\n /**\n * Matches the descendant combinator ' '.\n * @private\n * @param {object} twig - The twig object.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _matchDescendantCombinator = (twig, node, opt = {}) => {\n const { leaves } = twig;\n const { parentNode } = node;\n const { dir } = opt;\n if (dir === DIR_NEXT) {\n return this._findDescendantNodes(leaves, node, opt);\n }\n // DIR_PREV\n const ancestors = [];\n let refNode = parentNode;\n while (refNode) {\n if (this._matchLeaves(leaves, refNode, opt)) {\n ancestors.push(refNode);\n }\n refNode = refNode.parentNode;\n }\n if (ancestors.length) {\n // Reverse to maintain document order.\n return new Set(ancestors.reverse());\n }\n return new Set();\n };\n\n /**\n * Matches the child combinator '>'.\n * @private\n * @param {object} twig - The twig object.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _matchChildCombinator = (twig, node, opt = {}) => {\n const { leaves } = twig;\n const { dir } = opt;\n const { parentNode } = node;\n const matched = new Set();\n if (dir === DIR_NEXT) {\n let refNode = node.firstElementChild;\n while (refNode) {\n if (this._matchLeaves(leaves, refNode, opt)) {\n matched.add(refNode);\n }\n refNode = refNode.nextElementSibling;\n }\n } else {\n // DIR_PREV\n if (parentNode && this._matchLeaves(leaves, parentNode, opt)) {\n matched.add(parentNode);\n }\n }\n return matched;\n };\n\n /**\n * Matches the adjacent sibling combinator '+'.\n * @private\n * @param {object} twig - The twig object.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _matchAdjacentSiblingCombinator = (twig, node, opt = {}) => {\n const { leaves } = twig;\n const { dir } = opt;\n const matched = new Set();\n const refNode =\n dir === DIR_NEXT ? node.nextElementSibling : node.previousElementSibling;\n if (refNode && this._matchLeaves(leaves, refNode, opt)) {\n matched.add(refNode);\n }\n return matched;\n };\n\n /**\n * Matches the general sibling combinator '~'.\n * @private\n * @param {object} twig - The twig object.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _matchGeneralSiblingCombinator = (twig, node, opt = {}) => {\n const { leaves } = twig;\n const { dir } = opt;\n const matched = new Set();\n let refNode =\n dir === DIR_NEXT ? node.nextElementSibling : node.previousElementSibling;\n while (refNode) {\n if (this._matchLeaves(leaves, refNode, opt)) {\n matched.add(refNode);\n }\n refNode =\n dir === DIR_NEXT\n ? refNode.nextElementSibling\n : refNode.previousElementSibling;\n }\n return matched;\n };\n\n /**\n * Matches a combinator.\n * @private\n * @param {object} twig - The twig object.\n * @param {object} node - The Element node.\n * @param {object} [opt] - Options.\n * @returns {Set.} A collection of matched nodes.\n */\n _matchCombinator = (twig, node, opt = {}) => {\n const {\n combo: { name: comboName }\n } = twig;\n switch (comboName) {\n case '+': {\n return this._matchAdjacentSiblingCombinator(twig, node, opt);\n }\n case '~': {\n return this._matchGeneralSiblingCombinator(twig, node, opt);\n }\n case '>': {\n return this._matchChildCombinator(twig, node, opt);\n }\n case ' ':\n default: {\n return this._matchDescendantCombinator(twig, node, opt);\n }\n }\n };\n\n /**\n * Traverses with a TreeWalker and collects nodes matching the leaves.\n * @private\n * @param {TreeWalker} walker - The TreeWalker instance to use.\n * @param {Array} leaves - The AST leaves to match against.\n * @param {object} options - Traversal options.\n * @param {Node} options.startNode - The node to start traversal from.\n * @param {string} options.targetType - The type of target ('all' or 'first').\n * @param {Node} [options.boundaryNode] - The node to stop traversal at.\n * @param {boolean} [options.force] - Force traversal to the next node.\n * @returns {Array.} An array of matched nodes.\n */\n _traverseAndCollectNodes = (walker, leaves, options) => {\n const { boundaryNode, force, startNode, targetType } = options;\n const collectedNodes = [];\n let currentNode = traverseNode(startNode, walker, !!force);\n if (!currentNode) {\n return [];\n }\n // Adjust starting node.\n if (currentNode.nodeType !== ELEMENT_NODE) {\n currentNode = walker.nextNode();\n } else if (currentNode === startNode && currentNode !== this.#root) {\n currentNode = walker.nextNode();\n }\n const matchOpt = {\n warn: this.#warn\n };\n while (currentNode) {\n // Stop when we reach the boundary.\n if (boundaryNode) {\n if (currentNode === boundaryNode) {\n break;\n } else if (\n targetType === TARGET_ALL &&\n !boundaryNode.contains(currentNode)\n ) {\n break;\n }\n }\n if (\n this._matchLeaves(leaves, currentNode, matchOpt) &&\n currentNode !== this.#node\n ) {\n collectedNodes.push(currentNode);\n // Stop after the first match if not collecting all.\n if (targetType !== TARGET_ALL) {\n break;\n }\n }\n currentNode = walker.nextNode();\n }\n return collectedNodes;\n };\n\n /**\n * Finds matched node(s) preceding this.#node.\n * @private\n * @param {Array.} leaves - The AST leaves.\n * @param {object} node - The node to start from.\n * @param {object} opt - Options.\n * @param {boolean} [opt.force] - If true, traverses only to the next node.\n * @param {string} [opt.targetType] - The target type.\n * @returns {Array.} A collection of matched nodes.\n */\n _findPrecede = (leaves, node, opt = {}) => {\n const { force, targetType } = opt;\n if (!this.#rootWalker) {\n this.#rootWalker = this._createTreeWalker(this.#root);\n }\n return this._traverseAndCollectNodes(this.#rootWalker, leaves, {\n force,\n targetType,\n boundaryNode: this.#node,\n startNode: node\n });\n };\n\n /**\n * Finds matched node(s) in #nodeWalker.\n * @private\n * @param {Array.} leaves - The AST leaves.\n * @param {object} node - The node to start from.\n * @param {object} opt - Options.\n * @param {boolean} [opt.precede] - If true, finds preceding nodes.\n * @returns {Array.} A collection of matched nodes.\n */\n _findNodeWalker = (leaves, node, opt = {}) => {\n const { precede, ...traversalOpts } = opt;\n if (precede) {\n const precedeNodes = this._findPrecede(leaves, this.#root, opt);\n if (precedeNodes.length) {\n return precedeNodes;\n }\n }\n if (!this.#nodeWalker) {\n this.#nodeWalker = this._createTreeWalker(this.#node);\n }\n return this._traverseAndCollectNodes(this.#nodeWalker, leaves, {\n startNode: node,\n ...traversalOpts\n });\n };\n\n /**\n * Matches the node itself.\n * @private\n * @param {Array} leaves - The AST leaves.\n * @param {boolean} check - Indicates if running in internal check().\n * @returns {Array} An array containing [nodes, filtered, pseudoElement].\n */\n _matchSelf = (leaves, check = false) => {\n const options = { check, warn: this.#warn };\n const matched = this._matchLeaves(leaves, this.#node, options);\n const nodes = matched ? [this.#node] : [];\n return [nodes, matched, this.#pseudoElement];\n };\n\n /**\n * Finds lineal nodes (self and ancestors).\n * @private\n * @param {Array} leaves - The AST leaves.\n * @param {object} opt - Options.\n * @returns {Array} An array containing [nodes, filtered].\n */\n _findLineal = (leaves, opt) => {\n const { complex } = opt;\n const nodes = [];\n const options = { warn: this.#warn };\n const selfMatched = this._matchLeaves(leaves, this.#node, options);\n if (selfMatched) {\n nodes.push(this.#node);\n }\n if (!selfMatched || complex) {\n let currentNode = this.#node.parentNode;\n while (currentNode) {\n if (this._matchLeaves(leaves, currentNode, options)) {\n nodes.push(currentNode);\n }\n currentNode = currentNode.parentNode;\n }\n }\n const filtered = nodes.length > 0;\n return [nodes, filtered];\n };\n\n /**\n * Finds entry nodes for pseudo-element selectors.\n * @private\n * @param {object} leaf - The pseudo-element leaf from the AST.\n * @param {Array.} filterLeaves - Leaves for compound selectors.\n * @param {string} targetType - The type of target to find.\n * @returns {object} The result { nodes, filtered, pending }.\n */\n _findEntryNodesForPseudoElement = (leaf, filterLeaves, targetType) => {\n let nodes = [];\n let filtered = false;\n if (targetType === TARGET_SELF && this.#check) {\n const css = generateCSS(leaf);\n this.#pseudoElement.push(css);\n if (filterLeaves.length) {\n [nodes, filtered] = this._matchSelf(filterLeaves, this.#check);\n } else {\n nodes.push(this.#node);\n filtered = true;\n }\n } else {\n matchPseudoElementSelector(leaf.name, leaf.type, { warn: this.#warn });\n }\n return { nodes, filtered, pending: false };\n };\n\n /**\n * Finds entry nodes for ID selectors.\n * @private\n * @param {object} twig - The current twig from the AST branch.\n * @param {string} targetType - The type of target to find.\n * @param {object} opt - Additional options for finding nodes.\n * @returns {object} The result { nodes, filtered, pending }.\n */\n _findEntryNodesForId = (twig, targetType, opt) => {\n const { leaves } = twig;\n const [leaf, ...filterLeaves] = leaves;\n const { complex, precede } = opt;\n let nodes = [];\n let filtered = false;\n if (targetType === TARGET_SELF) {\n [nodes, filtered] = this._matchSelf(leaves);\n } else if (targetType === TARGET_LINEAL) {\n [nodes, filtered] = this._findLineal(leaves, { complex });\n } else if (\n targetType === TARGET_FIRST &&\n this.#root.nodeType !== ELEMENT_NODE\n ) {\n const node = this.#root.getElementById(leaf.name);\n if (node) {\n if (filterLeaves.length) {\n if (this._matchLeaves(filterLeaves, node, { warn: this.#warn })) {\n nodes.push(node);\n filtered = true;\n }\n } else {\n nodes.push(node);\n filtered = true;\n }\n }\n } else {\n nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType });\n filtered = nodes.length > 0;\n }\n return { nodes, filtered, pending: false };\n };\n\n /**\n * Finds entry nodes for class selectors.\n * @private\n * @param {Array.} leaves - The AST leaves for the selector.\n * @param {string} targetType - The type of target to find.\n * @param {object} opt - Additional options for finding nodes.\n * @returns {object} The result { nodes, filtered, pending }.\n */\n _findEntryNodesForClass = (leaves, targetType, opt) => {\n const { complex, precede } = opt;\n let nodes = [];\n let filtered = false;\n if (targetType === TARGET_SELF) {\n [nodes, filtered] = this._matchSelf(leaves);\n } else if (targetType === TARGET_LINEAL) {\n [nodes, filtered] = this._findLineal(leaves, { complex });\n } else {\n nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType });\n filtered = nodes.length > 0;\n }\n return { nodes, filtered, pending: false };\n };\n\n /**\n * Finds entry nodes for type selectors.\n * @private\n * @param {Array.} leaves - The AST leaves for the selector.\n * @param {string} targetType - The type of target to find.\n * @param {object} opt - Additional options for finding nodes.\n * @returns {object} The result { nodes, filtered, pending }.\n */\n _findEntryNodesForType = (leaves, targetType, opt) => {\n const { complex, precede } = opt;\n let nodes = [];\n let filtered = false;\n if (targetType === TARGET_SELF) {\n [nodes, filtered] = this._matchSelf(leaves);\n } else if (targetType === TARGET_LINEAL) {\n [nodes, filtered] = this._findLineal(leaves, { complex });\n } else {\n nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType });\n filtered = nodes.length > 0;\n }\n return { nodes, filtered, pending: false };\n };\n\n /**\n * Finds entry nodes for other selector types (default case).\n * @private\n * @param {object} twig - The current twig from the AST branch.\n * @param {string} targetType - The type of target to find.\n * @param {object} opt - Additional options for finding nodes.\n * @returns {object} The result { nodes, filtered, pending }.\n */\n _findEntryNodesForOther = (twig, targetType, opt) => {\n const { leaves } = twig;\n const [leaf, ...filterLeaves] = leaves;\n const { complex, precede } = opt;\n let nodes = [];\n let filtered = false;\n let pending = false;\n if (targetType !== TARGET_LINEAL && /host(?:-context)?/.test(leaf.name)) {\n let shadowRoot = null;\n if (this.#shadow && this.#node.nodeType === DOCUMENT_FRAGMENT_NODE) {\n shadowRoot = this._matchShadowHostPseudoClass(leaf, this.#node);\n } else if (filterLeaves.length && this.#node.nodeType === ELEMENT_NODE) {\n shadowRoot = this._matchShadowHostPseudoClass(\n leaf,\n this.#node.shadowRoot\n );\n }\n if (shadowRoot) {\n let bool = true;\n const l = filterLeaves.length;\n for (let i = 0; i < l; i++) {\n const filterLeaf = filterLeaves[i];\n switch (filterLeaf.name) {\n case 'host':\n case 'host-context': {\n const matchedNode = this._matchShadowHostPseudoClass(\n filterLeaf,\n shadowRoot\n );\n bool = matchedNode === shadowRoot;\n break;\n }\n case 'has': {\n bool = this._matchPseudoClassSelector(\n filterLeaf,\n shadowRoot,\n {}\n ).has(shadowRoot);\n break;\n }\n default: {\n bool = false;\n }\n }\n if (!bool) {\n break;\n }\n }\n if (bool) {\n nodes.push(shadowRoot);\n filtered = true;\n }\n }\n } else if (targetType === TARGET_SELF) {\n [nodes, filtered] = this._matchSelf(leaves);\n } else if (targetType === TARGET_LINEAL) {\n [nodes, filtered] = this._findLineal(leaves, { complex });\n } else if (targetType === TARGET_FIRST) {\n nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType });\n filtered = nodes.length > 0;\n } else {\n pending = true;\n }\n return { nodes, filtered, pending };\n };\n\n /**\n * Finds entry nodes.\n * @private\n * @param {object} twig - The twig object.\n * @param {string} targetType - The target type.\n * @param {object} [opt] - Options.\n * @param {boolean} [opt.complex] - If true, the selector is complex.\n * @param {string} [opt.dir] - The find direction.\n * @returns {object} An object with nodes and their state.\n */\n _findEntryNodes = (twig, targetType, opt = {}) => {\n const { leaves } = twig;\n const [leaf, ...filterLeaves] = leaves;\n const { complex = false, dir = DIR_PREV } = opt;\n const precede =\n dir === DIR_NEXT &&\n this.#node.nodeType === ELEMENT_NODE &&\n this.#node !== this.#root;\n let result;\n switch (leaf.type) {\n case PS_ELEMENT_SELECTOR: {\n result = this._findEntryNodesForPseudoElement(\n leaf,\n filterLeaves,\n targetType\n );\n break;\n }\n case ID_SELECTOR: {\n result = this._findEntryNodesForId(twig, targetType, {\n complex,\n precede\n });\n break;\n }\n case CLASS_SELECTOR: {\n result = this._findEntryNodesForClass(leaves, targetType, {\n complex,\n precede\n });\n break;\n }\n case TYPE_SELECTOR: {\n result = this._findEntryNodesForType(leaves, targetType, {\n complex,\n precede\n });\n break;\n }\n default: {\n result = this._findEntryNodesForOther(twig, targetType, {\n complex,\n precede\n });\n }\n }\n return {\n compound: filterLeaves.length > 0,\n filtered: result.filtered,\n nodes: result.nodes,\n pending: result.pending\n };\n };\n\n /**\n * Determines the direction and starting twig for a selector branch.\n * @private\n * @param {Array.} branch - The AST branch.\n * @param {string} targetType - The type of target to find.\n * @returns {object} An object with the direction and starting twig.\n */\n _determineTraversalStrategy = (branch, targetType) => {\n const branchLen = branch.length;\n const firstTwig = branch[0];\n const lastTwig = branch[branchLen - 1];\n if (branchLen === 1) {\n return { dir: DIR_PREV, twig: firstTwig };\n }\n // Complex selector (branchLen > 1).\n const {\n leaves: [{ name: firstName, type: firstType }]\n } = firstTwig;\n const {\n leaves: [{ name: lastName, type: lastType }]\n } = lastTwig;\n const { combo: firstCombo } = firstTwig;\n if (\n this.#selector.includes(':scope') ||\n lastType === PS_ELEMENT_SELECTOR ||\n lastType === ID_SELECTOR\n ) {\n return { dir: DIR_PREV, twig: lastTwig };\n }\n if (firstType === ID_SELECTOR) {\n return { dir: DIR_NEXT, twig: firstTwig };\n }\n if (firstName === '*' && firstType === TYPE_SELECTOR) {\n return { dir: DIR_PREV, twig: lastTwig };\n }\n if (lastName === '*' && lastType === TYPE_SELECTOR) {\n return { dir: DIR_NEXT, twig: firstTwig };\n }\n if (branchLen === 2) {\n if (targetType === TARGET_FIRST) {\n return { dir: DIR_PREV, twig: lastTwig };\n }\n const { name: comboName } = firstCombo;\n if (comboName === '+' || comboName === '~') {\n return { dir: DIR_PREV, twig: lastTwig };\n }\n } else if (branchLen > 2 && this.#scoped && targetType === TARGET_FIRST) {\n if (lastType === TYPE_SELECTOR) {\n return { dir: DIR_PREV, twig: lastTwig };\n }\n let isChildOrDescendant = false;\n for (const { combo } of branch) {\n if (combo) {\n const { name: comboName } = combo;\n isChildOrDescendant = comboName === '>' || comboName === ' ';\n if (!isChildOrDescendant) {\n break;\n }\n }\n }\n if (isChildOrDescendant) {\n return { dir: DIR_PREV, twig: lastTwig };\n }\n }\n // Default strategy for complex selectors.\n return { dir: DIR_NEXT, twig: firstTwig };\n };\n\n /**\n * Processes pending items not resolved with a direct strategy.\n * @private\n * @param {Set.} pendingItems - The set of pending items.\n */\n _processPendingItems = pendingItems => {\n if (!pendingItems.size) {\n return;\n }\n if (!this.#rootWalker) {\n this.#rootWalker = this._createTreeWalker(this.#root);\n }\n const walker = this.#rootWalker;\n let node = this.#root;\n if (this.#scoped) {\n node = this.#node;\n }\n let nextNode = traverseNode(node, walker);\n while (nextNode) {\n const isWithinScope =\n this.#node.nodeType !== ELEMENT_NODE ||\n nextNode === this.#node ||\n this.#node.contains(nextNode);\n if (isWithinScope) {\n for (const pendingItem of pendingItems) {\n const { leaves } = pendingItem.get('twig');\n if (this._matchLeaves(leaves, nextNode, { warn: this.#warn })) {\n const index = pendingItem.get('index');\n this.#ast[index].filtered = true;\n this.#ast[index].find = true;\n this.#nodes[index].push(nextNode);\n }\n }\n } else if (this.#scoped) {\n break;\n }\n nextNode = walker.nextNode();\n }\n };\n\n /**\n * Collects nodes.\n * @private\n * @param {string} targetType - The target type.\n * @returns {Array.>} An array containing the AST and nodes.\n */\n _collectNodes = targetType => {\n const ast = this.#ast.values();\n if (targetType === TARGET_ALL || targetType === TARGET_FIRST) {\n const pendingItems = new Set();\n let i = 0;\n for (const { branch } of ast) {\n const complex = branch.length > 1;\n const { dir, twig } = this._determineTraversalStrategy(\n branch,\n targetType\n );\n const { compound, filtered, nodes, pending } = this._findEntryNodes(\n twig,\n targetType,\n { complex, dir }\n );\n if (nodes.length) {\n this.#ast[i].find = true;\n this.#nodes[i] = nodes;\n } else if (pending) {\n pendingItems.add(\n new Map([\n ['index', i],\n ['twig', twig]\n ])\n );\n }\n this.#ast[i].dir = dir;\n this.#ast[i].filtered = filtered || !compound;\n i++;\n }\n this._processPendingItems(pendingItems);\n } else {\n let i = 0;\n for (const { branch } of ast) {\n const twig = branch[branch.length - 1];\n const complex = branch.length > 1;\n const dir = DIR_PREV;\n const { compound, filtered, nodes } = this._findEntryNodes(\n twig,\n targetType,\n { complex, dir }\n );\n if (nodes.length) {\n this.#ast[i].find = true;\n this.#nodes[i] = nodes;\n }\n this.#ast[i].dir = dir;\n this.#ast[i].filtered = filtered || !compound;\n i++;\n }\n }\n return [this.#ast, this.#nodes];\n };\n\n /**\n * Gets combined nodes.\n * @private\n * @param {object} twig - The twig object.\n * @param {object} nodes - A collection of nodes.\n * @param {string} dir - The direction.\n * @returns {Array.} A collection of matched nodes.\n */\n _getCombinedNodes = (twig, nodes, dir) => {\n const arr = [];\n const options = {\n dir,\n warn: this.#warn\n };\n for (const node of nodes) {\n const matched = this._matchCombinator(twig, node, options);\n if (matched.size) {\n arr.push(...matched);\n }\n }\n return arr;\n };\n\n /**\n * Matches a node in the 'next' direction.\n * @private\n * @param {Array} branch - The branch.\n * @param {Set.} nodes - A collection of Element nodes.\n * @param {object} opt - Options.\n * @param {object} opt.combo - The combo object.\n * @param {number} opt.index - The index.\n * @returns {?object} The matched node.\n */\n _matchNodeNext = (branch, nodes, opt) => {\n const { combo, index } = opt;\n const { combo: nextCombo, leaves } = branch[index];\n const twig = {\n combo,\n leaves\n };\n const nextNodes = new Set(this._getCombinedNodes(twig, nodes, DIR_NEXT));\n if (nextNodes.size) {\n if (index === branch.length - 1) {\n const [nextNode] = sortNodes(nextNodes);\n return nextNode;\n }\n return this._matchNodeNext(branch, nextNodes, {\n combo: nextCombo,\n index: index + 1\n });\n }\n return null;\n };\n\n /**\n * Matches a node in the 'previous' direction.\n * @private\n * @param {Array} branch - The branch.\n * @param {object} node - The Element node.\n * @param {object} opt - Options.\n * @param {number} opt.index - The index.\n * @returns {?object} The node.\n */\n _matchNodePrev = (branch, node, opt) => {\n const { index } = opt;\n const twig = branch[index];\n const nodes = new Set([node]);\n const nextNodes = new Set(this._getCombinedNodes(twig, nodes, DIR_PREV));\n if (nextNodes.size) {\n if (index === 0) {\n return node;\n }\n let matched;\n for (const nextNode of nextNodes) {\n matched = this._matchNodePrev(branch, nextNode, {\n index: index - 1\n });\n if (matched) {\n break;\n }\n }\n if (matched) {\n return node;\n }\n }\n return null;\n };\n\n /**\n * Processes a complex selector branch to find all matching nodes.\n * @private\n * @param {Array} branch - The selector branch from the AST.\n * @param {Array} entryNodes - The initial set of nodes to start from.\n * @param {string} dir - The direction of traversal ('next' or 'prev').\n * @returns {Set.} A set of all matched nodes.\n */\n _processComplexBranchAll = (branch, entryNodes, dir) => {\n const matchedNodes = new Set();\n const branchLen = branch.length;\n const lastIndex = branchLen - 1;\n\n if (dir === DIR_NEXT) {\n const { combo: firstCombo } = branch[0];\n for (const node of entryNodes) {\n let combo = firstCombo;\n let nextNodes = new Set([node]);\n for (let j = 1; j < branchLen; j++) {\n const { combo: nextCombo, leaves } = branch[j];\n const twig = { combo, leaves };\n const nodesArr = this._getCombinedNodes(twig, nextNodes, dir);\n if (nodesArr.length) {\n if (j === lastIndex) {\n for (const nextNode of nodesArr) {\n matchedNodes.add(nextNode);\n }\n }\n combo = nextCombo;\n nextNodes = new Set(nodesArr);\n } else {\n // No further matches down this path.\n nextNodes.clear();\n break;\n }\n }\n }\n // DIR_PREV\n } else {\n for (const node of entryNodes) {\n let nextNodes = new Set([node]);\n for (let j = lastIndex - 1; j >= 0; j--) {\n const twig = branch[j];\n const nodesArr = this._getCombinedNodes(twig, nextNodes, dir);\n if (nodesArr.length) {\n // The entry node is the final match\n if (j === 0) {\n matchedNodes.add(node);\n }\n nextNodes = new Set(nodesArr);\n } else {\n // No further matches down this path.\n nextNodes.clear();\n break;\n }\n }\n }\n }\n return matchedNodes;\n };\n\n /**\n * Processes a complex selector branch to find the first matching node.\n * @private\n * @param {Array} branch - The selector branch from the AST.\n * @param {Array} entryNodes - The initial set of nodes to start from.\n * @param {string} dir - The direction of traversal ('next' or 'prev').\n * @param {string} targetType - The type of search (e.g., 'first').\n * @returns {?object} The first matched node, or null.\n */\n _processComplexBranchFirst = (branch, entryNodes, dir, targetType) => {\n const branchLen = branch.length;\n const lastIndex = branchLen - 1;\n // DIR_NEXT logic for finding the first match.\n if (dir === DIR_NEXT) {\n const { combo: entryCombo } = branch[0];\n for (const node of entryNodes) {\n const matchedNode = this._matchNodeNext(branch, new Set([node]), {\n combo: entryCombo,\n index: 1\n });\n if (matchedNode) {\n if (this.#node.nodeType === ELEMENT_NODE) {\n if (\n matchedNode !== this.#node &&\n this.#node.contains(matchedNode)\n ) {\n return matchedNode;\n }\n } else {\n return matchedNode;\n }\n }\n }\n // Fallback logic if no direct match found.\n const { leaves: entryLeaves } = branch[0];\n const [entryNode] = entryNodes;\n if (this.#node.contains(entryNode)) {\n let [refNode] = this._findNodeWalker(entryLeaves, entryNode, {\n targetType\n });\n while (refNode) {\n const matchedNode = this._matchNodeNext(branch, new Set([refNode]), {\n combo: entryCombo,\n index: 1\n });\n if (matchedNode) {\n if (this.#node.nodeType === ELEMENT_NODE) {\n if (\n matchedNode !== this.#node &&\n this.#node.contains(matchedNode)\n ) {\n return matchedNode;\n }\n } else {\n return matchedNode;\n }\n }\n [refNode] = this._findNodeWalker(entryLeaves, refNode, {\n targetType,\n force: true\n });\n }\n }\n // DIR_PREV logic for finding the first match.\n } else {\n for (const node of entryNodes) {\n const matchedNode = this._matchNodePrev(branch, node, {\n index: lastIndex - 1\n });\n if (matchedNode) {\n return matchedNode;\n }\n }\n // Fallback for TARGET_FIRST.\n if (targetType === TARGET_FIRST) {\n const { leaves: entryLeaves } = branch[lastIndex];\n const [entryNode] = entryNodes;\n let [refNode] = this._findNodeWalker(entryLeaves, entryNode, {\n targetType\n });\n while (refNode) {\n const matchedNode = this._matchNodePrev(branch, refNode, {\n index: lastIndex - 1\n });\n if (matchedNode) {\n return refNode;\n }\n [refNode] = this._findNodeWalker(entryLeaves, refNode, {\n targetType,\n force: true\n });\n }\n }\n }\n return null;\n };\n\n /**\n * Finds matched nodes.\n * @param {string} targetType - The target type.\n * @returns {Set.} A collection of matched nodes.\n */\n find = targetType => {\n const [[...branches], collectedNodes] = this._collectNodes(targetType);\n const l = branches.length;\n let sort =\n l > 1 && targetType === TARGET_ALL && this.#selector.includes(':scope');\n let nodes = new Set();\n for (let i = 0; i < l; i++) {\n const { branch, dir, find } = branches[i];\n if (!branch.length || !find) {\n continue;\n }\n const entryNodes = collectedNodes[i];\n const lastIndex = branch.length - 1;\n // Handle simple selectors (no combinators).\n if (lastIndex === 0) {\n if (\n (targetType === TARGET_ALL || targetType === TARGET_FIRST) &&\n this.#node.nodeType === ELEMENT_NODE\n ) {\n for (const node of entryNodes) {\n if (node !== this.#node && this.#node.contains(node)) {\n nodes.add(node);\n if (targetType === TARGET_FIRST) {\n break;\n }\n }\n }\n } else if (targetType === TARGET_ALL) {\n if (nodes.size) {\n for (const node of entryNodes) {\n nodes.add(node);\n }\n sort = true;\n } else {\n nodes = new Set(entryNodes);\n }\n } else {\n if (entryNodes.length) {\n nodes.add(entryNodes[0]);\n }\n }\n // Handle complex selectors.\n } else {\n if (targetType === TARGET_ALL) {\n const newNodes = this._processComplexBranchAll(\n branch,\n entryNodes,\n dir\n );\n if (nodes.size) {\n for (const newNode of newNodes) {\n nodes.add(newNode);\n }\n sort = true;\n } else {\n nodes = newNodes;\n }\n } else {\n const matchedNode = this._processComplexBranchFirst(\n branch,\n entryNodes,\n dir,\n targetType\n );\n if (matchedNode) {\n nodes.add(matchedNode);\n }\n }\n }\n }\n if (this.#check) {\n const match = !!nodes.size;\n let pseudoElement;\n if (this.#pseudoElement.length) {\n pseudoElement = this.#pseudoElement.join('');\n } else {\n pseudoElement = null;\n }\n return { match, pseudoElement };\n }\n if (targetType === TARGET_FIRST || targetType === TARGET_ALL) {\n nodes.delete(this.#node);\n }\n if ((sort || targetType === TARGET_FIRST) && nodes.size > 1) {\n return new Set(sortNodes(nodes));\n }\n return nodes;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,uBAAyB;;;ACHzB,IAAAA,WAAyB;;;ACAzB,oBAAmB;AACnB,qBAAwB;AACxB,cAAyB;AACzB,8CAAgC;;;ACFzB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,aAAa;AACnB,IAAM,QAAQ;AACd,IAAM,cAAc;AACpB,IAAM,oBAAoB;AAC1B,IAAM,MAAM;AAEZ,IAAM,oBAAoB;AAC1B,IAAM,sBAAsB;AAG5B,IAAM,WAAW;AAEjB,IAAM,SAAS;AACf,IAAM,aAAa;AACnB,IAAM,aAAa;AACnB,IAAM,eAAe;AACrB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AAGtB,IAAM,SAAS;AACf,IAAM,SAAS;AACf,IAAM,SAAS;AACf,IAAM,SAAS;AACf,IAAM,SAAS;AACf,IAAM,SAAS;AACf,IAAM,WAAW;AACjB,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,YAAY;AAClB,IAAM,UAAU;AAGhB,IAAM,eAAe;AACrB,IAAM,YAAY;AAClB,IAAM,gBAAgB;AACtB,IAAM,yBAAyB;AAC/B,IAAM,8BAA8B;AACpC,IAAM,6BAA6B;AAInC,IAAM,WAAW;AACjB,IAAM,iBAAiB;AAMvB,IAAM,YAAY;AAClB,IAAM,YAAY;AAClB,IAAM,QAAQ;AACd,IAAM,YAAY,OAAO,SAAS;AAClC,IAAM,eAAe,iBAAiB,SAAS;AAC/C,IAAM,MAAM,WAAW,KAAK,iBAAiB,KAAK,kBAAkB,KAAK;AAEzE,IAAM,QAAQ;AACd,IAAM,UAAU;AAChB,IAAM,UAAU;AAEhB,IAAM,WAAW;AAEjB,IAAM,OAAO,qDAAqD,GAAG;AAErE,IAAM,WAAW;AACjB,IAAM,qBAAqB;AAE3B,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,WAAW,MAAM,QAAQ,OAAO,QAAQ,QAAQ,QAAQ;AAC9D,IAAM,aAAa,MAAM,QAAQ,OAAO,QAAQ,QAAQ,QAAQ,IAAI,QAAQ;AAC5E,IAAM,aAAa,MAAM,UAAU,OAAO,UAAU,QAAQ,QAAQ;AACpE,IAAM,qBAAqB,MAAM,QAAQ,OAAO,QAAQ,QAAQ,kBAAkB;AAClF,IAAM,UAAU,GAAG,QAAQ,MAAM,KAAK,GAAG,QAAQ;AACjD,IAAM,YAAY,GAAG,UAAU,MAAM,KAAK,GAAG,UAAU;AACvD,IAAM,eAAe,oBAAoB,kBAAkB;AAC3D,IAAM,iBAAiB,oBAAoB,UAAU,eAAe,UAAU;AAC9E,IAAM,gBAAgB,oBAAoB,SAAS,eAAe,SAAS;AAG3E,IAAM,aAAa,OAAO,OAAO;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACM,IAAM,eAAe,OAAO,OAAO,CAAC,UAAU,SAAS,QAAQ,CAAC;AAChE,IAAM,cAAc,OAAO,OAAO,CAAC,YAAY,OAAO,CAAC;AACvD,IAAM,aAAa,OAAO,OAAO;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACM,IAAM,aAAa,OAAO,OAAO;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACM,IAAM,aAAa,OAAO,OAAO;AAAA,EACtC,GAAG;AAAA,EACH,GAAG;AAAA,EACH;AACF,CAAC;AACM,IAAM,YAAY,OAAO,OAAO;AAAA,EACrC,GAAG;AAAA,EACH;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,IAAM,eAAe,oBAAI,IAAI,CAAC,OAAO,MAAM,OAAO,OAAO,CAAC;;;ADvFjE,IAAM,gBAAgB,oBAAI,IAAI,CAAC,GAAG,cAAc,GAAG,YAAY,QAAQ,CAAC;AACxE,IAAM,eAAe,IAAI,IAAI,SAAS;AACtC,IAAM,kBAAkB,IAAI,IAAI,UAAU;AAC1C,IAAM,wBAAwB,oBAAI,IAAI,CAAC,OAAO,UAAU,SAAS,UAAU,CAAC;AAC5E,IAAM,sBAAsB,oBAAI,IAAI,CAAC,UAAU,UAAU,UAAU,CAAC;AACpE,IAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,oBACJ;AACF,IAAM,cAAc,IAAI,OAAO,GAAG,UAAU,GAAG,KAAK,GAAG,UAAU,IAAI,GAAG;AACxE,IAAM,cAAc,IAAI,OAAO,GAAG,UAAU,GAAG,OAAO,GAAG,UAAU,IAAI,GAAG;AAC1E,IAAM,cAAc,IAAI,OAAO,GAAG,UAAU,GAAG,OAAO,GAAG,UAAU,IAAI,GAAG;AAC1E,IAAM,oBAAoB,IAAI;AAAA,EAC5B,OAAO,YAAY,IAAI,IAAI,IAAI,aAAa;AAC9C;AACA,IAAM,qBAAqB,IAAI;AAAA,EAC7B,OAAO,YAAY,IAAI,IAAI,IAAI,cAAc;AAC/C;AACA,IAAM,yBAAyB,IAAI;AAAA,EACjC,OAAO,YAAY,IAAI,IAAI,IAAI,cAAc,IAAI,YAAY;AAC/D;AACA,IAAM,mBAAmB,IAAI,OAAO,IAAI,YAAY,GAAG;AACvD,IAAM,iBAAiB,IAAI,OAAO,OAAO,YAAY,IAAI,IAAI,GAAG;AAChE,IAAM,cAAc;AACpB,IAAM,aACJ;AAkFK,IAAM,UAAU,OACrB,OAAO,UAAU,SAAS,KAAK,CAAC,EAAE,MAAM,WAAW,OAAO;AA+BrD,IAAM,oBAAoB,CAAC,KAAK,MAAM,eAAe,eAAe;AACzE,SAAO,IAAI,aAAa,aAAa,KAAK,IAAI;AAChD;AAOO,IAAM,gBAAgB,UAAQ;AACnC,SAAO,KAAK,SAAS;AACvB;AAOO,IAAM,2BAA2B,UAAQ;AAC9C,MAAI,aAAa,IAAI,KAAK,IAAI,KAAa,aAAK,MAAM,aAAa,GAAG;AACpE,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAWO,IAAM,mBAAmB,CAAC,OAAO,QAAQ;AAC9C,QAAM,EAAE,GAAG,GAAG,QAAQ,IAAI;AAC1B,QAAM,iBAAiB,UAAU,CAAC,GAAG,KAAK,EAAE,QAAQ,IAAI;AACxD,QAAM,IAAI,MAAM;AAChB,QAAM,UAAU,CAAC;AACjB,MAAI,MAAM,GAAG;AACX,QAAI,IAAI,KAAK,KAAK,GAAG;AACnB,cAAQ,KAAK,eAAe,IAAI,CAAC,CAAC;AAAA,IACpC;AACA,WAAO;AAAA,EACT;AACA,MAAI,aAAa,IAAI;AACrB,MAAI,IAAI,GAAG;AACT,WAAO,aAAa,GAAG;AACrB,oBAAc;AAAA,IAChB;AACA,aAAS,IAAI,YAAY,IAAI,GAAG,KAAK,GAAG;AACtC,cAAQ,KAAK,eAAe,CAAC,CAAC;AAAA,IAChC;AAAA,EACF,WAAW,cAAc,GAAG;AAC1B,aAAS,IAAI,YAAY,KAAK,GAAG,KAAK,GAAG;AACvC,cAAQ,KAAK,eAAe,CAAC,CAAC;AAAA,IAChC;AACA,WAAO,QAAQ,QAAQ;AAAA,EACzB;AACA,SAAO;AACT;AAOO,IAAM,iBAAiB,UAAQ;AACpC,MAAI,CAAC,MAAM,UAAU;AACnB,UAAM,IAAI,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AAAA,EACxD;AACA,MAAI;AACJ,MAAI;AACJ,MAAI;AACJ,UAAQ,KAAK,UAAU;AAAA,IACrB,KAAK,eAAe;AAClB,iBAAW;AACX,aAAO;AACP;AAAA,IACF;AAAA,IACA,KAAK,wBAAwB;AAC3B,YAAM,EAAE,MAAM,MAAM,cAAc,IAAI;AACtC,iBAAW;AACX,aAAO;AACP,eAAS,SAAS,SAAS,WAAW,SAAS;AAC/C;AAAA,IACF;AAAA,IACA,KAAK,cAAc;AACjB,iBAAW,KAAK;AAChB,UAAI,UAAU;AACd,aAAO,SAAS;AACd,cAAM,EAAE,MAAM,MAAM,UAAU,WAAW,IAAI;AAC7C,YAAI,aAAa,wBAAwB;AACvC,mBAAS,SAAS,SAAS,WAAW,SAAS;AAC/C;AAAA,QACF,WAAW,YAAY;AACrB,oBAAU;AAAA,QACZ,OAAO;AACL;AAAA,QACF;AAAA,MACF;AACA,aAAO;AACP;AAAA,IACF;AAAA,IACA,SAAS;AACP,YAAM,IAAI,UAAU,mBAAmB,KAAK,QAAQ,EAAE;AAAA,IACxD;AAAA,EACF;AACA,SAAO,CAAC,UAAU,MAAM,CAAC,CAAC,MAAM;AAClC;AASO,IAAM,eAAe,CAAC,MAAM,QAAQ,QAAQ,UAAU;AAC3D,MAAI,CAAC,MAAM,UAAU;AACnB,UAAM,IAAI,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AAAA,EACxD;AACA,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AACA,MAAI,UAAU,OAAO;AACrB,MAAI,YAAY,MAAM;AACpB,WAAO;AAAA,EACT,WAAW,SAAS,QAAQ,SAAS,IAAI,GAAG;AAC1C,cAAU,OAAO,SAAS;AAC1B,WAAO,SAAS;AACd,UAAI,YAAY,MAAM;AACpB;AAAA,MACF;AACA,gBAAU,OAAO,SAAS;AAAA,IAC5B;AACA,WAAO;AAAA,EACT,OAAO;AACL,QAAI,YAAY,OAAO,MAAM;AAC3B,UAAI;AACJ,aAAO,SAAS;AACd,YAAI,YAAY,MAAM;AACpB,iBAAO;AACP;AAAA,QACF,WAAW,YAAY,OAAO,QAAQ,QAAQ,SAAS,IAAI,GAAG;AAC5D;AAAA,QACF;AACA,kBAAU,OAAO,WAAW;AAAA,MAC9B;AACA,UAAI,MAAM;AACR,eAAO;AAAA,MACT;AAAA,IACF;AACA,QAAI,KAAK,aAAa,cAAc;AAClC,UAAI;AACJ,aAAO,SAAS;AACd,YAAI,YAAY,MAAM;AACpB,iBAAO;AACP;AAAA,QACF;AACA,kBAAU,OAAO,SAAS;AAAA,MAC5B;AACA,UAAI,MAAM;AACR,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAQO,IAAM,kBAAkB,CAAC,MAAM,MAAM,CAAC,MAAM;AACjD,MAAI,CAAC,MAAM,UAAU;AACnB,UAAM,IAAI,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AAAA,EACxD;AACA,MAAI,KAAK,aAAa,cAAc;AAClC,WAAO;AAAA,EACT;AACA,QAAM,EAAE,WAAW,cAAc,IAAI;AACrC,QAAM,EAAE,eAAe,IAAI;AAC3B,QAAM,SAAS,cAAc;AAC7B,MAAI;AACJ,QAAM,OAAO,KAAK,aAAa,IAAI;AACnC,MAAI,MAAM;AACR,yBACE,wCAAAC,SAAoB,IAAI,KAAK,OAAO,eAAe,IAAI,IAAI;AAAA,EAC/D,OAAO;AACL,yBACE,wCAAAA,SAAoB,SAAS,KAAK,OAAO,eAAe,IAAI,SAAS;AAAA,EACzE;AACA,MAAI,gBAAgB;AAClB,QAAI,gBAAgB;AAClB,aAAO,CAAC,CAAC,eAAe;AAAA,IAC1B;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAOO,IAAM,wBAAwB,UAAQ;AAC3C,MAAI,CAAC,MAAM,UAAU;AACnB,UAAM,IAAI,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AAAA,EACxD;AACA,MAAI,OAAO,KAAK,kBAAkB,YAAY;AAC5C,WAAO;AAAA,EACT;AACA,QAAM,QAAQ,KAAK,cAAc;AACjC,MAAI,MAAM,QAAQ;AAChB,QAAI,OAAO;AACX,UAAM,IAAI,MAAM;AAChB,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,YAAM,OAAO,MAAM,CAAC;AACpB,aAAO,KAAK,YAAY,KAAK;AAC7B,UAAI,MAAM;AACR;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACA,SAAO,KAAK,YAAY,KAAK;AAC/B;AAQO,IAAM,oBAAoB,UAAQ;AACvC,MAAI,CAAC,MAAM,UAAU;AACnB,UAAM,IAAI,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AAAA,EACxD;AACA,MAAI,KAAK,aAAa,cAAc;AAClC,WAAO;AAAA,EACT;AACA,QAAM,EAAE,KAAK,SAAS,WAAW,WAAW,IAAI;AAChD,QAAM,EAAE,mBAAmB,QAAI,eAAAC,SAAY;AAC3C,MAAI,YAAY,SAAS,YAAY,OAAO;AAC1C,WAAO;AAAA,EACT,WAAW,YAAY,QAAQ;AAC7B,QAAI,OAAO;AACX,YAAQ,WAAW;AAAA,MACjB,KAAK,SAAS;AACZ,YAAI,CAAC,KAAK,QAAQ,cAAc,IAAI,KAAK,IAAI,GAAG;AAC9C,iBAAO,KAAK;AAAA,QACd,WAAW,aAAa,IAAI,KAAK,IAAI,GAAG;AACtC,iBAAO;AAAA,QACT;AACA;AAAA,MACF;AAAA,MACA,KAAK,QAAQ;AACX,eAAO,sBAAsB,IAAI;AACjC;AAAA,MACF;AAAA,MACA,KAAK,YAAY;AACf,eAAO,KAAK;AACZ;AAAA,MACF;AAAA,MACA,SAAS;AACP,cAAM,QAAQ,CAAC,EAAE,MAAM,KAAK,KAAK,UAAU;AAC3C,mBAAW,QAAQ,OAAO;AACxB,gBAAM;AAAA,YACJ,KAAK;AAAA,YACL,WAAW;AAAA,YACX,UAAU;AAAA,YACV,aAAa;AAAA,UACf,IAAI;AACJ,cAAI,iBAAiB,WAAW;AAC9B,mBAAO,gBAAgB,KAAK;AAAA,UAC9B,WACE,iBAAiB,gBACjB,CAAC,sBAAsB,IAAI,aAAa,MACvC,CAAC,WAAY,YAAY,SAAS,YAAY,QAC/C;AACA,gBAAI,kBAAkB,QAAQ;AAC5B,qBAAO,sBAAsB,IAAI;AAAA,YACnC,OAAO;AACL,qBAAO,gBAAgB,KAAK;AAAA,YAC9B;AAAA,UACF;AACA,cAAI,MAAM;AACR;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,QAAI,MAAM;AACR,YAAM;AAAA,QACJ,YAAY,CAAC,EAAE,MAAM,CAAC;AAAA,MACxB,IAAI,mBAAmB,IAAI;AAC3B,UAAI,QAAQ,MAAM,GAAG;AACnB,eAAO;AAAA,MACT;AAAA,IACF,WAAW,YAAY;AACrB,YAAM,EAAE,UAAU,eAAe,IAAI;AACrC,UAAI,mBAAmB,cAAc;AACnC,eAAO,kBAAkB,UAAU;AAAA,MACrC;AAAA,IACF;AAAA,EACF,WAAW,cAAc,WAAW,KAAK,SAAS,OAAO;AACvD,WAAO;AAAA,EACT,WAAW,cAAc,OAAO;AAC9B,UAAM,OAAO,KAAK,YAAY,KAAK;AACnC,QAAI,MAAM;AACR,YAAM;AAAA,QACJ,YAAY,CAAC,EAAE,MAAM,CAAC;AAAA,MACxB,IAAI,mBAAmB,IAAI;AAC3B,UAAI,QAAQ,MAAM,GAAG;AACnB,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF,WAAW,YAAY;AACrB,QAAI,cAAc,QAAQ;AACxB,YAAM,OAAO,sBAAsB,IAAI;AACvC,UAAI,MAAM;AACR,cAAM;AAAA,UACJ,YAAY,CAAC,EAAE,MAAM,CAAC;AAAA,QACxB,IAAI,mBAAmB,IAAI;AAC3B,YAAI,QAAQ,MAAM,GAAG;AACnB,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT;AAAA,IACF;AACA,UAAM,EAAE,UAAU,eAAe,IAAI;AACrC,QAAI,mBAAmB,cAAc;AACnC,aAAO,kBAAkB,UAAU;AAAA,IACrC;AAAA,EACF;AACA,SAAO;AACT;AAQO,IAAM,uBAAuB,UAAQ;AAC1C,MAAI,CAAC,MAAM,UAAU;AACnB,UAAM,IAAI,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AAAA,EACxD;AACA,MAAI,KAAK,aAAa,cAAc;AAClC,WAAO;AAAA,EACT;AACA,QAAM,EAAE,YAAY,IAAI,KAAK;AAC7B,QAAM,SAAS,YAAY,KAAK,WAAW;AAC3C,QAAM,QAAQ,WAAW,KAAK,WAAW;AACzC,MAAI,WAAW;AAEf,MAAI,UAAU;AACd,SAAO,SAAS;AAEd,YAAQ,QAAQ,UAAU;AAAA,MACxB,KAAK,cAAc;AAEjB,YAAI,UAAU,QAAQ,aAAa,MAAM,GAAG;AAC1C,iBAAO,QAAQ,aAAa,MAAM;AAAA,QACpC,WAAW,SAAS,QAAQ,aAAa,UAAU,GAAG;AACpD,iBAAO,QAAQ,aAAa,UAAU;AAAA,QACxC;AACA;AAAA,MACF;AAAA,MACA,KAAK,wBAAwB;AAE3B,YAAI,QAAQ,MAAM;AAChB,qBAAW;AAAA,QACb;AACA;AAAA,MACF;AAAA,MACA,KAAK;AAAA,MACL,SAAS;AAEP,eAAO;AAAA,MACT;AAAA,IACF;AACA,QAAI,UAAU;AACZ,gBAAU,QAAQ;AAClB,iBAAW;AAAA,IACb,WAAW,QAAQ,YAAY;AAC7B,gBAAU,QAAQ;AAAA,IACpB,OAAO;AACL;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAQO,IAAM,oBAAoB,UAAQ;AACvC,MAAI,CAAC,MAAM,UAAU;AACnB,UAAM,IAAI,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AAAA,EACxD;AACA,MAAI,KAAK,aAAa,cAAc;AAClC,WAAO;AAAA,EACT;AACA,MAAI,OAAO,KAAK,sBAAsB,WAAW;AAC/C,WAAO,KAAK;AAAA,EACd,WAAW,KAAK,cAAc,eAAe,MAAM;AACjD,WAAO;AAAA,EACT,OAAO;AACL,QAAI;AACJ,QAAI,KAAK,aAAa,iBAAiB,GAAG;AACxC,aAAO,KAAK,aAAa,iBAAiB;AAAA,IAC5C,OAAO;AACL,aAAO;AAAA,IACT;AACA,YAAQ,MAAM;AAAA,MACZ,KAAK;AAAA,MACL,KAAK,QAAQ;AACX,eAAO;AAAA,MACT;AAAA,MACA,KAAK,kBAAkB;AAIrB,eAAO;AAAA,MACT;AAAA,MACA,KAAK,SAAS;AACZ,eAAO;AAAA,MACT;AAAA,MACA,SAAS;AACP,YAAI,MAAM,YAAY,aAAa,cAAc;AAC/C,iBAAO,kBAAkB,KAAK,UAAU;AAAA,QAC1C;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;AAOO,IAAM,YAAY,UAAQ;AAC/B,MAAI,MAAM,aAAa,cAAc;AACnC,WAAO;AAAA,EACT;AACA,QAAM,SAAS,KAAK,cAAc;AAClC,QAAM,EAAE,SAAS,WAAW,IAAI,OAAO,iBAAiB,IAAI;AAC5D,MAAI,YAAY,UAAU,eAAe,WAAW;AAClD,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAOO,IAAM,iBAAiB,UAAQ;AACpC,MAAI,MAAM,aAAa,cAAc;AACnC,WAAO;AAAA,EACT;AACA,QAAM,EAAE,WAAW,KAAK,IAAI;AAC5B,UAAQ,WAAW;AAAA,IACjB,KAAK,SAAS;AACZ,UAAI,CAAC,QAAQ,gBAAgB,IAAI,IAAI,GAAG;AACtC,eAAO;AAAA,MACT;AACA,aAAO;AAAA,IACT;AAAA,IACA,KAAK,YAAY;AACf,aAAO;AAAA,IACT;AAAA,IACA,SAAS;AACP,aAAO,kBAAkB,IAAI;AAAA,IAC/B;AAAA,EACF;AACF;AAOO,IAAM,kBAAkB,UAAQ;AACrC,MAAI,MAAM,aAAa,cAAc;AACnC,WAAO;AAAA,EACT;AACA,MAAI,CAAC,KAAK,aAAa;AACrB,WAAO;AAAA,EACT;AACA,QAAM,SAAS,KAAK,cAAc;AAClC,MAAI,gBAAgB,OAAO,aAAa;AACtC,QAAI,OAAO,UAAU,SAAS,KAAK,aAAa,UAAU,CAAC,CAAC,GAAG;AAC7D,aAAO;AAAA,IACT;AACA,QAAI,kBAAkB,IAAI,GAAG;AAC3B,aAAO;AAAA,IACT;AACA,UAAM,EAAE,WAAW,WAAW,IAAI;AAClC,YAAQ,WAAW;AAAA,MACjB,KAAK,KAAK;AACR,YAAI,KAAK,QAAQ,KAAK,aAAa,MAAM,GAAG;AAC1C,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT;AAAA,MACA,KAAK,UAAU;AACb,eAAO;AAAA,MACT;AAAA,MACA,KAAK,SAAS;AACZ,YACE,KAAK,YACL,KAAK,aAAa,UAAU,KAC5B,KAAK,UACL,KAAK,aAAa,QAAQ,GAC1B;AACA,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT;AAAA,MACA,KAAK,WAAW;AACd,YAAI,WAAW,cAAc,WAAW;AACtC,cAAI,QAAQ,WAAW;AACvB,cAAI,OAAO;AACX,iBAAO,OAAO;AACZ,gBAAI,MAAM,cAAc,WAAW;AACjC,qBAAO,UAAU;AACjB;AAAA,YACF;AACA,oBAAQ,MAAM;AAAA,UAChB;AACA,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT;AAAA,MACA,SAAS;AACP,YACE,oBAAoB,IAAI,SAAS,KACjC,EAAE,KAAK,YAAY,KAAK,aAAa,UAAU,IAC/C;AACA,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAAA,EACF,WAAW,gBAAgB,OAAO,YAAY;AAC5C,QAAI,OAAO,UAAU,SAAS,KAAK,eAAe,MAAM,UAAU,CAAC,CAAC,GAAG;AACrE,YAAM,KAAK;AACX,UAAI;AACJ,UAAI,UAAU;AACd,aAAO,QAAQ,iBAAiB,IAAI;AAClC,eAAO,wBAAwB,IAAI,QAAQ,SAAS;AACpD,YAAI,MAAM;AACR;AAAA,QACF;AACA,YAAI,SAAS,YAAY,iBAAiB,IAAI;AAC5C,oBAAU,QAAQ;AAAA,QACpB,OAAO;AACL;AAAA,QACF;AAAA,MACF;AACA,UAAI,MAAM;AACR,eAAO;AAAA,MACT;AACA,aAAO;AAAA,IACT;AACA,QACE,KAAK,cAAc,QAClB,KAAK,QAAQ,KAAK,eAAe,MAAM,MAAM,IAC9C;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAqDO,IAAM,kBAAkB,CAAC,IAAI,SAAS;AAC3C,MAAI,OAAO,OAAO,UAAU;AAC1B,UAAM,IAAI,UAAU,mBAAmB,QAAQ,EAAE,CAAC,EAAE;AAAA,EACtD,WAAW,CAAC,MAAM,UAAU;AAC1B,UAAM,IAAI,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AAAA,EACxD;AACA,MAAI,CAAC,MAAM,KAAK,aAAa,cAAc;AACzC,WAAO;AAAA,EACT;AACA,QAAM,EAAE,WAAW,IAAI;AACvB,MAAI;AACJ,aAAW,QAAQ,YAAY;AAC7B,UAAM,EAAE,MAAM,cAAc,QAAQ,MAAM,IAAI;AAC9C,QAAI,SAAS,SAAS,EAAE,IAAI;AAC1B,YAAM;AAAA,IACR,WAAW,WAAW,IAAI;AACxB,YAAM;AAAA,IACR;AACA,QAAI,KAAK;AACP;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO;AAChB;AAQO,IAAM,sBAAsB,CAAC,KAAK,IAAI,OAAO,CAAC,MAAM;AACzD,MAAI,CAAC,MAAM,OAAO,OAAO,YAAY,MAAM,aAAa,cAAc;AACpE,WAAO;AAAA,EACT;AACA,MAAI,KAAK,mBAAmB,EAAE,GAAG;AAC/B,WAAO;AAAA,EACT;AACA,QAAM,OAAO,KAAK,cAAc;AAChC,MAAI,SAAS;AACb,MAAI;AACJ,SAAO,QAAQ;AACb,UAAM,gBAAgB,IAAI,MAAM;AAChC,QAAI,OAAO,WAAW,MAAM;AAC1B;AAAA,IACF;AACA,aAAS,OAAO;AAAA,EAClB;AACA,SAAO,CAAC,CAAC;AACX;AAQO,IAAM,cAAc,CAAC,OAAO,UAAU;AAC3C,MAAI,CAAC,OAAO,UAAU;AACpB,UAAM,IAAI,UAAU,mBAAmB,QAAQ,KAAK,CAAC,EAAE;AAAA,EACzD,WAAW,CAAC,OAAO,UAAU;AAC3B,UAAM,IAAI,UAAU,mBAAmB,QAAQ,KAAK,CAAC,EAAE;AAAA,EACzD;AACA,MAAI,MAAM,aAAa,gBAAgB,MAAM,aAAa,cAAc;AACtE,WAAO;AAAA,EACT;AACA,QAAM,SAAS,MAAM,wBAAwB,KAAK;AAClD,QAAM,MACJ,SAAS,+BAA+B,SAAS;AACnD,SAAO,CAAC,CAAC;AACX;AAQO,IAAM,eAAe,CAAC,GAAG,MAAM;AACpC,MAAI,YAAY,GAAG,CAAC,GAAG;AACrB,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAOO,IAAM,YAAY,CAAC,QAAQ,CAAC,MAAM;AACvC,QAAM,MAAM,CAAC,GAAG,KAAK;AACrB,MAAI,IAAI,SAAS,GAAG;AAClB,QAAI,KAAK,YAAY;AAAA,EACvB;AACA,SAAO;AACT;AAkGO,IAAM,aAAa,CAAC,QAAQ,aAAa;AAC9C,MAAI,CAAC,QAAQ,cAAc;AACzB,UAAM,IAAI,UAAU,4BAA4B,QAAQ,MAAM,CAAC,EAAE;AAAA,EACnE;AACA,MAAI,UAAU,aAAa,eAAe;AACxC,eAAW,OAAO;AAAA,EACpB;AACA,QAAM,SAAK,cAAAC,SAAO;AAAA,IAChB;AAAA,IACA,cAAc,OAAO;AAAA,EACvB,CAAC;AACD,KAAG,UAAU;AAAA,IACX,WAAW;AAAA,EACb,CAAC;AACD,SAAO;AACT;AAQO,IAAM,iBAAiB,CAAC,UAAU,WAAW;AAClD,QAAM,sBAAsB,WAAW,gBAAgB,WAAW;AAClE,MACE,CAAC,YACD,OAAO,aAAa,YACpB,iBAAiB,KAAK,QAAQ,GAC9B;AACA,WAAO;AAAA,EACT;AAEA,MAAI,SAAS,SAAS,GAAG,GAAG;AAC1B,UAAM,QAAQ,SAAS,YAAY,GAAG;AACtC,UAAM,MAAM,SAAS,UAAU,KAAK;AACpC,QAAI,IAAI,QAAQ,GAAG,IAAI,GAAG;AACxB,aAAO;AAAA,IACT;AAAA,EACF;AAWA,MAAI,SAAS,SAAS,GAAG,KAAK,kBAAkB,KAAK,QAAQ,GAAG;AAC9D,WAAO;AAAA,EACT;AAEA,MAAI,SAAS,SAAS,GAAG,GAAG;AAC1B,QAAI,UAAU;AACd,QAAI,WAAW,qBAAqB;AAClC,gBAAU,YAAY,KAAK,QAAQ;AAAA,IACrC;AACA,QACE,uBACA,YAAY,KAAK,QAAQ,KACzB,CAAC,YAAY,KAAK,QAAQ,GAC1B;AACA,aAAO;AAAA,IACT,WAAW,CAAC,uBAAuB,SAAS,KAAK,QAAQ,GAAG;AAC1D,UAAI,CAAC,WAAW,uBAAuB,KAAK,QAAQ,GAAG;AACrD,eAAO;AAAA,MACT;AACA,aAAO,iBAAiB,KAAK,QAAQ;AAAA,IACvC,WAAW,gBAAgB,KAAK,QAAQ,GAAG;AACzC,UAAI,SAAS;AACX,eAAO,CAAC,kBAAkB,KAAK,QAAQ;AAAA,MACzC,OAAO;AACL,eAAO,CAAC,mBAAmB,KAAK,QAAQ;AAAA,MAC1C;AAAA,IACF,OAAO;AACL,aAAO,CAAC,eAAe,KAAK,QAAQ;AAAA,IACtC;AAAA,EACF;AACA,SAAO;AACT;;;ADpqBA,sBAAyD;AAhZzD,IAAM,iBAAiB,oBAAI,IAAI;AAAA,EAC7B,CAAC,qBAAqB,MAAM;AAAA,EAC5B,CAAC,aAAa,MAAM;AAAA,EACpB,CAAC,gBAAgB,MAAM;AAAA,EACvB,CAAC,eAAe,MAAM;AAAA,EACtB,CAAC,eAAe,MAAM;AAAA,EACtB,CAAC,mBAAmB,MAAM;AAC5B,CAAC;AACD,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,mBAAmB,oBAAI,IAAI,CAAC,QAAQ,cAAc,CAAC;AACzD,IAAM,oBACJ;AACF,IAAM,wBAAwB;AAC9B,IAAM,SAAS;AAOR,IAAM,mBAAmB,CAAC,WAAW,OAAO;AACjD,MAAI,OAAO,aAAa,YAAY,SAAS,QAAQ,MAAM,CAAC,KAAK,GAAG;AAClE,UAAM,MAAM,SAAS,MAAM,IAAI;AAC/B,UAAM,gBAAgB,CAAC,IAAI,CAAC,CAAC;AAC7B,UAAM,IAAI,IAAI;AACd,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,YAAM,OAAO,IAAI,CAAC;AAClB,UAAI,SAAS,MAAM,MAAM,IAAI,GAAG;AAC9B,sBAAc,KAAK,MAAM;AAAA,MAC3B,OAAO;AACL,cAAM,YAAY,sBAAsB,KAAK,IAAI;AACjD,YAAI,WAAW;AACb,gBAAM,CAAC,EAAE,GAAG,IAAI;AAChB,cAAI;AACJ,cAAI;AACF,kBAAM,MAAM,SAAS,QAAQ,GAAG;AAChC,kBAAM,OAAO,SAAS,QAAQ,GAAG;AACjC,kBAAM,OAAO,SAAS,KAAK,GAAG;AAC9B,gBAAI,SAAS,KAAM,QAAQ,OAAO,QAAQ,MAAO;AAC/C,oBAAM;AAAA,YACR,OAAO;AACL,oBAAM,OAAO,cAAc,IAAI;AAAA,YACjC;AAAA,UACF,SAAS,GAAG;AACV,kBAAM;AAAA,UACR;AACA,cAAI,UAAU;AACd,cAAI,KAAK,SAAS,IAAI,QAAQ;AAC5B,sBAAU,KAAK,UAAU,IAAI,MAAM;AAAA,UACrC;AACA,wBAAc,KAAK,GAAG,GAAG,GAAG,OAAO,EAAE;AAAA,QAEvC,WAAW,YAAY,KAAK,IAAI,GAAG;AACjC,wBAAc,KAAK,KAAK,IAAI,EAAE;AAAA,QAChC,OAAO;AACL,wBAAc,KAAK,IAAI;AAAA,QACzB;AAAA,MACF;AAAA,IACF;AACA,WAAO,cAAc,KAAK,EAAE;AAAA,EAC9B;AACA,SAAO;AACT;AAQO,IAAM,aAAa,WAAS;AAEjC,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,UAAU,UAAa,UAAU,MAAM;AACzC,aAAO,QAAQ,KAAK,EAAE,YAAY;AAAA,IACpC,WAAW,MAAM,QAAQ,KAAK,GAAG;AAC/B,aAAO,MAAM,KAAK,GAAG;AAAA,IACvB,WAAW,OAAO,OAAO,OAAO,UAAU,GAAG;AAC3C,aAAO,MAAM,SAAS;AAAA,IACxB,OAAO;AACL,YAAM,IAAI,aAAa,oBAAoB,KAAK,IAAI,UAAU;AAAA,IAChE;AAAA,EACF;AACA,MAAI,WAAW;AACf,MAAI,QAAQ;AACZ,SAAO,SAAS,GAAG;AAEjB,YAAQ,SAAS,QAAQ,KAAK,KAAK;AACnC,QAAI,QAAQ,GAAG;AACb;AAAA,IACF;AACA,UAAM,UAAU,SAAS,UAAU,GAAG,QAAQ,CAAC;AAC/C,QAAI,WAAW,SAAS,UAAU,QAAQ,CAAC;AAC3C,UAAM,YAAY,SAAS,YAAY,CAAC;AACxC,QAAI,YAAY,UAAU;AACxB,YAAM,MAAM,KAAK,UAAU,SAAS,GAAG,CAAC;AACxC,UAAI,SAAS,WAAW,KAAK;AAC3B,mBAAW;AAAA,MACb,OAAO;AACL,mBAAW,GAAG,GAAG,GAAG,SAAS,UAAU,GAAG,CAAC;AAAA,MAC7C;AAAA,IACF;AACA,eAAW,GAAG,OAAO,GAAG,QAAQ;AAChC;AAAA,EACF;AACA,SAAO,SACJ,QAAQ,aAAa,IAAI,EACzB,QAAQ,0BAA0B,MAAM,EACxC,QAAQ,SAAS,QAAQ;AAC9B;AAOO,IAAM,gBAAgB,SAAO;AAClC,QAAM,WAAW,WAAW,GAAG;AAE/B,MAAI,iBAAiB,KAAK,QAAQ,GAAG;AACnC,UAAM,IAAI,aAAa,oBAAoB,QAAQ,IAAI,UAAU;AAAA,EACnE;AACA,MAAI;AACF,UAAM,MAAc,eAAM,UAAU;AAAA,MAClC,SAAS;AAAA,MACT,qBAAqB;AAAA,IACvB,CAAC;AACD,WAAe,uBAAc,GAAG;AAAA,EAClC,SAAS,GAAG;AACV,UAAM,EAAE,QAAQ,IAAI;AACpB,QACE,2DAA2D;AAAA,MACzD;AAAA,IACF,KACA,CAAC,SAAS,SAAS,GAAG,GACtB;AACA,YAAM,QAAQ,SAAS,YAAY,GAAG;AACtC,YAAM,UAAU,SAAS,UAAU,KAAK;AACxC,UAAI,QAAQ,SAAS,GAAG,GAAG;AACzB,cAAM,SAAS,QAAQ,MAAM,IAAI,EAAE;AACnC,YAAI,SAAS,GAAG;AACd,iBAAO,cAAc,GAAG,QAAQ,IAAI;AAAA,QACtC;AACA,eAAO,cAAc,GAAG,QAAQ,GAAG;AAAA,MACrC;AACA,aAAO,cAAc,GAAG,QAAQ,GAAG;AAAA,IACrC,WAAW,YAAY,mBAAmB;AAExC,UAAI,kBAAkB,KAAK,QAAQ,GAAG;AACpC,eAAO,cAAc,GAAG,SAAS,WAAW,mBAAmB,IAAI,CAAC,EAAE;AAAA,MACxE,WAAW,CAAC,SAAS,SAAS,GAAG,GAAG;AAClC,eAAO,cAAc,GAAG,QAAQ,GAAG;AAAA,MACrC,OAAO;AACL,cAAM,IAAI,aAAa,oBAAoB,QAAQ,IAAI,UAAU;AAAA,MACnE;AAAA,IACF,OAAO;AACL,YAAM,IAAI,aAAa,oBAAoB,QAAQ,IAAI,UAAU;AAAA,IACnE;AAAA,EACF;AACF;AAQO,IAAM,UAAU,CAAC,MAAM,CAAC,MAAM;AACnC,QAAM,WAAW,oBAAI,IAAI;AACzB,QAAM,OAAO;AAAA,IACX,uBAAuB;AAAA,IACvB,kBAAkB;AAAA,IAClB,sBAAsB;AAAA,IACtB,kBAAkB;AAAA,IAClB,uBAAuB;AAAA,IACvB,mBAAmB;AAAA,IACnB,qBAAqB;AAAA,EACvB;AACA,QAAM,MAAM;AAAA,IACV,MAAM,MAAM;AACV,cAAQ,KAAK,MAAM;AAAA,QACjB,KAAK,gBAAgB;AACnB,cAAI,QAAQ,KAAK,KAAK,IAAI,GAAG;AAC3B,kBAAM,IAAI;AAAA,cACR,qBAAqB,KAAK,IAAI;AAAA,cAC9B;AAAA,YACF;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK,aAAa;AAChB,cAAI,QAAQ,KAAK,KAAK,IAAI,GAAG;AAC3B,kBAAM,IAAI;AAAA,cACR,qBAAqB,KAAK,IAAI;AAAA,cAC9B;AAAA,YACF;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK,mBAAmB;AACtB,cAAI,aAAa,IAAI,KAAK,IAAI,GAAG;AAC/B,iBAAK,oBAAoB;AACzB,iBAAK,uBAAuB;AAC5B,gBAAI,KAAK,SAAS,OAAO;AACvB,mBAAK,mBAAmB;AAAA,YAC1B,WAAW,KAAK,SAAS,OAAO;AAC9B,mBAAK,mBAAmB;AAAA,YAC1B,OAAO;AACL,mBAAK,wBAAwB;AAAA,YAC/B;AAAA,UACF,WAAW,oBAAoB,IAAI,KAAK,IAAI,GAAG;AAC7C,iBAAK,sBAAsB;AAAA,UAC7B,WACE,iBAAiB,IAAI,KAAK,IAAI,KAC9B,MAAM,QAAQ,KAAK,QAAQ,KAC3B,KAAK,SAAS,QACd;AACA,iBAAK,oBAAoB;AAAA,UAC3B;AACA;AAAA,QACF;AAAA,QACA,KAAK,qBAAqB;AACxB,cAAI,sBAAsB,KAAK,KAAK,IAAI,GAAG;AACzC,iBAAK,oBAAoB;AAAA,UAC3B;AACA;AAAA,QACF;AAAA,QACA,KAAK,KAAK;AACR,cAAI,KAAK,UAAU;AACjB,iBAAK,oBAAoB;AACzB,iBAAK,wBAAwB;AAAA,UAC/B;AACA;AAAA,QACF;AAAA,QACA,KAAK,UAAU;AACb,mBAAS,IAAI,KAAK,QAAQ;AAC1B;AAAA,QACF;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,EAAQ,cAAK,KAAK,GAAG;AACrB,MAAI,KAAK,sBAAsB,MAAM;AACnC,IAAQ,iBAAQ,KAAK,CAAC,MAAM,MAAM,SAAS;AACzC,UAAI,MAAM;AACR,YAAI,KAAK,SAAS,qBAAqB,aAAa,IAAI,KAAK,IAAI,GAAG;AAClE,gBAAM,WAAW,KAAK,OAAO,OAAK;AAChC,kBAAM,EAAE,MAAM,KAAK,IAAI;AACvB,mBAAO,SAAS,qBAAqB,aAAa,IAAI,IAAI;AAAA,UAC5D,CAAC;AACD,qBAAW,EAAE,SAAS,KAAK,UAAU;AAEnC,uBAAW,EAAE,UAAU,cAAc,KAAK,UAAU;AAElD,yBAAW,EAAE,UAAU,mBAAmB,KAAK,eAAe;AAC5D,oBAAI,SAAS,IAAI,kBAAkB,GAAG;AACpC,2BAAS,OAAO,kBAAkB;AAAA,gBACpC;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,QACF,WACE,KAAK,SAAS,qBACd,iBAAiB,IAAI,KAAK,IAAI,KAC9B,MAAM,QAAQ,KAAK,QAAQ,KAC3B,KAAK,SAAS,QACd;AACA,gBAAM,WAAW,KAAK,OAAO,OAAK;AAChC,kBAAM,EAAE,UAAU,MAAM,KAAK,IAAI;AACjC,kBAAM,MACJ,SAAS,qBACT,iBAAiB,IAAI,IAAI,KACzB,MAAM,QAAQ,QAAQ,KACtB,SAAS;AACX,mBAAO;AAAA,UACT,CAAC;AACD,qBAAW,EAAE,SAAS,KAAK,UAAU;AAEnC,uBAAW,EAAE,UAAU,cAAc,KAAK,UAAU;AAClD,kBAAI,SAAS,IAAI,aAAa,GAAG;AAC/B,yBAAS,OAAO,aAAa;AAAA,cAC/B;AAAA,YACF;AAAA,UACF;AAAA,QACF,WACE,KAAK,SAAS,uBACd,sBAAsB,KAAK,KAAK,IAAI,GACpC;AACA,gBAAM,WAAW,KAAK,OAAO,OAAK;AAChC,kBAAM,EAAE,MAAM,KAAK,IAAI;AACvB,kBAAM,MACJ,SAAS,uBAAuB,sBAAsB,KAAK,IAAI;AACjE,mBAAO;AAAA,UACT,CAAC;AACD,qBAAW,EAAE,SAAS,KAAK,UAAU;AAEnC,uBAAW,EAAE,UAAU,cAAc,KAAK,UAAU;AAClD,kBAAI,SAAS,IAAI,aAAa,GAAG;AAC/B,yBAAS,OAAO,aAAa;AAAA,cAC/B;AAAA,YACF;AAAA,UACF;AAAA,QACF,WAAW,KAAK,SAAS,OAAO,KAAK,UAAU;AAC7C,gBAAM,WAAW,KAAK,OAAO,OAAK;AAChC,kBAAM,EAAE,UAAU,KAAK,IAAI;AAC3B,kBAAM,MAAM,SAAS,OAAO;AAC5B,mBAAO;AAAA,UACT,CAAC;AACD,qBAAW,EAAE,SAAS,KAAK,UAAU;AACnC,kBAAM,EAAE,SAAS,IAAI;AAErB,uBAAW,EAAE,UAAU,cAAc,KAAK,UAAU;AAClD,kBAAI,SAAS,IAAI,aAAa,GAAG;AAC/B,yBAAS,OAAO,aAAa;AAAA,cAC/B;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO;AAAA,IACL;AAAA,IACA,UAAU,CAAC,GAAG,QAAQ;AAAA,EACxB;AACF;AAQO,IAAM,kBAAkB,CAAC,GAAG,MAAM;AACvC,QAAM,OAAO,eAAe,IAAI,EAAE,IAAI;AACtC,QAAM,OAAO,eAAe,IAAI,EAAE,IAAI;AACtC,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT,WAAW,OAAO,MAAM;AACtB,WAAO;AAAA,EACT,OAAO;AACL,WAAO;AAAA,EACT;AACF;AAOO,IAAM,UAAU,UAAQ;AAC7B,QAAM,MAAM,CAAC,GAAG,IAAI;AACpB,MAAI,IAAI,SAAS,GAAG;AAClB,QAAI,KAAK,eAAe;AAAA,EAC1B;AACA,SAAO;AACT;AAQO,IAAM,eAAe,cAAY;AACtC,MAAI;AACJ,MAAI;AACJ,MAAI,YAAY,OAAO,aAAa,UAAU;AAC5C,QAAI,SAAS,QAAQ,GAAG,IAAI,IAAI;AAC9B,OAAC,QAAQ,SAAS,IAAI,SAAS,MAAM,GAAG;AAAA,IAC1C,OAAO;AACL,eAAS;AACT,kBAAY;AAAA,IACd;AAAA,EACF,OAAO;AACL,UAAM,IAAI,aAAa,oBAAoB,QAAQ,IAAI,UAAU;AAAA,EACnE;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;;;AG/YA,IAAM,wBAAwB,oBAAI,IAAI;AAAA,EACpC,GAAG;AAAA,EACH;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAMC,mBAAkB,IAAI,IAAI,UAAU;AAC1C,IAAM,iBAAiB,IAAI,OAAO,aAAa,SAAS,GAAG,SAAS,KAAK,GAAG;AAC5E,IAAM,eAAe;AAYd,IAAM,6BAA6B,CAAC,SAAS,SAAS,MAAM,CAAC,MAAM;AACxE,QAAM,EAAE,SAAS,cAAc,KAAK,IAAI;AACxC,MAAI,YAAY,qBAAqB;AAEnC,UAAM,IAAI,UAAU,uBAAuB,QAAQ,OAAO,CAAC,EAAE;AAAA,EAC/D;AACA,UAAQ,SAAS;AAAA,IACf,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK,eAAe;AAElB,UAAI,MAAM;AACR,cAAM;AAAA,UACJ,gCAAgC,OAAO;AAAA,UACvC;AAAA,UACA;AAAA,QACF;AAAA,MACF;AACA;AAAA,IACF;AAAA,IACA,KAAK;AAAA,IACL,KAAK,WAAW;AAEd,UAAI,MAAM;AACR,cAAM;AAAA,UACJ,gCAAgC,OAAO;AAAA,UACvC;AAAA,UACA;AAAA,QACF;AAAA,MACF;AACA;AAAA,IACF;AAAA,IACA,SAAS;AAEP,UAAI,QAAQ,WAAW,UAAU,GAAG;AAClC,YAAI,MAAM;AACR,gBAAM;AAAA,YACJ,gCAAgC,OAAO;AAAA,YACvC;AAAA,YACA;AAAA,UACF;AAAA,QACF;AAAA,MAEF,WAAW,CAAC,SAAS;AACnB,cAAM;AAAA,UACJ,4BAA4B,OAAO;AAAA,UACnC;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AASO,IAAM,4BAA4B,CAAC,KAAK,SAAS;AACtD,QAAM,EAAE,KAAK,IAAI;AAEjB,MAAI,CAAC,MAAM;AACT,UAAM,OAAO,SAAS,KAAK,mBAAmB,QAAQ,IAAI;AAC1D,UAAM,IAAI,UAAU,uBAAuB,IAAI,EAAE;AAAA,EACnD;AAEA,QAAM,MAAM,kBAAkB,IAAI;AAElC,SAAO,SAAS;AAClB;AASO,IAAM,2BAA2B,CAAC,KAAK,SAAS;AACrD,QAAM,EAAE,MAAM,MAAM,MAAM,IAAI;AAC9B,MAAI;AAEJ,MAAI,SAAS,UAAU,OAAO;AAC5B,kBAAc;AAAA,EAChB,WAAW,SAAS,SAAS,MAAM;AACjC,kBAAc,iBAAiB,IAAI;AAAA,EACrC;AAEA,MAAI,OAAO,gBAAgB,UAAU;AACnC,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,qBAAqB,IAAI;AAE7C,MAAI,gBAAgB,MAAM;AACxB,WAAO;AAAA,EACT;AAEA,MAAI,gBAAgB,KAAK;AAEvB,WAAO,gBAAgB;AAAA,EACzB;AAEA,MAAI,CAAC,eAAe,KAAK,WAAW,GAAG;AACrC,WAAO;AAAA,EACT;AAEA,MAAI;AACJ,MAAI,YAAY,QAAQ,GAAG,IAAI,IAAI;AAEjC,UAAM,CAAC,UAAU,SAAS,GAAG,QAAQ,IAAI,YAAY,MAAM,GAAG;AAC9D,UAAM,eACJ,aAAa,MAAM,GAAG,SAAS,GAAG,SAAS,KAAK,GAAG,QAAQ,GAAG,SAAS;AACzE,UAAM,cAAc,IAAI,OAAO,GAAG,SAAS;AAC3C,QAAI,eAAe;AAEnB,aAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,sBAAgB,IAAI,SAAS,CAAC,CAAC,GAAG,SAAS;AAAA,IAC7C;AACA,mBAAe,IAAI;AAAA,MACjB,IAAI,YAAY,GAAG,WAAW,GAAG,YAAY;AAAA,MAC7C;AAAA,IACF;AAAA,EACF,OAAO;AAEL,mBAAe,IAAI,OAAO,IAAI,WAAW,GAAG,SAAS,KAAK,GAAG;AAAA,EAC/D;AAEA,SAAO,aAAa,KAAK,WAAW;AACtC;AAQO,IAAM,2BAA2B,CAAC,SAAS,SAAS;AACzD,QAAM,EAAE,WAAW,WAAW,IAAI;AAClC,MACE,CAAC,sBAAsB,IAAI,SAAS,KACpC,CAAC,gBAAgB,MAAM,EAAE,gBAAgB,KAAK,CAAC,GAC/C;AACA,WAAO;AAAA,EACT;AACA,MAAI,aAAa;AACjB,MAAI,KAAK,YAAY,KAAK,aAAa,UAAU,GAAG;AAClD,iBAAa;AAAA,EACf,WAAW,cAAc,UAAU;AACjC,QACE,cACA,WAAW,cAAc,eACxB,WAAW,YAAY,WAAW,aAAa,UAAU,IAC1D;AACA,mBAAa;AAAA,IACf;AAAA,EACF,WAAW,cAAc,YAAY;AACnC,QAAI,UAAU;AACd,WAAO,SAAS;AACd,UACE,QAAQ,cAAc,eACrB,QAAQ,YAAY,QAAQ,aAAa,UAAU,IACpD;AAEA,YAAI;AACJ,YAAI,UAAU,QAAQ;AACtB,eAAO,SAAS;AACd,cAAI,QAAQ,cAAc,UAAU;AAClC,qBAAS;AACT;AAAA,UACF;AACA,oBAAU,QAAQ;AAAA,QACpB;AACA,YAAI,CAAC,UAAU,CAAC,OAAO,SAAS,IAAI,GAAG;AACrC,uBAAa;AAAA,QACf;AAEA;AAAA,MACF;AACA,gBAAU,QAAQ;AAAA,IACpB;AAAA,EACF;AACA,MAAI,YAAY,YAAY;AAC1B,WAAO;AAAA,EACT;AACA,SAAO,CAAC;AACV;AAQO,IAAM,2BAA2B,CAAC,SAAS,SAAS;AACzD,QAAM,EAAE,UAAU,IAAI;AACtB,MAAI,aAAa;AACjB,UAAQ,WAAW;AAAA,IACjB,KAAK;AAAA,IACL,KAAK,SAAS;AACZ,YAAM,kBAAkB,CAAC,KAAK,QAAQA,iBAAgB,IAAI,KAAK,IAAI;AACnE,UAAI,cAAc,cAAc,iBAAiB;AAC/C,qBACE,KAAK,YACL,KAAK,aAAa,UAAU,KAC5B,KAAK,YACL,KAAK,aAAa,UAAU;AAAA,MAChC,OAAO;AAEL,qBAAa;AAAA,MACf;AACA;AAAA,IACF;AAAA,IACA,SAAS;AACP,mBAAa,CAAC,kBAAkB,IAAI;AAAA,IACtC;AAAA,EACF;AACA,MAAI,YAAY,aAAa;AAC3B,WAAO;AAAA,EACT;AACA,SAAO,CAAC;AACV;AAaO,IAAM,yBAAyB,CAAC,KAAK,MAAM,MAAM,CAAC,MAAM;AAC7D,QAAM;AAAA,IACJ,OAAO;AAAA,IACP,SAAS;AAAA,IACT,MAAM;AAAA,IACN,OAAO;AAAA,EACT,IAAI;AACJ,QAAM,EAAE,OAAO,SAAS,aAAa,IAAI;AAEzC,MAAI,OAAO,aAAa,YAAY,CAAC,UAAU,KAAK,QAAQ,KAAK,CAAC,SAAS;AACzE,UAAM,UAAM,0BAAY,GAAG;AAC3B,UAAM;AAAA,MACJ,oBAAoB,GAAG;AAAA,MACvB;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,QAAM,EAAE,WAAW,IAAI;AAEvB,MAAI,CAAC,cAAc,CAAC,WAAW,QAAQ;AACrC,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,KAAK,cAAc;AACvC,MAAI;AACJ,MAAI,gBAAgB,aAAa;AAC/B,QAAI,OAAO,aAAa,YAAY,OAAO,KAAK,QAAQ,GAAG;AACzD,wBAAkB;AAAA,IACpB,OAAO;AACL,wBAAkB;AAAA,IACpB;AAAA,EACF,WAAW,OAAO,aAAa,YAAY,OAAO,KAAK,QAAQ,GAAG;AAChE,sBAAkB;AAAA,EACpB,OAAO;AACL,sBAAkB;AAAA,EACpB;AAEA,MAAI,cAAc,iBAAiB,QAAQ,IAAI;AAC/C,MAAI,iBAAiB;AACnB,kBAAc,YAAY,YAAY;AAAA,EACxC;AAEA,QAAM,aAAa,oBAAI,IAAI;AAE3B,MAAI,YAAY,QAAQ,GAAG,IAAI,IAAI;AACjC,UAAM,EAAE,QAAQ,WAAW,WAAW,aAAa,IACjD,aAAa,WAAW;AAC1B,eAAW,QAAQ,YAAY;AAC7B,UAAI,EAAE,MAAM,UAAU,OAAO,UAAU,IAAI;AAC3C,UAAI,iBAAiB;AACnB,mBAAW,SAAS,YAAY;AAChC,oBAAY,UAAU,YAAY;AAAA,MACpC;AACA,cAAQ,WAAW;AAAA,QACjB,KAAK,IAAI;AACP,cAAI,iBAAiB,UAAU;AAC7B,uBAAW,IAAI,SAAS;AAAA,UAC1B;AACA;AAAA,QACF;AAAA,QACA,KAAK,KAAK;AACR,cAAI,SAAS,QAAQ,GAAG,IAAI,IAAI;AAC9B,kBAAM,CAAC,EAAE,GAAG,YAAY,IAAI,SAAS,MAAM,GAAG;AAC9C,kBAAM,gBAAgB,aAAa,KAAK,GAAG,EAAE,QAAQ,MAAM,EAAE;AAC7D,gBAAI,kBAAkB,cAAc;AAClC,yBAAW,IAAI,SAAS;AAAA,YAC1B;AAAA,UACF,WAAW,iBAAiB,UAAU;AACpC,uBAAW,IAAI,SAAS;AAAA,UAC1B;AACA;AAAA,QACF;AAAA,QACA,SAAS;AACP,cAAI,CAAC,OAAO;AACV,gBAAI,SAAS;AACX,qBAAO;AAAA,YACT;AACA,kBAAM,UAAM,0BAAY,GAAG;AAC3B,kBAAM;AAAA,cACJ,oBAAoB,GAAG;AAAA,cACvB;AAAA,cACA;AAAA,YACF;AAAA,UACF;AACA,cAAI,SAAS,QAAQ,GAAG,IAAI,IAAI;AAC9B,kBAAM,CAAC,YAAY,GAAG,YAAY,IAAI,SAAS,MAAM,GAAG;AACxD,kBAAM,gBAAgB,aAAa,KAAK,GAAG,EAAE,QAAQ,MAAM,EAAE;AAE7D,gBAAI,eAAe,SAAS,kBAAkB,QAAQ;AACpD;AAAA,YACF,WACE,cAAc,cACd,iBAAiB,eACjB;AACA,oBAAM,oBAAoB,oBAAoB,WAAW,IAAI;AAC7D,kBAAI,mBAAmB;AACrB,2BAAW,IAAI,SAAS;AAAA,cAC1B;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EAEF,OAAO;AACL,aAAS,EAAE,MAAM,UAAU,OAAO,UAAU,KAAK,YAAY;AAC3D,UAAI,iBAAiB;AACnB,mBAAW,SAAS,YAAY;AAChC,oBAAY,UAAU,YAAY;AAAA,MACpC;AACA,UAAI,SAAS,QAAQ,GAAG,IAAI,IAAI;AAC9B,cAAM,CAAC,YAAY,GAAG,YAAY,IAAI,SAAS,MAAM,GAAG;AACxD,cAAM,gBAAgB,aAAa,KAAK,GAAG,EAAE,QAAQ,MAAM,EAAE;AAE7D,YAAI,CAAC,cAAc,gBAAgB,IAAI,aAAa,IAAI;AACtD,qBAAW,IAAI,SAAS;AAAA,QAE1B,WAAW,eAAe,SAAS,kBAAkB,QAAQ;AAC3D;AAAA,QACF,WAAW,gBAAgB,eAAe;AACxC,qBAAW,IAAI,SAAS;AAAA,QAC1B;AAAA,MACF,WAAW,gBAAgB,UAAU;AACnC,mBAAW,IAAI,SAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACA,MAAI,CAAC,WAAW,MAAM;AACpB,WAAO;AAAA,EACT;AAEA,QAAM,EAAE,MAAM,eAAe,OAAO,eAAe,IAAI,YAAY,CAAC;AACpE,MAAI;AACJ,MAAI,eAAe;AACjB,QAAI,iBAAiB;AACnB,kBAAY,cAAc,YAAY;AAAA,IACxC,OAAO;AACL,kBAAY;AAAA,IACd;AAAA,EACF,WAAW,gBAAgB;AACzB,QAAI,iBAAiB;AACnB,kBAAY,eAAe,YAAY;AAAA,IACzC,OAAO;AACL,kBAAY;AAAA,IACd;AAAA,EACF,WAAW,mBAAmB,IAAI;AAChC,gBAAY;AAAA,EACd;AAEA,UAAQ,YAAY;AAAA,IAClB,KAAK,KAAK;AACR,aAAO,OAAO,cAAc,YAAY,WAAW,IAAI,SAAS;AAAA,IAClE;AAAA,IACA,KAAK,MAAM;AACT,UAAI,aAAa,OAAO,cAAc,UAAU;AAC9C,mBAAW,SAAS,YAAY;AAC9B,gBAAM,OAAO,IAAI,IAAI,MAAM,MAAM,KAAK,CAAC;AACvC,cAAI,KAAK,IAAI,SAAS,GAAG;AACvB,mBAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,KAAK,MAAM;AACT,UAAI,aAAa,OAAO,cAAc,UAAU;AAC9C,mBAAW,SAAS,YAAY;AAC9B,cAAI,UAAU,aAAa,MAAM,WAAW,GAAG,SAAS,GAAG,GAAG;AAC5D,mBAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,KAAK,MAAM;AACT,UAAI,aAAa,OAAO,cAAc,UAAU;AAC9C,mBAAW,SAAS,YAAY;AAC9B,cAAI,MAAM,WAAW,GAAG,SAAS,EAAE,GAAG;AACpC,mBAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,KAAK,MAAM;AACT,UAAI,aAAa,OAAO,cAAc,UAAU;AAC9C,mBAAW,SAAS,YAAY;AAC9B,cAAI,MAAM,SAAS,GAAG,SAAS,EAAE,GAAG;AAClC,mBAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,KAAK,MAAM;AACT,UAAI,aAAa,OAAO,cAAc,UAAU;AAC9C,mBAAW,SAAS,YAAY;AAC9B,cAAI,MAAM,SAAS,GAAG,SAAS,EAAE,GAAG;AAClC,mBAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,KAAK;AAAA,IACL,SAAS;AAEP,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAWO,IAAM,oBAAoB,CAAC,KAAK,MAAM,MAAM,CAAC,MAAM;AACxD,QAAM,UAAU,iBAAiB,IAAI,IAAI;AACzC,QAAM,EAAE,WAAW,cAAc,OAAO,IAAI;AAC5C,QAAM,EAAE,OAAO,SAAS,aAAa,IAAI;AACzC,MAAI,EAAE,QAAQ,WAAW,WAAW,aAAa,IAAI;AAAA,IACnD;AAAA,IACA;AAAA,EACF;AACA,MACE,KAAK,cAAc,gBAAgB,gBAClC,CAAC,gBAAgB,iBAAiB,mCACnC,aAAa,KAAK,SAAS,GAC3B;AACA,gBAAY,UAAU,YAAY;AAClC,mBAAe,aAAa,YAAY;AAAA,EAC1C;AACA,MAAI;AACJ,MAAI;AAEJ,MAAI,UAAU,QAAQ,GAAG,IAAI,IAAI;AAC/B,KAAC,YAAY,aAAa,IAAI,UAAU,MAAM,GAAG;AAAA,EACnD,OAAO;AACL,iBAAa,UAAU;AACvB,oBAAgB;AAAA,EAClB;AACA,UAAQ,WAAW;AAAA,IACjB,KAAK,IAAI;AACP,UACE,CAAC,cACD,CAAC,iBACA,iBAAiB,OAAO,iBAAiB,gBAC1C;AACA,eAAO;AAAA,MACT;AACA,aAAO;AAAA,IACT;AAAA,IACA,KAAK,KAAK;AACR,UAAI,iBAAiB,OAAO,iBAAiB,eAAe;AAC1D,eAAO;AAAA,MACT;AACA,aAAO;AAAA,IACT;AAAA,IACA,SAAS;AACP,UAAI,CAAC,OAAO;AACV,YAAI,SAAS;AACX,iBAAO;AAAA,QACT;AACA,cAAM,UAAM,0BAAY,GAAG;AAC3B,cAAM;AAAA,UACJ,oBAAoB,GAAG;AAAA,UACvB;AAAA,UACA;AAAA,QACF;AAAA,MACF;AACA,YAAM,QAAQ,KAAK,mBAAmB,SAAS;AAC/C,YAAM,SAAS,KAAK,mBAAmB,UAAU;AACjD,UAAI,UAAU,UAAU,cAAc,YAAY;AAChD,YAAI,iBAAiB,OAAO,iBAAiB,eAAe;AAC1D,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT,WAAW,CAAC,WAAW,CAAC,OAAO;AAC7B,cAAM;AAAA,UACJ,wBAAwB,SAAS;AAAA,UACjC;AAAA,UACA;AAAA,QACF;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;;;AC5gBA,IAAM,WAAW;AACjB,IAAM,WAAW;AACjB,IAAM,YAAY,oBAAI,IAAI,CAAC,GAAG,YAAY,YAAY,MAAM,CAAC;AAC7D,IAAM,qBAAqB,oBAAI,IAAI,CAAC,GAAG,YAAY,MAAM,CAAC;AAC1D,IAAM,mBAAmB,IAAI,IAAI,WAAW;AAC5C,IAAM,yBAAyB,oBAAI,IAAI,CAAC,GAAG,YAAY,QAAQ,CAAC;AAChE,IAAM,mBAAmB,oBAAI,IAAI,CAAC,GAAG,YAAY,UAAU,OAAO,CAAC;AACnE,IAAM,sBAAsB,oBAAI,IAAI,CAAC,GAAG,aAAa,GAAG,YAAY,MAAM,CAAC;AAC3E,IAAM,mBAAmB,oBAAI,IAAI,CAAC,UAAU,OAAO,CAAC;AACpD,IAAM,oBAAoB,oBAAI,IAAI,CAAC,SAAS,QAAQ,CAAC;AACrD,IAAM,gBAAgB,oBAAI,IAAI;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,kBAAkB,oBAAI,IAAI;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAMM,IAAM,SAAN,MAAa;AAAA;AAAA,EAElB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAY,QAAQ;AAClB,SAAK,UAAU;AACf,SAAK,YAAY,oBAAI,QAAQ;AAC7B,SAAK,iBAAiB,oBAAI,QAAQ;AAClC,SAAK,SAAS;AACd,SAAK,SAAS;AACd,SAAK,oBAAoB;AACzB,SAAK,iBAAiB,oBAAI,IAAI;AAAA,MAC5B;AAAA,QACE,MAAM,CAAC,SAAS,SAAS;AAAA,QACzB,SAAS,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,QACE,MAAM,CAAC,WAAW,OAAO;AAAA,QACzB,SAAS,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,QACE,MAAM,CAAC,aAAa,aAAa,WAAW,SAAS,UAAU;AAAA,QAC/D,SAAS,KAAK;AAAA,MAChB;AAAA,IACF,CAAC;AACD,SAAK,wBAAwB;AAC7B,SAAK,aAAa,IAAI;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,UAAU,CAAC,GAAG,MAAM,CAAC,MAAM;AACzB,UAAM,WAAW,IAAI,YAAY,KAAK;AACtC,QAAI,UAAU;AACZ;AAAA,IACF;AACA,UAAM,iBACJ,aAAa,gBAAgB,aAAa,KAAK,QAAQ;AACzD,QAAI,gBAAgB;AAClB,UAAI,EAAE,SAAS,mBAAmB;AAChC,YAAI,KAAK,OAAO;AACd,kBAAQ,KAAK,EAAE,OAAO;AAAA,QACxB;AACA;AAAA,MACF;AACA,YAAM,IAAI,KAAK,QAAQ,aAAa,EAAE,SAAS,EAAE,IAAI;AAAA,IACvD;AACA,QAAI,EAAE,QAAQ,KAAK,SAAS;AAC1B,YAAM,IAAI,KAAK,QAAQ,EAAE,IAAI,EAAE,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC;AAAA,IACxD;AACA,UAAM;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,QAAQ,CAAC,UAAU,MAAM,MAAM,CAAC,MAAM;AACpC,UAAM,EAAE,OAAO,UAAU,KAAK,IAAI;AAClC,SAAK,SAAS,CAAC,CAAC;AAChB,SAAK,YAAY,CAAC,CAAC;AACnB,SAAK,QAAQ,CAAC,CAAC;AACf,KAAC,KAAK,WAAW,KAAK,OAAO,KAAK,OAAO,IAAI,eAAe,IAAI;AAChE,SAAK,eAAe;AACpB,SAAK,QAAQ;AACb,SAAK,UACH,KAAK,UAAU,KAAK,SAAS,KAAK,MAAM,aAAa;AACvD,SAAK,YAAY;AACjB,KAAC,KAAK,MAAM,KAAK,MAAM,IAAI,KAAK,YAAY,QAAQ;AACpD,SAAK,iBAAiB,CAAC;AACvB,SAAK,WAAW,oBAAI,QAAQ;AAC5B,SAAK,cAAc;AACnB,SAAK,cAAc;AACnB,SAAK,oBAAoB;AACzB,SAAK,aAAa;AAClB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,eAAe,CAAC,MAAM,UAAU;AAC9B,SAAK,qBAAqB,oBAAI,QAAQ;AACtC,QAAI,KAAK;AACP,WAAK,WAAW,oBAAI,QAAQ;AAAA,IAC9B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,oBAAoB,SAAO;AACzB,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,uBAAuB,SAAO;AAC5B,UAAM,EAAE,IAAI,IAAI;AAChB,QAAI,CAAC,cAAc,IAAI,GAAG,GAAG;AAC3B,WAAK,SAAS;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,oBAAoB,SAAO;AACzB,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,0BAA0B,MAAM;AAC9B,UAAM,MAAM;AAAA,MACV,SAAS;AAAA,MACT,SAAS;AAAA,IACX;AACA,UAAM,OAAO,CAAC;AACd,eAAW,gBAAgB,KAAK,gBAAgB;AAC9C,YAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,YAAM,IAAI,KAAK;AACf,eAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,cAAM,MAAM,KAAK,CAAC;AAClB,aAAK,KAAK,KAAK,QAAQ,iBAAiB,KAAK,SAAS,GAAG,CAAC;AAAA,MAC5D;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,2BAA2B,CAAC,UAAU,aAAa;AACjD,QAAI,aAAa;AACjB,UAAM,MAAM,CAAC;AACb,UAAM,IAAI,SAAS;AACnB,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,YAAM,QAAQ,CAAC,GAAG,SAAS,CAAC,CAAC;AAC7B,YAAM,SAAS,CAAC;AAChB,UAAI,OAAO,MAAM,MAAM;AACvB,UAAI,QAAQ,KAAK,SAAS,YAAY;AACpC,cAAM,SAAS,oBAAI,IAAI;AACvB,eAAO,MAAM;AACX,cAAI,KAAK,SAAS,YAAY;AAC5B,kBAAM,CAAC,QAAQ,IAAI;AACnB,gBAAI,CAAC,YAAY,SAAS,SAAS,YAAY;AAC7C,oBAAM,MAAM,oBAAoB,QAAQ;AACxC,mBAAK,QAAQ,kBAAkB,KAAK,YAAY,KAAK,OAAO,CAAC;AAE7D,qBAAO,EAAE,KAAK,CAAC,GAAG,YAAY,OAAO,YAAY,MAAM;AAAA,YACzD;AACA,gBAAI,KAAK,SAAS,OAAO,KAAK,SAAS,KAAK;AAC1C,2BAAa;AAAA,YACf;AACA,mBAAO,KAAK,EAAE,OAAO,MAAM,QAAQ,QAAQ,MAAM,EAAE,CAAC;AACpD,mBAAO,MAAM;AAAA,UACf,OAAO;AACL,gBAAI,KAAK,QAAQ,OAAO,KAAK,SAAS,UAAU;AAC9C,oBAAM,gBAAgB,iBAAiB,KAAK,IAAI;AAChD,kBAAI,kBAAkB,KAAK,MAAM;AAC/B,qBAAK,OAAO;AAAA,cACd;AACA,kBAAI,OAAO,KAAK,aAAa,GAAG;AAC9B,qBAAK,YAAY;AAAA,cACnB;AAAA,YACF;AACA,mBAAO,IAAI,IAAI;AAAA,UACjB;AACA,cAAI,MAAM,QAAQ;AAChB,mBAAO,MAAM,MAAM;AAAA,UACrB,OAAO;AACL,mBAAO,KAAK,EAAE,OAAO,MAAM,QAAQ,QAAQ,MAAM,EAAE,CAAC;AACpD,mBAAO,MAAM;AACb;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACA,UAAI,KAAK,EAAE,QAAQ,KAAK,MAAM,UAAU,OAAO,MAAM,MAAM,CAAC;AAAA,IAC9D;AACA,WAAO,EAAE,KAAK,WAAW;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,cAAc,cAAY;AACxB,UAAM,QAAQ,CAAC;AACf,SAAK,cAAc;AACnB,SAAK,cAAc;AACnB,QAAI;AACJ,QAAI,KAAK,eAAe,IAAI,KAAK,SAAS,GAAG;AAC3C,YAAM,aAAa,KAAK,eAAe,IAAI,KAAK,SAAS;AACzD,UAAI,cAAc,WAAW,IAAI,GAAG,QAAQ,EAAE,GAAG;AAC/C,cAAM,OAAO,WAAW,IAAI,GAAG,QAAQ,EAAE;AACzC,cAAM,KAAK;AACX,aAAK,cAAc,KAAK;AACxB,aAAK,cAAc,KAAK;AAAA,MAC1B;AAAA,IACF;AACA,QAAI,KAAK;AACP,YAAM,IAAI,IAAI;AACd,eAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,YAAI,CAAC,EAAE,MAAM;AACb,YAAI,CAAC,EAAE,WAAW;AAClB,YAAI,CAAC,EAAE,OAAO;AACd,cAAM,CAAC,IAAI,CAAC;AAAA,MACd;AAAA,IACF,OAAO;AACL,UAAI;AACJ,UAAI;AACF,iBAAS,cAAc,QAAQ;AAAA,MACjC,SAAS,GAAG;AACV,eAAO,KAAK,QAAQ,CAAC;AAAA,MACvB;AACA,YAAM,EAAE,UAAU,KAAK,IAAI,QAAQ,MAAM;AACzC,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,IAAI;AACJ,WAAK,cACH,oBACA,uBACA,CAAC,EAAE,wBAAwB;AAC7B,YAAM,YAAY,KAAK,yBAAyB,UAAU,QAAQ;AAClE,YAAM,UAAU;AAChB,WAAK,cAAc,UAAU;AAC7B,UAAI;AACJ,UAAI,KAAK,eAAe,IAAI,KAAK,SAAS,GAAG;AAC3C,qBAAa,KAAK,eAAe,IAAI,KAAK,SAAS;AAAA,MACrD,OAAO;AACL,qBAAa,oBAAI,IAAI;AAAA,MACvB;AACA,iBAAW,IAAI,GAAG,QAAQ,IAAI;AAAA,QAC5B;AAAA,QACA,YAAY,KAAK;AAAA,QACjB,YAAY,KAAK;AAAA,MACnB,CAAC;AACD,WAAK,eAAe,IAAI,KAAK,WAAW,UAAU;AAElD,eAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,cAAM,CAAC,IAAI,CAAC;AAAA,MACd;AAAA,IACF;AACA,WAAO,CAAC,KAAK,KAAK;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,oBAAoB,CAAC,MAAM,MAAM,CAAC,MAAM;AACtC,UAAM,EAAE,QAAQ,OAAO,aAAa,eAAe,IAAI;AACvD,QAAI,OAAO;AACT,aAAO,KAAK,UAAU,iBAAiB,MAAM,UAAU;AAAA,IACzD,WAAW,KAAK,SAAS,IAAI,IAAI,GAAG;AAClC,aAAO,KAAK,SAAS,IAAI,IAAI;AAAA,IAC/B;AACA,UAAM,SAAS,KAAK,UAAU,iBAAiB,MAAM,UAAU;AAC/D,SAAK,SAAS,IAAI,MAAM,MAAM;AAC9B,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,uBAAuB,cAAY;AACjC,QAAI,KAAK,UAAU,IAAI,QAAQ,GAAG;AAChC,aAAO,KAAK,UAAU,IAAI,QAAQ;AAAA,IACpC;AACA,UAAM,EAAE,SAAS,IAAI,QAAQ,QAAQ;AACrC,SAAK,UAAU,IAAI,UAAU,QAAQ;AACrC,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,uBAAuB,CAAC,YAAY,kBAAkB,MAAM,CAAC,MAAM;AACjE,UAAM,WAAW,CAAC;AAClB,UAAM,SAAS,KAAK,kBAAkB,YAAY,EAAE,OAAO,KAAK,CAAC;AACjE,QAAI,YAAY,OAAO,WAAW;AAClC,WAAO,WAAW;AAChB,UAAI,kBAAkB;AACpB,YAAI,UAAU,SAAS,GAAG;AACxB,cAAI,UAAU;AACd,gBAAM,IAAI,iBAAiB;AAC3B,mBAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,kBAAM,SAAS,iBAAiB,CAAC;AACjC,gBAAI,KAAK,aAAa,QAAQ,WAAW,GAAG,GAAG;AAC7C,wBAAU;AACV;AAAA,YACF;AAAA,UACF;AACA,cAAI,SAAS;AACX,qBAAS,KAAK,SAAS;AAAA,UACzB;AAAA,QACF;AAAA,MACF,OAAO;AACL,iBAAS,KAAK,SAAS;AAAA,MACzB;AACA,kBAAY,OAAO,YAAY;AAAA,IACjC;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,mBAAmB,CAAC,KAAK,MAAM,MAAM,CAAC,MAAM;AAC1C,UAAM,EAAE,GAAG,GAAG,SAAS,IAAI;AAC3B,UAAM,EAAE,WAAW,IAAI;AACvB,QAAI,CAAC,YAAY;AACf,YAAM,cAAc,oBAAI,IAAI;AAC5B,UAAI,SAAS,KAAK,SAAS,IAAI,IAAI,IAAI,MAAM,GAAG;AAC9C,YAAI,UAAU;AACZ,gBAAMC,oBAAmB,KAAK,qBAAqB,QAAQ;AAC3D,gBAAM,IAAIA,kBAAiB;AAC3B,mBAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,kBAAM,SAASA,kBAAiB,CAAC;AACjC,gBAAI,KAAK,aAAa,QAAQ,MAAM,GAAG,GAAG;AACxC,0BAAY,IAAI,IAAI;AACpB;AAAA,YACF;AAAA,UACF;AAAA,QACF,OAAO;AACL,sBAAY,IAAI,IAAI;AAAA,QACtB;AAAA,MACF;AACA,aAAO;AAAA,IACT;AACA,UAAM,mBAAmB,WACrB,KAAK,qBAAqB,QAAQ,IAClC;AACJ,UAAM,WAAW,KAAK;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,UAAM,eAAe,iBAAiB,UAAU,GAAG;AACnD,WAAO,IAAI,IAAI,YAAY;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,oBAAoB,CAAC,KAAK,SAAS;AACjC,UAAM,EAAE,WAAW,IAAI;AACvB,QAAI,CAAC,YAAY;AACf,UAAI,SAAS,KAAK,SAAS,IAAI,IAAI,IAAI,IAAI,IAAI,MAAM,GAAG;AACtD,eAAO,oBAAI,IAAI,CAAC,IAAI,CAAC;AAAA,MACvB;AACA,aAAO,oBAAI,IAAI;AAAA,IACjB;AACA,UAAM,gBAAgB,CAAC;AACvB,UAAM,SAAS,KAAK,kBAAkB,YAAY,EAAE,OAAO,KAAK,CAAC;AACjE,QAAI,UAAU,OAAO,WAAW;AAChC,WAAO,SAAS;AACd,UACE,QAAQ,cAAc,KAAK,aAC3B,QAAQ,iBAAiB,KAAK,gBAC9B,QAAQ,WAAW,KAAK,QACxB;AACA,sBAAc,KAAK,OAAO;AAAA,MAC5B;AACA,gBAAU,OAAO,YAAY;AAAA,IAC/B;AACA,UAAM,eAAe,iBAAiB,eAAe,GAAG;AACxD,WAAO,IAAI,IAAI,YAAY;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,gBAAgB,CAAC,KAAK,MAAM,SAAS,MAAM,CAAC,MAAM;AAChD,UAAM;AAAA,MACJ,KAAK,EAAE,GAAG,GAAG,MAAM,aAAa;AAAA,MAChC;AAAA,IACF,IAAI;AACJ,UAAM,SAAS,oBAAI,IAAI;AACvB,QAAI,cAAc;AAChB,UAAI,iBAAiB,QAAQ;AAC3B,eAAO,IAAI,KAAK,CAAC;AACjB,eAAO,IAAI,KAAK,CAAC;AAAA,MACnB,WAAW,iBAAiB,OAAO;AACjC,eAAO,IAAI,KAAK,CAAC;AACjB,eAAO,IAAI,KAAK,CAAC;AAAA,MACnB;AACA,UAAI,QAAQ,QAAQ,MAAM,IAAI,IAAI;AAChC,eAAO,IAAI,WAAW,IAAI;AAAA,MAC5B;AAAA,IACF,OAAO;AACL,UAAI,OAAO,MAAM,YAAY,QAAQ,KAAK,CAAC,GAAG;AAC5C,eAAO,IAAI,KAAK,IAAI,CAAC;AAAA,MACvB,OAAO;AACL,eAAO,IAAI,KAAK,CAAC;AAAA,MACnB;AACA,UAAI,OAAO,MAAM,YAAY,QAAQ,KAAK,CAAC,GAAG;AAC5C,eAAO,IAAI,KAAK,IAAI,CAAC;AAAA,MACvB,OAAO;AACL,eAAO,IAAI,KAAK,CAAC;AAAA,MACnB;AACA,UAAI,QAAQ,QAAQ,MAAM,IAAI,IAAI;AAChC,eAAO,IAAI,WAAW,IAAI;AAAA,MAC5B;AAAA,IACF;AACA,QAAI,YAAY,eAAe,YAAY,kBAAkB;AAC3D,UAAI,UAAU;AACZ,eAAO,IAAI,YAAY,QAAQ;AAAA,MACjC;AACA,YAAM,MAAM,OAAO,YAAY,MAAM;AACrC,YAAM,QAAQ,KAAK,iBAAiB,KAAK,MAAM,GAAG;AAClD,aAAO;AAAA,IACT,WAAW,YAAY,iBAAiB,YAAY,oBAAoB;AACtE,YAAM,MAAM,OAAO,YAAY,MAAM;AACrC,YAAM,QAAQ,KAAK,kBAAkB,KAAK,IAAI;AAC9C,aAAO;AAAA,IACT;AACA,WAAO,oBAAI,IAAI;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,sBAAsB,CAAC,WAAW,MAAM,MAAM,CAAC,MAAM;AACnD,QAAI,MAAM,QAAQ,SAAS,KAAK,UAAU,QAAQ;AAEhD,YAAM,SAAS,CAAC,GAAG,SAAS;AAC5B,YAAM,CAAC,IAAI,IAAI;AACf,YAAM,EAAE,MAAM,SAAS,IAAI;AAC3B,UAAI;AACJ,UAAI,aAAa,YAAY;AAC3B,gBAAQ,OAAO,MAAM;AAAA,MACvB,OAAO;AACL,gBAAQ;AAAA,UACN,MAAM;AAAA,UACN,MAAM;AAAA,QACR;AAAA,MACF;AACA,YAAM,aAAa,CAAC;AACpB,aAAO,OAAO,QAAQ;AACpB,cAAM,CAAC,IAAI,IAAI;AACf,cAAM,EAAE,MAAM,SAAS,IAAI;AAC3B,YAAI,aAAa,YAAY;AAC3B;AAAA,QACF,OAAO;AACL,qBAAW,KAAK,OAAO,MAAM,CAAC;AAAA,QAChC;AAAA,MACF;AACA,YAAM,OAAO;AAAA,QACX;AAAA,QACA,QAAQ;AAAA,MACV;AACA,UAAI,MAAM;AACV,YAAM,QAAQ,KAAK,iBAAiB,MAAM,MAAM,GAAG;AACnD,UAAI,MAAM,MAAM;AACd,YAAI,OAAO,QAAQ;AACjB,cAAI,OAAO;AACX,qBAAW,YAAY,OAAO;AAC5B,mBAAO,KAAK,oBAAoB,QAAQ,UAAU,GAAG;AACrD,gBAAI,MAAM;AACR;AAAA,YACF;AAAA,UACF;AACA,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,qBAAqB,CAAC,SAAS,MAAM,QAAQ;AAC3C,UAAM,EAAE,SAAS,IAAI;AACrB,QAAI,OAAO;AACX,UAAM,IAAI,SAAS;AACnB,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,YAAM,SAAS,SAAS,CAAC;AACzB,aAAO,KAAK,oBAAoB,QAAQ,MAAM,GAAG;AACjD,UAAI,MAAM;AACR;AAAA,MACF;AAAA,IACF;AACA,QAAI,CAAC,MAAM;AACT,aAAO;AAAA,IACT;AACA,SACG,IAAI,gBAAgB,KAAK,YAC1B,KAAK,aAAa,wBAClB;AACA,aAAO,KAAK,oBAAoB,OAAO;AAAA,IACzC;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,0BAA0B,CAAC,SAAS,MAAM,MAAM,CAAC,MAAM;AACrD,UAAM,EAAE,SAAS,UAAU,aAAa,IAAI;AAE5C,QAAI,YAAY,OAAO;AACrB,aAAO,KAAK,mBAAmB,SAAS,MAAM,GAAG;AAAA,IACnD;AAEA,UAAM,gBACH,IAAI,gBAAgB,KAAK,YAC1B,KAAK,aAAa;AAEpB,QAAI,cAAc;AAChB,UAAI,UAAU;AACd,iBAAW,UAAU,UAAU;AAC7B,YAAI,OAAO,SAAS,GAAG;AACrB,oBAAU;AACV;AAAA,QACF,WAAW,YAAY,OAAO;AAC5B,gBAAM,CAAC,EAAE,MAAM,aAAa,CAAC,IAAI;AACjC,cAAI,iBAAiB,mBAAmB;AACtC,sBAAU;AACV;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACA,UAAI,SAAS;AACX,eAAO;AAAA,MACT;AAAA,IACF;AACA,QAAI,UAAU,YAAY,QAAQ,YAAY;AAC9C,UAAM,IAAI,aAAa;AACvB,QAAI;AACJ,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,YAAM,SAAS,aAAa,CAAC;AAC7B,YAAM,YAAY,OAAO,SAAS;AAClC,YAAM,EAAE,OAAO,IAAI,OAAO,SAAS;AACnC,aAAO,KAAK,aAAa,QAAQ,MAAM,GAAG;AAC1C,UAAI,QAAQ,YAAY,GAAG;AACzB,YAAI,YAAY,oBAAI,IAAI,CAAC,IAAI,CAAC;AAC9B,iBAAS,IAAI,YAAY,GAAG,KAAK,GAAG,KAAK;AACvC,gBAAM,OAAO,OAAO,CAAC;AACrB,gBAAM,MAAM,CAAC;AACb,cAAI,MAAM;AACV,qBAAW,YAAY,WAAW;AAChC,kBAAM,IAAI,KAAK,iBAAiB,MAAM,UAAU,GAAG;AACnD,gBAAI,EAAE,MAAM;AACV,kBAAI,KAAK,GAAG,CAAC;AAAA,YACf;AAAA,UACF;AACA,cAAI,IAAI,QAAQ;AACd,gBAAI,MAAM,GAAG;AACX,qBAAO;AAAA,YACT,OAAO;AACL,0BAAY,IAAI,IAAI,GAAG;AAAA,YACzB;AAAA,UACF,OAAO;AACL,mBAAO;AACP;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACA,UAAI,MAAM;AACR;AAAA,MACF;AAAA,IACF;AACA,QAAI,YAAY,OAAO;AACrB,UAAI,MAAM;AACR,eAAO;AAAA,MACT;AACA,aAAO;AAAA,IACT,WAAW,MAAM;AACf,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,0BAA0B,KAAK,MAAM,MAAM,CAAC,GAAG;AAC7C,UAAM,EAAE,UAAU,aAAa,MAAM,QAAQ,IAAI;AACjD,UAAM,EAAE,WAAW,WAAW,IAAI;AAClC,UAAM,EAAE,SAAS,OAAO,KAAK,MAAM,IAAI;AACvC,UAAM,UAAU,oBAAI,IAAI;AAExB,QAAI,MAAM,QAAQ,WAAW,KAAK,aAAa,IAAI,OAAO,GAAG;AAC3D,UAAI,CAAC,YAAY,UAAU,YAAY,QAAQ,YAAY,SAAS;AAClE,cAAM,UAAM,0BAAY,GAAG;AAC3B,cAAM,MAAM,oBAAoB,GAAG;AACnC,eAAO,KAAK,QAAQ,kBAAkB,KAAK,YAAY,KAAK,OAAO,CAAC;AAAA,MACtE;AACA,UAAI;AACJ,UAAI,KAAK,UAAU,IAAI,GAAG,GAAG;AAC3B,kBAAU,KAAK,UAAU,IAAI,GAAG;AAAA,MAClC,OAAO;AACL,cAAM,EAAE,SAAS,IAAI,QAAQ,GAAG;AAChC,YAAI,YAAY,OAAO;AAErB,cAAI,WAAW;AACf,gBAAM,IAAI,YAAY;AACtB,mBAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,kBAAM,QAAQ,YAAY,CAAC;AAC3B,kBAAM,WAAO,sBAAQ,OAAO,wBAAwB;AACpD,gBAAI,MAAM;AACR,oBAAM,WAAW,KAAK;AACtB,kBAAI,aAAa,QAAQ,aAAa,SAAS;AAC7C,2BAAW;AACX;AAAA,cACF,OAAO;AACL,sBAAM,UAAM,0BAAY,GAAG;AAC3B,sBAAM,MAAM,oBAAoB,GAAG;AACnC,uBAAO,KAAK;AAAA,kBACV,kBAAkB,KAAK,YAAY,KAAK,OAAO;AAAA,gBACjD;AAAA,cACF;AAAA,YACF;AAAA,UACF;AACA,cAAI,UAAU;AACZ,mBAAO;AAAA,UACT;AACA,oBAAU;AAAA,YACR;AAAA,YACA;AAAA,UACF;AAAA,QACF,OAAO;AACL,gBAAM,eAAe,CAAC;AACtB,gBAAM,IAAI,SAAS;AACnB,mBAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,kBAAM,CAAC,GAAG,MAAM,IAAI,SAAS,CAAC;AAC9B,kBAAM,SAAS,CAAC;AAChB,kBAAM,YAAY,oBAAI,IAAI;AAC1B,gBAAI,OAAO,OAAO,MAAM;AACxB,mBAAO,MAAM;AACX,kBAAI,KAAK,SAAS,YAAY;AAC5B,uBAAO,KAAK;AAAA,kBACV,OAAO;AAAA,kBACP,QAAQ,CAAC,GAAG,SAAS;AAAA,gBACvB,CAAC;AACD,0BAAU,MAAM;AAAA,cAClB,WAAW,MAAM;AACf,0BAAU,IAAI,IAAI;AAAA,cACpB;AACA,kBAAI,OAAO,QAAQ;AACjB,uBAAO,OAAO,MAAM;AAAA,cACtB,OAAO;AACL,uBAAO,KAAK;AAAA,kBACV,OAAO;AAAA,kBACP,QAAQ,CAAC,GAAG,SAAS;AAAA,gBACvB,CAAC;AACD,0BAAU,MAAM;AAChB;AAAA,cACF;AAAA,YACF;AACA,yBAAa,KAAK,MAAM;AAAA,UAC1B;AACA,oBAAU;AAAA,YACR;AAAA,YACA;AAAA,YACA;AAAA,UACF;AACA,eAAK,UAAU,IAAI,KAAK,OAAO;AAAA,QACjC;AAAA,MACF;AACA,YAAM,MAAM,KAAK,wBAAwB,SAAS,MAAM,GAAG;AAC3D,UAAI,KAAK;AACP,gBAAQ,IAAI,GAAG;AAAA,MACjB;AAAA,IACF,WAAW,MAAM,QAAQ,WAAW,GAAG;AAErC,UAAI,oCAAoC,KAAK,OAAO,GAAG;AACrD,YAAI,YAAY,WAAW,GAAG;AAC5B,gBAAM,UAAM,0BAAY,GAAG;AAC3B,iBAAO,KAAK;AAAA,YACV;AAAA,cACE,oBAAoB,GAAG;AAAA,cACvB;AAAA,cACA,KAAK;AAAA,YACP;AAAA,UACF;AAAA,QACF;AACA,cAAM,CAAC,MAAM,IAAI;AACjB,cAAM,QAAQ,KAAK,cAAc,QAAQ,MAAM,SAAS,GAAG;AAC3D,eAAO;AAAA,MACT,OAAO;AACL,gBAAQ,SAAS;AAAA;AAAA,UAEf,KAAK,OAAO;AACV,gBAAI,YAAY,WAAW,GAAG;AAC5B,oBAAM,UAAM,0BAAY,GAAG;AAC3B,qBAAO,KAAK;AAAA,gBACV;AAAA,kBACE,oBAAoB,GAAG;AAAA,kBACvB;AAAA,kBACA,KAAK;AAAA,gBACP;AAAA,cACF;AAAA,YACF;AACA,kBAAM,CAAC,QAAQ,IAAI;AACnB,kBAAM,MAAM,0BAA0B,UAAU,IAAI;AACpD,gBAAI,KAAK;AACP,sBAAQ,IAAI,IAAI;AAAA,YAClB;AACA;AAAA,UACF;AAAA;AAAA,UAEA,KAAK,QAAQ;AACX,gBAAI,CAAC,YAAY,QAAQ;AACvB,oBAAM,UAAM,0BAAY,GAAG;AAC3B,qBAAO,KAAK;AAAA,gBACV;AAAA,kBACE,oBAAoB,GAAG;AAAA,kBACvB;AAAA,kBACA,KAAK;AAAA,gBACP;AAAA,cACF;AAAA,YACF;AACA,gBAAI;AACJ,uBAAW,YAAY,aAAa;AAClC,qBAAO,yBAAyB,UAAU,IAAI;AAC9C,kBAAI,MAAM;AACR;AAAA,cACF;AAAA,YACF;AACA,gBAAI,MAAM;AACR,sBAAQ,IAAI,IAAI;AAAA,YAClB;AACA;AAAA,UACF;AAAA;AAAA,UAEA,KAAK,SAAS;AACZ,gBAAI,gBAAgB,IAAI,GAAG;AACzB,oBAAM,CAAC,EAAE,OAAO,WAAW,CAAC,IAAI;AAChC,kBAAI,YAAY;AACd,oBAAI,KAAK,UAAU,GAAG;AACpB,0BAAQ,IAAI,IAAI;AAAA,gBAClB,OAAO;AACL,6BAAW,KAAK,MAAM;AACpB,0BAAM,OAAO,KAAK,CAAC;AACnB,wBAAI,gBAAgB,KAAK,QAAQ,kBAAkB;AACjD,0BAAI,MAAM,QAAQ,IAAI,UAAU,GAAG;AACjC,gCAAQ,IAAI,IAAI;AAAA,sBAClB;AACA;AAAA,oBACF;AAAA,kBACF;AAAA,gBACF;AAAA,cACF;AAAA,YACF;AACA;AAAA,UACF;AAAA,UACA,KAAK;AAAA,UACL,KAAK;AAAA,UACL,KAAK;AAAA,UACL,KAAK,gBAAgB;AACnB,gBAAI,MAAM;AACR,mBAAK;AAAA,gBACH;AAAA,kBACE,6BAA6B,OAAO;AAAA,kBACpC;AAAA,kBACA,KAAK;AAAA,gBACP;AAAA,cACF;AAAA,YACF;AACA;AAAA,UACF;AAAA;AAAA,UAEA,KAAK;AAAA,UACL,KAAK,gBAAgB;AACnB;AAAA,UACF;AAAA;AAAA,UAEA,KAAK,YAAY;AACf,gBAAI,MAAM;AACR,mBAAK;AAAA,gBACH;AAAA,kBACE,yBAAyB,OAAO;AAAA,kBAChC;AAAA,kBACA,KAAK;AAAA,gBACP;AAAA,cACF;AAAA,YACF;AACA;AAAA,UACF;AAAA,UACA,SAAS;AACP,gBAAI,CAAC,SAAS;AACZ,mBAAK;AAAA,gBACH;AAAA,kBACE,yBAAyB,OAAO;AAAA,kBAChC;AAAA,kBACA,KAAK;AAAA,gBACP;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,WAAW,oBAAoB,IAAI,OAAO,GAAG;AAC3C,UAAI,SAAS,KAAK,OAAO;AACvB,gBAAQ,IAAI,IAAI;AAAA,MAClB,WAAW,YAAY;AACrB,gBAAQ,SAAS;AAAA,UACf,KAAK,iBAAiB;AACpB,kBAAM,CAAC,KAAK,IAAI,KAAK;AAAA,cACnB;AAAA,gBACE,GAAG;AAAA,gBACH,GAAG;AAAA,cACL;AAAA,cACA;AAAA,YACF;AACA,gBAAI,OAAO;AACT,sBAAQ,IAAI,KAAK;AAAA,YACnB;AACA;AAAA,UACF;AAAA,UACA,KAAK,gBAAgB;AACnB,kBAAM,CAAC,KAAK,IAAI,KAAK;AAAA,cACnB;AAAA,gBACE,GAAG;AAAA,gBACH,GAAG;AAAA,gBACH,SAAS;AAAA,cACX;AAAA,cACA;AAAA,YACF;AACA,gBAAI,OAAO;AACT,sBAAQ,IAAI,KAAK;AAAA,YACnB;AACA;AAAA,UACF;AAAA;AAAA,UAEA,SAAS;AACP,kBAAM,CAAC,KAAK,IAAI,KAAK;AAAA,cACnB;AAAA,gBACE,GAAG;AAAA,gBACH,GAAG;AAAA,cACL;AAAA,cACA;AAAA,YACF;AACA,gBAAI,UAAU,MAAM;AAClB,oBAAM,CAAC,KAAK,IAAI,KAAK;AAAA,gBACnB;AAAA,kBACE,GAAG;AAAA,kBACH,GAAG;AAAA,kBACH,SAAS;AAAA,gBACX;AAAA,gBACA;AAAA,cACF;AACA,kBAAI,UAAU,MAAM;AAClB,wBAAQ,IAAI,IAAI;AAAA,cAClB;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,OAAO;AACL,cAAQ,SAAS;AAAA,QACf,KAAK;AAAA,QACL,KAAK,WAAW;AACd,gBAAM,UAAU,yBAAyB,SAAS,IAAI;AACtD,cAAI,SAAS;AACX,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK;AAAA,QACL,KAAK,cAAc;AACjB,gBAAM,UAAU,yBAAyB,SAAS,IAAI;AACtD,cAAI,SAAS;AACX,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK;AAAA,QACL,KAAK,QAAQ;AACX,eACG,cAAc,OAAO,cAAc,WACpC,KAAK,aAAa,MAAM,GACxB;AACA,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,cAAc;AACjB,eACG,cAAc,OAAO,cAAc,WACpC,KAAK,aAAa,MAAM,GACxB;AACA,gBAAI,CAAC,KAAK,cAAc;AACtB,mBAAK,eAAe,IAAI,IAAI,KAAK,UAAU,GAAG;AAAA,YAChD;AACA,kBAAM,EAAE,MAAM,QAAQ,SAAS,IAAI,KAAK;AACxC,kBAAM,UAAU,IAAI,IAAI,KAAK,aAAa,MAAM,GAAG,IAAI;AACvD,gBAAI,QAAQ,WAAW,UAAU,QAAQ,aAAa,UAAU;AAC9D,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK,WAAW;AAEd;AAAA,QACF;AAAA,QACA,KAAK,SAAS;AACZ,gBAAM,EAAE,QAAQ,KAAK,IAAI,KAAK,UAAU,CAAC;AACzC,cACE,oCAAoC,KAAK,IAAI,KAC7C,KAAK,SAAS,MAAM,GACpB;AACA,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,UAAU;AACb,gBAAM,EAAE,SAAS,QAAQ,KAAK,IAAI,KAAK,UAAU,CAAC;AAClD,cAAI,SAAS,eAAe,UAAU,KAAK,KAAK,SAAS,MAAM,GAAG;AAChE,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,UAAU;AACb,cAAI,CAAC,KAAK,cAAc;AACtB,iBAAK,eAAe,IAAI,IAAI,KAAK,UAAU,GAAG;AAAA,UAChD;AACA,gBAAM,EAAE,KAAK,IAAI,KAAK;AACtB,cACE,KAAK,MACL,SAAS,IAAI,KAAK,EAAE,MACpB,KAAK,UAAU,SAAS,IAAI,GAC5B;AACA,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,iBAAiB;AACpB,cAAI,CAAC,KAAK,cAAc;AACtB,iBAAK,eAAe,IAAI,IAAI,KAAK,UAAU,GAAG;AAAA,UAChD;AACA,gBAAM,EAAE,KAAK,IAAI,KAAK;AACtB,cAAI,MAAM;AACR,kBAAM,KAAK,KAAK,QAAQ,MAAM,EAAE;AAChC,gBAAI,UAAU,KAAK,UAAU,eAAe,EAAE;AAC9C,mBAAO,SAAS;AACd,kBAAI,YAAY,MAAM;AACpB,wBAAQ,IAAI,IAAI;AAChB;AAAA,cACF;AACA,wBAAU,QAAQ;AAAA,YACpB;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK,SAAS;AACZ,cAAI,KAAK,MAAM,aAAa,cAAc;AACxC,gBAAI,CAAC,KAAK,WAAW,SAAS,KAAK,OAAO;AACxC,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UACF,WAAW,SAAS,KAAK,UAAU,iBAAiB;AAClD,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,SAAS;AACZ,gBAAM,gBAAgB,KAAK,UAAU;AACrC,cAAI,SAAS,iBAAiB,gBAAgB,IAAI,GAAG;AACnD,oBAAQ,IAAI,IAAI;AAAA,UAClB,WAAW,cAAc,YAAY;AACnC,kBAAM,sBAAsB,cAAc,WAAW;AACrD,gBAAI,UAAU;AACd,mBAAO,SAAS;AACd,kBAAI,QAAQ,aAAa,wBAAwB;AAC/C,sBAAM,EAAE,KAAK,IAAI;AACjB,oBAAI,SAAS,eAAe;AAC1B,sBAAI,gBAAgB,IAAI,GAAG;AACzB,4BAAQ,IAAI,IAAI;AAAA,kBAClB,OAAO;AACL,4BAAQ,IAAI,IAAI;AAAA,kBAClB;AAAA,gBACF;AACA;AAAA,cACF,OAAO;AACL,0BAAU,QAAQ;AAAA,cACpB;AAAA,YACF;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK,iBAAiB;AACpB,cAAI,SAAS,KAAK,UAAU,iBAAiB,gBAAgB,IAAI,GAAG;AAClE,gBAAI;AACJ,gBAAI,eAAe,IAAI,GAAG;AACxB,qBAAO;AAAA,YACT,WAAW,KAAK,QAAQ;AACtB,oBAAM,EAAE,eAAe,QAAQ,YAAY,IAAI,KAAK;AACpD,kBAAI,gBAAgB,MAAM;AACxB,oBAAI,eAAe,aAAa,GAAG;AACjC,yBAAO;AAAA,gBACT,WAAW,KAAK,QAAQ;AACtB,wBAAM;AAAA,oBACJ,QAAQ;AAAA,oBACR,SAAS;AAAA,oBACT,KAAK;AAAA,oBACL,SAAS;AAAA,oBACT,QAAQ;AAAA,oBACR,MAAM;AAAA,kBACR,IAAI,KAAK;AAET,sBAAI,gBAAgB,eAAe;AACjC,wBAAI,KAAK,sBAAsB,MAAM;AACnC,6BAAO;AAAA,oBACT,WAAW,gBAAgB,KAAK,mBAAmB;AACjD,6BAAO;AAAA,oBACT;AAAA,kBACF,WAAW,aAAa,OAAO;AAC7B,wBACG,cAAc,aAAa,gBAAgB,QAC3C,cAAc,WAAW,gBAAgB,MAC1C;AACA,0BAAI,gBAAgB,aAAa;AAC/B,4BAAI,KAAK,sBAAsB,MAAM;AACnC,iCAAO;AAAA,wBACT,WACE,gBAAgB,KAAK,qBACrB,kBAAkB,MAClB;AACA,iCAAO;AAAA,wBACT;AAAA,sBACF,OAAO;AACL,+BAAO;AAAA,sBACT;AAAA,oBACF;AAAA,kBACF,WAAW,UAAU;AACnB,yBACG,cAAc,aAAa,cAAc,YAC1C,CAAC,eACD,CAAC,gBACD,CAAC,gBACD,gBAAgB,MAChB;AACA,6BAAO;AAAA,oBACT;AAAA,kBACF;AAAA,gBACF,WACE,kBAAkB,QAClB,kBAAkB,KAAK,mBACvB;AACA,yBAAO;AAAA,gBACT;AAAA,cACF;AAAA,YACF;AACA,gBAAI,MAAM;AACR,mBAAK,oBAAoB;AACzB,sBAAQ,IAAI,IAAI;AAAA,YAClB,WAAW,KAAK,sBAAsB,MAAM;AAC1C,mBAAK,oBAAoB;AAAA,YAC3B;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK,gBAAgB;AACnB,gBAAM,gBAAgB,KAAK,UAAU;AACrC,cAAI,KAAK,SAAS,aAAa,KAAK,gBAAgB,aAAa,GAAG;AAClE,oBAAQ,IAAI,IAAI;AAAA,UAClB,WAAW,cAAc,YAAY;AACnC,kBAAM,sBAAsB,cAAc,WAAW;AACrD,gBAAI,KAAK,SAAS,mBAAmB,GAAG;AACtC,sBAAQ,IAAI,IAAI;AAAA,YAClB,OAAO;AACL,kBAAI,UAAU;AACd,qBAAO,SAAS;AACd,oBAAI,QAAQ,aAAa,wBAAwB;AAC/C,wBAAM,EAAE,KAAK,IAAI;AACjB,sBAAI,SAAS,iBAAiB,KAAK,SAAS,IAAI,GAAG;AACjD,4BAAQ,IAAI,IAAI;AAAA,kBAClB;AACA;AAAA,gBACF,OAAO;AACL,4BAAU,QAAQ;AAAA,gBACpB;AAAA,cACF;AAAA,YACF;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK;AAAA,QACL,KAAK,UAAU;AACb,cAAI,cAAc,aAAa,cAAc,UAAU;AACrD,gBAAI,KAAK,aAAa,MAAM,GAAG;AAC7B,kBAAI,YAAY,QAAQ;AACtB,wBAAQ,IAAI,IAAI;AAAA,cAClB;AAAA,YACF,WAAW,YAAY,UAAU;AAC/B,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK,qBAAqB;AACxB,cAAI;AACJ,cAAI,KAAK,aAAa;AACpB,0BAAc,KAAK;AAAA,UACrB,WAAW,KAAK,aAAa,aAAa,GAAG;AAC3C,0BAAc,KAAK,aAAa,aAAa;AAAA,UAC/C;AACA,cAAI,OAAO,gBAAgB,YAAY,CAAC,SAAS,KAAK,WAAW,GAAG;AAClE,gBAAI;AACJ,gBAAI,cAAc,YAAY;AAC5B,2BAAa;AAAA,YACf,WAAW,cAAc,SAAS;AAChC,kBAAI,KAAK,aAAa,MAAM,GAAG;AAC7B,oBAAI,uBAAuB,IAAI,KAAK,aAAa,MAAM,CAAC,GAAG;AACzD,+BAAa;AAAA,gBACf;AAAA,cACF,OAAO;AACL,6BAAa;AAAA,cACf;AAAA,YACF;AACA,gBAAI,cAAc,KAAK,UAAU,IAAI;AACnC,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK,WAAW;AACd,gBAAM,WAAW,KAAK,aAAa,MAAM;AACzC,cACG,KAAK,WACJ,cAAc,YACb,aAAa,cAAc,aAAa,YAC1C,KAAK,YAAY,cAAc,UAChC;AACA,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,iBAAiB;AACpB,cACG,KAAK,iBACJ,cAAc,WACd,KAAK,SAAS,cACf,cAAc,cAAc,CAAC,KAAK,aAAa,OAAO,GACvD;AACA,oBAAQ,IAAI,IAAI;AAAA,UAClB,WACE,cAAc,WACd,KAAK,SAAS,WACd,CAAC,KAAK,aAAa,SAAS,GAC5B;AACA,kBAAM,WAAW,KAAK;AACtB,gBAAI,SAAS,KAAK;AAClB,mBAAO,QAAQ;AACb,kBAAI,OAAO,cAAc,QAAQ;AAC/B;AAAA,cACF;AACA,uBAAS,OAAO;AAAA,YAClB;AACA,gBAAI,CAAC,QAAQ;AACX,uBAAS,KAAK,UAAU;AAAA,YAC1B;AACA,kBAAM,SAAS,KAAK,kBAAkB,MAAM;AAC5C,gBAAI,UAAU,aAAa,QAAQ,MAAM;AACzC,sBAAU,OAAO,WAAW;AAC5B,gBAAI;AACJ,mBAAO,SAAS;AACd,kBACE,QAAQ,cAAc,WACtB,QAAQ,aAAa,MAAM,MAAM,SACjC;AACA,oBAAI,QAAQ,aAAa,MAAM,GAAG;AAChC,sBAAI,QAAQ,aAAa,MAAM,MAAM,UAAU;AAC7C,8BAAU,CAAC,CAAC,QAAQ;AAAA,kBACtB;AAAA,gBACF,OAAO;AACL,4BAAU,CAAC,CAAC,QAAQ;AAAA,gBACtB;AACA,oBAAI,SAAS;AACX;AAAA,gBACF;AAAA,cACF;AACA,wBAAU,OAAO,SAAS;AAAA,YAC5B;AACA,gBAAI,CAAC,SAAS;AACZ,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK,WAAW;AAEd,gBAAM,WAAW,KAAK,aAAa,MAAM;AACzC,cACG,cAAc,YACb,EAAE,KAAK,aAAa,MAAM,KAAK,iBAAiB,IAAI,QAAQ,MAC7D,cAAc,WACb,KAAK,aAAa,MAAM,KACxB,kBAAkB,IAAI,QAAQ,GAChC;AACA,gBAAI,OAAO,KAAK;AAChB,mBAAO,MAAM;AACX,kBAAI,KAAK,cAAc,QAAQ;AAC7B;AAAA,cACF;AACA,qBAAO,KAAK;AAAA,YACd;AACA,gBAAI,MAAM;AACR,oBAAM,SAAS,KAAK,kBAAkB,IAAI;AAC1C,kBAAI,UAAU,aAAa,MAAM,MAAM;AACvC,wBAAU,OAAO,WAAW;AAC5B,qBAAO,SAAS;AACd,sBAAM,WAAW,QAAQ;AACzB,sBAAM,eAAe,QAAQ,aAAa,MAAM;AAChD,oBAAI;AACJ,oBAAI,aAAa,UAAU;AACzB,sBAAI,EACF,QAAQ,aAAa,MAAM,KAC3B,iBAAiB,IAAI,YAAY;AAAA,gBAErC,WAAW,aAAa,SAAS;AAC/B,sBACE,QAAQ,aAAa,MAAM,KAC3B,kBAAkB,IAAI,YAAY;AAAA,gBACtC;AACA,oBAAI,GAAG;AACL,sBAAI,YAAY,MAAM;AACpB,4BAAQ,IAAI,IAAI;AAAA,kBAClB;AACA;AAAA,gBACF;AACA,0BAAU,OAAO,SAAS;AAAA,cAC5B;AAAA,YACF;AAAA,UAEF,WACE,cAAc,WACd,KAAK,aAAa,MAAM,KACxB,KAAK,aAAa,SAAS,KAC3B,iBAAiB,IAAI,QAAQ,GAC7B;AACA,oBAAQ,IAAI,IAAI;AAAA,UAElB,WAAW,cAAc,YAAY,KAAK,aAAa,UAAU,GAAG;AAClE,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK;AAAA,QACL,KAAK,WAAW;AACd,cAAI,mBAAmB,IAAI,SAAS,GAAG;AACrC,gBAAI;AACJ,gBAAI,KAAK,cAAc,GAAG;AACxB,kBAAI,KAAK,aAAa,GAAG;AACvB,oBAAI,KAAK,aAAa,KAAK,MAAM,QAAQ;AACvC,0BAAQ;AAAA,gBACV;AAAA,cACF,OAAO;AACL,wBAAQ;AAAA,cACV;AAAA,YACF;AACA,gBAAI,OAAO;AACT,kBAAI,YAAY,SAAS;AACvB,wBAAQ,IAAI,IAAI;AAAA,cAClB;AAAA,YACF,WAAW,YAAY,WAAW;AAChC,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UACF,WAAW,cAAc,YAAY;AACnC,kBAAM,SAAS,KAAK,kBAAkB,IAAI;AAC1C,gBAAI,UAAU,aAAa,MAAM,MAAM;AACvC,sBAAU,OAAO,WAAW;AAC5B,gBAAI;AACJ,gBAAI,CAAC,SAAS;AACZ,sBAAQ;AAAA,YACV,OAAO;AACL,qBAAO,SAAS;AACd,oBAAI,mBAAmB,IAAI,QAAQ,SAAS,GAAG;AAC7C,sBAAI,QAAQ,cAAc,GAAG;AAC3B,wBAAI,QAAQ,aAAa,GAAG;AAC1B,8BAAQ,QAAQ,aAAa,QAAQ,MAAM;AAAA,oBAC7C,OAAO;AACL,8BAAQ;AAAA,oBACV;AAAA,kBACF,OAAO;AACL,4BAAQ;AAAA,kBACV;AACA,sBAAI,CAAC,OAAO;AACV;AAAA,kBACF;AAAA,gBACF;AACA,0BAAU,OAAO,SAAS;AAAA,cAC5B;AAAA,YACF;AACA,gBAAI,OAAO;AACT,kBAAI,YAAY,SAAS;AACvB,wBAAQ,IAAI,IAAI;AAAA,cAClB;AAAA,YACF,WAAW,YAAY,WAAW;AAChC,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK;AAAA,QACL,KAAK,gBAAgB;AACnB,gBAAM,WAAW,KAAK,aAAa,MAAM;AACzC,cACE,cAAc,WACd,EAAE,KAAK,YAAY,KAAK,aAAa,UAAU,MAC/C,EAAE,KAAK,YAAY,KAAK,aAAa,UAAU,MAC/C,iBAAiB,IAAI,QAAQ,GAC7B;AACA,kBAAM,SACJ,KAAK,SAAS,kBAAkB,KAAK,SAAS;AAChD,gBAAI,YAAY,kBAAkB,QAAQ;AACxC,sBAAQ,IAAI,IAAI;AAAA,YAClB,WACE,YAAY,cACZ,CAAC,WACA,KAAK,aAAa,KAAK,KACtB,KAAK,aAAa,KAAK,KACvB,aAAa,UACf;AACA,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,KAAK;AAAA,QACL,KAAK,YAAY;AACf,cAAI;AACJ,cAAI;AACJ,cAAI,cAAc,YAAY,cAAc,YAAY;AACtD,gBAAI,KAAK,YAAY,KAAK,aAAa,UAAU,GAAG;AAClD,yBAAW;AAAA,YACb,OAAO;AACL,yBAAW;AAAA,YACb;AAAA,UACF,WAAW,cAAc,SAAS;AAChC,gBAAI,KAAK,aAAa,MAAM,GAAG;AAC7B,oBAAM,WAAW,KAAK,aAAa,MAAM;AACzC,kBAAI,oBAAoB,IAAI,QAAQ,GAAG;AACrC,oBAAI,KAAK,YAAY,KAAK,aAAa,UAAU,GAAG;AAClD,6BAAW;AAAA,gBACb,OAAO;AACL,6BAAW;AAAA,gBACb;AAAA,cACF,OAAO;AACL,2BAAW;AAAA,cACb;AAAA,YACF,WAAW,KAAK,YAAY,KAAK,aAAa,UAAU,GAAG;AACzD,yBAAW;AAAA,YACb,OAAO;AACL,yBAAW;AAAA,YACb;AAAA,UACF;AACA,cAAI,YAAY,cAAc,UAAU;AACtC,oBAAQ,IAAI,IAAI;AAAA,UAClB,WAAW,YAAY,cAAc,UAAU;AAC7C,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,QAAQ;AACX,cAAI,SAAS,KAAK,UAAU,iBAAiB;AAC3C,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,SAAS;AACZ,cAAI,KAAK,cAAc,GAAG;AACxB,kBAAM,SAAS,KAAK,kBAAkB,MAAM;AAAA,cAC1C,OAAO;AAAA,cACP,YAAY;AAAA,YACd,CAAC;AACD,gBAAI,UAAU,OAAO,WAAW;AAChC,gBAAI;AACJ,mBAAO,SAAS;AACd,qBACE,QAAQ,aAAa,gBACrB,QAAQ,aAAa;AACvB,kBAAI,CAAC,MAAM;AACT;AAAA,cACF;AACA,wBAAU,OAAO,YAAY;AAAA,YAC/B;AACA,gBAAI,MAAM;AACR,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UACF,OAAO;AACL,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,eAAe;AAClB,cACG,cAAc,SAAS,WAAW,qBACnC,SAAS,KAAK,OACd;AACA,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,cAAc;AACjB,cACG,cAAc,SAAS,WAAW,oBACnC,SAAS,KAAK,OACd;AACA,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,cAAc;AACjB,cACG,cACC,SAAS,WAAW,qBACpB,SAAS,WAAW,oBACtB,SAAS,KAAK,OACd;AACA,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,WAAW;AACd,cAAI,KAAK,aAAa,IAAI,KAAK,UAAU,SAAS,GAAG,GAAG;AACtD,gBAAI,gBAAgB,IAAI,GAAG;AACzB,sBAAQ,IAAI,IAAI;AAAA,YAClB;AAAA,UAEF,WACE,gBAAgB,KAAK,QAAQ,eAC7B,gBAAgB,KAAK,QAAQ,YAC7B;AACA,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA,QACA,KAAK,gBAAgB;AACnB,cAAI,KAAK,WAAW,UAAU,IAAI,GAAG;AACnC,oBAAQ,IAAI,IAAI;AAAA,UAClB;AACA;AAAA,QACF;AAAA;AAAA,QAEA,KAAK,QAAQ;AACX;AAAA,QACF;AAAA;AAAA,QAEA,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK,cAAc;AACjB,cAAI,MAAM;AACR,iBAAK;AAAA,cACH;AAAA,gBACE,gCAAgC,OAAO;AAAA,gBACvC;AAAA,gBACA,KAAK;AAAA,cACP;AAAA,YACF;AAAA,UACF;AACA;AAAA,QACF;AAAA;AAAA,QAEA,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK,oBAAoB;AACvB,cAAI,MAAM;AACR,iBAAK;AAAA,cACH;AAAA,gBACE,6BAA6B,OAAO;AAAA,gBACpC;AAAA,gBACA,KAAK;AAAA,cACP;AAAA,YACF;AAAA,UACF;AACA;AAAA,QACF;AAAA,QACA,SAAS;AACP,cAAI,QAAQ,WAAW,UAAU,GAAG;AAClC,gBAAI,MAAM;AACR,mBAAK;AAAA,gBACH;AAAA,kBACE,6BAA6B,OAAO;AAAA,kBACpC;AAAA,kBACA,KAAK;AAAA,gBACP;AAAA,cACF;AAAA,YACF;AAAA,UACF,WAAW,CAAC,SAAS;AACnB,iBAAK;AAAA,cACH;AAAA,gBACE,yBAAyB,OAAO;AAAA,gBAChC;AAAA,gBACA,KAAK;AAAA,cACP;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,sBAAsB,CAAC,QAAQ,MAAM,QAAQ;AAC3C,UAAM,IAAI,OAAO;AACjB,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,YAAM,OAAO,OAAO,CAAC;AACrB,UAAI,KAAK,SAAS,YAAY;AAC5B,cAAM,UAAM,0BAAY,GAAG;AAC3B,cAAM,MAAM,oBAAoB,GAAG;AACnC,aAAK,QAAQ,kBAAkB,KAAK,YAAY,KAAK,OAAO,CAAC;AAC7D,eAAO;AAAA,MACT;AACA,UAAI,CAAC,KAAK,eAAe,MAAM,IAAI,EAAE,IAAI,IAAI,GAAG;AAC9C,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,6BAA6B,CAAC,QAAQ,MAAM,QAAQ;AAClD,QAAI,SAAS;AACb,WAAO,QAAQ;AACb,UAAI;AACJ,YAAM,IAAI,OAAO;AACjB,eAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,cAAM,OAAO,OAAO,CAAC;AACrB,YAAI,KAAK,SAAS,YAAY;AAC5B,gBAAM,UAAM,0BAAY,GAAG;AAC3B,gBAAM,MAAM,oBAAoB,GAAG;AACnC,eAAK,QAAQ,kBAAkB,KAAK,YAAY,KAAK,OAAO,CAAC;AAC7D,iBAAO;AAAA,QACT;AACA,eAAO,KAAK,eAAe,MAAM,MAAM,EAAE,IAAI,MAAM;AACnD,YAAI,CAAC,MAAM;AACT;AAAA,QACF;AAAA,MACF;AACA,UAAI,MAAM;AACR,eAAO;AAAA,MACT;AACA,eAAS,OAAO;AAAA,IAClB;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,8BAA8B,CAAC,KAAK,SAAS;AAC3C,UAAM,EAAE,UAAU,aAAa,MAAM,QAAQ,IAAI;AAEjD,QAAI,CAAC,MAAM,QAAQ,WAAW,GAAG;AAC/B,UAAI,YAAY,QAAQ;AACtB,eAAO;AAAA,MACT;AACA,YAAM,MAAM,qBAAqB,OAAO;AACxC,aAAO,KAAK,QAAQ,kBAAkB,KAAK,YAAY,KAAK,OAAO,CAAC;AAAA,IACtE;AAEA,QAAI,YAAY,UAAU,YAAY,gBAAgB;AACpD,YAAM,MAAM,qBAAqB,OAAO;AACxC,aAAO,KAAK,QAAQ,kBAAkB,KAAK,YAAY,KAAK,OAAO,CAAC;AAAA,IACtE;AACA,QAAI,YAAY,WAAW,GAAG;AAC5B,YAAM,UAAM,0BAAY,GAAG;AAC3B,YAAM,MAAM,oBAAoB,GAAG;AACnC,aAAO,KAAK,QAAQ,kBAAkB,KAAK,YAAY,KAAK,OAAO,CAAC;AAAA,IACtE;AACA,UAAM,EAAE,KAAK,IAAI;AACjB,UAAM,EAAE,SAAS,IAAI,QAAQ,YAAY,CAAC,CAAC;AAC3C,UAAM,CAAC,MAAM,IAAI;AACjB,UAAM,CAAC,GAAG,MAAM,IAAI;AACpB,QAAI,UAAU;AACd,QAAI,YAAY,QAAQ;AACtB,gBAAU,KAAK,oBAAoB,QAAQ,MAAM,GAAG;AAAA,IAEtD,OAAO;AACL,gBAAU,KAAK,2BAA2B,QAAQ,MAAM,GAAG;AAAA,IAC7D;AACA,WAAO,UAAU,OAAO;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,2BAA2B,CAAC,KAAK,MAAM,MAAM,CAAC,MAAM;AAClD,UAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,UAAM,UAAU,iBAAiB,IAAI,IAAI;AACzC,UAAM,UAAU,oBAAI,IAAI;AACxB,YAAQ,SAAS;AAAA,MACf,KAAK,eAAe;AAClB,YAAI,uBAAuB,KAAK,MAAM,GAAG,GAAG;AAC1C,kBAAQ,IAAI,IAAI;AAAA,QAClB;AACA;AAAA,MACF;AAAA,MACA,KAAK,aAAa;AAChB,YAAI,KAAK,OAAO,SAAS;AACvB,kBAAQ,IAAI,IAAI;AAAA,QAClB;AACA;AAAA,MACF;AAAA,MACA,KAAK,gBAAgB;AACnB,YAAI,KAAK,UAAU,SAAS,OAAO,GAAG;AACpC,kBAAQ,IAAI,IAAI;AAAA,QAClB;AACA;AAAA,MACF;AAAA,MACA,KAAK,mBAAmB;AACtB,eAAO,KAAK,0BAA0B,KAAK,MAAM,GAAG;AAAA,MACtD;AAAA,MACA,KAAK,eAAe;AAClB,YAAI,kBAAkB,KAAK,MAAM,GAAG,GAAG;AACrC,kBAAQ,IAAI,IAAI;AAAA,QAClB;AACA;AAAA,MACF;AAAA;AAAA,MAEA,SAAS;AACP,YAAI;AACF,cAAI,IAAI,OAAO;AACb,kBAAM,UAAM,0BAAY,GAAG;AAC3B,iBAAK,eAAe,KAAK,GAAG;AAC5B,oBAAQ,IAAI,IAAI;AAAA,UAClB,OAAO;AACL,uCAA2B,SAAS,SAAS,GAAG;AAAA,UAClD;AAAA,QACF,SAAS,GAAG;AACV,eAAK,QAAQ,CAAC;AAAA,QAChB;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,8BAA8B,CAAC,KAAK,MAAM,MAAM,CAAC,MAAM;AACrD,UAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,QAAI,aAAa,IAAI,OAAO,GAAG;AAC7B,UAAI,eAAe;AACnB,aAAO,KAAK,0BAA0B,KAAK,MAAM,GAAG;AAAA,IACtD;AACA,UAAM,UAAU,oBAAI,IAAI;AACxB,QAAI,YAAY,UAAU,YAAY,gBAAgB;AACpD,YAAM,MAAM,KAAK,4BAA4B,KAAK,MAAM,GAAG;AAC3D,UAAI,KAAK;AACP,aAAK,oBAAoB;AACzB,gBAAQ,IAAI,GAAG;AAAA,MACjB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,iBAAiB,CAAC,KAAK,MAAM,MAAM,CAAC,MAAM;AACxC,QAAI,KAAK,aAAa,cAAc;AAClC,aAAO,KAAK,yBAAyB,KAAK,MAAM,GAAG;AAAA,IACrD;AACA,QACE,KAAK,WACL,KAAK,aAAa,0BAClB,IAAI,SAAS,mBACb;AACA,aAAO,KAAK,4BAA4B,KAAK,MAAM,GAAG;AAAA,IACxD;AACA,WAAO,oBAAI,IAAI;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,eAAe,CAAC,QAAQ,MAAM,MAAM,CAAC,MAAM;AACzC,UAAM,UAAU,KAAK,cAAc,KAAK,qBAAqB,KAAK;AAClE,QAAI,SAAS,QAAQ,IAAI,MAAM;AAC/B,QAAI,UAAU,OAAO,IAAI,IAAI,GAAG;AAC9B,YAAM,EAAE,QAAQ,IAAI,OAAO,IAAI,IAAI;AACnC,aAAO;AAAA,IACT;AACA,QAAI,YAAY;AAChB,QAAI,KAAK,aAAa,gBAAgB,UAAU,IAAI,KAAK,SAAS,GAAG;AACnE,kBAAY;AAAA,IACd;AACA,QAAI;AACJ,UAAM,IAAI,OAAO;AACjB,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,YAAM,OAAO,OAAO,CAAC;AACrB,cAAQ,KAAK,MAAM;AAAA,QACjB,KAAK;AAAA,QACL,KAAK,aAAa;AAChB,sBAAY;AACZ;AAAA,QACF;AAAA,QACA,KAAK,mBAAmB;AACtB,cAAI,gBAAgB,IAAI,KAAK,IAAI,GAAG;AAClC,wBAAY;AAAA,UACd;AACA;AAAA,QACF;AAAA,QACA,SAAS;AAAA,QAET;AAAA,MACF;AACA,aAAO,KAAK,eAAe,MAAM,MAAM,GAAG,EAAE,IAAI,IAAI;AACpD,UAAI,CAAC,MAAM;AACT;AAAA,MACF;AAAA,IACF;AACA,QAAI,WAAW;AACb,UAAI,CAAC,QAAQ;AACX,iBAAS,oBAAI,QAAQ;AAAA,MACvB;AACA,aAAO,IAAI,MAAM;AAAA,QACf,SAAS;AAAA,MACX,CAAC;AACD,cAAQ,IAAI,QAAQ,MAAM;AAAA,IAC5B;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,0BAA0B,CAAC,UAAU,QAAQ,MAAM,CAAC,MAAM;AACxD,UAAM,SAAS,KAAK,kBAAkB,QAAQ;AAC9C,iBAAa,UAAU,MAAM;AAC7B,QAAI,cAAc,OAAO,WAAW;AACpC,UAAM,QAAQ,oBAAI,IAAI;AACtB,WAAO,aAAa;AAClB,UAAI,KAAK,aAAa,QAAQ,aAAa,GAAG,GAAG;AAC/C,cAAM,IAAI,WAAW;AAAA,MACvB;AACA,oBAAc,OAAO,SAAS;AAAA,IAChC;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,uBAAuB,CAAC,QAAQ,UAAU,MAAM,CAAC,MAAM;AACrD,UAAM,CAAC,MAAM,GAAG,YAAY,IAAI;AAChC,UAAM,EAAE,MAAM,SAAS,IAAI;AAC3B,YAAQ,UAAU;AAAA,MAChB,KAAK,aAAa;AAChB,cAAM,uBACJ,CAAC,KAAK,WACN,SAAS,aAAa,gBACtB,KAAK,MAAM,aAAa;AAC1B,YAAI,sBAAsB;AACxB,gBAAM,WAAW,iBAAiB,KAAK,IAAI;AAC3C,gBAAM,QAAQ,oBAAI,IAAI;AACtB,gBAAM,YAAY,KAAK,MAAM,eAAe,QAAQ;AACpD,cACE,aACA,cAAc,YACd,SAAS,SAAS,SAAS,GAC3B;AACA,kBAAM,qBAAqB,aAAa,SAAS;AACjD,gBACE,CAAC,sBACD,KAAK,aAAa,cAAc,WAAW,GAAG,GAC9C;AACA,oBAAM,IAAI,SAAS;AAAA,YACrB;AAAA,UACF;AACA,iBAAO;AAAA,QACT;AAEA,eAAO,KAAK,wBAAwB,UAAU,QAAQ,GAAG;AAAA,MAC3D;AAAA,MACA,KAAK,qBAAqB;AACxB,cAAM,WAAW,iBAAiB,KAAK,IAAI;AAC3C,mCAA2B,UAAU,UAAU,GAAG;AAClD,eAAO,oBAAI,IAAI;AAAA,MACjB;AAAA,MACA,SAAS;AACP,eAAO,KAAK,wBAAwB,UAAU,QAAQ,GAAG;AAAA,MAC3D;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,6BAA6B,CAAC,MAAM,MAAM,MAAM,CAAC,MAAM;AACrD,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,EAAE,WAAW,IAAI;AACvB,UAAM,EAAE,IAAI,IAAI;AAChB,QAAI,QAAQ,UAAU;AACpB,aAAO,KAAK,qBAAqB,QAAQ,MAAM,GAAG;AAAA,IACpD;AAEA,UAAM,YAAY,CAAC;AACnB,QAAI,UAAU;AACd,WAAO,SAAS;AACd,UAAI,KAAK,aAAa,QAAQ,SAAS,GAAG,GAAG;AAC3C,kBAAU,KAAK,OAAO;AAAA,MACxB;AACA,gBAAU,QAAQ;AAAA,IACpB;AACA,QAAI,UAAU,QAAQ;AAEpB,aAAO,IAAI,IAAI,UAAU,QAAQ,CAAC;AAAA,IACpC;AACA,WAAO,oBAAI,IAAI;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,wBAAwB,CAAC,MAAM,MAAM,MAAM,CAAC,MAAM;AAChD,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,EAAE,IAAI,IAAI;AAChB,UAAM,EAAE,WAAW,IAAI;AACvB,UAAM,UAAU,oBAAI,IAAI;AACxB,QAAI,QAAQ,UAAU;AACpB,UAAI,UAAU,KAAK;AACnB,aAAO,SAAS;AACd,YAAI,KAAK,aAAa,QAAQ,SAAS,GAAG,GAAG;AAC3C,kBAAQ,IAAI,OAAO;AAAA,QACrB;AACA,kBAAU,QAAQ;AAAA,MACpB;AAAA,IACF,OAAO;AAEL,UAAI,cAAc,KAAK,aAAa,QAAQ,YAAY,GAAG,GAAG;AAC5D,gBAAQ,IAAI,UAAU;AAAA,MACxB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,kCAAkC,CAAC,MAAM,MAAM,MAAM,CAAC,MAAM;AAC1D,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,EAAE,IAAI,IAAI;AAChB,UAAM,UAAU,oBAAI,IAAI;AACxB,UAAM,UACJ,QAAQ,WAAW,KAAK,qBAAqB,KAAK;AACpD,QAAI,WAAW,KAAK,aAAa,QAAQ,SAAS,GAAG,GAAG;AACtD,cAAQ,IAAI,OAAO;AAAA,IACrB;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,iCAAiC,CAAC,MAAM,MAAM,MAAM,CAAC,MAAM;AACzD,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,EAAE,IAAI,IAAI;AAChB,UAAM,UAAU,oBAAI,IAAI;AACxB,QAAI,UACF,QAAQ,WAAW,KAAK,qBAAqB,KAAK;AACpD,WAAO,SAAS;AACd,UAAI,KAAK,aAAa,QAAQ,SAAS,GAAG,GAAG;AAC3C,gBAAQ,IAAI,OAAO;AAAA,MACrB;AACA,gBACE,QAAQ,WACJ,QAAQ,qBACR,QAAQ;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,mBAAmB,CAAC,MAAM,MAAM,MAAM,CAAC,MAAM;AAC3C,UAAM;AAAA,MACJ,OAAO,EAAE,MAAM,UAAU;AAAA,IAC3B,IAAI;AACJ,YAAQ,WAAW;AAAA,MACjB,KAAK,KAAK;AACR,eAAO,KAAK,gCAAgC,MAAM,MAAM,GAAG;AAAA,MAC7D;AAAA,MACA,KAAK,KAAK;AACR,eAAO,KAAK,+BAA+B,MAAM,MAAM,GAAG;AAAA,MAC5D;AAAA,MACA,KAAK,KAAK;AACR,eAAO,KAAK,sBAAsB,MAAM,MAAM,GAAG;AAAA,MACnD;AAAA,MACA,KAAK;AAAA,MACL,SAAS;AACP,eAAO,KAAK,2BAA2B,MAAM,MAAM,GAAG;AAAA,MACxD;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,2BAA2B,CAAC,QAAQ,QAAQ,YAAY;AACtD,UAAM,EAAE,cAAc,OAAO,WAAW,WAAW,IAAI;AACvD,UAAM,iBAAiB,CAAC;AACxB,QAAI,cAAc,aAAa,WAAW,QAAQ,CAAC,CAAC,KAAK;AACzD,QAAI,CAAC,aAAa;AAChB,aAAO,CAAC;AAAA,IACV;AAEA,QAAI,YAAY,aAAa,cAAc;AACzC,oBAAc,OAAO,SAAS;AAAA,IAChC,WAAW,gBAAgB,aAAa,gBAAgB,KAAK,OAAO;AAClE,oBAAc,OAAO,SAAS;AAAA,IAChC;AACA,UAAM,WAAW;AAAA,MACf,MAAM,KAAK;AAAA,IACb;AACA,WAAO,aAAa;AAElB,UAAI,cAAc;AAChB,YAAI,gBAAgB,cAAc;AAChC;AAAA,QACF,WACE,eAAe,cACf,CAAC,aAAa,SAAS,WAAW,GAClC;AACA;AAAA,QACF;AAAA,MACF;AACA,UACE,KAAK,aAAa,QAAQ,aAAa,QAAQ,KAC/C,gBAAgB,KAAK,OACrB;AACA,uBAAe,KAAK,WAAW;AAE/B,YAAI,eAAe,YAAY;AAC7B;AAAA,QACF;AAAA,MACF;AACA,oBAAc,OAAO,SAAS;AAAA,IAChC;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,eAAe,CAAC,QAAQ,MAAM,MAAM,CAAC,MAAM;AACzC,UAAM,EAAE,OAAO,WAAW,IAAI;AAC9B,QAAI,CAAC,KAAK,aAAa;AACrB,WAAK,cAAc,KAAK,kBAAkB,KAAK,KAAK;AAAA,IACtD;AACA,WAAO,KAAK,yBAAyB,KAAK,aAAa,QAAQ;AAAA,MAC7D;AAAA,MACA;AAAA,MACA,cAAc,KAAK;AAAA,MACnB,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,kBAAkB,CAAC,QAAQ,MAAM,MAAM,CAAC,MAAM;AAC5C,UAAM,EAAE,SAAS,GAAG,cAAc,IAAI;AACtC,QAAI,SAAS;AACX,YAAM,eAAe,KAAK,aAAa,QAAQ,KAAK,OAAO,GAAG;AAC9D,UAAI,aAAa,QAAQ;AACvB,eAAO;AAAA,MACT;AAAA,IACF;AACA,QAAI,CAAC,KAAK,aAAa;AACrB,WAAK,cAAc,KAAK,kBAAkB,KAAK,KAAK;AAAA,IACtD;AACA,WAAO,KAAK,yBAAyB,KAAK,aAAa,QAAQ;AAAA,MAC7D,WAAW;AAAA,MACX,GAAG;AAAA,IACL,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,aAAa,CAAC,QAAQ,QAAQ,UAAU;AACtC,UAAM,UAAU,EAAE,OAAO,MAAM,KAAK,MAAM;AAC1C,UAAM,UAAU,KAAK,aAAa,QAAQ,KAAK,OAAO,OAAO;AAC7D,UAAM,QAAQ,UAAU,CAAC,KAAK,KAAK,IAAI,CAAC;AACxC,WAAO,CAAC,OAAO,SAAS,KAAK,cAAc;AAAA,EAC7C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,cAAc,CAAC,QAAQ,QAAQ;AAC7B,UAAM,EAAE,QAAQ,IAAI;AACpB,UAAM,QAAQ,CAAC;AACf,UAAM,UAAU,EAAE,MAAM,KAAK,MAAM;AACnC,UAAM,cAAc,KAAK,aAAa,QAAQ,KAAK,OAAO,OAAO;AACjE,QAAI,aAAa;AACf,YAAM,KAAK,KAAK,KAAK;AAAA,IACvB;AACA,QAAI,CAAC,eAAe,SAAS;AAC3B,UAAI,cAAc,KAAK,MAAM;AAC7B,aAAO,aAAa;AAClB,YAAI,KAAK,aAAa,QAAQ,aAAa,OAAO,GAAG;AACnD,gBAAM,KAAK,WAAW;AAAA,QACxB;AACA,sBAAc,YAAY;AAAA,MAC5B;AAAA,IACF;AACA,UAAM,WAAW,MAAM,SAAS;AAChC,WAAO,CAAC,OAAO,QAAQ;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,kCAAkC,CAAC,MAAM,cAAc,eAAe;AACpE,QAAI,QAAQ,CAAC;AACb,QAAI,WAAW;AACf,QAAI,eAAe,eAAe,KAAK,QAAQ;AAC7C,YAAM,UAAM,0BAAY,IAAI;AAC5B,WAAK,eAAe,KAAK,GAAG;AAC5B,UAAI,aAAa,QAAQ;AACvB,SAAC,OAAO,QAAQ,IAAI,KAAK,WAAW,cAAc,KAAK,MAAM;AAAA,MAC/D,OAAO;AACL,cAAM,KAAK,KAAK,KAAK;AACrB,mBAAW;AAAA,MACb;AAAA,IACF,OAAO;AACL,iCAA2B,KAAK,MAAM,KAAK,MAAM,EAAE,MAAM,KAAK,MAAM,CAAC;AAAA,IACvE;AACA,WAAO,EAAE,OAAO,UAAU,SAAS,MAAM;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,uBAAuB,CAAC,MAAM,YAAY,QAAQ;AAChD,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,CAAC,MAAM,GAAG,YAAY,IAAI;AAChC,UAAM,EAAE,SAAS,QAAQ,IAAI;AAC7B,QAAI,QAAQ,CAAC;AACb,QAAI,WAAW;AACf,QAAI,eAAe,aAAa;AAC9B,OAAC,OAAO,QAAQ,IAAI,KAAK,WAAW,MAAM;AAAA,IAC5C,WAAW,eAAe,eAAe;AACvC,OAAC,OAAO,QAAQ,IAAI,KAAK,YAAY,QAAQ,EAAE,QAAQ,CAAC;AAAA,IAC1D,WACE,eAAe,gBACf,KAAK,MAAM,aAAa,cACxB;AACA,YAAM,OAAO,KAAK,MAAM,eAAe,KAAK,IAAI;AAChD,UAAI,MAAM;AACR,YAAI,aAAa,QAAQ;AACvB,cAAI,KAAK,aAAa,cAAc,MAAM,EAAE,MAAM,KAAK,MAAM,CAAC,GAAG;AAC/D,kBAAM,KAAK,IAAI;AACf,uBAAW;AAAA,UACb;AAAA,QACF,OAAO;AACL,gBAAM,KAAK,IAAI;AACf,qBAAW;AAAA,QACb;AAAA,MACF;AAAA,IACF,OAAO;AACL,cAAQ,KAAK,gBAAgB,QAAQ,KAAK,OAAO,EAAE,SAAS,WAAW,CAAC;AACxE,iBAAW,MAAM,SAAS;AAAA,IAC5B;AACA,WAAO,EAAE,OAAO,UAAU,SAAS,MAAM;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,0BAA0B,CAAC,QAAQ,YAAY,QAAQ;AACrD,UAAM,EAAE,SAAS,QAAQ,IAAI;AAC7B,QAAI,QAAQ,CAAC;AACb,QAAI,WAAW;AACf,QAAI,eAAe,aAAa;AAC9B,OAAC,OAAO,QAAQ,IAAI,KAAK,WAAW,MAAM;AAAA,IAC5C,WAAW,eAAe,eAAe;AACvC,OAAC,OAAO,QAAQ,IAAI,KAAK,YAAY,QAAQ,EAAE,QAAQ,CAAC;AAAA,IAC1D,OAAO;AACL,cAAQ,KAAK,gBAAgB,QAAQ,KAAK,OAAO,EAAE,SAAS,WAAW,CAAC;AACxE,iBAAW,MAAM,SAAS;AAAA,IAC5B;AACA,WAAO,EAAE,OAAO,UAAU,SAAS,MAAM;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,yBAAyB,CAAC,QAAQ,YAAY,QAAQ;AACpD,UAAM,EAAE,SAAS,QAAQ,IAAI;AAC7B,QAAI,QAAQ,CAAC;AACb,QAAI,WAAW;AACf,QAAI,eAAe,aAAa;AAC9B,OAAC,OAAO,QAAQ,IAAI,KAAK,WAAW,MAAM;AAAA,IAC5C,WAAW,eAAe,eAAe;AACvC,OAAC,OAAO,QAAQ,IAAI,KAAK,YAAY,QAAQ,EAAE,QAAQ,CAAC;AAAA,IAC1D,OAAO;AACL,cAAQ,KAAK,gBAAgB,QAAQ,KAAK,OAAO,EAAE,SAAS,WAAW,CAAC;AACxE,iBAAW,MAAM,SAAS;AAAA,IAC5B;AACA,WAAO,EAAE,OAAO,UAAU,SAAS,MAAM;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,0BAA0B,CAAC,MAAM,YAAY,QAAQ;AACnD,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,CAAC,MAAM,GAAG,YAAY,IAAI;AAChC,UAAM,EAAE,SAAS,QAAQ,IAAI;AAC7B,QAAI,QAAQ,CAAC;AACb,QAAI,WAAW;AACf,QAAI,UAAU;AACd,QAAI,eAAe,iBAAiB,oBAAoB,KAAK,KAAK,IAAI,GAAG;AACvE,UAAI,aAAa;AACjB,UAAI,KAAK,WAAW,KAAK,MAAM,aAAa,wBAAwB;AAClE,qBAAa,KAAK,4BAA4B,MAAM,KAAK,KAAK;AAAA,MAChE,WAAW,aAAa,UAAU,KAAK,MAAM,aAAa,cAAc;AACtE,qBAAa,KAAK;AAAA,UAChB;AAAA,UACA,KAAK,MAAM;AAAA,QACb;AAAA,MACF;AACA,UAAI,YAAY;AACd,YAAI,OAAO;AACX,cAAM,IAAI,aAAa;AACvB,iBAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,gBAAM,aAAa,aAAa,CAAC;AACjC,kBAAQ,WAAW,MAAM;AAAA,YACvB,KAAK;AAAA,YACL,KAAK,gBAAgB;AACnB,oBAAM,cAAc,KAAK;AAAA,gBACvB;AAAA,gBACA;AAAA,cACF;AACA,qBAAO,gBAAgB;AACvB;AAAA,YACF;AAAA,YACA,KAAK,OAAO;AACV,qBAAO,KAAK;AAAA,gBACV;AAAA,gBACA;AAAA,gBACA,CAAC;AAAA,cACH,EAAE,IAAI,UAAU;AAChB;AAAA,YACF;AAAA,YACA,SAAS;AACP,qBAAO;AAAA,YACT;AAAA,UACF;AACA,cAAI,CAAC,MAAM;AACT;AAAA,UACF;AAAA,QACF;AACA,YAAI,MAAM;AACR,gBAAM,KAAK,UAAU;AACrB,qBAAW;AAAA,QACb;AAAA,MACF;AAAA,IACF,WAAW,eAAe,aAAa;AACrC,OAAC,OAAO,QAAQ,IAAI,KAAK,WAAW,MAAM;AAAA,IAC5C,WAAW,eAAe,eAAe;AACvC,OAAC,OAAO,QAAQ,IAAI,KAAK,YAAY,QAAQ,EAAE,QAAQ,CAAC;AAAA,IAC1D,WAAW,eAAe,cAAc;AACtC,cAAQ,KAAK,gBAAgB,QAAQ,KAAK,OAAO,EAAE,SAAS,WAAW,CAAC;AACxE,iBAAW,MAAM,SAAS;AAAA,IAC5B,OAAO;AACL,gBAAU;AAAA,IACZ;AACA,WAAO,EAAE,OAAO,UAAU,QAAQ;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,kBAAkB,CAAC,MAAM,YAAY,MAAM,CAAC,MAAM;AAChD,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,CAAC,MAAM,GAAG,YAAY,IAAI;AAChC,UAAM,EAAE,UAAU,OAAO,MAAM,SAAS,IAAI;AAC5C,UAAM,UACJ,QAAQ,YACR,KAAK,MAAM,aAAa,gBACxB,KAAK,UAAU,KAAK;AACtB,QAAI;AACJ,YAAQ,KAAK,MAAM;AAAA,MACjB,KAAK,qBAAqB;AACxB,iBAAS,KAAK;AAAA,UACZ;AAAA,UACA;AAAA,UACA;AAAA,QACF;AACA;AAAA,MACF;AAAA,MACA,KAAK,aAAa;AAChB,iBAAS,KAAK,qBAAqB,MAAM,YAAY;AAAA,UACnD;AAAA,UACA;AAAA,QACF,CAAC;AACD;AAAA,MACF;AAAA,MACA,KAAK,gBAAgB;AACnB,iBAAS,KAAK,wBAAwB,QAAQ,YAAY;AAAA,UACxD;AAAA,UACA;AAAA,QACF,CAAC;AACD;AAAA,MACF;AAAA,MACA,KAAK,eAAe;AAClB,iBAAS,KAAK,uBAAuB,QAAQ,YAAY;AAAA,UACvD;AAAA,UACA;AAAA,QACF,CAAC;AACD;AAAA,MACF;AAAA,MACA,SAAS;AACP,iBAAS,KAAK,wBAAwB,MAAM,YAAY;AAAA,UACtD;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AACA,WAAO;AAAA,MACL,UAAU,aAAa,SAAS;AAAA,MAChC,UAAU,OAAO;AAAA,MACjB,OAAO,OAAO;AAAA,MACd,SAAS,OAAO;AAAA,IAClB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,8BAA8B,CAAC,QAAQ,eAAe;AACpD,UAAM,YAAY,OAAO;AACzB,UAAM,YAAY,OAAO,CAAC;AAC1B,UAAM,WAAW,OAAO,YAAY,CAAC;AACrC,QAAI,cAAc,GAAG;AACnB,aAAO,EAAE,KAAK,UAAU,MAAM,UAAU;AAAA,IAC1C;AAEA,UAAM;AAAA,MACJ,QAAQ,CAAC,EAAE,MAAM,WAAW,MAAM,UAAU,CAAC;AAAA,IAC/C,IAAI;AACJ,UAAM;AAAA,MACJ,QAAQ,CAAC,EAAE,MAAM,UAAU,MAAM,SAAS,CAAC;AAAA,IAC7C,IAAI;AACJ,UAAM,EAAE,OAAO,WAAW,IAAI;AAC9B,QACE,KAAK,UAAU,SAAS,QAAQ,KAChC,aAAa,uBACb,aAAa,aACb;AACA,aAAO,EAAE,KAAK,UAAU,MAAM,SAAS;AAAA,IACzC;AACA,QAAI,cAAc,aAAa;AAC7B,aAAO,EAAE,KAAK,UAAU,MAAM,UAAU;AAAA,IAC1C;AACA,QAAI,cAAc,OAAO,cAAc,eAAe;AACpD,aAAO,EAAE,KAAK,UAAU,MAAM,SAAS;AAAA,IACzC;AACA,QAAI,aAAa,OAAO,aAAa,eAAe;AAClD,aAAO,EAAE,KAAK,UAAU,MAAM,UAAU;AAAA,IAC1C;AACA,QAAI,cAAc,GAAG;AACnB,UAAI,eAAe,cAAc;AAC/B,eAAO,EAAE,KAAK,UAAU,MAAM,SAAS;AAAA,MACzC;AACA,YAAM,EAAE,MAAM,UAAU,IAAI;AAC5B,UAAI,cAAc,OAAO,cAAc,KAAK;AAC1C,eAAO,EAAE,KAAK,UAAU,MAAM,SAAS;AAAA,MACzC;AAAA,IACF,WAAW,YAAY,KAAK,KAAK,WAAW,eAAe,cAAc;AACvE,UAAI,aAAa,eAAe;AAC9B,eAAO,EAAE,KAAK,UAAU,MAAM,SAAS;AAAA,MACzC;AACA,UAAI,sBAAsB;AAC1B,iBAAW,EAAE,MAAM,KAAK,QAAQ;AAC9B,YAAI,OAAO;AACT,gBAAM,EAAE,MAAM,UAAU,IAAI;AAC5B,gCAAsB,cAAc,OAAO,cAAc;AACzD,cAAI,CAAC,qBAAqB;AACxB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACA,UAAI,qBAAqB;AACvB,eAAO,EAAE,KAAK,UAAU,MAAM,SAAS;AAAA,MACzC;AAAA,IACF;AAEA,WAAO,EAAE,KAAK,UAAU,MAAM,UAAU;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,uBAAuB,kBAAgB;AACrC,QAAI,CAAC,aAAa,MAAM;AACtB;AAAA,IACF;AACA,QAAI,CAAC,KAAK,aAAa;AACrB,WAAK,cAAc,KAAK,kBAAkB,KAAK,KAAK;AAAA,IACtD;AACA,UAAM,SAAS,KAAK;AACpB,QAAI,OAAO,KAAK;AAChB,QAAI,KAAK,SAAS;AAChB,aAAO,KAAK;AAAA,IACd;AACA,QAAI,WAAW,aAAa,MAAM,MAAM;AACxC,WAAO,UAAU;AACf,YAAM,gBACJ,KAAK,MAAM,aAAa,gBACxB,aAAa,KAAK,SAClB,KAAK,MAAM,SAAS,QAAQ;AAC9B,UAAI,eAAe;AACjB,mBAAW,eAAe,cAAc;AACtC,gBAAM,EAAE,OAAO,IAAI,YAAY,IAAI,MAAM;AACzC,cAAI,KAAK,aAAa,QAAQ,UAAU,EAAE,MAAM,KAAK,MAAM,CAAC,GAAG;AAC7D,kBAAM,QAAQ,YAAY,IAAI,OAAO;AACrC,iBAAK,KAAK,KAAK,EAAE,WAAW;AAC5B,iBAAK,KAAK,KAAK,EAAE,OAAO;AACxB,iBAAK,OAAO,KAAK,EAAE,KAAK,QAAQ;AAAA,UAClC;AAAA,QACF;AAAA,MACF,WAAW,KAAK,SAAS;AACvB;AAAA,MACF;AACA,iBAAW,OAAO,SAAS;AAAA,IAC7B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,gBAAgB,gBAAc;AAC5B,UAAM,MAAM,KAAK,KAAK,OAAO;AAC7B,QAAI,eAAe,cAAc,eAAe,cAAc;AAC5D,YAAM,eAAe,oBAAI,IAAI;AAC7B,UAAI,IAAI;AACR,iBAAW,EAAE,OAAO,KAAK,KAAK;AAC5B,cAAM,UAAU,OAAO,SAAS;AAChC,cAAM,EAAE,KAAK,KAAK,IAAI,KAAK;AAAA,UACzB;AAAA,UACA;AAAA,QACF;AACA,cAAM,EAAE,UAAU,UAAU,OAAO,QAAQ,IAAI,KAAK;AAAA,UAClD;AAAA,UACA;AAAA,UACA,EAAE,SAAS,IAAI;AAAA,QACjB;AACA,YAAI,MAAM,QAAQ;AAChB,eAAK,KAAK,CAAC,EAAE,OAAO;AACpB,eAAK,OAAO,CAAC,IAAI;AAAA,QACnB,WAAW,SAAS;AAClB,uBAAa;AAAA,YACX,oBAAI,IAAI;AAAA,cACN,CAAC,SAAS,CAAC;AAAA,cACX,CAAC,QAAQ,IAAI;AAAA,YACf,CAAC;AAAA,UACH;AAAA,QACF;AACA,aAAK,KAAK,CAAC,EAAE,MAAM;AACnB,aAAK,KAAK,CAAC,EAAE,WAAW,YAAY,CAAC;AACrC;AAAA,MACF;AACA,WAAK,qBAAqB,YAAY;AAAA,IACxC,OAAO;AACL,UAAI,IAAI;AACR,iBAAW,EAAE,OAAO,KAAK,KAAK;AAC5B,cAAM,OAAO,OAAO,OAAO,SAAS,CAAC;AACrC,cAAM,UAAU,OAAO,SAAS;AAChC,cAAM,MAAM;AACZ,cAAM,EAAE,UAAU,UAAU,MAAM,IAAI,KAAK;AAAA,UACzC;AAAA,UACA;AAAA,UACA,EAAE,SAAS,IAAI;AAAA,QACjB;AACA,YAAI,MAAM,QAAQ;AAChB,eAAK,KAAK,CAAC,EAAE,OAAO;AACpB,eAAK,OAAO,CAAC,IAAI;AAAA,QACnB;AACA,aAAK,KAAK,CAAC,EAAE,MAAM;AACnB,aAAK,KAAK,CAAC,EAAE,WAAW,YAAY,CAAC;AACrC;AAAA,MACF;AAAA,IACF;AACA,WAAO,CAAC,KAAK,MAAM,KAAK,MAAM;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,oBAAoB,CAAC,MAAM,OAAO,QAAQ;AACxC,UAAM,MAAM,CAAC;AACb,UAAM,UAAU;AAAA,MACd;AAAA,MACA,MAAM,KAAK;AAAA,IACb;AACA,eAAW,QAAQ,OAAO;AACxB,YAAM,UAAU,KAAK,iBAAiB,MAAM,MAAM,OAAO;AACzD,UAAI,QAAQ,MAAM;AAChB,YAAI,KAAK,GAAG,OAAO;AAAA,MACrB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,iBAAiB,CAAC,QAAQ,OAAO,QAAQ;AACvC,UAAM,EAAE,OAAO,MAAM,IAAI;AACzB,UAAM,EAAE,OAAO,WAAW,OAAO,IAAI,OAAO,KAAK;AACjD,UAAM,OAAO;AAAA,MACX;AAAA,MACA;AAAA,IACF;AACA,UAAM,YAAY,IAAI,IAAI,KAAK,kBAAkB,MAAM,OAAO,QAAQ,CAAC;AACvE,QAAI,UAAU,MAAM;AAClB,UAAI,UAAU,OAAO,SAAS,GAAG;AAC/B,cAAM,CAAC,QAAQ,IAAI,UAAU,SAAS;AACtC,eAAO;AAAA,MACT;AACA,aAAO,KAAK,eAAe,QAAQ,WAAW;AAAA,QAC5C,OAAO;AAAA,QACP,OAAO,QAAQ;AAAA,MACjB,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,iBAAiB,CAAC,QAAQ,MAAM,QAAQ;AACtC,UAAM,EAAE,MAAM,IAAI;AAClB,UAAM,OAAO,OAAO,KAAK;AACzB,UAAM,QAAQ,oBAAI,IAAI,CAAC,IAAI,CAAC;AAC5B,UAAM,YAAY,IAAI,IAAI,KAAK,kBAAkB,MAAM,OAAO,QAAQ,CAAC;AACvE,QAAI,UAAU,MAAM;AAClB,UAAI,UAAU,GAAG;AACf,eAAO;AAAA,MACT;AACA,UAAI;AACJ,iBAAW,YAAY,WAAW;AAChC,kBAAU,KAAK,eAAe,QAAQ,UAAU;AAAA,UAC9C,OAAO,QAAQ;AAAA,QACjB,CAAC;AACD,YAAI,SAAS;AACX;AAAA,QACF;AAAA,MACF;AACA,UAAI,SAAS;AACX,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,2BAA2B,CAAC,QAAQ,YAAY,QAAQ;AACtD,UAAM,eAAe,oBAAI,IAAI;AAC7B,UAAM,YAAY,OAAO;AACzB,UAAM,YAAY,YAAY;AAE9B,QAAI,QAAQ,UAAU;AACpB,YAAM,EAAE,OAAO,WAAW,IAAI,OAAO,CAAC;AACtC,iBAAW,QAAQ,YAAY;AAC7B,YAAI,QAAQ;AACZ,YAAI,YAAY,oBAAI,IAAI,CAAC,IAAI,CAAC;AAC9B,iBAAS,IAAI,GAAG,IAAI,WAAW,KAAK;AAClC,gBAAM,EAAE,OAAO,WAAW,OAAO,IAAI,OAAO,CAAC;AAC7C,gBAAM,OAAO,EAAE,OAAO,OAAO;AAC7B,gBAAM,WAAW,KAAK,kBAAkB,MAAM,WAAW,GAAG;AAC5D,cAAI,SAAS,QAAQ;AACnB,gBAAI,MAAM,WAAW;AACnB,yBAAW,YAAY,UAAU;AAC/B,6BAAa,IAAI,QAAQ;AAAA,cAC3B;AAAA,YACF;AACA,oBAAQ;AACR,wBAAY,IAAI,IAAI,QAAQ;AAAA,UAC9B,OAAO;AAEL,sBAAU,MAAM;AAChB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IAEF,OAAO;AACL,iBAAW,QAAQ,YAAY;AAC7B,YAAI,YAAY,oBAAI,IAAI,CAAC,IAAI,CAAC;AAC9B,iBAAS,IAAI,YAAY,GAAG,KAAK,GAAG,KAAK;AACvC,gBAAM,OAAO,OAAO,CAAC;AACrB,gBAAM,WAAW,KAAK,kBAAkB,MAAM,WAAW,GAAG;AAC5D,cAAI,SAAS,QAAQ;AAEnB,gBAAI,MAAM,GAAG;AACX,2BAAa,IAAI,IAAI;AAAA,YACvB;AACA,wBAAY,IAAI,IAAI,QAAQ;AAAA,UAC9B,OAAO;AAEL,sBAAU,MAAM;AAChB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,6BAA6B,CAAC,QAAQ,YAAY,KAAK,eAAe;AACpE,UAAM,YAAY,OAAO;AACzB,UAAM,YAAY,YAAY;AAE9B,QAAI,QAAQ,UAAU;AACpB,YAAM,EAAE,OAAO,WAAW,IAAI,OAAO,CAAC;AACtC,iBAAW,QAAQ,YAAY;AAC7B,cAAM,cAAc,KAAK,eAAe,QAAQ,oBAAI,IAAI,CAAC,IAAI,CAAC,GAAG;AAAA,UAC/D,OAAO;AAAA,UACP,OAAO;AAAA,QACT,CAAC;AACD,YAAI,aAAa;AACf,cAAI,KAAK,MAAM,aAAa,cAAc;AACxC,gBACE,gBAAgB,KAAK,SACrB,KAAK,MAAM,SAAS,WAAW,GAC/B;AACA,qBAAO;AAAA,YACT;AAAA,UACF,OAAO;AACL,mBAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF;AAEA,YAAM,EAAE,QAAQ,YAAY,IAAI,OAAO,CAAC;AACxC,YAAM,CAAC,SAAS,IAAI;AACpB,UAAI,KAAK,MAAM,SAAS,SAAS,GAAG;AAClC,YAAI,CAAC,OAAO,IAAI,KAAK,gBAAgB,aAAa,WAAW;AAAA,UAC3D;AAAA,QACF,CAAC;AACD,eAAO,SAAS;AACd,gBAAM,cAAc,KAAK,eAAe,QAAQ,oBAAI,IAAI,CAAC,OAAO,CAAC,GAAG;AAAA,YAClE,OAAO;AAAA,YACP,OAAO;AAAA,UACT,CAAC;AACD,cAAI,aAAa;AACf,gBAAI,KAAK,MAAM,aAAa,cAAc;AACxC,kBACE,gBAAgB,KAAK,SACrB,KAAK,MAAM,SAAS,WAAW,GAC/B;AACA,uBAAO;AAAA,cACT;AAAA,YACF,OAAO;AACL,qBAAO;AAAA,YACT;AAAA,UACF;AACA,WAAC,OAAO,IAAI,KAAK,gBAAgB,aAAa,SAAS;AAAA,YACrD;AAAA,YACA,OAAO;AAAA,UACT,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IAEF,OAAO;AACL,iBAAW,QAAQ,YAAY;AAC7B,cAAM,cAAc,KAAK,eAAe,QAAQ,MAAM;AAAA,UACpD,OAAO,YAAY;AAAA,QACrB,CAAC;AACD,YAAI,aAAa;AACf,iBAAO;AAAA,QACT;AAAA,MACF;AAEA,UAAI,eAAe,cAAc;AAC/B,cAAM,EAAE,QAAQ,YAAY,IAAI,OAAO,SAAS;AAChD,cAAM,CAAC,SAAS,IAAI;AACpB,YAAI,CAAC,OAAO,IAAI,KAAK,gBAAgB,aAAa,WAAW;AAAA,UAC3D;AAAA,QACF,CAAC;AACD,eAAO,SAAS;AACd,gBAAM,cAAc,KAAK,eAAe,QAAQ,SAAS;AAAA,YACvD,OAAO,YAAY;AAAA,UACrB,CAAC;AACD,cAAI,aAAa;AACf,mBAAO;AAAA,UACT;AACA,WAAC,OAAO,IAAI,KAAK,gBAAgB,aAAa,SAAS;AAAA,YACrD;AAAA,YACA,OAAO;AAAA,UACT,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,gBAAc;AACnB,UAAM,CAAC,CAAC,GAAG,QAAQ,GAAG,cAAc,IAAI,KAAK,cAAc,UAAU;AACrE,UAAM,IAAI,SAAS;AACnB,QAAI,OACF,IAAI,KAAK,eAAe,cAAc,KAAK,UAAU,SAAS,QAAQ;AACxE,QAAI,QAAQ,oBAAI,IAAI;AACpB,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,YAAM,EAAE,QAAQ,KAAK,MAAAC,MAAK,IAAI,SAAS,CAAC;AACxC,UAAI,CAAC,OAAO,UAAU,CAACA,OAAM;AAC3B;AAAA,MACF;AACA,YAAM,aAAa,eAAe,CAAC;AACnC,YAAM,YAAY,OAAO,SAAS;AAElC,UAAI,cAAc,GAAG;AACnB,aACG,eAAe,cAAc,eAAe,iBAC7C,KAAK,MAAM,aAAa,cACxB;AACA,qBAAW,QAAQ,YAAY;AAC7B,gBAAI,SAAS,KAAK,SAAS,KAAK,MAAM,SAAS,IAAI,GAAG;AACpD,oBAAM,IAAI,IAAI;AACd,kBAAI,eAAe,cAAc;AAC/B;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,QACF,WAAW,eAAe,YAAY;AACpC,cAAI,MAAM,MAAM;AACd,uBAAW,QAAQ,YAAY;AAC7B,oBAAM,IAAI,IAAI;AAAA,YAChB;AACA,mBAAO;AAAA,UACT,OAAO;AACL,oBAAQ,IAAI,IAAI,UAAU;AAAA,UAC5B;AAAA,QACF,OAAO;AACL,cAAI,WAAW,QAAQ;AACrB,kBAAM,IAAI,WAAW,CAAC,CAAC;AAAA,UACzB;AAAA,QACF;AAAA,MAEF,OAAO;AACL,YAAI,eAAe,YAAY;AAC7B,gBAAM,WAAW,KAAK;AAAA,YACpB;AAAA,YACA;AAAA,YACA;AAAA,UACF;AACA,cAAI,MAAM,MAAM;AACd,uBAAW,WAAW,UAAU;AAC9B,oBAAM,IAAI,OAAO;AAAA,YACnB;AACA,mBAAO;AAAA,UACT,OAAO;AACL,oBAAQ;AAAA,UACV;AAAA,QACF,OAAO;AACL,gBAAM,cAAc,KAAK;AAAA,YACvB;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AACA,cAAI,aAAa;AACf,kBAAM,IAAI,WAAW;AAAA,UACvB;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,QAAI,KAAK,QAAQ;AACf,YAAM,QAAQ,CAAC,CAAC,MAAM;AACtB,UAAI;AACJ,UAAI,KAAK,eAAe,QAAQ;AAC9B,wBAAgB,KAAK,eAAe,KAAK,EAAE;AAAA,MAC7C,OAAO;AACL,wBAAgB;AAAA,MAClB;AACA,aAAO,EAAE,OAAO,cAAc;AAAA,IAChC;AACA,QAAI,eAAe,gBAAgB,eAAe,YAAY;AAC5D,YAAM,OAAO,KAAK,KAAK;AAAA,IACzB;AACA,SAAK,QAAQ,eAAe,iBAAiB,MAAM,OAAO,GAAG;AAC3D,aAAO,IAAI,IAAI,UAAU,KAAK,CAAC;AAAA,IACjC;AACA,WAAO;AAAA,EACT;AACF;;;AL3hGA,IAAM,YAAY;AASX,IAAM,cAAN,MAAkB;AAAA;AAAA,EAEvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,YAAY,QAAQ,UAAU,MAAM,CAAC,GAAG;AACtC,UAAM,EAAE,SAAS,IAAI;AACrB,SAAK,UAAU;AACf,SAAK,YAAY,YAAY,OAAO;AACpC,SAAK,UAAU,IAAI,OAAO,MAAM;AAChC,SAAK,YAAY;AACjB,SAAK,UAAU,WAAW,QAAQ,QAAQ;AAC1C,SAAK,SAAS,IAAI,0BAAS;AAAA,MACzB,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ,MAAM;AACZ,SAAK,QAAQ,aAAa,IAAI;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,QAAQ,CAAC,UAAU,MAAM,MAAM,CAAC,MAAM;AACpC,QAAI,CAAC,MAAM,UAAU;AACnB,YAAM,IAAI,IAAI,KAAK,QAAQ,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AACvE,aAAO,KAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IACpC,WAAW,KAAK,aAAa,cAAc;AACzC,YAAM,IAAI,IAAI,KAAK,QAAQ,UAAU,mBAAmB,KAAK,QAAQ,EAAE;AACvE,aAAO,KAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IACpC;AACA,UAAM,WAAW,KAAK;AACtB,QACE,aAAa,KAAK,aAClB,SAAS,gBAAgB,eACzB,SAAS,mBACT,KAAK,YACL;AACA,YAAM,WAAW,SAAS,QAAQ;AAClC,UAAI,gBAAgB;AACpB,UAAI,KAAK,OAAO,IAAI,QAAQ,GAAG;AAC7B,wBAAgB,KAAK,OAAO,IAAI,QAAQ;AAAA,MAC1C,OAAO;AACL,wBAAgB,eAAe,UAAU,WAAW;AACpD,aAAK,OAAO,IAAI,UAAU,aAAa;AAAA,MACzC;AACA,UAAI,eAAe;AACjB,YAAI;AACF,gBAAM,IAAI,KAAK,YAAY,KAAK,UAAU,eAAe,IAAI,IAAI;AACjE,gBAAM,QAAQ,KAAK,QAAQ,MAAM,UAAU,CAAC;AAC5C,iBAAO;AAAA,YACL;AAAA,YACA,eAAe;AAAA,UACjB;AAAA,QACF,SAAS,GAAG;AAAA,QAEZ;AAAA,MACF;AAAA,IACF;AACA,QAAI;AACJ,QAAI;AACF,UAAI,KAAK,WAAW;AAClB,eAAO,KAAK,UAAU,eAAe,IAAI;AAAA,MAC3C;AACA,UAAI,QAAQ;AACZ,UAAI,UAAU;AACd,UAAI,OAAO;AACX,WAAK,QAAQ,MAAM,UAAU,MAAM,GAAG;AACtC,YAAM,KAAK,QAAQ,KAAK,WAAW;AAAA,IACrC,SAAS,GAAG;AACV,WAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IAC7B;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,UAAU,CAAC,UAAU,MAAM,MAAM,CAAC,MAAM;AACtC,QAAI,CAAC,MAAM,UAAU;AACnB,YAAM,IAAI,IAAI,KAAK,QAAQ,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AACvE,aAAO,KAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IACpC,WAAW,KAAK,aAAa,cAAc;AACzC,YAAM,IAAI,IAAI,KAAK,QAAQ,UAAU,mBAAmB,KAAK,QAAQ,EAAE;AACvE,aAAO,KAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IACpC;AACA,UAAM,WAAW,KAAK;AACtB,QACE,aAAa,KAAK,aAClB,SAAS,gBAAgB,eACzB,SAAS,mBACT,KAAK,YACL;AACA,YAAM,WAAW,WAAW,QAAQ;AACpC,UAAI,gBAAgB;AACpB,UAAI,KAAK,OAAO,IAAI,QAAQ,GAAG;AAC7B,wBAAgB,KAAK,OAAO,IAAI,QAAQ;AAAA,MAC1C,OAAO;AACL,wBAAgB,eAAe,UAAU,WAAW;AACpD,aAAK,OAAO,IAAI,UAAU,aAAa;AAAA,MACzC;AACA,UAAI,eAAe;AACjB,YAAI;AACF,gBAAM,IAAI,KAAK,YAAY,KAAK,UAAU,eAAe,IAAI,IAAI;AACjE,gBAAMC,OAAM,KAAK,QAAQ,MAAM,UAAU,CAAC;AAC1C,iBAAOA;AAAA,QACT,SAAS,GAAG;AAAA,QAEZ;AAAA,MACF;AAAA,IACF;AACA,QAAI;AACJ,QAAI;AACF,UAAI,KAAK,WAAW;AAClB,eAAO,KAAK,UAAU,eAAe,IAAI;AAAA,MAC3C;AACA,WAAK,QAAQ,MAAM,UAAU,MAAM,GAAG;AACtC,YAAM,QAAQ,KAAK,QAAQ,KAAK,WAAW;AAC3C,YAAM,MAAM;AAAA,IACd,SAAS,GAAG;AACV,WAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IAC7B;AACA,WAAO,CAAC,CAAC;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,UAAU,CAAC,UAAU,MAAM,MAAM,CAAC,MAAM;AACtC,QAAI,CAAC,MAAM,UAAU;AACnB,YAAM,IAAI,IAAI,KAAK,QAAQ,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AACvE,aAAO,KAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IACpC,WAAW,KAAK,aAAa,cAAc;AACzC,YAAM,IAAI,IAAI,KAAK,QAAQ,UAAU,mBAAmB,KAAK,QAAQ,EAAE;AACvE,aAAO,KAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IACpC;AACA,UAAM,WAAW,KAAK;AACtB,QACE,aAAa,KAAK,aAClB,SAAS,gBAAgB,eACzB,SAAS,mBACT,KAAK,YACL;AACA,YAAM,WAAW,WAAW,QAAQ;AACpC,UAAI,gBAAgB;AACpB,UAAI,KAAK,OAAO,IAAI,QAAQ,GAAG;AAC7B,wBAAgB,KAAK,OAAO,IAAI,QAAQ;AAAA,MAC1C,OAAO;AACL,wBAAgB,eAAe,UAAU,aAAa;AACtD,aAAK,OAAO,IAAI,UAAU,aAAa;AAAA,MACzC;AACA,UAAI,eAAe;AACjB,YAAI;AACF,gBAAM,IAAI,KAAK,YAAY,KAAK,UAAU,eAAe,IAAI,IAAI;AACjE,gBAAMA,OAAM,KAAK,QAAQ,QAAQ,UAAU,CAAC;AAC5C,iBAAOA;AAAA,QACT,SAAS,GAAG;AAAA,QAEZ;AAAA,MACF;AAAA,IACF;AACA,QAAI;AACJ,QAAI;AACF,UAAI,KAAK,WAAW;AAClB,eAAO,KAAK,UAAU,eAAe,IAAI;AAAA,MAC3C;AACA,WAAK,QAAQ,MAAM,UAAU,MAAM,GAAG;AACtC,YAAM,QAAQ,KAAK,QAAQ,KAAK,aAAa;AAC7C,UAAI,MAAM,MAAM;AACd,YAAI,UAAU;AACd,eAAO,SAAS;AACd,cAAI,MAAM,IAAI,OAAO,GAAG;AACtB,kBAAM;AACN;AAAA,UACF;AACA,oBAAU,QAAQ;AAAA,QACpB;AAAA,MACF;AAAA,IACF,SAAS,GAAG;AACV,WAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IAC7B;AACA,WAAO,OAAO;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,gBAAgB,CAAC,UAAU,MAAM,MAAM,CAAC,MAAM;AAC5C,QAAI,CAAC,MAAM,UAAU;AACnB,YAAM,IAAI,IAAI,KAAK,QAAQ,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AACvE,aAAO,KAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IACpC;AA6BA,QAAI;AACJ,QAAI;AACF,UAAI,KAAK,WAAW;AAClB,eAAO,KAAK,UAAU,eAAe,IAAI;AAAA,MAC3C;AACA,WAAK,QAAQ,MAAM,UAAU,MAAM,GAAG;AACtC,YAAM,QAAQ,KAAK,QAAQ,KAAK,YAAY;AAC5C,UAAI,MAAM,MAAM;AACd,SAAC,GAAG,IAAI,CAAC,GAAG,KAAK;AAAA,MACnB;AAAA,IACF,SAAS,GAAG;AACV,WAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IAC7B;AACA,WAAO,OAAO;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,mBAAmB,CAAC,UAAU,MAAM,MAAM,CAAC,MAAM;AAC/C,QAAI,CAAC,MAAM,UAAU;AACnB,YAAM,IAAI,IAAI,KAAK,QAAQ,UAAU,mBAAmB,QAAQ,IAAI,CAAC,EAAE;AACvE,aAAO,KAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IACpC;AACA,UAAM,WACJ,KAAK,aAAa,gBAAgB,OAAO,KAAK;AAChD,QACE,aAAa,KAAK,aAClB,SAAS,gBAAgB,eACzB,SAAS,oBACR,KAAK,aAAa,0BAA0B,CAAC,KAAK,OACnD;AACA,YAAM,WAAW,oBAAoB,QAAQ;AAC7C,UAAI,gBAAgB;AACpB,UAAI,KAAK,OAAO,IAAI,QAAQ,GAAG;AAC7B,wBAAgB,KAAK,OAAO,IAAI,QAAQ;AAAA,MAC1C,OAAO;AACL,wBAAgB,eAAe,UAAU,UAAU;AACnD,aAAK,OAAO,IAAI,UAAU,aAAa;AAAA,MACzC;AACA,UAAI,eAAe;AACjB,YAAI;AACF,gBAAM,IAAI,KAAK,YAAY,KAAK,UAAU,eAAe,IAAI,IAAI;AACjE,gBAAMA,OAAM,KAAK,QAAQ,OAAO,UAAU,CAAC;AAC3C,iBAAOA;AAAA,QACT,SAAS,GAAG;AAAA,QAEZ;AAAA,MACF;AAAA,IACF;AACA,QAAI;AACJ,QAAI;AACF,UAAI,KAAK,WAAW;AAClB,eAAO,KAAK,UAAU,eAAe,IAAI;AAAA,MAC3C;AACA,WAAK,QAAQ,MAAM,UAAU,MAAM,GAAG;AACtC,YAAM,QAAQ,KAAK,QAAQ,KAAK,UAAU;AAC1C,UAAI,MAAM,MAAM;AACd,cAAM,CAAC,GAAG,KAAK;AAAA,MACjB;AAAA,IACF,SAAS,GAAG;AACV,WAAK,QAAQ,QAAQ,GAAG,GAAG;AAAA,IAC7B;AACA,WAAO,OAAO,CAAC;AAAA,EACjB;AACF;","names":["cssTree","isCustomElementName","bidiFactory","nwsapi","KEYS_INPUT_EDIT","selectorBranches","find","res"]} \ No newline at end of file diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.d.cts b/vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.d.cts new file mode 100644 index 0000000..a5a8b10 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/dist/cjs/index.d.cts @@ -0,0 +1,16 @@ +declare class DOMSelector { + constructor(window: Window, document: Document, opt?: object); + clear: () => void; + check: (selector: string, node: Element, opt?: object) => CheckResult; + matches: (selector: string, node: Element, opt?: object) => boolean; + closest: (selector: string, node: Element, opt?: object) => Element | null; + querySelector: (selector: string, node: Document | DocumentFragment | Element, opt?: object) => Element | null; + querySelectorAll: (selector: string, node: Document | DocumentFragment | Element, opt?: object) => Array; + #private; +} +type CheckResult = { + match: boolean; + pseudoElement: string | null; +}; + +export { type CheckResult, DOMSelector }; diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/package.json b/vanilla/node_modules/@asamuzakjp/dom-selector/package.json new file mode 100644 index 0000000..4e8736f --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/package.json @@ -0,0 +1,81 @@ +{ + "name": "@asamuzakjp/dom-selector", + "description": "A CSS selector engine.", + "author": "asamuzaK", + "license": "MIT", + "homepage": "https://github.com/asamuzaK/domSelector#readme", + "bugs": { + "url": "https://github.com/asamuzaK/domSelector/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/asamuzaK/domSelector.git" + }, + "files": [ + "dist", + "src", + "types" + ], + "type": "module", + "exports": { + "import": { + "types": "./types/index.d.ts", + "default": "./src/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + }, + "default": { + "types": "./dist/cjs/types/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "types": "types/index.d.ts", + "dependencies": { + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.1.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.5" + }, + "devDependencies": { + "@types/css-tree": "^2.3.11", + "benchmark": "^2.1.4", + "c8": "^10.1.3", + "chai": "^6.2.2", + "commander": "^14.0.3", + "esbuild": "^0.27.2", + "eslint": "^9.39.2", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-jsdoc": "^62.5.0", + "eslint-plugin-prettier": "^5.5.5", + "eslint-plugin-regexp": "^3.0.0", + "eslint-plugin-unicorn": "^62.0.0", + "globals": "^17.2.0", + "jsdom": "^27.4.0", + "mocha": "^11.7.5", + "neostandard": "^0.12.2", + "prettier": "^3.8.1", + "sinon": "^21.0.1", + "tsup": "^8.5.1", + "typescript": "^5.9.3", + "wpt-runner": "^6.1.0" + }, + "overrides": { + "jsdom": "$jsdom" + }, + "scripts": { + "bench": "node benchmark/bench.js", + "bench:sizzle": "node benchmark/bench-sizzle.js", + "build": "npm run tsc && npm run lint && npm test && npm run bundle && npm run test:cjs", + "bundle": "tsup src/index.js --format=cjs --platform=node --outDir=dist/cjs/ --sourcemap --dts", + "lint": "eslint --fix .", + "test": "c8 --reporter=text mocha --parallel --exit test/**/*.test.js", + "test:cjs": "mocha --exit test/index.test.cjs", + "test:wpt": "node test/wpt/wpt-runner.js", + "tsc": "node scripts/index clean --dir=types -i && npx tsc", + "update:wpt": "git submodule update --init --recursive --remote" + }, + "version": "6.7.8" +} diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/src/index.js b/vanilla/node_modules/@asamuzakjp/dom-selector/src/index.js new file mode 100644 index 0000000..8ec7b67 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/src/index.js @@ -0,0 +1,353 @@ +/*! + * DOM Selector - A CSS selector engine. + * @license MIT + * @copyright asamuzaK (Kazz) + * @see {@link https://github.com/asamuzaK/domSelector/blob/main/LICENSE} + */ + +/* import */ +import { LRUCache } from 'lru-cache'; +import { Finder } from './js/finder.js'; +import { filterSelector, getType, initNwsapi } from './js/utility.js'; + +/* constants */ +import { + DOCUMENT_NODE, + DOCUMENT_FRAGMENT_NODE, + ELEMENT_NODE, + TARGET_ALL, + TARGET_FIRST, + TARGET_LINEAL, + TARGET_SELF +} from './js/constant.js'; +const MAX_CACHE = 1024; + +/** + * @typedef {object} CheckResult + * @property {boolean} match - The match result. + * @property {string?} pseudoElement - The pseudo-element, if any. + */ + +/* DOMSelector */ +export class DOMSelector { + /* private fields */ + #window; + #document; + #finder; + #idlUtils; + #nwsapi; + #cache; + + /** + * Creates an instance of DOMSelector. + * @param {Window} window - The window object. + * @param {Document} document - The document object. + * @param {object} [opt] - Options. + */ + constructor(window, document, opt = {}) { + const { idlUtils } = opt; + this.#window = window; + this.#document = document ?? window.document; + this.#finder = new Finder(window); + this.#idlUtils = idlUtils; + this.#nwsapi = initNwsapi(window, document); + this.#cache = new LRUCache({ + max: MAX_CACHE + }); + } + + /** + * Clears the internal cache of finder results. + * @returns {void} + */ + clear = () => { + this.#finder.clearResults(true); + }; + + /** + * Checks if an element matches a CSS selector. + * @param {string} selector - The CSS selector to check against. + * @param {Element} node - The element node to check. + * @param {object} [opt] - Optional parameters. + * @returns {CheckResult} An object containing the check result. + */ + check = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } else if (node.nodeType !== ELEMENT_NODE) { + const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`); + return this.#finder.onError(e, opt); + } + const document = node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + node.parentNode + ) { + const cacheKey = `check_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_SELF); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const match = this.#nwsapi.match(selector, n); + return { + match, + pseudoElement: null + }; + } catch (e) { + // fall through + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + opt.check = true; + opt.noexept = true; + opt.warn = false; + this.#finder.setup(selector, node, opt); + res = this.#finder.find(TARGET_SELF); + } catch (e) { + this.#finder.onError(e, opt); + } + return res; + }; + + /** + * Returns true if the element matches the selector. + * @param {string} selector - The CSS selector to match against. + * @param {Element} node - The element node to test. + * @param {object} [opt] - Optional parameters. + * @returns {boolean} `true` if the element matches, or `false` otherwise. + */ + matches = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } else if (node.nodeType !== ELEMENT_NODE) { + const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`); + return this.#finder.onError(e, opt); + } + const document = node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + node.parentNode + ) { + const cacheKey = `matches_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_SELF); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const res = this.#nwsapi.match(selector, n); + return res; + } catch (e) { + // fall through + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + this.#finder.setup(selector, node, opt); + const nodes = this.#finder.find(TARGET_SELF); + res = nodes.size; + } catch (e) { + this.#finder.onError(e, opt); + } + return !!res; + }; + + /** + * Traverses up the DOM tree to find the first node that matches the selector. + * @param {string} selector - The CSS selector to match against. + * @param {Element} node - The element from which to start traversing. + * @param {object} [opt] - Optional parameters. + * @returns {?Element} The first matching ancestor element, or `null`. + */ + closest = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } else if (node.nodeType !== ELEMENT_NODE) { + const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`); + return this.#finder.onError(e, opt); + } + const document = node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + node.parentNode + ) { + const cacheKey = `closest_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_LINEAL); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const res = this.#nwsapi.closest(selector, n); + return res; + } catch (e) { + // fall through + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + this.#finder.setup(selector, node, opt); + const nodes = this.#finder.find(TARGET_LINEAL); + if (nodes.size) { + let refNode = node; + while (refNode) { + if (nodes.has(refNode)) { + res = refNode; + break; + } + refNode = refNode.parentNode; + } + } + } catch (e) { + this.#finder.onError(e, opt); + } + return res ?? null; + }; + + /** + * Returns the first element within the subtree that matches the selector. + * @param {string} selector - The CSS selector to match. + * @param {Document|DocumentFragment|Element} node - The node to find within. + * @param {object} [opt] - Optional parameters. + * @returns {?Element} The first matching element, or `null`. + */ + querySelector = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } + /* + const document = + node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + (node.nodeType !== DOCUMENT_FRAGMENT_NODE || !node.host) + ) { + const cacheKey = `querySelector_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_FIRST); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const res = this.#nwsapi.first(selector, n); + return res; + } catch (e) { + // fall through + } + } + } + */ + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + this.#finder.setup(selector, node, opt); + const nodes = this.#finder.find(TARGET_FIRST); + if (nodes.size) { + [res] = [...nodes]; + } + } catch (e) { + this.#finder.onError(e, opt); + } + return res ?? null; + }; + + /** + * Returns an array of elements within the subtree that match the selector. + * Note: This method returns an Array, not a NodeList. + * @param {string} selector - The CSS selector to match. + * @param {Document|DocumentFragment|Element} node - The node to find within. + * @param {object} [opt] - Optional parameters. + * @returns {Array} An array of elements, or an empty array. + */ + querySelectorAll = (selector, node, opt = {}) => { + if (!node?.nodeType) { + const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`); + return this.#finder.onError(e, opt); + } + const document = + node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument; + if ( + document === this.#document && + document.contentType === 'text/html' && + document.documentElement && + (node.nodeType !== DOCUMENT_FRAGMENT_NODE || !node.host) + ) { + const cacheKey = `querySelectorAll_${selector}`; + let filterMatches = false; + if (this.#cache.has(cacheKey)) { + filterMatches = this.#cache.get(cacheKey); + } else { + filterMatches = filterSelector(selector, TARGET_ALL); + this.#cache.set(cacheKey, filterMatches); + } + if (filterMatches) { + try { + const n = this.#idlUtils ? this.#idlUtils.wrapperForImpl(node) : node; + const res = this.#nwsapi.select(selector, n); + return res; + } catch (e) { + // fall through + } + } + } + let res; + try { + if (this.#idlUtils) { + node = this.#idlUtils.wrapperForImpl(node); + } + this.#finder.setup(selector, node, opt); + const nodes = this.#finder.find(TARGET_ALL); + if (nodes.size) { + res = [...nodes]; + } + } catch (e) { + this.#finder.onError(e, opt); + } + return res ?? []; + }; +} diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/constant.js b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/constant.js new file mode 100644 index 0000000..02986ec --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/constant.js @@ -0,0 +1,129 @@ +/** + * constant.js + */ + +/* string */ +export const ATRULE = 'Atrule'; +export const ATTR_SELECTOR = 'AttributeSelector'; +export const CLASS_SELECTOR = 'ClassSelector'; +export const COMBINATOR = 'Combinator'; +export const IDENT = 'Identifier'; +export const ID_SELECTOR = 'IdSelector'; +export const NOT_SUPPORTED_ERR = 'NotSupportedError'; +export const NTH = 'Nth'; +export const OPERATOR = 'Operator'; +export const PS_CLASS_SELECTOR = 'PseudoClassSelector'; +export const PS_ELEMENT_SELECTOR = 'PseudoElementSelector'; +export const RULE = 'Rule'; +export const SCOPE = 'Scope'; +export const SELECTOR = 'Selector'; +export const SELECTOR_LIST = 'SelectorList'; +export const STRING = 'String'; +export const SYNTAX_ERR = 'SyntaxError'; +export const TARGET_ALL = 'all'; +export const TARGET_FIRST = 'first'; +export const TARGET_LINEAL = 'lineal'; +export const TARGET_SELF = 'self'; +export const TYPE_SELECTOR = 'TypeSelector'; + +/* numeric */ +export const BIT_01 = 1; +export const BIT_02 = 2; +export const BIT_04 = 4; +export const BIT_08 = 8; +export const BIT_16 = 0x10; +export const BIT_32 = 0x20; +export const BIT_FFFF = 0xffff; +export const DUO = 2; +export const HEX = 16; +export const TYPE_FROM = 8; +export const TYPE_TO = -1; + +/* Node */ +export const ELEMENT_NODE = 1; +export const TEXT_NODE = 3; +export const DOCUMENT_NODE = 9; +export const DOCUMENT_FRAGMENT_NODE = 11; +export const DOCUMENT_POSITION_PRECEDING = 2; +export const DOCUMENT_POSITION_CONTAINS = 8; +export const DOCUMENT_POSITION_CONTAINED_BY = 0x10; + +/* NodeFilter */ +export const SHOW_ALL = 0xffffffff; +export const SHOW_CONTAINER = 0x501; +export const SHOW_DOCUMENT = 0x100; +export const SHOW_DOCUMENT_FRAGMENT = 0x400; +export const SHOW_ELEMENT = 1; + +/* selectors */ +export const ALPHA_NUM = '[A-Z\\d]+'; +export const CHILD_IDX = '(?:first|last|only)-(?:child|of-type)'; +export const DIGIT = '(?:0|[1-9]\\d*)'; +export const LANG_PART = `(?:-${ALPHA_NUM})*`; +export const PSEUDO_CLASS = `(?:any-)?link|${CHILD_IDX}|checked|empty|indeterminate|read-(?:only|write)|target`; +export const ANB = `[+-]?(?:${DIGIT}n?|n)|(?:[+-]?${DIGIT})?n\\s*[+-]\\s*${DIGIT}`; +// combinators +export const COMBO = '\\s?[\\s>~+]\\s?'; +export const DESCEND = '\\s?[\\s>]\\s?'; +export const SIBLING = '\\s?[+~]\\s?'; +// LOGIC_IS: :is() +export const LOGIC_IS = `:is\\(\\s*[^)]+\\s*\\)`; +// N_TH: excludes An+B with selector list, e.g. :nth-child(2n+1 of .foo) +export const N_TH = `nth-(?:last-)?(?:child|of-type)\\(\\s*(?:even|odd|${ANB})\\s*\\)`; +// SUB_TYPE: attr, id, class, pseudo-class, note that [foo|=bar] is excluded +export const SUB_TYPE = '\\[[^|\\]]+\\]|[#.:][\\w-]+'; +export const SUB_TYPE_WO_PSEUDO = '\\[[^|\\]]+\\]|[#.][\\w-]+'; +// TAG_TYPE: *, tag +export const TAG_TYPE = '\\*|[A-Za-z][\\w-]*'; +export const TAG_TYPE_I = '\\*|[A-Z][\\w-]*'; +export const COMPOUND = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE})+)`; +export const COMPOUND_L = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE}|${LOGIC_IS})+)`; +export const COMPOUND_I = `(?:${TAG_TYPE_I}|(?:${TAG_TYPE_I})?(?:${SUB_TYPE})+)`; +export const COMPOUND_WO_PSEUDO = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE_WO_PSEUDO})+)`; +export const COMPLEX = `${COMPOUND}(?:${COMBO}${COMPOUND})*`; +export const COMPLEX_L = `${COMPOUND_L}(?:${COMBO}${COMPOUND_L})*`; +export const HAS_COMPOUND = `has\\([\\s>]?\\s*${COMPOUND_WO_PSEUDO}\\s*\\)`; +export const LOGIC_COMPOUND = `(?:is|not)\\(\\s*${COMPOUND_L}(?:\\s*,\\s*${COMPOUND_L})*\\s*\\)`; +export const LOGIC_COMPLEX = `(?:is|not)\\(\\s*${COMPLEX_L}(?:\\s*,\\s*${COMPLEX_L})*\\s*\\)`; + +/* forms and input types */ +export const FORM_PARTS = Object.freeze([ + 'button', + 'input', + 'select', + 'textarea' +]); +export const INPUT_BUTTON = Object.freeze(['button', 'reset', 'submit']); +export const INPUT_CHECK = Object.freeze(['checkbox', 'radio']); +export const INPUT_DATE = Object.freeze([ + 'date', + 'datetime-local', + 'month', + 'time', + 'week' +]); +export const INPUT_TEXT = Object.freeze([ + 'email', + 'password', + 'search', + 'tel', + 'text', + 'url' +]); +export const INPUT_EDIT = Object.freeze([ + ...INPUT_DATE, + ...INPUT_TEXT, + 'number' +]); +export const INPUT_LTR = Object.freeze([ + ...INPUT_CHECK, + 'color', + 'date', + 'image', + 'number', + 'range', + 'time' +]); + +/* logical combination pseudo-classes */ +export const KEYS_LOGICAL = new Set(['has', 'is', 'not', 'where']); diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/finder.js b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/finder.js new file mode 100644 index 0000000..05538d7 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/finder.js @@ -0,0 +1,3122 @@ +/** + * finder.js + */ + +/* import */ +import { + matchAttributeSelector, + matchDirectionPseudoClass, + matchDisabledPseudoClass, + matchLanguagePseudoClass, + matchPseudoElementSelector, + matchReadOnlyPseudoClass, + matchTypeSelector +} from './matcher.js'; +import { + findAST, + generateCSS, + parseSelector, + sortAST, + unescapeSelector, + walkAST +} from './parser.js'; +import { + filterNodesByAnB, + findLogicalWithNestedHas, + generateException, + isCustomElement, + isFocusVisible, + isFocusableArea, + isVisible, + resolveContent, + sortNodes, + traverseNode +} from './utility.js'; + +/* constants */ +import { + ATTR_SELECTOR, + CLASS_SELECTOR, + COMBINATOR, + DOCUMENT_FRAGMENT_NODE, + ELEMENT_NODE, + FORM_PARTS, + ID_SELECTOR, + INPUT_CHECK, + INPUT_DATE, + INPUT_EDIT, + INPUT_TEXT, + KEYS_LOGICAL, + NOT_SUPPORTED_ERR, + PS_CLASS_SELECTOR, + PS_ELEMENT_SELECTOR, + SHOW_ALL, + SHOW_CONTAINER, + SYNTAX_ERR, + TARGET_ALL, + TARGET_FIRST, + TARGET_LINEAL, + TARGET_SELF, + TEXT_NODE, + TYPE_SELECTOR +} from './constant.js'; +const DIR_NEXT = 'next'; +const DIR_PREV = 'prev'; +const KEYS_FORM = new Set([...FORM_PARTS, 'fieldset', 'form']); +const KEYS_FORM_PS_VALID = new Set([...FORM_PARTS, 'form']); +const KEYS_INPUT_CHECK = new Set(INPUT_CHECK); +const KEYS_INPUT_PLACEHOLDER = new Set([...INPUT_TEXT, 'number']); +const KEYS_INPUT_RANGE = new Set([...INPUT_DATE, 'number', 'range']); +const KEYS_INPUT_REQUIRED = new Set([...INPUT_CHECK, ...INPUT_EDIT, 'file']); +const KEYS_INPUT_RESET = new Set(['button', 'reset']); +const KEYS_INPUT_SUBMIT = new Set(['image', 'submit']); +const KEYS_MODIFIER = new Set([ + 'Alt', + 'AltGraph', + 'CapsLock', + 'Control', + 'Fn', + 'FnLock', + 'Hyper', + 'Meta', + 'NumLock', + 'ScrollLock', + 'Shift', + 'Super', + 'Symbol', + 'SymbolLock' +]); +const KEYS_PS_UNCACHE = new Set([ + 'any-link', + 'defined', + 'dir', + 'link', + 'scope' +]); +const KEYS_PS_NTH_OF_TYPE = new Set([ + 'first-of-type', + 'last-of-type', + 'only-of-type' +]); + +/** + * Finder + * NOTE: #ast[i] corresponds to #nodes[i] + */ +export class Finder { + /* private fields */ + #ast; + #astCache; + #check; + #descendant; + #document; + #documentCache; + #documentURL; + #event; + #eventHandlers; + #focus; + #invalidate; + #invalidateResults; + #lastFocusVisible; + #node; + #nodeWalker; + #nodes; + #noexcept; + #pseudoElement; + #results; + #root; + #rootWalker; + #scoped; + #selector; + #shadow; + #verifyShadowHost; + #walkers; + #warn; + #window; + + /** + * constructor + * @param {object} window - The window object. + */ + constructor(window) { + this.#window = window; + this.#astCache = new WeakMap(); + this.#documentCache = new WeakMap(); + this.#event = null; + this.#focus = null; + this.#lastFocusVisible = null; + this.#eventHandlers = new Set([ + { + keys: ['focus', 'focusin'], + handler: this._handleFocusEvent + }, + { + keys: ['keydown', 'keyup'], + handler: this._handleKeyboardEvent + }, + { + keys: ['mouseover', 'mousedown', 'mouseup', 'click', 'mouseout'], + handler: this._handleMouseEvent + } + ]); + this._registerEventListeners(); + this.clearResults(true); + } + + /** + * Handles errors. + * @param {Error} e - The error object. + * @param {object} [opt] - Options. + * @param {boolean} [opt.noexcept] - If true, exceptions are not thrown. + * @throws {Error} Throws an error. + * @returns {void} + */ + onError = (e, opt = {}) => { + const noexcept = opt.noexcept ?? this.#noexcept; + if (noexcept) { + return; + } + const isDOMException = + e instanceof DOMException || e instanceof this.#window.DOMException; + if (isDOMException) { + if (e.name === NOT_SUPPORTED_ERR) { + if (this.#warn) { + console.warn(e.message); + } + return; + } + throw new this.#window.DOMException(e.message, e.name); + } + if (e.name in this.#window) { + throw new this.#window[e.name](e.message, { cause: e }); + } + throw e; + }; + + /** + * Sets up the finder. + * @param {string} selector - The CSS selector. + * @param {object} node - Document, DocumentFragment, or Element. + * @param {object} [opt] - Options. + * @param {boolean} [opt.check] - Indicates if running in internal check(). + * @param {boolean} [opt.noexcept] - If true, exceptions are not thrown. + * @param {boolean} [opt.warn] - If true, console warnings are enabled. + * @returns {object} The finder instance. + */ + setup = (selector, node, opt = {}) => { + const { check, noexcept, warn } = opt; + this.#check = !!check; + this.#noexcept = !!noexcept; + this.#warn = !!warn; + [this.#document, this.#root, this.#shadow] = resolveContent(node); + this.#documentURL = null; + this.#node = node; + this.#scoped = + this.#node !== this.#root && this.#node.nodeType === ELEMENT_NODE; + this.#selector = selector; + [this.#ast, this.#nodes] = this._correspond(selector); + this.#pseudoElement = []; + this.#walkers = new WeakMap(); + this.#nodeWalker = null; + this.#rootWalker = null; + this.#verifyShadowHost = null; + this.clearResults(); + return this; + }; + + /** + * Clear cached results. + * @param {boolean} all - clear all results + * @returns {void} + */ + clearResults = (all = false) => { + this.#invalidateResults = new WeakMap(); + if (all) { + this.#results = new WeakMap(); + } + }; + + /** + * Handles focus events. + * @private + * @param {Event} evt - The event object. + * @returns {void} + */ + _handleFocusEvent = evt => { + this.#focus = evt; + }; + + /** + * Handles keyboard events. + * @private + * @param {Event} evt - The event object. + * @returns {void} + */ + _handleKeyboardEvent = evt => { + const { key } = evt; + if (!KEYS_MODIFIER.has(key)) { + this.#event = evt; + } + }; + + /** + * Handles mouse events. + * @private + * @param {Event} evt - The event object. + * @returns {void} + */ + _handleMouseEvent = evt => { + this.#event = evt; + }; + + /** + * Registers event listeners. + * @private + * @returns {Array.} An array of return values from addEventListener. + */ + _registerEventListeners = () => { + const opt = { + capture: true, + passive: true + }; + const func = []; + for (const eventHandler of this.#eventHandlers) { + const { keys, handler } = eventHandler; + const l = keys.length; + for (let i = 0; i < l; i++) { + const key = keys[i]; + func.push(this.#window.addEventListener(key, handler, opt)); + } + } + return func; + }; + + /** + * Processes selector branches into the internal AST structure. + * @private + * @param {Array.>} branches - The branches from walkAST. + * @param {string} selector - The original selector for error reporting. + * @returns {{ast: Array, descendant: boolean}} + * An object with the AST, descendant flag. + */ + _processSelectorBranches = (branches, selector) => { + let descendant = false; + const ast = []; + const l = branches.length; + for (let i = 0; i < l; i++) { + const items = [...branches[i]]; + const branch = []; + let item = items.shift(); + if (item && item.type !== COMBINATOR) { + const leaves = new Set(); + while (item) { + if (item.type === COMBINATOR) { + const [nextItem] = items; + if (!nextItem || nextItem.type === COMBINATOR) { + const msg = `Invalid selector ${selector}`; + this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + // Stop processing on invalid selector. + return { ast: [], descendant: false, invalidate: false }; + } + if (item.name === ' ' || item.name === '>') { + descendant = true; + } + branch.push({ combo: item, leaves: sortAST(leaves) }); + leaves.clear(); + } else { + if (item.name && typeof item.name === 'string') { + const unescapedName = unescapeSelector(item.name); + if (unescapedName !== item.name) { + item.name = unescapedName; + } + if (/[|:]/.test(unescapedName)) { + item.namespace = true; + } + } + leaves.add(item); + } + if (items.length) { + item = items.shift(); + } else { + branch.push({ combo: null, leaves: sortAST(leaves) }); + leaves.clear(); + break; + } + } + } + ast.push({ branch, dir: null, filtered: false, find: false }); + } + return { ast, descendant }; + }; + + /** + * Corresponds AST and nodes. + * @private + * @param {string} selector - The CSS selector. + * @returns {Array.>} An array with the AST and nodes. + */ + _correspond = selector => { + const nodes = []; + this.#descendant = false; + this.#invalidate = false; + let ast; + if (this.#documentCache.has(this.#document)) { + const cachedItem = this.#documentCache.get(this.#document); + if (cachedItem && cachedItem.has(`${selector}`)) { + const item = cachedItem.get(`${selector}`); + ast = item.ast; + this.#descendant = item.descendant; + this.#invalidate = item.invalidate; + } + } + if (ast) { + const l = ast.length; + for (let i = 0; i < l; i++) { + ast[i].dir = null; + ast[i].filtered = false; + ast[i].find = false; + nodes[i] = []; + } + } else { + let cssAst; + try { + cssAst = parseSelector(selector); + } catch (e) { + return this.onError(e); + } + const { branches, info } = walkAST(cssAst); + const { + hasHasPseudoFunc, + hasLogicalPseudoFunc, + hasNthChildOfSelector, + hasStatePseudoClass + } = info; + this.#invalidate = + hasHasPseudoFunc || + hasStatePseudoClass || + !!(hasLogicalPseudoFunc && hasNthChildOfSelector); + const processed = this._processSelectorBranches(branches, selector); + ast = processed.ast; + this.#descendant = processed.descendant; + let cachedItem; + if (this.#documentCache.has(this.#document)) { + cachedItem = this.#documentCache.get(this.#document); + } else { + cachedItem = new Map(); + } + cachedItem.set(`${selector}`, { + ast, + descendant: this.#descendant, + invalidate: this.#invalidate + }); + this.#documentCache.set(this.#document, cachedItem); + // Initialize nodes array for each branch. + for (let i = 0; i < ast.length; i++) { + nodes[i] = []; + } + } + return [ast, nodes]; + }; + + /** + * Creates a TreeWalker. + * @private + * @param {object} node - The Document, DocumentFragment, or Element node. + * @param {object} [opt] - Options. + * @param {boolean} [opt.force] - Force creation of a new TreeWalker. + * @param {number} [opt.whatToShow] - The NodeFilter whatToShow value. + * @returns {object} The TreeWalker object. + */ + _createTreeWalker = (node, opt = {}) => { + const { force = false, whatToShow = SHOW_CONTAINER } = opt; + if (force) { + return this.#document.createTreeWalker(node, whatToShow); + } else if (this.#walkers.has(node)) { + return this.#walkers.get(node); + } + const walker = this.#document.createTreeWalker(node, whatToShow); + this.#walkers.set(node, walker); + return walker; + }; + + /** + * Gets selector branches from cache or parses them. + * @private + * @param {object} selector - The AST. + * @returns {Array.>} The selector branches. + */ + _getSelectorBranches = selector => { + if (this.#astCache.has(selector)) { + return this.#astCache.get(selector); + } + const { branches } = walkAST(selector); + this.#astCache.set(selector, branches); + return branches; + }; + + /** + * Gets the children of a node, optionally filtered by a selector. + * @private + * @param {object} parentNode - The parent element. + * @param {Array.>} selectorBranches - The selector branches. + * @param {object} [opt] - Options. + * @returns {Array.} An array of child nodes. + */ + _getFilteredChildren = (parentNode, selectorBranches, opt = {}) => { + const children = []; + const walker = this._createTreeWalker(parentNode, { force: true }); + let childNode = walker.firstChild(); + while (childNode) { + if (selectorBranches) { + if (isVisible(childNode)) { + let isMatch = false; + const l = selectorBranches.length; + for (let i = 0; i < l; i++) { + const leaves = selectorBranches[i]; + if (this._matchLeaves(leaves, childNode, opt)) { + isMatch = true; + break; + } + } + if (isMatch) { + children.push(childNode); + } + } + } else { + children.push(childNode); + } + childNode = walker.nextSibling(); + } + return children; + }; + + /** + * Collects nth-child nodes. + * @private + * @param {object} anb - An+B options. + * @param {number} anb.a - The 'a' value. + * @param {number} anb.b - The 'b' value. + * @param {boolean} [anb.reverse] - If true, reverses the order. + * @param {object} [anb.selector] - The AST. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _collectNthChild = (anb, node, opt = {}) => { + const { a, b, selector } = anb; + const { parentNode } = node; + if (!parentNode) { + const matchedNode = new Set(); + if (node === this.#root && a * 1 + b * 1 === 1) { + if (selector) { + const selectorBranches = this._getSelectorBranches(selector); + const l = selectorBranches.length; + for (let i = 0; i < l; i++) { + const leaves = selectorBranches[i]; + if (this._matchLeaves(leaves, node, opt)) { + matchedNode.add(node); + break; + } + } + } else { + matchedNode.add(node); + } + } + return matchedNode; + } + const selectorBranches = selector + ? this._getSelectorBranches(selector) + : null; + const children = this._getFilteredChildren( + parentNode, + selectorBranches, + opt + ); + const matchedNodes = filterNodesByAnB(children, anb); + return new Set(matchedNodes); + }; + + /** + * Collects nth-of-type nodes. + * @private + * @param {object} anb - An+B options. + * @param {number} anb.a - The 'a' value. + * @param {number} anb.b - The 'b' value. + * @param {boolean} [anb.reverse] - If true, reverses the order. + * @param {object} node - The Element node. + * @returns {Set.} A collection of matched nodes. + */ + _collectNthOfType = (anb, node) => { + const { parentNode } = node; + if (!parentNode) { + if (node === this.#root && anb.a * 1 + anb.b * 1 === 1) { + return new Set([node]); + } + return new Set(); + } + const typedSiblings = []; + const walker = this._createTreeWalker(parentNode, { force: true }); + let sibling = walker.firstChild(); + while (sibling) { + if ( + sibling.localName === node.localName && + sibling.namespaceURI === node.namespaceURI && + sibling.prefix === node.prefix + ) { + typedSiblings.push(sibling); + } + sibling = walker.nextSibling(); + } + const matchedNodes = filterNodesByAnB(typedSiblings, anb); + return new Set(matchedNodes); + }; + + /** + * Matches An+B. + * @private + * @param {object} ast - The AST. + * @param {object} node - The Element node. + * @param {string} nthName - The name of the nth pseudo-class. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchAnPlusB = (ast, node, nthName, opt = {}) => { + const { + nth: { a, b, name: nthIdentName }, + selector + } = ast; + const anbMap = new Map(); + if (nthIdentName) { + if (nthIdentName === 'even') { + anbMap.set('a', 2); + anbMap.set('b', 0); + } else if (nthIdentName === 'odd') { + anbMap.set('a', 2); + anbMap.set('b', 1); + } + if (nthName.indexOf('last') > -1) { + anbMap.set('reverse', true); + } + } else { + if (typeof a === 'string' && /-?\d+/.test(a)) { + anbMap.set('a', a * 1); + } else { + anbMap.set('a', 0); + } + if (typeof b === 'string' && /-?\d+/.test(b)) { + anbMap.set('b', b * 1); + } else { + anbMap.set('b', 0); + } + if (nthName.indexOf('last') > -1) { + anbMap.set('reverse', true); + } + } + if (nthName === 'nth-child' || nthName === 'nth-last-child') { + if (selector) { + anbMap.set('selector', selector); + } + const anb = Object.fromEntries(anbMap); + const nodes = this._collectNthChild(anb, node, opt); + return nodes; + } else if (nthName === 'nth-of-type' || nthName === 'nth-last-of-type') { + const anb = Object.fromEntries(anbMap); + const nodes = this._collectNthOfType(anb, node); + return nodes; + } + return new Set(); + }; + + /** + * Matches the :has() pseudo-class function. + * @private + * @param {Array.} astLeaves - The AST leaves. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {boolean} The result. + */ + _matchHasPseudoFunc = (astLeaves, node, opt = {}) => { + if (Array.isArray(astLeaves) && astLeaves.length) { + // Prepare a copy to avoid astLeaves being consumed. + const leaves = [...astLeaves]; + const [leaf] = leaves; + const { type: leafType } = leaf; + let combo; + if (leafType === COMBINATOR) { + combo = leaves.shift(); + } else { + combo = { + name: ' ', + type: COMBINATOR + }; + } + const twigLeaves = []; + while (leaves.length) { + const [item] = leaves; + const { type: itemType } = item; + if (itemType === COMBINATOR) { + break; + } else { + twigLeaves.push(leaves.shift()); + } + } + const twig = { + combo, + leaves: twigLeaves + }; + opt.dir = DIR_NEXT; + const nodes = this._matchCombinator(twig, node, opt); + if (nodes.size) { + if (leaves.length) { + let bool = false; + for (const nextNode of nodes) { + bool = this._matchHasPseudoFunc(leaves, nextNode, opt); + if (bool) { + break; + } + } + return bool; + } + return true; + } + } + return false; + }; + + /** + * Evaluates the :has() pseudo-class. + * @private + * @param {object} astData - The AST data. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {?object} The matched node. + */ + _evaluateHasPseudo = (astData, node, opt) => { + const { branches } = astData; + let bool = false; + const l = branches.length; + for (let i = 0; i < l; i++) { + const leaves = branches[i]; + bool = this._matchHasPseudoFunc(leaves, node, opt); + if (bool) { + break; + } + } + if (!bool) { + return null; + } + if ( + (opt.isShadowRoot || this.#shadow) && + node.nodeType === DOCUMENT_FRAGMENT_NODE + ) { + return this.#verifyShadowHost ? node : null; + } + return node; + }; + + /** + * Matches logical pseudo-class functions. + * @private + * @param {object} astData - The AST data. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {?object} The matched node. + */ + _matchLogicalPseudoFunc = (astData, node, opt = {}) => { + const { astName, branches, twigBranches } = astData; + // Handle :has(). + if (astName === 'has') { + return this._evaluateHasPseudo(astData, node, opt); + } + // Handle :is(), :not(), :where(). + const isShadowRoot = + (opt.isShadowRoot || this.#shadow) && + node.nodeType === DOCUMENT_FRAGMENT_NODE; + // Check for invalid shadow root. + if (isShadowRoot) { + let invalid = false; + for (const branch of branches) { + if (branch.length > 1) { + invalid = true; + break; + } else if (astName === 'not') { + const [{ type: childAstType }] = branch; + if (childAstType !== PS_CLASS_SELECTOR) { + invalid = true; + break; + } + } + } + if (invalid) { + return null; + } + } + opt.forgive = astName === 'is' || astName === 'where'; + const l = twigBranches.length; + let bool; + for (let i = 0; i < l; i++) { + const branch = twigBranches[i]; + const lastIndex = branch.length - 1; + const { leaves } = branch[lastIndex]; + bool = this._matchLeaves(leaves, node, opt); + if (bool && lastIndex > 0) { + let nextNodes = new Set([node]); + for (let j = lastIndex - 1; j >= 0; j--) { + const twig = branch[j]; + const arr = []; + opt.dir = DIR_PREV; + for (const nextNode of nextNodes) { + const m = this._matchCombinator(twig, nextNode, opt); + if (m.size) { + arr.push(...m); + } + } + if (arr.length) { + if (j === 0) { + bool = true; + } else { + nextNodes = new Set(arr); + } + } else { + bool = false; + break; + } + } + } + if (bool) { + break; + } + } + if (astName === 'not') { + if (bool) { + return null; + } + return node; + } else if (bool) { + return node; + } + return null; + }; + + /** + * match pseudo-class selector + * @private + * @see https://html.spec.whatwg.org/#pseudo-classes + * @param {object} ast - AST + * @param {object} node - Element node + * @param {object} [opt] - options + * @returns {Set.} - collection of matched nodes + */ + _matchPseudoClassSelector(ast, node, opt = {}) { + const { children: astChildren, name: astName } = ast; + const { localName, parentNode } = node; + const { forgive, warn = this.#warn } = opt; + const matched = new Set(); + // :has(), :is(), :not(), :where() + if (Array.isArray(astChildren) && KEYS_LOGICAL.has(astName)) { + if (!astChildren.length && astName !== 'is' && astName !== 'where') { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + let astData; + if (this.#astCache.has(ast)) { + astData = this.#astCache.get(ast); + } else { + const { branches } = walkAST(ast); + if (astName === 'has') { + // Check for nested :has(). + let forgiven = false; + const l = astChildren.length; + for (let i = 0; i < l; i++) { + const child = astChildren[i]; + const item = findAST(child, findLogicalWithNestedHas); + if (item) { + const itemName = item.name; + if (itemName === 'is' || itemName === 'where') { + forgiven = true; + break; + } else { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + return this.onError( + generateException(msg, SYNTAX_ERR, this.#window) + ); + } + } + } + if (forgiven) { + return matched; + } + astData = { + astName, + branches + }; + } else { + const twigBranches = []; + const l = branches.length; + for (let i = 0; i < l; i++) { + const [...leaves] = branches[i]; + const branch = []; + const leavesSet = new Set(); + let item = leaves.shift(); + while (item) { + if (item.type === COMBINATOR) { + branch.push({ + combo: item, + leaves: [...leavesSet] + }); + leavesSet.clear(); + } else if (item) { + leavesSet.add(item); + } + if (leaves.length) { + item = leaves.shift(); + } else { + branch.push({ + combo: null, + leaves: [...leavesSet] + }); + leavesSet.clear(); + break; + } + } + twigBranches.push(branch); + } + astData = { + astName, + branches, + twigBranches + }; + this.#astCache.set(ast, astData); + } + } + const res = this._matchLogicalPseudoFunc(astData, node, opt); + if (res) { + matched.add(res); + } + } else if (Array.isArray(astChildren)) { + // :nth-child(), :nth-last-child(), nth-of-type(), :nth-last-of-type() + if (/^nth-(?:last-)?(?:child|of-type)$/.test(astName)) { + if (astChildren.length !== 1) { + const css = generateCSS(ast); + return this.onError( + generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + this.#window + ) + ); + } + const [branch] = astChildren; + const nodes = this._matchAnPlusB(branch, node, astName, opt); + return nodes; + } else { + switch (astName) { + // :dir() + case 'dir': { + if (astChildren.length !== 1) { + const css = generateCSS(ast); + return this.onError( + generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + this.#window + ) + ); + } + const [astChild] = astChildren; + const res = matchDirectionPseudoClass(astChild, node); + if (res) { + matched.add(node); + } + break; + } + // :lang() + case 'lang': { + if (!astChildren.length) { + const css = generateCSS(ast); + return this.onError( + generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + this.#window + ) + ); + } + let bool; + for (const astChild of astChildren) { + bool = matchLanguagePseudoClass(astChild, node); + if (bool) { + break; + } + } + if (bool) { + matched.add(node); + } + break; + } + // :state() + case 'state': { + if (isCustomElement(node)) { + const [{ value: stateValue }] = astChildren; + if (stateValue) { + if (node[stateValue]) { + matched.add(node); + } else { + for (const i in node) { + const prop = node[i]; + if (prop instanceof this.#window.ElementInternals) { + if (prop?.states?.has(stateValue)) { + matched.add(node); + } + break; + } + } + } + } + } + break; + } + case 'current': + case 'heading': + case 'nth-col': + case 'nth-last-col': { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-class :${astName}()`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + // Ignore :host() and :host-context(). + case 'host': + case 'host-context': { + break; + } + // Deprecated in CSS Selectors 3. + case 'contains': { + if (warn) { + this.onError( + generateException( + `Unknown pseudo-class :${astName}()`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + default: { + if (!forgive) { + this.onError( + generateException( + `Unknown pseudo-class :${astName}()`, + SYNTAX_ERR, + this.#window + ) + ); + } + } + } + } + } else if (KEYS_PS_NTH_OF_TYPE.has(astName)) { + if (node === this.#root) { + matched.add(node); + } else if (parentNode) { + switch (astName) { + case 'first-of-type': { + const [node1] = this._collectNthOfType( + { + a: 0, + b: 1 + }, + node + ); + if (node1) { + matched.add(node1); + } + break; + } + case 'last-of-type': { + const [node1] = this._collectNthOfType( + { + a: 0, + b: 1, + reverse: true + }, + node + ); + if (node1) { + matched.add(node1); + } + break; + } + // 'only-of-type' is handled by default. + default: { + const [node1] = this._collectNthOfType( + { + a: 0, + b: 1 + }, + node + ); + if (node1 === node) { + const [node2] = this._collectNthOfType( + { + a: 0, + b: 1, + reverse: true + }, + node + ); + if (node2 === node) { + matched.add(node); + } + } + } + } + } + } else { + switch (astName) { + case 'disabled': + case 'enabled': { + const isMatch = matchDisabledPseudoClass(astName, node); + if (isMatch) { + matched.add(node); + } + break; + } + case 'read-only': + case 'read-write': { + const isMatch = matchReadOnlyPseudoClass(astName, node); + if (isMatch) { + matched.add(node); + } + break; + } + case 'any-link': + case 'link': { + if ( + (localName === 'a' || localName === 'area') && + node.hasAttribute('href') + ) { + matched.add(node); + } + break; + } + case 'local-link': { + if ( + (localName === 'a' || localName === 'area') && + node.hasAttribute('href') + ) { + if (!this.#documentURL) { + this.#documentURL = new URL(this.#document.URL); + } + const { href, origin, pathname } = this.#documentURL; + const attrURL = new URL(node.getAttribute('href'), href); + if (attrURL.origin === origin && attrURL.pathname === pathname) { + matched.add(node); + } + } + break; + } + case 'visited': { + // prevent fingerprinting + break; + } + case 'hover': { + const { target, type } = this.#event ?? {}; + if ( + /^(?:click|mouse(?:down|over|up))$/.test(type) && + node.contains(target) + ) { + matched.add(node); + } + break; + } + case 'active': { + const { buttons, target, type } = this.#event ?? {}; + if (type === 'mousedown' && buttons & 1 && node.contains(target)) { + matched.add(node); + } + break; + } + case 'target': { + if (!this.#documentURL) { + this.#documentURL = new URL(this.#document.URL); + } + const { hash } = this.#documentURL; + if ( + node.id && + hash === `#${node.id}` && + this.#document.contains(node) + ) { + matched.add(node); + } + break; + } + case 'target-within': { + if (!this.#documentURL) { + this.#documentURL = new URL(this.#document.URL); + } + const { hash } = this.#documentURL; + if (hash) { + const id = hash.replace(/^#/, ''); + let current = this.#document.getElementById(id); + while (current) { + if (current === node) { + matched.add(node); + break; + } + current = current.parentNode; + } + } + break; + } + case 'scope': { + if (this.#node.nodeType === ELEMENT_NODE) { + if (!this.#shadow && node === this.#node) { + matched.add(node); + } + } else if (node === this.#document.documentElement) { + matched.add(node); + } + break; + } + case 'focus': { + const activeElement = this.#document.activeElement; + if (node === activeElement && isFocusableArea(node)) { + matched.add(node); + } else if (activeElement.shadowRoot) { + const activeShadowElement = activeElement.shadowRoot.activeElement; + let current = activeShadowElement; + while (current) { + if (current.nodeType === DOCUMENT_FRAGMENT_NODE) { + const { host } = current; + if (host === activeElement) { + if (isFocusableArea(node)) { + matched.add(node); + } else { + matched.add(host); + } + } + break; + } else { + current = current.parentNode; + } + } + } + break; + } + case 'focus-visible': { + if (node === this.#document.activeElement && isFocusableArea(node)) { + let bool; + if (isFocusVisible(node)) { + bool = true; + } else if (this.#focus) { + const { relatedTarget, target: focusTarget } = this.#focus; + if (focusTarget === node) { + if (isFocusVisible(relatedTarget)) { + bool = true; + } else if (this.#event) { + const { + altKey: eventAltKey, + ctrlKey: eventCtrlKey, + key: eventKey, + metaKey: eventMetaKey, + target: eventTarget, + type: eventType + } = this.#event; + // this.#event is irrelevant if eventTarget === relatedTarget + if (eventTarget === relatedTarget) { + if (this.#lastFocusVisible === null) { + bool = true; + } else if (focusTarget === this.#lastFocusVisible) { + bool = true; + } + } else if (eventKey === 'Tab') { + if ( + (eventType === 'keydown' && eventTarget !== node) || + (eventType === 'keyup' && eventTarget === node) + ) { + if (eventTarget === focusTarget) { + if (this.#lastFocusVisible === null) { + bool = true; + } else if ( + eventTarget === this.#lastFocusVisible && + relatedTarget === null + ) { + bool = true; + } + } else { + bool = true; + } + } + } else if (eventKey) { + if ( + (eventType === 'keydown' || eventType === 'keyup') && + !eventAltKey && + !eventCtrlKey && + !eventMetaKey && + eventTarget === node + ) { + bool = true; + } + } + } else if ( + relatedTarget === null || + relatedTarget === this.#lastFocusVisible + ) { + bool = true; + } + } + } + if (bool) { + this.#lastFocusVisible = node; + matched.add(node); + } else if (this.#lastFocusVisible === node) { + this.#lastFocusVisible = null; + } + } + break; + } + case 'focus-within': { + const activeElement = this.#document.activeElement; + if (node.contains(activeElement) && isFocusableArea(activeElement)) { + matched.add(node); + } else if (activeElement.shadowRoot) { + const activeShadowElement = activeElement.shadowRoot.activeElement; + if (node.contains(activeShadowElement)) { + matched.add(node); + } else { + let current = activeShadowElement; + while (current) { + if (current.nodeType === DOCUMENT_FRAGMENT_NODE) { + const { host } = current; + if (host === activeElement && node.contains(host)) { + matched.add(node); + } + break; + } else { + current = current.parentNode; + } + } + } + } + break; + } + case 'open': + case 'closed': { + if (localName === 'details' || localName === 'dialog') { + if (node.hasAttribute('open')) { + if (astName === 'open') { + matched.add(node); + } + } else if (astName === 'closed') { + matched.add(node); + } + } + break; + } + case 'placeholder-shown': { + let placeholder; + if (node.placeholder) { + placeholder = node.placeholder; + } else if (node.hasAttribute('placeholder')) { + placeholder = node.getAttribute('placeholder'); + } + if (typeof placeholder === 'string' && !/[\r\n]/.test(placeholder)) { + let targetNode; + if (localName === 'textarea') { + targetNode = node; + } else if (localName === 'input') { + if (node.hasAttribute('type')) { + if (KEYS_INPUT_PLACEHOLDER.has(node.getAttribute('type'))) { + targetNode = node; + } + } else { + targetNode = node; + } + } + if (targetNode && node.value === '') { + matched.add(node); + } + } + break; + } + case 'checked': { + const attrType = node.getAttribute('type'); + if ( + (node.checked && + localName === 'input' && + (attrType === 'checkbox' || attrType === 'radio')) || + (node.selected && localName === 'option') + ) { + matched.add(node); + } + break; + } + case 'indeterminate': { + if ( + (node.indeterminate && + localName === 'input' && + node.type === 'checkbox') || + (localName === 'progress' && !node.hasAttribute('value')) + ) { + matched.add(node); + } else if ( + localName === 'input' && + node.type === 'radio' && + !node.hasAttribute('checked') + ) { + const nodeName = node.name; + let parent = node.parentNode; + while (parent) { + if (parent.localName === 'form') { + break; + } + parent = parent.parentNode; + } + if (!parent) { + parent = this.#document.documentElement; + } + const walker = this._createTreeWalker(parent); + let refNode = traverseNode(parent, walker); + refNode = walker.firstChild(); + let checked; + while (refNode) { + if ( + refNode.localName === 'input' && + refNode.getAttribute('type') === 'radio' + ) { + if (refNode.hasAttribute('name')) { + if (refNode.getAttribute('name') === nodeName) { + checked = !!refNode.checked; + } + } else { + checked = !!refNode.checked; + } + if (checked) { + break; + } + } + refNode = walker.nextNode(); + } + if (!checked) { + matched.add(node); + } + } + break; + } + case 'default': { + // button[type="submit"], input[type="submit"], input[type="image"] + const attrType = node.getAttribute('type'); + if ( + (localName === 'button' && + !(node.hasAttribute('type') && KEYS_INPUT_RESET.has(attrType))) || + (localName === 'input' && + node.hasAttribute('type') && + KEYS_INPUT_SUBMIT.has(attrType)) + ) { + let form = node.parentNode; + while (form) { + if (form.localName === 'form') { + break; + } + form = form.parentNode; + } + if (form) { + const walker = this._createTreeWalker(form); + let refNode = traverseNode(form, walker); + refNode = walker.firstChild(); + while (refNode) { + const nodeName = refNode.localName; + const nodeAttrType = refNode.getAttribute('type'); + let m; + if (nodeName === 'button') { + m = !( + refNode.hasAttribute('type') && + KEYS_INPUT_RESET.has(nodeAttrType) + ); + } else if (nodeName === 'input') { + m = + refNode.hasAttribute('type') && + KEYS_INPUT_SUBMIT.has(nodeAttrType); + } + if (m) { + if (refNode === node) { + matched.add(node); + } + break; + } + refNode = walker.nextNode(); + } + } + // input[type="checkbox"], input[type="radio"] + } else if ( + localName === 'input' && + node.hasAttribute('type') && + node.hasAttribute('checked') && + KEYS_INPUT_CHECK.has(attrType) + ) { + matched.add(node); + // option + } else if (localName === 'option' && node.hasAttribute('selected')) { + matched.add(node); + } + break; + } + case 'valid': + case 'invalid': { + if (KEYS_FORM_PS_VALID.has(localName)) { + let valid; + if (node.checkValidity()) { + if (node.maxLength >= 0) { + if (node.maxLength >= node.value.length) { + valid = true; + } + } else { + valid = true; + } + } + if (valid) { + if (astName === 'valid') { + matched.add(node); + } + } else if (astName === 'invalid') { + matched.add(node); + } + } else if (localName === 'fieldset') { + const walker = this._createTreeWalker(node); + let refNode = traverseNode(node, walker); + refNode = walker.firstChild(); + let valid; + if (!refNode) { + valid = true; + } else { + while (refNode) { + if (KEYS_FORM_PS_VALID.has(refNode.localName)) { + if (refNode.checkValidity()) { + if (refNode.maxLength >= 0) { + valid = refNode.maxLength >= refNode.value.length; + } else { + valid = true; + } + } else { + valid = false; + } + if (!valid) { + break; + } + } + refNode = walker.nextNode(); + } + } + if (valid) { + if (astName === 'valid') { + matched.add(node); + } + } else if (astName === 'invalid') { + matched.add(node); + } + } + break; + } + case 'in-range': + case 'out-of-range': { + const attrType = node.getAttribute('type'); + if ( + localName === 'input' && + !(node.readonly || node.hasAttribute('readonly')) && + !(node.disabled || node.hasAttribute('disabled')) && + KEYS_INPUT_RANGE.has(attrType) + ) { + const flowed = + node.validity.rangeUnderflow || node.validity.rangeOverflow; + if (astName === 'out-of-range' && flowed) { + matched.add(node); + } else if ( + astName === 'in-range' && + !flowed && + (node.hasAttribute('min') || + node.hasAttribute('max') || + attrType === 'range') + ) { + matched.add(node); + } + } + break; + } + case 'required': + case 'optional': { + let required; + let optional; + if (localName === 'select' || localName === 'textarea') { + if (node.required || node.hasAttribute('required')) { + required = true; + } else { + optional = true; + } + } else if (localName === 'input') { + if (node.hasAttribute('type')) { + const attrType = node.getAttribute('type'); + if (KEYS_INPUT_REQUIRED.has(attrType)) { + if (node.required || node.hasAttribute('required')) { + required = true; + } else { + optional = true; + } + } else { + optional = true; + } + } else if (node.required || node.hasAttribute('required')) { + required = true; + } else { + optional = true; + } + } + if (astName === 'required' && required) { + matched.add(node); + } else if (astName === 'optional' && optional) { + matched.add(node); + } + break; + } + case 'root': { + if (node === this.#document.documentElement) { + matched.add(node); + } + break; + } + case 'empty': { + if (node.hasChildNodes()) { + const walker = this._createTreeWalker(node, { + force: true, + whatToShow: SHOW_ALL + }); + let refNode = walker.firstChild(); + let bool; + while (refNode) { + bool = + refNode.nodeType !== ELEMENT_NODE && + refNode.nodeType !== TEXT_NODE; + if (!bool) { + break; + } + refNode = walker.nextSibling(); + } + if (bool) { + matched.add(node); + } + } else { + matched.add(node); + } + break; + } + case 'first-child': { + if ( + (parentNode && node === parentNode.firstElementChild) || + node === this.#root + ) { + matched.add(node); + } + break; + } + case 'last-child': { + if ( + (parentNode && node === parentNode.lastElementChild) || + node === this.#root + ) { + matched.add(node); + } + break; + } + case 'only-child': { + if ( + (parentNode && + node === parentNode.firstElementChild && + node === parentNode.lastElementChild) || + node === this.#root + ) { + matched.add(node); + } + break; + } + case 'defined': { + if (node.hasAttribute('is') || localName.includes('-')) { + if (isCustomElement(node)) { + matched.add(node); + } + // NOTE: MathMLElement is not implemented in jsdom. + } else if ( + node instanceof this.#window.HTMLElement || + node instanceof this.#window.SVGElement + ) { + matched.add(node); + } + break; + } + case 'popover-open': { + if (node.popover && isVisible(node)) { + matched.add(node); + } + break; + } + // Ignore :host. + case 'host': { + break; + } + // Legacy pseudo-elements. + case 'after': + case 'before': + case 'first-letter': + case 'first-line': { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-element ::${astName}`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + // Not supported. + case 'autofill': + case 'blank': + case 'buffering': + case 'current': + case 'fullscreen': + case 'future': + case 'has-slotted': + case 'heading': + case 'modal': + case 'muted': + case 'past': + case 'paused': + case 'picture-in-picture': + case 'playing': + case 'seeking': + case 'stalled': + case 'user-invalid': + case 'user-valid': + case 'volume-locked': + case '-webkit-autofill': { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-class :${astName}`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + break; + } + default: { + if (astName.startsWith('-webkit-')) { + if (warn) { + this.onError( + generateException( + `Unsupported pseudo-class :${astName}`, + NOT_SUPPORTED_ERR, + this.#window + ) + ); + } + } else if (!forgive) { + this.onError( + generateException( + `Unknown pseudo-class :${astName}`, + SYNTAX_ERR, + this.#window + ) + ); + } + } + } + } + return matched; + } + + /** + * Evaluates the :host() pseudo-class. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} host - The host element. + * @param {object} ast - The original AST for error reporting. + * @returns {boolean} True if matched. + */ + _evaluateHostPseudo = (leaves, host, ast) => { + const l = leaves.length; + for (let i = 0; i < l; i++) { + const leaf = leaves[i]; + if (leaf.type === COMBINATOR) { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + return false; + } + if (!this._matchSelector(leaf, host).has(host)) { + return false; + } + } + return true; + }; + + /** + * Evaluates the :host-context() pseudo-class. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} host - The host element. + * @param {object} ast - The original AST for error reporting. + * @returns {boolean} True if matched. + */ + _evaluateHostContextPseudo = (leaves, host, ast) => { + let parent = host; + while (parent) { + let bool; + const l = leaves.length; + for (let i = 0; i < l; i++) { + const leaf = leaves[i]; + if (leaf.type === COMBINATOR) { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + return false; + } + bool = this._matchSelector(leaf, parent).has(parent); + if (!bool) { + break; + } + } + if (bool) { + return true; + } + parent = parent.parentNode; + } + return false; + }; + + /** + * Matches shadow host pseudo-classes. + * @private + * @param {object} ast - The AST. + * @param {object} node - The DocumentFragment node. + * @returns {?object} The matched node. + */ + _matchShadowHostPseudoClass = (ast, node) => { + const { children: astChildren, name: astName } = ast; + // Handle simple pseudo-class (no arguments). + if (!Array.isArray(astChildren)) { + if (astName === 'host') { + return node; + } + const msg = `Invalid selector :${astName}`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + // Handle functional pseudo-class like :host(...). + if (astName !== 'host' && astName !== 'host-context') { + const msg = `Invalid selector :${astName}()`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + if (astChildren.length !== 1) { + const css = generateCSS(ast); + const msg = `Invalid selector ${css}`; + return this.onError(generateException(msg, SYNTAX_ERR, this.#window)); + } + const { host } = node; + const { branches } = walkAST(astChildren[0]); + const [branch] = branches; + const [...leaves] = branch; + let isMatch = false; + if (astName === 'host') { + isMatch = this._evaluateHostPseudo(leaves, host, ast); + // astName === 'host-context'. + } else { + isMatch = this._evaluateHostContextPseudo(leaves, host, ast); + } + return isMatch ? node : null; + }; + + /** + * Matches a selector for element nodes. + * @private + * @param {object} ast - The AST. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchSelectorForElement = (ast, node, opt = {}) => { + const { type: astType } = ast; + const astName = unescapeSelector(ast.name); + const matched = new Set(); + switch (astType) { + case ATTR_SELECTOR: { + if (matchAttributeSelector(ast, node, opt)) { + matched.add(node); + } + break; + } + case ID_SELECTOR: { + if (node.id === astName) { + matched.add(node); + } + break; + } + case CLASS_SELECTOR: { + if (node.classList.contains(astName)) { + matched.add(node); + } + break; + } + case PS_CLASS_SELECTOR: { + return this._matchPseudoClassSelector(ast, node, opt); + } + case TYPE_SELECTOR: { + if (matchTypeSelector(ast, node, opt)) { + matched.add(node); + } + break; + } + // PS_ELEMENT_SELECTOR is handled by default. + default: { + try { + if (opt.check) { + const css = generateCSS(ast); + this.#pseudoElement.push(css); + matched.add(node); + } else { + matchPseudoElementSelector(astName, astType, opt); + } + } catch (e) { + this.onError(e); + } + } + } + return matched; + }; + + /** + * Matches a selector for a shadow root. + * @private + * @param {object} ast - The AST. + * @param {object} node - The DocumentFragment node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchSelectorForShadowRoot = (ast, node, opt = {}) => { + const { name: astName } = ast; + if (KEYS_LOGICAL.has(astName)) { + opt.isShadowRoot = true; + return this._matchPseudoClassSelector(ast, node, opt); + } + const matched = new Set(); + if (astName === 'host' || astName === 'host-context') { + const res = this._matchShadowHostPseudoClass(ast, node, opt); + if (res) { + this.#verifyShadowHost = true; + matched.add(res); + } + } + return matched; + }; + + /** + * Matches a selector. + * @private + * @param {object} ast - The AST. + * @param {object} node - The Document, DocumentFragment, or Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchSelector = (ast, node, opt = {}) => { + if (node.nodeType === ELEMENT_NODE) { + return this._matchSelectorForElement(ast, node, opt); + } + if ( + this.#shadow && + node.nodeType === DOCUMENT_FRAGMENT_NODE && + ast.type === PS_CLASS_SELECTOR + ) { + return this._matchSelectorForShadowRoot(ast, node, opt); + } + return new Set(); + }; + + /** + * Matches leaves. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} node - The node. + * @param {object} [opt] - Options. + * @returns {boolean} The result. + */ + _matchLeaves = (leaves, node, opt = {}) => { + const results = this.#invalidate ? this.#invalidateResults : this.#results; + let result = results.get(leaves); + if (result && result.has(node)) { + const { matched } = result.get(node); + return matched; + } + let cacheable = true; + if (node.nodeType === ELEMENT_NODE && KEYS_FORM.has(node.localName)) { + cacheable = false; + } + let bool; + const l = leaves.length; + for (let i = 0; i < l; i++) { + const leaf = leaves[i]; + switch (leaf.type) { + case ATTR_SELECTOR: + case ID_SELECTOR: { + cacheable = false; + break; + } + case PS_CLASS_SELECTOR: { + if (KEYS_PS_UNCACHE.has(leaf.name)) { + cacheable = false; + } + break; + } + default: { + // No action needed for other types. + } + } + bool = this._matchSelector(leaf, node, opt).has(node); + if (!bool) { + break; + } + } + if (cacheable) { + if (!result) { + result = new WeakMap(); + } + result.set(node, { + matched: bool + }); + results.set(leaves, result); + } + return bool; + }; + + /** + * Traverses all descendant nodes and collects matches. + * @private + * @param {object} baseNode - The base Element node or Element.shadowRoot. + * @param {Array.} leaves - The AST leaves. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _traverseAllDescendants = (baseNode, leaves, opt = {}) => { + const walker = this._createTreeWalker(baseNode); + traverseNode(baseNode, walker); + let currentNode = walker.firstChild(); + const nodes = new Set(); + while (currentNode) { + if (this._matchLeaves(leaves, currentNode, opt)) { + nodes.add(currentNode); + } + currentNode = walker.nextNode(); + } + return nodes; + }; + + /** + * Finds descendant nodes. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} baseNode - The base Element node or Element.shadowRoot. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _findDescendantNodes = (leaves, baseNode, opt = {}) => { + const [leaf, ...filterLeaves] = leaves; + const { type: leafType } = leaf; + switch (leafType) { + case ID_SELECTOR: { + const canUseGetElementById = + !this.#shadow && + baseNode.nodeType === ELEMENT_NODE && + this.#root.nodeType !== ELEMENT_NODE; + if (canUseGetElementById) { + const leafName = unescapeSelector(leaf.name); + const nodes = new Set(); + const foundNode = this.#root.getElementById(leafName); + if ( + foundNode && + foundNode !== baseNode && + baseNode.contains(foundNode) + ) { + const isCompoundSelector = filterLeaves.length > 0; + if ( + !isCompoundSelector || + this._matchLeaves(filterLeaves, foundNode, opt) + ) { + nodes.add(foundNode); + } + } + return nodes; + } + // Fallback to default traversal if fast path is not applicable. + return this._traverseAllDescendants(baseNode, leaves, opt); + } + case PS_ELEMENT_SELECTOR: { + const leafName = unescapeSelector(leaf.name); + matchPseudoElementSelector(leafName, leafType, opt); + return new Set(); + } + default: { + return this._traverseAllDescendants(baseNode, leaves, opt); + } + } + }; + + /** + * Matches the descendant combinator ' '. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchDescendantCombinator = (twig, node, opt = {}) => { + const { leaves } = twig; + const { parentNode } = node; + const { dir } = opt; + if (dir === DIR_NEXT) { + return this._findDescendantNodes(leaves, node, opt); + } + // DIR_PREV + const ancestors = []; + let refNode = parentNode; + while (refNode) { + if (this._matchLeaves(leaves, refNode, opt)) { + ancestors.push(refNode); + } + refNode = refNode.parentNode; + } + if (ancestors.length) { + // Reverse to maintain document order. + return new Set(ancestors.reverse()); + } + return new Set(); + }; + + /** + * Matches the child combinator '>'. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchChildCombinator = (twig, node, opt = {}) => { + const { leaves } = twig; + const { dir } = opt; + const { parentNode } = node; + const matched = new Set(); + if (dir === DIR_NEXT) { + let refNode = node.firstElementChild; + while (refNode) { + if (this._matchLeaves(leaves, refNode, opt)) { + matched.add(refNode); + } + refNode = refNode.nextElementSibling; + } + } else { + // DIR_PREV + if (parentNode && this._matchLeaves(leaves, parentNode, opt)) { + matched.add(parentNode); + } + } + return matched; + }; + + /** + * Matches the adjacent sibling combinator '+'. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchAdjacentSiblingCombinator = (twig, node, opt = {}) => { + const { leaves } = twig; + const { dir } = opt; + const matched = new Set(); + const refNode = + dir === DIR_NEXT ? node.nextElementSibling : node.previousElementSibling; + if (refNode && this._matchLeaves(leaves, refNode, opt)) { + matched.add(refNode); + } + return matched; + }; + + /** + * Matches the general sibling combinator '~'. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchGeneralSiblingCombinator = (twig, node, opt = {}) => { + const { leaves } = twig; + const { dir } = opt; + const matched = new Set(); + let refNode = + dir === DIR_NEXT ? node.nextElementSibling : node.previousElementSibling; + while (refNode) { + if (this._matchLeaves(leaves, refNode, opt)) { + matched.add(refNode); + } + refNode = + dir === DIR_NEXT + ? refNode.nextElementSibling + : refNode.previousElementSibling; + } + return matched; + }; + + /** + * Matches a combinator. + * @private + * @param {object} twig - The twig object. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {Set.} A collection of matched nodes. + */ + _matchCombinator = (twig, node, opt = {}) => { + const { + combo: { name: comboName } + } = twig; + switch (comboName) { + case '+': { + return this._matchAdjacentSiblingCombinator(twig, node, opt); + } + case '~': { + return this._matchGeneralSiblingCombinator(twig, node, opt); + } + case '>': { + return this._matchChildCombinator(twig, node, opt); + } + case ' ': + default: { + return this._matchDescendantCombinator(twig, node, opt); + } + } + }; + + /** + * Traverses with a TreeWalker and collects nodes matching the leaves. + * @private + * @param {TreeWalker} walker - The TreeWalker instance to use. + * @param {Array} leaves - The AST leaves to match against. + * @param {object} options - Traversal options. + * @param {Node} options.startNode - The node to start traversal from. + * @param {string} options.targetType - The type of target ('all' or 'first'). + * @param {Node} [options.boundaryNode] - The node to stop traversal at. + * @param {boolean} [options.force] - Force traversal to the next node. + * @returns {Array.} An array of matched nodes. + */ + _traverseAndCollectNodes = (walker, leaves, options) => { + const { boundaryNode, force, startNode, targetType } = options; + const collectedNodes = []; + let currentNode = traverseNode(startNode, walker, !!force); + if (!currentNode) { + return []; + } + // Adjust starting node. + if (currentNode.nodeType !== ELEMENT_NODE) { + currentNode = walker.nextNode(); + } else if (currentNode === startNode && currentNode !== this.#root) { + currentNode = walker.nextNode(); + } + const matchOpt = { + warn: this.#warn + }; + while (currentNode) { + // Stop when we reach the boundary. + if (boundaryNode) { + if (currentNode === boundaryNode) { + break; + } else if ( + targetType === TARGET_ALL && + !boundaryNode.contains(currentNode) + ) { + break; + } + } + if ( + this._matchLeaves(leaves, currentNode, matchOpt) && + currentNode !== this.#node + ) { + collectedNodes.push(currentNode); + // Stop after the first match if not collecting all. + if (targetType !== TARGET_ALL) { + break; + } + } + currentNode = walker.nextNode(); + } + return collectedNodes; + }; + + /** + * Finds matched node(s) preceding this.#node. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} node - The node to start from. + * @param {object} opt - Options. + * @param {boolean} [opt.force] - If true, traverses only to the next node. + * @param {string} [opt.targetType] - The target type. + * @returns {Array.} A collection of matched nodes. + */ + _findPrecede = (leaves, node, opt = {}) => { + const { force, targetType } = opt; + if (!this.#rootWalker) { + this.#rootWalker = this._createTreeWalker(this.#root); + } + return this._traverseAndCollectNodes(this.#rootWalker, leaves, { + force, + targetType, + boundaryNode: this.#node, + startNode: node + }); + }; + + /** + * Finds matched node(s) in #nodeWalker. + * @private + * @param {Array.} leaves - The AST leaves. + * @param {object} node - The node to start from. + * @param {object} opt - Options. + * @param {boolean} [opt.precede] - If true, finds preceding nodes. + * @returns {Array.} A collection of matched nodes. + */ + _findNodeWalker = (leaves, node, opt = {}) => { + const { precede, ...traversalOpts } = opt; + if (precede) { + const precedeNodes = this._findPrecede(leaves, this.#root, opt); + if (precedeNodes.length) { + return precedeNodes; + } + } + if (!this.#nodeWalker) { + this.#nodeWalker = this._createTreeWalker(this.#node); + } + return this._traverseAndCollectNodes(this.#nodeWalker, leaves, { + startNode: node, + ...traversalOpts + }); + }; + + /** + * Matches the node itself. + * @private + * @param {Array} leaves - The AST leaves. + * @param {boolean} check - Indicates if running in internal check(). + * @returns {Array} An array containing [nodes, filtered, pseudoElement]. + */ + _matchSelf = (leaves, check = false) => { + const options = { check, warn: this.#warn }; + const matched = this._matchLeaves(leaves, this.#node, options); + const nodes = matched ? [this.#node] : []; + return [nodes, matched, this.#pseudoElement]; + }; + + /** + * Finds lineal nodes (self and ancestors). + * @private + * @param {Array} leaves - The AST leaves. + * @param {object} opt - Options. + * @returns {Array} An array containing [nodes, filtered]. + */ + _findLineal = (leaves, opt) => { + const { complex } = opt; + const nodes = []; + const options = { warn: this.#warn }; + const selfMatched = this._matchLeaves(leaves, this.#node, options); + if (selfMatched) { + nodes.push(this.#node); + } + if (!selfMatched || complex) { + let currentNode = this.#node.parentNode; + while (currentNode) { + if (this._matchLeaves(leaves, currentNode, options)) { + nodes.push(currentNode); + } + currentNode = currentNode.parentNode; + } + } + const filtered = nodes.length > 0; + return [nodes, filtered]; + }; + + /** + * Finds entry nodes for pseudo-element selectors. + * @private + * @param {object} leaf - The pseudo-element leaf from the AST. + * @param {Array.} filterLeaves - Leaves for compound selectors. + * @param {string} targetType - The type of target to find. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForPseudoElement = (leaf, filterLeaves, targetType) => { + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF && this.#check) { + const css = generateCSS(leaf); + this.#pseudoElement.push(css); + if (filterLeaves.length) { + [nodes, filtered] = this._matchSelf(filterLeaves, this.#check); + } else { + nodes.push(this.#node); + filtered = true; + } + } else { + matchPseudoElementSelector(leaf.name, leaf.type, { warn: this.#warn }); + } + return { nodes, filtered, pending: false }; + }; + + /** + * Finds entry nodes for ID selectors. + * @private + * @param {object} twig - The current twig from the AST branch. + * @param {string} targetType - The type of target to find. + * @param {object} opt - Additional options for finding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForId = (twig, targetType, opt) => { + const { leaves } = twig; + const [leaf, ...filterLeaves] = leaves; + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else if ( + targetType === TARGET_FIRST && + this.#root.nodeType !== ELEMENT_NODE + ) { + const node = this.#root.getElementById(leaf.name); + if (node) { + if (filterLeaves.length) { + if (this._matchLeaves(filterLeaves, node, { warn: this.#warn })) { + nodes.push(node); + filtered = true; + } + } else { + nodes.push(node); + filtered = true; + } + } + } else { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } + return { nodes, filtered, pending: false }; + }; + + /** + * Finds entry nodes for class selectors. + * @private + * @param {Array.} leaves - The AST leaves for the selector. + * @param {string} targetType - The type of target to find. + * @param {object} opt - Additional options for finding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForClass = (leaves, targetType, opt) => { + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } + return { nodes, filtered, pending: false }; + }; + + /** + * Finds entry nodes for type selectors. + * @private + * @param {Array.} leaves - The AST leaves for the selector. + * @param {string} targetType - The type of target to find. + * @param {object} opt - Additional options for finding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForType = (leaves, targetType, opt) => { + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } + return { nodes, filtered, pending: false }; + }; + + /** + * Finds entry nodes for other selector types (default case). + * @private + * @param {object} twig - The current twig from the AST branch. + * @param {string} targetType - The type of target to find. + * @param {object} opt - Additional options for finding nodes. + * @returns {object} The result { nodes, filtered, pending }. + */ + _findEntryNodesForOther = (twig, targetType, opt) => { + const { leaves } = twig; + const [leaf, ...filterLeaves] = leaves; + const { complex, precede } = opt; + let nodes = []; + let filtered = false; + let pending = false; + if (targetType !== TARGET_LINEAL && /host(?:-context)?/.test(leaf.name)) { + let shadowRoot = null; + if (this.#shadow && this.#node.nodeType === DOCUMENT_FRAGMENT_NODE) { + shadowRoot = this._matchShadowHostPseudoClass(leaf, this.#node); + } else if (filterLeaves.length && this.#node.nodeType === ELEMENT_NODE) { + shadowRoot = this._matchShadowHostPseudoClass( + leaf, + this.#node.shadowRoot + ); + } + if (shadowRoot) { + let bool = true; + const l = filterLeaves.length; + for (let i = 0; i < l; i++) { + const filterLeaf = filterLeaves[i]; + switch (filterLeaf.name) { + case 'host': + case 'host-context': { + const matchedNode = this._matchShadowHostPseudoClass( + filterLeaf, + shadowRoot + ); + bool = matchedNode === shadowRoot; + break; + } + case 'has': { + bool = this._matchPseudoClassSelector( + filterLeaf, + shadowRoot, + {} + ).has(shadowRoot); + break; + } + default: { + bool = false; + } + } + if (!bool) { + break; + } + } + if (bool) { + nodes.push(shadowRoot); + filtered = true; + } + } + } else if (targetType === TARGET_SELF) { + [nodes, filtered] = this._matchSelf(leaves); + } else if (targetType === TARGET_LINEAL) { + [nodes, filtered] = this._findLineal(leaves, { complex }); + } else if (targetType === TARGET_FIRST) { + nodes = this._findNodeWalker(leaves, this.#node, { precede, targetType }); + filtered = nodes.length > 0; + } else { + pending = true; + } + return { nodes, filtered, pending }; + }; + + /** + * Finds entry nodes. + * @private + * @param {object} twig - The twig object. + * @param {string} targetType - The target type. + * @param {object} [opt] - Options. + * @param {boolean} [opt.complex] - If true, the selector is complex. + * @param {string} [opt.dir] - The find direction. + * @returns {object} An object with nodes and their state. + */ + _findEntryNodes = (twig, targetType, opt = {}) => { + const { leaves } = twig; + const [leaf, ...filterLeaves] = leaves; + const { complex = false, dir = DIR_PREV } = opt; + const precede = + dir === DIR_NEXT && + this.#node.nodeType === ELEMENT_NODE && + this.#node !== this.#root; + let result; + switch (leaf.type) { + case PS_ELEMENT_SELECTOR: { + result = this._findEntryNodesForPseudoElement( + leaf, + filterLeaves, + targetType + ); + break; + } + case ID_SELECTOR: { + result = this._findEntryNodesForId(twig, targetType, { + complex, + precede + }); + break; + } + case CLASS_SELECTOR: { + result = this._findEntryNodesForClass(leaves, targetType, { + complex, + precede + }); + break; + } + case TYPE_SELECTOR: { + result = this._findEntryNodesForType(leaves, targetType, { + complex, + precede + }); + break; + } + default: { + result = this._findEntryNodesForOther(twig, targetType, { + complex, + precede + }); + } + } + return { + compound: filterLeaves.length > 0, + filtered: result.filtered, + nodes: result.nodes, + pending: result.pending + }; + }; + + /** + * Determines the direction and starting twig for a selector branch. + * @private + * @param {Array.} branch - The AST branch. + * @param {string} targetType - The type of target to find. + * @returns {object} An object with the direction and starting twig. + */ + _determineTraversalStrategy = (branch, targetType) => { + const branchLen = branch.length; + const firstTwig = branch[0]; + const lastTwig = branch[branchLen - 1]; + if (branchLen === 1) { + return { dir: DIR_PREV, twig: firstTwig }; + } + // Complex selector (branchLen > 1). + const { + leaves: [{ name: firstName, type: firstType }] + } = firstTwig; + const { + leaves: [{ name: lastName, type: lastType }] + } = lastTwig; + const { combo: firstCombo } = firstTwig; + if ( + this.#selector.includes(':scope') || + lastType === PS_ELEMENT_SELECTOR || + lastType === ID_SELECTOR + ) { + return { dir: DIR_PREV, twig: lastTwig }; + } + if (firstType === ID_SELECTOR) { + return { dir: DIR_NEXT, twig: firstTwig }; + } + if (firstName === '*' && firstType === TYPE_SELECTOR) { + return { dir: DIR_PREV, twig: lastTwig }; + } + if (lastName === '*' && lastType === TYPE_SELECTOR) { + return { dir: DIR_NEXT, twig: firstTwig }; + } + if (branchLen === 2) { + if (targetType === TARGET_FIRST) { + return { dir: DIR_PREV, twig: lastTwig }; + } + const { name: comboName } = firstCombo; + if (comboName === '+' || comboName === '~') { + return { dir: DIR_PREV, twig: lastTwig }; + } + } else if (branchLen > 2 && this.#scoped && targetType === TARGET_FIRST) { + if (lastType === TYPE_SELECTOR) { + return { dir: DIR_PREV, twig: lastTwig }; + } + let isChildOrDescendant = false; + for (const { combo } of branch) { + if (combo) { + const { name: comboName } = combo; + isChildOrDescendant = comboName === '>' || comboName === ' '; + if (!isChildOrDescendant) { + break; + } + } + } + if (isChildOrDescendant) { + return { dir: DIR_PREV, twig: lastTwig }; + } + } + // Default strategy for complex selectors. + return { dir: DIR_NEXT, twig: firstTwig }; + }; + + /** + * Processes pending items not resolved with a direct strategy. + * @private + * @param {Set.} pendingItems - The set of pending items. + */ + _processPendingItems = pendingItems => { + if (!pendingItems.size) { + return; + } + if (!this.#rootWalker) { + this.#rootWalker = this._createTreeWalker(this.#root); + } + const walker = this.#rootWalker; + let node = this.#root; + if (this.#scoped) { + node = this.#node; + } + let nextNode = traverseNode(node, walker); + while (nextNode) { + const isWithinScope = + this.#node.nodeType !== ELEMENT_NODE || + nextNode === this.#node || + this.#node.contains(nextNode); + if (isWithinScope) { + for (const pendingItem of pendingItems) { + const { leaves } = pendingItem.get('twig'); + if (this._matchLeaves(leaves, nextNode, { warn: this.#warn })) { + const index = pendingItem.get('index'); + this.#ast[index].filtered = true; + this.#ast[index].find = true; + this.#nodes[index].push(nextNode); + } + } + } else if (this.#scoped) { + break; + } + nextNode = walker.nextNode(); + } + }; + + /** + * Collects nodes. + * @private + * @param {string} targetType - The target type. + * @returns {Array.>} An array containing the AST and nodes. + */ + _collectNodes = targetType => { + const ast = this.#ast.values(); + if (targetType === TARGET_ALL || targetType === TARGET_FIRST) { + const pendingItems = new Set(); + let i = 0; + for (const { branch } of ast) { + const complex = branch.length > 1; + const { dir, twig } = this._determineTraversalStrategy( + branch, + targetType + ); + const { compound, filtered, nodes, pending } = this._findEntryNodes( + twig, + targetType, + { complex, dir } + ); + if (nodes.length) { + this.#ast[i].find = true; + this.#nodes[i] = nodes; + } else if (pending) { + pendingItems.add( + new Map([ + ['index', i], + ['twig', twig] + ]) + ); + } + this.#ast[i].dir = dir; + this.#ast[i].filtered = filtered || !compound; + i++; + } + this._processPendingItems(pendingItems); + } else { + let i = 0; + for (const { branch } of ast) { + const twig = branch[branch.length - 1]; + const complex = branch.length > 1; + const dir = DIR_PREV; + const { compound, filtered, nodes } = this._findEntryNodes( + twig, + targetType, + { complex, dir } + ); + if (nodes.length) { + this.#ast[i].find = true; + this.#nodes[i] = nodes; + } + this.#ast[i].dir = dir; + this.#ast[i].filtered = filtered || !compound; + i++; + } + } + return [this.#ast, this.#nodes]; + }; + + /** + * Gets combined nodes. + * @private + * @param {object} twig - The twig object. + * @param {object} nodes - A collection of nodes. + * @param {string} dir - The direction. + * @returns {Array.} A collection of matched nodes. + */ + _getCombinedNodes = (twig, nodes, dir) => { + const arr = []; + const options = { + dir, + warn: this.#warn + }; + for (const node of nodes) { + const matched = this._matchCombinator(twig, node, options); + if (matched.size) { + arr.push(...matched); + } + } + return arr; + }; + + /** + * Matches a node in the 'next' direction. + * @private + * @param {Array} branch - The branch. + * @param {Set.} nodes - A collection of Element nodes. + * @param {object} opt - Options. + * @param {object} opt.combo - The combo object. + * @param {number} opt.index - The index. + * @returns {?object} The matched node. + */ + _matchNodeNext = (branch, nodes, opt) => { + const { combo, index } = opt; + const { combo: nextCombo, leaves } = branch[index]; + const twig = { + combo, + leaves + }; + const nextNodes = new Set(this._getCombinedNodes(twig, nodes, DIR_NEXT)); + if (nextNodes.size) { + if (index === branch.length - 1) { + const [nextNode] = sortNodes(nextNodes); + return nextNode; + } + return this._matchNodeNext(branch, nextNodes, { + combo: nextCombo, + index: index + 1 + }); + } + return null; + }; + + /** + * Matches a node in the 'previous' direction. + * @private + * @param {Array} branch - The branch. + * @param {object} node - The Element node. + * @param {object} opt - Options. + * @param {number} opt.index - The index. + * @returns {?object} The node. + */ + _matchNodePrev = (branch, node, opt) => { + const { index } = opt; + const twig = branch[index]; + const nodes = new Set([node]); + const nextNodes = new Set(this._getCombinedNodes(twig, nodes, DIR_PREV)); + if (nextNodes.size) { + if (index === 0) { + return node; + } + let matched; + for (const nextNode of nextNodes) { + matched = this._matchNodePrev(branch, nextNode, { + index: index - 1 + }); + if (matched) { + break; + } + } + if (matched) { + return node; + } + } + return null; + }; + + /** + * Processes a complex selector branch to find all matching nodes. + * @private + * @param {Array} branch - The selector branch from the AST. + * @param {Array} entryNodes - The initial set of nodes to start from. + * @param {string} dir - The direction of traversal ('next' or 'prev'). + * @returns {Set.} A set of all matched nodes. + */ + _processComplexBranchAll = (branch, entryNodes, dir) => { + const matchedNodes = new Set(); + const branchLen = branch.length; + const lastIndex = branchLen - 1; + + if (dir === DIR_NEXT) { + const { combo: firstCombo } = branch[0]; + for (const node of entryNodes) { + let combo = firstCombo; + let nextNodes = new Set([node]); + for (let j = 1; j < branchLen; j++) { + const { combo: nextCombo, leaves } = branch[j]; + const twig = { combo, leaves }; + const nodesArr = this._getCombinedNodes(twig, nextNodes, dir); + if (nodesArr.length) { + if (j === lastIndex) { + for (const nextNode of nodesArr) { + matchedNodes.add(nextNode); + } + } + combo = nextCombo; + nextNodes = new Set(nodesArr); + } else { + // No further matches down this path. + nextNodes.clear(); + break; + } + } + } + // DIR_PREV + } else { + for (const node of entryNodes) { + let nextNodes = new Set([node]); + for (let j = lastIndex - 1; j >= 0; j--) { + const twig = branch[j]; + const nodesArr = this._getCombinedNodes(twig, nextNodes, dir); + if (nodesArr.length) { + // The entry node is the final match + if (j === 0) { + matchedNodes.add(node); + } + nextNodes = new Set(nodesArr); + } else { + // No further matches down this path. + nextNodes.clear(); + break; + } + } + } + } + return matchedNodes; + }; + + /** + * Processes a complex selector branch to find the first matching node. + * @private + * @param {Array} branch - The selector branch from the AST. + * @param {Array} entryNodes - The initial set of nodes to start from. + * @param {string} dir - The direction of traversal ('next' or 'prev'). + * @param {string} targetType - The type of search (e.g., 'first'). + * @returns {?object} The first matched node, or null. + */ + _processComplexBranchFirst = (branch, entryNodes, dir, targetType) => { + const branchLen = branch.length; + const lastIndex = branchLen - 1; + // DIR_NEXT logic for finding the first match. + if (dir === DIR_NEXT) { + const { combo: entryCombo } = branch[0]; + for (const node of entryNodes) { + const matchedNode = this._matchNodeNext(branch, new Set([node]), { + combo: entryCombo, + index: 1 + }); + if (matchedNode) { + if (this.#node.nodeType === ELEMENT_NODE) { + if ( + matchedNode !== this.#node && + this.#node.contains(matchedNode) + ) { + return matchedNode; + } + } else { + return matchedNode; + } + } + } + // Fallback logic if no direct match found. + const { leaves: entryLeaves } = branch[0]; + const [entryNode] = entryNodes; + if (this.#node.contains(entryNode)) { + let [refNode] = this._findNodeWalker(entryLeaves, entryNode, { + targetType + }); + while (refNode) { + const matchedNode = this._matchNodeNext(branch, new Set([refNode]), { + combo: entryCombo, + index: 1 + }); + if (matchedNode) { + if (this.#node.nodeType === ELEMENT_NODE) { + if ( + matchedNode !== this.#node && + this.#node.contains(matchedNode) + ) { + return matchedNode; + } + } else { + return matchedNode; + } + } + [refNode] = this._findNodeWalker(entryLeaves, refNode, { + targetType, + force: true + }); + } + } + // DIR_PREV logic for finding the first match. + } else { + for (const node of entryNodes) { + const matchedNode = this._matchNodePrev(branch, node, { + index: lastIndex - 1 + }); + if (matchedNode) { + return matchedNode; + } + } + // Fallback for TARGET_FIRST. + if (targetType === TARGET_FIRST) { + const { leaves: entryLeaves } = branch[lastIndex]; + const [entryNode] = entryNodes; + let [refNode] = this._findNodeWalker(entryLeaves, entryNode, { + targetType + }); + while (refNode) { + const matchedNode = this._matchNodePrev(branch, refNode, { + index: lastIndex - 1 + }); + if (matchedNode) { + return refNode; + } + [refNode] = this._findNodeWalker(entryLeaves, refNode, { + targetType, + force: true + }); + } + } + } + return null; + }; + + /** + * Finds matched nodes. + * @param {string} targetType - The target type. + * @returns {Set.} A collection of matched nodes. + */ + find = targetType => { + const [[...branches], collectedNodes] = this._collectNodes(targetType); + const l = branches.length; + let sort = + l > 1 && targetType === TARGET_ALL && this.#selector.includes(':scope'); + let nodes = new Set(); + for (let i = 0; i < l; i++) { + const { branch, dir, find } = branches[i]; + if (!branch.length || !find) { + continue; + } + const entryNodes = collectedNodes[i]; + const lastIndex = branch.length - 1; + // Handle simple selectors (no combinators). + if (lastIndex === 0) { + if ( + (targetType === TARGET_ALL || targetType === TARGET_FIRST) && + this.#node.nodeType === ELEMENT_NODE + ) { + for (const node of entryNodes) { + if (node !== this.#node && this.#node.contains(node)) { + nodes.add(node); + if (targetType === TARGET_FIRST) { + break; + } + } + } + } else if (targetType === TARGET_ALL) { + if (nodes.size) { + for (const node of entryNodes) { + nodes.add(node); + } + sort = true; + } else { + nodes = new Set(entryNodes); + } + } else { + if (entryNodes.length) { + nodes.add(entryNodes[0]); + } + } + // Handle complex selectors. + } else { + if (targetType === TARGET_ALL) { + const newNodes = this._processComplexBranchAll( + branch, + entryNodes, + dir + ); + if (nodes.size) { + for (const newNode of newNodes) { + nodes.add(newNode); + } + sort = true; + } else { + nodes = newNodes; + } + } else { + const matchedNode = this._processComplexBranchFirst( + branch, + entryNodes, + dir, + targetType + ); + if (matchedNode) { + nodes.add(matchedNode); + } + } + } + } + if (this.#check) { + const match = !!nodes.size; + let pseudoElement; + if (this.#pseudoElement.length) { + pseudoElement = this.#pseudoElement.join(''); + } else { + pseudoElement = null; + } + return { match, pseudoElement }; + } + if (targetType === TARGET_FIRST || targetType === TARGET_ALL) { + nodes.delete(this.#node); + } + if ((sort || targetType === TARGET_FIRST) && nodes.size > 1) { + return new Set(sortNodes(nodes)); + } + return nodes; + }; +} diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/matcher.js b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/matcher.js new file mode 100644 index 0000000..6395560 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/matcher.js @@ -0,0 +1,587 @@ +/** + * matcher.js + */ + +/* import */ +import { generateCSS, parseAstName, unescapeSelector } from './parser.js'; +import { + generateException, + getDirectionality, + getLanguageAttribute, + getType, + isContentEditable, + isCustomElement, + isNamespaceDeclared +} from './utility.js'; + +/* constants */ +import { + ALPHA_NUM, + FORM_PARTS, + IDENT, + INPUT_EDIT, + LANG_PART, + NOT_SUPPORTED_ERR, + PS_ELEMENT_SELECTOR, + STRING, + SYNTAX_ERR +} from './constant.js'; +const KEYS_FORM_PS_DISABLED = new Set([ + ...FORM_PARTS, + 'fieldset', + 'optgroup', + 'option' +]); +const KEYS_INPUT_EDIT = new Set(INPUT_EDIT); +const REG_LANG_VALID = new RegExp(`^(?:\\*-)?${ALPHA_NUM}${LANG_PART}$`, 'i'); +const REG_TAG_NAME = /[A-Z][\\w-]*/i; + +/** + * Validates a pseudo-element selector. + * @param {string} astName - The name of the pseudo-element from the AST. + * @param {string} astType - The type of the selector from the AST. + * @param {object} [opt] - Optional parameters. + * @param {boolean} [opt.forgive] - If true, ignores unknown pseudo-elements. + * @param {boolean} [opt.warn] - If true, throws an error for unsupported ones. + * @throws {DOMException} If the selector is invalid or unsupported. + * @returns {void} + */ +export const matchPseudoElementSelector = (astName, astType, opt = {}) => { + const { forgive, globalObject, warn } = opt; + if (astType !== PS_ELEMENT_SELECTOR) { + // Ensure the AST node is a pseudo-element selector. + throw new TypeError(`Unexpected ast type ${getType(astType)}`); + } + switch (astName) { + case 'after': + case 'backdrop': + case 'before': + case 'cue': + case 'cue-region': + case 'first-letter': + case 'first-line': + case 'file-selector-button': + case 'marker': + case 'placeholder': + case 'selection': + case 'target-text': { + // Warn if the pseudo-element is known but unsupported. + if (warn) { + throw generateException( + `Unsupported pseudo-element ::${astName}`, + NOT_SUPPORTED_ERR, + globalObject + ); + } + break; + } + case 'part': + case 'slotted': { + // Warn if the functional pseudo-element is known but unsupported. + if (warn) { + throw generateException( + `Unsupported pseudo-element ::${astName}()`, + NOT_SUPPORTED_ERR, + globalObject + ); + } + break; + } + default: { + // Handle vendor-prefixed or unknown pseudo-elements. + if (astName.startsWith('-webkit-')) { + if (warn) { + throw generateException( + `Unsupported pseudo-element ::${astName}`, + NOT_SUPPORTED_ERR, + globalObject + ); + } + // Throw an error for unknown pseudo-elements if not forgiven. + } else if (!forgive) { + throw generateException( + `Unknown pseudo-element ::${astName}`, + SYNTAX_ERR, + globalObject + ); + } + } + } +}; + +/** + * Matches the :dir() pseudo-class against an element's directionality. + * @param {object} ast - The AST object for the pseudo-class. + * @param {object} node - The element node to match against. + * @throws {TypeError} If the AST does not contain a valid direction value. + * @returns {boolean} - True if the directionality matches, otherwise false. + */ +export const matchDirectionPseudoClass = (ast, node) => { + const { name } = ast; + // The :dir() pseudo-class requires a direction argument (e.g., "ltr"). + if (!name) { + const type = name === '' ? '(empty String)' : getType(name); + throw new TypeError(`Unexpected ast type ${type}`); + } + // Get the computed directionality of the element. + const dir = getDirectionality(node); + // Compare the expected direction with the element's actual direction. + return name === dir; +}; + +/** + * Matches the :lang() pseudo-class against an element's language. + * @see https://datatracker.ietf.org/doc/html/rfc4647#section-3.3.1 + * @param {object} ast - The AST object for the pseudo-class. + * @param {object} node - The element node to match against. + * @returns {boolean} - True if the language matches, otherwise false. + */ +export const matchLanguagePseudoClass = (ast, node) => { + const { name, type, value } = ast; + let langPattern; + // Determine the language pattern from the AST. + if (type === STRING && value) { + langPattern = value; + } else if (type === IDENT && name) { + langPattern = unescapeSelector(name); + } + // If no valid language pattern is provided, it cannot match. + if (typeof langPattern !== 'string') { + return false; + } + // Get the effective language attribute for the current node. + const elementLang = getLanguageAttribute(node); + // If the element has no language, it cannot match a specific pattern. + if (elementLang === null) { + return false; + } + // Handle the universal selector '*' for :lang. + if (langPattern === '*') { + // It matches any language unless attribute is not empty. + return elementLang !== ''; + } + // Validate the provided language pattern structure. + if (!REG_LANG_VALID.test(langPattern)) { + return false; + } + // Build a regex for extended language range matching. + let matcherRegex; + if (langPattern.indexOf('-') > -1) { + // Handle complex patterns with wildcards and sub-tags (e.g., '*-US'). + const [langMain, langSub, ...langRest] = langPattern.split('-'); + const extendedMain = + langMain === '*' ? `${ALPHA_NUM}${LANG_PART}` : `${langMain}${LANG_PART}`; + const extendedSub = `-${langSub}${LANG_PART}`; + let extendedRest = ''; + // Use a standard for loop for performance as per the rules. + for (let i = 0; i < langRest.length; i++) { + extendedRest += `-${langRest[i]}${LANG_PART}`; + } + matcherRegex = new RegExp( + `^${extendedMain}${extendedSub}${extendedRest}$`, + 'i' + ); + } else { + // Handle simple language patterns (e.g., 'en'). + matcherRegex = new RegExp(`^${langPattern}${LANG_PART}$`, 'i'); + } + // Test the element's language against the constructed regex. + return matcherRegex.test(elementLang); +}; + +/** + * Matches the :disabled and :enabled pseudo-classes. + * @param {string} astName - pseudo-class name + * @param {object} node - Element node + * @returns {boolean} - True if matched + */ +export const matchDisabledPseudoClass = (astName, node) => { + const { localName, parentNode } = node; + if ( + !KEYS_FORM_PS_DISABLED.has(localName) && + !isCustomElement(node, { formAssociated: true }) + ) { + return false; + } + let isDisabled = false; + if (node.disabled || node.hasAttribute('disabled')) { + isDisabled = true; + } else if (localName === 'option') { + if ( + parentNode && + parentNode.localName === 'optgroup' && + (parentNode.disabled || parentNode.hasAttribute('disabled')) + ) { + isDisabled = true; + } + } else if (localName !== 'optgroup') { + let current = parentNode; + while (current) { + if ( + current.localName === 'fieldset' && + (current.disabled || current.hasAttribute('disabled')) + ) { + // The first in a disabled
is not disabled. + let legend; + let element = current.firstElementChild; + while (element) { + if (element.localName === 'legend') { + legend = element; + break; + } + element = element.nextElementSibling; + } + if (!legend || !legend.contains(node)) { + isDisabled = true; + } + // Found the containing fieldset, stop searching up. + break; + } + current = current.parentNode; + } + } + if (astName === 'disabled') { + return isDisabled; + } + return !isDisabled; +}; + +/** + * Match the :read-only and :read-write pseudo-classes + * @param {string} astName - pseudo-class name + * @param {object} node - Element node + * @returns {boolean} - True if matched + */ +export const matchReadOnlyPseudoClass = (astName, node) => { + const { localName } = node; + let isReadOnly = false; + switch (localName) { + case 'textarea': + case 'input': { + const isEditableInput = !node.type || KEYS_INPUT_EDIT.has(node.type); + if (localName === 'textarea' || isEditableInput) { + isReadOnly = + node.readOnly || + node.hasAttribute('readonly') || + node.disabled || + node.hasAttribute('disabled'); + } else { + // Non-editable input types are always read-only + isReadOnly = true; + } + break; + } + default: { + isReadOnly = !isContentEditable(node); + } + } + if (astName === 'read-only') { + return isReadOnly; + } + return !isReadOnly; +}; + +/** + * Matches an attribute selector against an element. + * This function handles various attribute matchers like '=', '~=', '^=', etc., + * and considers namespaces and case sensitivity based on document type. + * @param {object} ast - The AST for the attribute selector. + * @param {object} node - The element node to match against. + * @param {object} [opt] - Optional parameters. + * @param {boolean} [opt.check] - True if running in an internal check. + * @param {boolean} [opt.forgive] - True to forgive certain syntax errors. + * @returns {boolean} - True if the attribute selector matches, otherwise false. + */ +export const matchAttributeSelector = (ast, node, opt = {}) => { + const { + flags: astFlags, + matcher: astMatcher, + name: astName, + value: astValue + } = ast; + const { check, forgive, globalObject } = opt; + // Validate selector flags ('i' or 's'). + if (typeof astFlags === 'string' && !/^[is]$/i.test(astFlags) && !forgive) { + const css = generateCSS(ast); + throw generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + globalObject + ); + } + const { attributes } = node; + // An element with no attributes cannot match. + if (!attributes || !attributes.length) { + return false; + } + // Determine case sensitivity based on document type and flags. + const contentType = node.ownerDocument.contentType; + let caseInsensitive; + if (contentType === 'text/html') { + if (typeof astFlags === 'string' && /^s$/i.test(astFlags)) { + caseInsensitive = false; + } else { + caseInsensitive = true; + } + } else if (typeof astFlags === 'string' && /^i$/i.test(astFlags)) { + caseInsensitive = true; + } else { + caseInsensitive = false; + } + // Prepare the attribute name from the selector for matching. + let astAttrName = unescapeSelector(astName.name); + if (caseInsensitive) { + astAttrName = astAttrName.toLowerCase(); + } + // A set to store the values of attributes whose names match. + const attrValues = new Set(); + // Handle namespaced attribute names (e.g., [*|attr], [ns|attr]). + if (astAttrName.indexOf('|') > -1) { + const { prefix: astPrefix, localName: astLocalName } = + parseAstName(astAttrName); + for (const item of attributes) { + let { name: itemName, value: itemValue } = item; + if (caseInsensitive) { + itemName = itemName.toLowerCase(); + itemValue = itemValue.toLowerCase(); + } + switch (astPrefix) { + case '': { + if (astLocalName === itemName) { + attrValues.add(itemValue); + } + break; + } + case '*': { + if (itemName.indexOf(':') > -1) { + const [, ...restItemName] = itemName.split(':'); + const itemLocalName = restItemName.join(':').replace(/^:/, ''); + if (itemLocalName === astLocalName) { + attrValues.add(itemValue); + } + } else if (astLocalName === itemName) { + attrValues.add(itemValue); + } + break; + } + default: { + if (!check) { + if (forgive) { + return false; + } + const css = generateCSS(ast); + throw generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + globalObject + ); + } + if (itemName.indexOf(':') > -1) { + const [itemPrefix, ...restItemName] = itemName.split(':'); + const itemLocalName = restItemName.join(':').replace(/^:/, ''); + // Ignore the 'xml:lang' attribute. + if (itemPrefix === 'xml' && itemLocalName === 'lang') { + continue; + } else if ( + astPrefix === itemPrefix && + astLocalName === itemLocalName + ) { + const namespaceDeclared = isNamespaceDeclared(astPrefix, node); + if (namespaceDeclared) { + attrValues.add(itemValue); + } + } + } + } + } + } + // Handle non-namespaced attribute names. + } else { + for (let { name: itemName, value: itemValue } of attributes) { + if (caseInsensitive) { + itemName = itemName.toLowerCase(); + itemValue = itemValue.toLowerCase(); + } + if (itemName.indexOf(':') > -1) { + const [itemPrefix, ...restItemName] = itemName.split(':'); + const itemLocalName = restItemName.join(':').replace(/^:/, ''); + // The attribute is starting with ':'. + if (!itemPrefix && astAttrName === `:${itemLocalName}`) { + attrValues.add(itemValue); + // Ignore the 'xml:lang' attribute. + } else if (itemPrefix === 'xml' && itemLocalName === 'lang') { + continue; + } else if (astAttrName === itemLocalName) { + attrValues.add(itemValue); + } + } else if (astAttrName === itemName) { + attrValues.add(itemValue); + } + } + } + if (!attrValues.size) { + return false; + } + // Prepare the value from the selector's RHS for comparison. + const { name: astIdentValue, value: astStringValue } = astValue ?? {}; + let attrValue; + if (astIdentValue) { + if (caseInsensitive) { + attrValue = astIdentValue.toLowerCase(); + } else { + attrValue = astIdentValue; + } + } else if (astStringValue) { + if (caseInsensitive) { + attrValue = astStringValue.toLowerCase(); + } else { + attrValue = astStringValue; + } + } else if (astStringValue === '') { + attrValue = astStringValue; + } + // Perform the final match based on the specified matcher. + switch (astMatcher) { + case '=': { + return typeof attrValue === 'string' && attrValues.has(attrValue); + } + case '~=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + const item = new Set(value.split(/\s+/)); + if (item.has(attrValue)) { + return true; + } + } + } + return false; + } + case '|=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + if (value === attrValue || value.startsWith(`${attrValue}-`)) { + return true; + } + } + } + return false; + } + case '^=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + if (value.startsWith(`${attrValue}`)) { + return true; + } + } + } + return false; + } + case '$=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + if (value.endsWith(`${attrValue}`)) { + return true; + } + } + } + return false; + } + case '*=': { + if (attrValue && typeof attrValue === 'string') { + for (const value of attrValues) { + if (value.includes(`${attrValue}`)) { + return true; + } + } + } + return false; + } + case null: + default: { + // This case handles attribute existence checks (e.g., '[disabled]'). + return true; + } + } +}; + +/** + * match type selector + * @param {object} ast - AST + * @param {object} node - Element node + * @param {object} [opt] - options + * @param {boolean} [opt.check] - running in internal check() + * @param {boolean} [opt.forgive] - forgive undeclared namespace + * @returns {boolean} - result + */ +export const matchTypeSelector = (ast, node, opt = {}) => { + const astName = unescapeSelector(ast.name); + const { localName, namespaceURI, prefix } = node; + const { check, forgive, globalObject } = opt; + let { prefix: astPrefix, localName: astLocalName } = parseAstName( + astName, + node + ); + if ( + node.ownerDocument.contentType === 'text/html' && + (!namespaceURI || namespaceURI === 'http://www.w3.org/1999/xhtml') && + REG_TAG_NAME.test(localName) + ) { + astPrefix = astPrefix.toLowerCase(); + astLocalName = astLocalName.toLowerCase(); + } + let nodePrefix; + let nodeLocalName; + // just in case that the namespaced content is parsed as text/html + if (localName.indexOf(':') > -1) { + [nodePrefix, nodeLocalName] = localName.split(':'); + } else { + nodePrefix = prefix || ''; + nodeLocalName = localName; + } + switch (astPrefix) { + case '': { + if ( + !nodePrefix && + !namespaceURI && + (astLocalName === '*' || astLocalName === nodeLocalName) + ) { + return true; + } + return false; + } + case '*': { + if (astLocalName === '*' || astLocalName === nodeLocalName) { + return true; + } + return false; + } + default: { + if (!check) { + if (forgive) { + return false; + } + const css = generateCSS(ast); + throw generateException( + `Invalid selector ${css}`, + SYNTAX_ERR, + globalObject + ); + } + const astNS = node.lookupNamespaceURI(astPrefix); + const nodeNS = node.lookupNamespaceURI(nodePrefix); + if (astNS === nodeNS && astPrefix === nodePrefix) { + if (astLocalName === '*' || astLocalName === nodeLocalName) { + return true; + } + return false; + } else if (!forgive && !astNS) { + throw generateException( + `Undeclared namespace ${astPrefix}`, + SYNTAX_ERR, + globalObject + ); + } + return false; + } + } +}; diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/parser.js b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/parser.js new file mode 100644 index 0000000..bf06d9f --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/parser.js @@ -0,0 +1,431 @@ +/** + * parser.js + */ + +/* import */ +import * as cssTree from 'css-tree'; +import { getType } from './utility.js'; + +/* constants */ +import { + ATTR_SELECTOR, + BIT_01, + BIT_02, + BIT_04, + BIT_08, + BIT_16, + BIT_32, + BIT_FFFF, + CLASS_SELECTOR, + DUO, + HEX, + ID_SELECTOR, + KEYS_LOGICAL, + NTH, + PS_CLASS_SELECTOR, + PS_ELEMENT_SELECTOR, + SELECTOR, + SYNTAX_ERR, + TYPE_SELECTOR +} from './constant.js'; +const AST_SORT_ORDER = new Map([ + [PS_ELEMENT_SELECTOR, BIT_01], + [ID_SELECTOR, BIT_02], + [CLASS_SELECTOR, BIT_04], + [TYPE_SELECTOR, BIT_08], + [ATTR_SELECTOR, BIT_16], + [PS_CLASS_SELECTOR, BIT_32] +]); +const KEYS_PS_CLASS_STATE = new Set([ + 'checked', + 'closed', + 'disabled', + 'empty', + 'enabled', + 'in-range', + 'indeterminate', + 'invalid', + 'open', + 'out-of-range', + 'placeholder-shown', + 'read-only', + 'read-write', + 'valid' +]); +const KEYS_SHADOW_HOST = new Set(['host', 'host-context']); +const REG_EMPTY_PS_FUNC = + /(?<=:(?:dir|has|host(?:-context)?|is|lang|not|nth-(?:last-)?(?:child|of-type)|where))\(\s+\)/g; +const REG_SHADOW_PS_ELEMENT = /^part|slotted$/; +const U_FFFD = '\uFFFD'; + +/** + * Unescapes a CSS selector string. + * @param {string} selector - The CSS selector to unescape. + * @returns {string} The unescaped selector string. + */ +export const unescapeSelector = (selector = '') => { + if (typeof selector === 'string' && selector.indexOf('\\', 0) >= 0) { + const arr = selector.split('\\'); + const selectorItems = [arr[0]]; + const l = arr.length; + for (let i = 1; i < l; i++) { + const item = arr[i]; + if (item === '' && i === l - 1) { + selectorItems.push(U_FFFD); + } else { + const hexExists = /^([\da-f]{1,6}\s?)/i.exec(item); + if (hexExists) { + const [, hex] = hexExists; + let str; + try { + const low = parseInt('D800', HEX); + const high = parseInt('DFFF', HEX); + const deci = parseInt(hex, HEX); + if (deci === 0 || (deci >= low && deci <= high)) { + str = U_FFFD; + } else { + str = String.fromCodePoint(deci); + } + } catch (e) { + str = U_FFFD; + } + let postStr = ''; + if (item.length > hex.length) { + postStr = item.substring(hex.length); + } + selectorItems.push(`${str}${postStr}`); + // whitespace + } else if (/^[\n\r\f]/.test(item)) { + selectorItems.push(`\\${item}`); + } else { + selectorItems.push(item); + } + } + } + return selectorItems.join(''); + } + return selector; +}; + +/** + * Preprocesses a selector string according to the specification. + * @see https://drafts.csswg.org/css-syntax-3/#input-preprocessing + * @param {string} value - The value to preprocess. + * @returns {string} The preprocessed selector string. + */ +export const preprocess = value => { + // Non-string values will be converted to string. + if (typeof value !== 'string') { + if (value === undefined || value === null) { + return getType(value).toLowerCase(); + } else if (Array.isArray(value)) { + return value.join(','); + } else if (Object.hasOwn(value, 'toString')) { + return value.toString(); + } else { + throw new DOMException(`Invalid selector ${value}`, SYNTAX_ERR); + } + } + let selector = value; + let index = 0; + while (index >= 0) { + // @see https://drafts.csswg.org/selectors/#id-selectors + index = selector.indexOf('#', index); + if (index < 0) { + break; + } + const preHash = selector.substring(0, index + 1); + let postHash = selector.substring(index + 1); + const codePoint = postHash.codePointAt(0); + if (codePoint > BIT_FFFF) { + const str = `\\${codePoint.toString(HEX)} `; + if (postHash.length === DUO) { + postHash = str; + } else { + postHash = `${str}${postHash.substring(DUO)}`; + } + } + selector = `${preHash}${postHash}`; + index++; + } + return selector + .replace(/\f|\r\n?/g, '\n') + .replace(/[\0\uD800-\uDFFF]|\\$/g, U_FFFD) + .replace(/\x26/g, ':scope'); +}; + +/** + * Creates an Abstract Syntax Tree (AST) from a CSS selector string. + * @param {string} sel - The CSS selector string. + * @returns {object} The parsed AST object. + */ +export const parseSelector = sel => { + const selector = preprocess(sel); + // invalid selectors + if (/^$|^\s*>|,\s*$/.test(selector)) { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + try { + const ast = cssTree.parse(selector, { + context: 'selectorList', + parseCustomProperty: true + }); + return cssTree.toPlainObject(ast); + } catch (e) { + const { message } = e; + if ( + /^(?:"\]"|Attribute selector [()\s,=~^$*|]+) is expected$/.test( + message + ) && + !selector.endsWith(']') + ) { + const index = selector.lastIndexOf('['); + const selPart = selector.substring(index); + if (selPart.includes('"')) { + const quotes = selPart.match(/"/g).length; + if (quotes % 2) { + return parseSelector(`${selector}"]`); + } + return parseSelector(`${selector}]`); + } + return parseSelector(`${selector}]`); + } else if (message === '")" is expected') { + // workaround for https://github.com/csstree/csstree/issues/283 + if (REG_EMPTY_PS_FUNC.test(selector)) { + return parseSelector(`${selector.replaceAll(REG_EMPTY_PS_FUNC, '()')}`); + } else if (!selector.endsWith(')')) { + return parseSelector(`${selector})`); + } else { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + } else { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + } +}; + +/** + * Walks the provided AST to collect selector branches and gather information + * about its contents. + * @param {object} ast - The AST to traverse. + * @returns {{branches: Array, info: object}} An object containing the selector branches and info. + */ +export const walkAST = (ast = {}) => { + const branches = new Set(); + const info = { + hasForgivenPseudoFunc: false, + hasHasPseudoFunc: false, + hasLogicalPseudoFunc: false, + hasNotPseudoFunc: false, + hasNthChildOfSelector: false, + hasNestedSelector: false, + hasStatePseudoClass: false + }; + const opt = { + enter(node) { + switch (node.type) { + case CLASS_SELECTOR: { + if (/^-?\d/.test(node.name)) { + throw new DOMException( + `Invalid selector .${node.name}`, + SYNTAX_ERR + ); + } + break; + } + case ID_SELECTOR: { + if (/^-?\d/.test(node.name)) { + throw new DOMException( + `Invalid selector #${node.name}`, + SYNTAX_ERR + ); + } + break; + } + case PS_CLASS_SELECTOR: { + if (KEYS_LOGICAL.has(node.name)) { + info.hasNestedSelector = true; + info.hasLogicalPseudoFunc = true; + if (node.name === 'has') { + info.hasHasPseudoFunc = true; + } else if (node.name === 'not') { + info.hasNotPseudoFunc = true; + } else { + info.hasForgivenPseudoFunc = true; + } + } else if (KEYS_PS_CLASS_STATE.has(node.name)) { + info.hasStatePseudoClass = true; + } else if ( + KEYS_SHADOW_HOST.has(node.name) && + Array.isArray(node.children) && + node.children.length + ) { + info.hasNestedSelector = true; + } + break; + } + case PS_ELEMENT_SELECTOR: { + if (REG_SHADOW_PS_ELEMENT.test(node.name)) { + info.hasNestedSelector = true; + } + break; + } + case NTH: { + if (node.selector) { + info.hasNestedSelector = true; + info.hasNthChildOfSelector = true; + } + break; + } + case SELECTOR: { + branches.add(node.children); + break; + } + default: + } + } + }; + cssTree.walk(ast, opt); + if (info.hasNestedSelector === true) { + cssTree.findAll(ast, (node, item, list) => { + if (list) { + if (node.type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(node.name)) { + const itemList = list.filter(i => { + const { name, type } = i; + return type === PS_CLASS_SELECTOR && KEYS_LOGICAL.has(name); + }); + for (const { children } of itemList) { + // SelectorList + for (const { children: grandChildren } of children) { + // Selector + for (const { children: greatGrandChildren } of grandChildren) { + if (branches.has(greatGrandChildren)) { + branches.delete(greatGrandChildren); + } + } + } + } + } else if ( + node.type === PS_CLASS_SELECTOR && + KEYS_SHADOW_HOST.has(node.name) && + Array.isArray(node.children) && + node.children.length + ) { + const itemList = list.filter(i => { + const { children, name, type } = i; + const res = + type === PS_CLASS_SELECTOR && + KEYS_SHADOW_HOST.has(name) && + Array.isArray(children) && + children.length; + return res; + }); + for (const { children } of itemList) { + // Selector + for (const { children: grandChildren } of children) { + if (branches.has(grandChildren)) { + branches.delete(grandChildren); + } + } + } + } else if ( + node.type === PS_ELEMENT_SELECTOR && + REG_SHADOW_PS_ELEMENT.test(node.name) + ) { + const itemList = list.filter(i => { + const { name, type } = i; + const res = + type === PS_ELEMENT_SELECTOR && REG_SHADOW_PS_ELEMENT.test(name); + return res; + }); + for (const { children } of itemList) { + // Selector + for (const { children: grandChildren } of children) { + if (branches.has(grandChildren)) { + branches.delete(grandChildren); + } + } + } + } else if (node.type === NTH && node.selector) { + const itemList = list.filter(i => { + const { selector, type } = i; + const res = type === NTH && selector; + return res; + }); + for (const { selector } of itemList) { + const { children } = selector; + // Selector + for (const { children: grandChildren } of children) { + if (branches.has(grandChildren)) { + branches.delete(grandChildren); + } + } + } + } + } + }); + } + return { + info, + branches: [...branches] + }; +}; + +/** + * Comparison function for sorting AST nodes based on specificity. + * @param {object} a - The first AST node. + * @param {object} b - The second AST node. + * @returns {number} -1, 0 or 1, depending on the sort order. + */ +export const compareASTNodes = (a, b) => { + const bitA = AST_SORT_ORDER.get(a.type); + const bitB = AST_SORT_ORDER.get(b.type); + if (bitA === bitB) { + return 0; + } else if (bitA > bitB) { + return 1; + } else { + return -1; + } +}; + +/** + * Sorts a collection of AST nodes based on CSS specificity rules. + * @param {Array} asts - A collection of AST nodes to sort. + * @returns {Array} A new array containing the sorted AST nodes. + */ +export const sortAST = asts => { + const arr = [...asts]; + if (arr.length > 1) { + arr.sort(compareASTNodes); + } + return arr; +}; + +/** + * Parses a type selector's name, which may include a namespace prefix. + * @param {string} selector - The type selector name (e.g., 'ns|E' or 'E'). + * @returns {{prefix: string, localName: string}} An object with `prefix` and + * `localName` properties. + */ +export const parseAstName = selector => { + let prefix; + let localName; + if (selector && typeof selector === 'string') { + if (selector.indexOf('|') > -1) { + [prefix, localName] = selector.split('|'); + } else { + prefix = '*'; + localName = selector; + } + } else { + throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR); + } + return { + prefix, + localName + }; +}; + +/* Re-exported from css-tree. */ +export { find as findAST, generate as generateCSS } from 'css-tree'; diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/utility.js b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/utility.js new file mode 100644 index 0000000..ce141a4 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/src/js/utility.js @@ -0,0 +1,1107 @@ +/** + * utility.js + */ + +/* import */ +import nwsapi from '@asamuzakjp/nwsapi'; +import bidiFactory from 'bidi-js'; +import * as cssTree from 'css-tree'; +import isCustomElementName from 'is-potential-custom-element-name'; + +/* constants */ +import { + ATRULE, + COMBO, + COMPOUND_I, + DESCEND, + DOCUMENT_FRAGMENT_NODE, + DOCUMENT_NODE, + DOCUMENT_POSITION_CONTAINS, + DOCUMENT_POSITION_PRECEDING, + ELEMENT_NODE, + HAS_COMPOUND, + INPUT_BUTTON, + INPUT_EDIT, + INPUT_LTR, + INPUT_TEXT, + KEYS_LOGICAL, + LOGIC_COMPLEX, + LOGIC_COMPOUND, + N_TH, + PSEUDO_CLASS, + RULE, + SCOPE, + SELECTOR_LIST, + SIBLING, + TARGET_ALL, + TARGET_FIRST, + TEXT_NODE, + TYPE_FROM, + TYPE_TO +} from './constant.js'; +const KEYS_DIR_AUTO = new Set([...INPUT_BUTTON, ...INPUT_TEXT, 'hidden']); +const KEYS_DIR_LTR = new Set(INPUT_LTR); +const KEYS_INPUT_EDIT = new Set(INPUT_EDIT); +const KEYS_NODE_DIR_EXCLUDE = new Set(['bdi', 'script', 'style', 'textarea']); +const KEYS_NODE_FOCUSABLE = new Set(['button', 'select', 'textarea']); +const KEYS_NODE_FOCUSABLE_SVG = new Set([ + 'clipPath', + 'defs', + 'desc', + 'linearGradient', + 'marker', + 'mask', + 'metadata', + 'pattern', + 'radialGradient', + 'script', + 'style', + 'symbol', + 'title' +]); +const REG_EXCLUDE_BASIC = + /[|\\]|::|[^\u0021-\u007F\s]|\[\s*[\w$*=^|~-]+(?:(?:"[\w$*=^|~\s'-]+"|'[\w$*=^|~\s"-]+')?(?:\s+[\w$*=^|~-]+)+|"[^"\]]{1,255}|'[^'\]]{1,255})\s*\]|:(?:is|where)\(\s*\)/; +const REG_COMPLEX = new RegExp(`${COMPOUND_I}${COMBO}${COMPOUND_I}`, 'i'); +const REG_DESCEND = new RegExp(`${COMPOUND_I}${DESCEND}${COMPOUND_I}`, 'i'); +const REG_SIBLING = new RegExp(`${COMPOUND_I}${SIBLING}${COMPOUND_I}`, 'i'); +const REG_LOGIC_COMPLEX = new RegExp( + `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPLEX})` +); +const REG_LOGIC_COMPOUND = new RegExp( + `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND})` +); +const REG_LOGIC_HAS_COMPOUND = new RegExp( + `:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND}|${HAS_COMPOUND})` +); +const REG_END_WITH_HAS = new RegExp(`:${HAS_COMPOUND}$`); +const REG_WO_LOGICAL = new RegExp(`:(?!${PSEUDO_CLASS}|${N_TH})`); +const REG_IS_HTML = /^(?:application\/xhtml\+x|text\/ht)ml$/; +const REG_IS_XML = + /^(?:application\/(?:[\w\-.]+\+)?|image\/[\w\-.]+\+|text\/)xml$/; + +/** + * Manages state for extracting nested selectors from a CSS AST. + */ +class SelectorExtractor { + constructor() { + this.selectors = []; + this.isScoped = false; + } + + /** + * Walker enter function. + * @param {object} node - The AST node. + */ + enter(node) { + switch (node.type) { + case ATRULE: { + if (node.name === 'scope') { + this.isScoped = true; + } + break; + } + case SCOPE: { + const { children, type } = node.root; + const arr = []; + if (type === SELECTOR_LIST) { + for (const child of children) { + const selector = cssTree.generate(child); + arr.push(selector); + } + this.selectors.push(arr); + } + break; + } + case RULE: { + const { children, type } = node.prelude; + const arr = []; + if (type === SELECTOR_LIST) { + let hasAmp = false; + for (const child of children) { + const selector = cssTree.generate(child); + if (this.isScoped && !hasAmp) { + hasAmp = /\x26/.test(selector); + } + arr.push(selector); + } + if (this.isScoped) { + if (hasAmp) { + this.selectors.push(arr); + /* FIXME: + } else { + this.selectors = arr; + this.isScoped = false; + */ + } + } else { + this.selectors.push(arr); + } + } + } + } + } + + /** + * Walker leave function. + * @param {object} node - The AST node. + */ + leave(node) { + if (node.type === ATRULE) { + if (node.name === 'scope') { + this.isScoped = false; + } + } + } +} + +/** + * Get type of an object. + * @param {object} o - Object to check. + * @returns {string} - Type of the object. + */ +export const getType = o => + Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO); + +/** + * Verify array contents. + * @param {Array} arr - The array. + * @param {string} type - Expected type, e.g. 'String'. + * @throws {TypeError} - Throws if array or its items are of unexpected type. + * @returns {Array} - The verified array. + */ +export const verifyArray = (arr, type) => { + if (!Array.isArray(arr)) { + throw new TypeError(`Unexpected type ${getType(arr)}`); + } + if (typeof type !== 'string') { + throw new TypeError(`Unexpected type ${getType(type)}`); + } + for (const item of arr) { + if (getType(item) !== type) { + throw new TypeError(`Unexpected type ${getType(item)}`); + } + } + return arr; +}; + +/** + * Generate a DOMException. + * @param {string} msg - The error message. + * @param {string} name - The error name. + * @param {object} globalObject - The global object (e.g., window). + * @returns {DOMException} The generated DOMException object. + */ +export const generateException = (msg, name, globalObject = globalThis) => { + return new globalObject.DOMException(msg, name); +}; + +/** + * Find a nested :has() pseudo-class. + * @param {object} leaf - The AST leaf to check. + * @returns {?object} The leaf if it's :has, otherwise null. + */ +export const findNestedHas = leaf => { + return leaf.name === 'has'; +}; + +/** + * Find a logical pseudo-class that contains a nested :has(). + * @param {object} leaf - The AST leaf to check. + * @returns {?object} The leaf if it matches, otherwise null. + */ +export const findLogicalWithNestedHas = leaf => { + if (KEYS_LOGICAL.has(leaf.name) && cssTree.find(leaf, findNestedHas)) { + return leaf; + } + return null; +}; + +/** + * Filter a list of nodes based on An+B logic + * @param {Array.} nodes - array of nodes to filter + * @param {object} anb - An+B options + * @param {number} anb.a - a + * @param {number} anb.b - b + * @param {boolean} [anb.reverse] - reverse order + * @returns {Array.} - array of matched nodes + */ +export const filterNodesByAnB = (nodes, anb) => { + const { a, b, reverse } = anb; + const processedNodes = reverse ? [...nodes].reverse() : nodes; + const l = nodes.length; + const matched = []; + if (a === 0) { + if (b > 0 && b <= l) { + matched.push(processedNodes[b - 1]); + } + return matched; + } + let startIndex = b - 1; + if (a > 0) { + while (startIndex < 0) { + startIndex += a; + } + for (let i = startIndex; i < l; i += a) { + matched.push(processedNodes[i]); + } + } else if (startIndex >= 0) { + for (let i = startIndex; i >= 0; i += a) { + matched.push(processedNodes[i]); + } + return matched.reverse(); + } + return matched; +}; + +/** + * Resolve content document, root node, and check if it's in a shadow DOM. + * @param {object} node - Document, DocumentFragment, or Element node. + * @returns {Array.} - [document, root, isInShadow]. + */ +export const resolveContent = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + let document; + let root; + let shadow; + switch (node.nodeType) { + case DOCUMENT_NODE: { + document = node; + root = node; + break; + } + case DOCUMENT_FRAGMENT_NODE: { + const { host, mode, ownerDocument } = node; + document = ownerDocument; + root = node; + shadow = host && (mode === 'close' || mode === 'open'); + break; + } + case ELEMENT_NODE: { + document = node.ownerDocument; + let refNode = node; + while (refNode) { + const { host, mode, nodeType, parentNode } = refNode; + if (nodeType === DOCUMENT_FRAGMENT_NODE) { + shadow = host && (mode === 'close' || mode === 'open'); + break; + } else if (parentNode) { + refNode = parentNode; + } else { + break; + } + } + root = refNode; + break; + } + default: { + throw new TypeError(`Unexpected node ${node.nodeName}`); + } + } + return [document, root, !!shadow]; +}; + +/** + * Traverse node tree with a TreeWalker. + * @param {object} node - The target node. + * @param {object} walker - The TreeWalker instance. + * @param {boolean} [force] - Traverse only to the next node. + * @returns {?object} - The current node if found, otherwise null. + */ +export const traverseNode = (node, walker, force = false) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (!walker) { + return null; + } + let refNode = walker.currentNode; + if (refNode === node) { + return refNode; + } else if (force || refNode.contains(node)) { + refNode = walker.nextNode(); + while (refNode) { + if (refNode === node) { + break; + } + refNode = walker.nextNode(); + } + return refNode; + } else { + if (refNode !== walker.root) { + let bool; + while (refNode) { + if (refNode === node) { + bool = true; + break; + } else if (refNode === walker.root || refNode.contains(node)) { + break; + } + refNode = walker.parentNode(); + } + if (bool) { + return refNode; + } + } + if (node.nodeType === ELEMENT_NODE) { + let bool; + while (refNode) { + if (refNode === node) { + bool = true; + break; + } + refNode = walker.nextNode(); + } + if (bool) { + return refNode; + } + } + } + return null; +}; + +/** + * Check if a node is a custom element. + * @param {object} node - The Element node. + * @param {object} [opt] - Options. + * @returns {boolean} - True if it's a custom element. + */ +export const isCustomElement = (node, opt = {}) => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return false; + } + const { localName, ownerDocument } = node; + const { formAssociated } = opt; + const window = ownerDocument.defaultView; + let elmConstructor; + const attr = node.getAttribute('is'); + if (attr) { + elmConstructor = + isCustomElementName(attr) && window.customElements.get(attr); + } else { + elmConstructor = + isCustomElementName(localName) && window.customElements.get(localName); + } + if (elmConstructor) { + if (formAssociated) { + return !!elmConstructor.formAssociated; + } + return true; + } + return false; +}; + +/** + * Get slotted text content. + * @param {object} node - The Element node (likely a ). + * @returns {?string} - The text content. + */ +export const getSlottedTextContent = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (typeof node.assignedNodes !== 'function') { + return null; + } + const nodes = node.assignedNodes(); + if (nodes.length) { + let text = ''; + const l = nodes.length; + for (let i = 0; i < l; i++) { + const item = nodes[i]; + text = item.textContent.trim(); + if (text) { + break; + } + } + return text; + } + return node.textContent.trim(); +}; + +/** + * Get directionality of a node. + * @see https://html.spec.whatwg.org/multipage/dom.html#the-dir-attribute + * @param {object} node - The Element node. + * @returns {?string} - 'ltr' or 'rtl'. + */ +export const getDirectionality = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return null; + } + const { dir: dirAttr, localName, parentNode } = node; + const { getEmbeddingLevels } = bidiFactory(); + if (dirAttr === 'ltr' || dirAttr === 'rtl') { + return dirAttr; + } else if (dirAttr === 'auto') { + let text = ''; + switch (localName) { + case 'input': { + if (!node.type || KEYS_DIR_AUTO.has(node.type)) { + text = node.value; + } else if (KEYS_DIR_LTR.has(node.type)) { + return 'ltr'; + } + break; + } + case 'slot': { + text = getSlottedTextContent(node); + break; + } + case 'textarea': { + text = node.value; + break; + } + default: { + const items = [].slice.call(node.childNodes); + for (const item of items) { + const { + dir: itemDir, + localName: itemLocalName, + nodeType: itemNodeType, + textContent: itemTextContent + } = item; + if (itemNodeType === TEXT_NODE) { + text = itemTextContent.trim(); + } else if ( + itemNodeType === ELEMENT_NODE && + !KEYS_NODE_DIR_EXCLUDE.has(itemLocalName) && + (!itemDir || (itemDir !== 'ltr' && itemDir !== 'rtl')) + ) { + if (itemLocalName === 'slot') { + text = getSlottedTextContent(item); + } else { + text = itemTextContent.trim(); + } + } + if (text) { + break; + } + } + } + } + if (text) { + const { + paragraphs: [{ level }] + } = getEmbeddingLevels(text); + if (level % 2 === 1) { + return 'rtl'; + } + } else if (parentNode) { + const { nodeType: parentNodeType } = parentNode; + if (parentNodeType === ELEMENT_NODE) { + return getDirectionality(parentNode); + } + } + } else if (localName === 'input' && node.type === 'tel') { + return 'ltr'; + } else if (localName === 'bdi') { + const text = node.textContent.trim(); + if (text) { + const { + paragraphs: [{ level }] + } = getEmbeddingLevels(text); + if (level % 2 === 1) { + return 'rtl'; + } + } + } else if (parentNode) { + if (localName === 'slot') { + const text = getSlottedTextContent(node); + if (text) { + const { + paragraphs: [{ level }] + } = getEmbeddingLevels(text); + if (level % 2 === 1) { + return 'rtl'; + } + return 'ltr'; + } + } + const { nodeType: parentNodeType } = parentNode; + if (parentNodeType === ELEMENT_NODE) { + return getDirectionality(parentNode); + } + } + return 'ltr'; +}; + +/** + * Traverses up the DOM tree to find the language attribute for a node. + * It checks for 'lang' in HTML and 'xml:lang' in XML contexts. + * @param {object} node - The starting element node. + * @returns {string|null} The language attribute value, or null if not found. + */ +export const getLanguageAttribute = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return null; + } + const { contentType } = node.ownerDocument; + const isHtml = REG_IS_HTML.test(contentType); + const isXml = REG_IS_XML.test(contentType); + let isShadow = false; + // Traverse up from the current node to the root. + let current = node; + while (current) { + // Check if the current node is an element. + switch (current.nodeType) { + case ELEMENT_NODE: { + // Check for and return the language attribute if present. + if (isHtml && current.hasAttribute('lang')) { + return current.getAttribute('lang'); + } else if (isXml && current.hasAttribute('xml:lang')) { + return current.getAttribute('xml:lang'); + } + break; + } + case DOCUMENT_FRAGMENT_NODE: { + // Continue traversal if the current node is a shadow root. + if (current.host) { + isShadow = true; + } + break; + } + case DOCUMENT_NODE: + default: { + // Stop if we reach the root document node. + return null; + } + } + if (isShadow) { + current = current.host; + isShadow = false; + } else if (current.parentNode) { + current = current.parentNode; + } else { + break; + } + } + // No language attribute was found in the hierarchy. + return null; +}; + +/** + * Check if content is editable. + * NOTE: Not implemented in jsdom https://github.com/jsdom/jsdom/issues/1670 + * @param {object} node - The Element node. + * @returns {boolean} - True if content is editable. + */ +export const isContentEditable = node => { + if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (node.nodeType !== ELEMENT_NODE) { + return false; + } + if (typeof node.isContentEditable === 'boolean') { + return node.isContentEditable; + } else if (node.ownerDocument.designMode === 'on') { + return true; + } else { + let attr; + if (node.hasAttribute('contenteditable')) { + attr = node.getAttribute('contenteditable'); + } else { + attr = 'inherit'; + } + switch (attr) { + case '': + case 'true': { + return true; + } + case 'plaintext-only': { + // FIXME: + // @see https://github.com/w3c/editing/issues/470 + // @see https://github.com/whatwg/html/issues/10651 + return true; + } + case 'false': { + return false; + } + default: { + if (node?.parentNode?.nodeType === ELEMENT_NODE) { + return isContentEditable(node.parentNode); + } + return false; + } + } + } +}; + +/** + * Check if a node is visible. + * @param {object} node - The Element node. + * @returns {boolean} - True if the node is visible. + */ +export const isVisible = node => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + const window = node.ownerDocument.defaultView; + const { display, visibility } = window.getComputedStyle(node); + if (display !== 'none' && visibility === 'visible') { + return true; + } + return false; +}; + +/** + * Check if focus is visible on the node. + * @param {object} node - The Element node. + * @returns {boolean} - True if focus is visible. + */ +export const isFocusVisible = node => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + const { localName, type } = node; + switch (localName) { + case 'input': { + if (!type || KEYS_INPUT_EDIT.has(type)) { + return true; + } + return false; + } + case 'textarea': { + return true; + } + default: { + return isContentEditable(node); + } + } +}; + +/** + * Check if an area is focusable. + * @param {object} node - The Element node. + * @returns {boolean} - True if the area is focusable. + */ +export const isFocusableArea = node => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + if (!node.isConnected) { + return false; + } + const window = node.ownerDocument.defaultView; + if (node instanceof window.HTMLElement) { + if (Number.isInteger(parseInt(node.getAttribute('tabindex')))) { + return true; + } + if (isContentEditable(node)) { + return true; + } + const { localName, parentNode } = node; + switch (localName) { + case 'a': { + if (node.href || node.hasAttribute('href')) { + return true; + } + return false; + } + case 'iframe': { + return true; + } + case 'input': { + if ( + node.disabled || + node.hasAttribute('disabled') || + node.hidden || + node.hasAttribute('hidden') + ) { + return false; + } + return true; + } + case 'summary': { + if (parentNode.localName === 'details') { + let child = parentNode.firstElementChild; + let bool = false; + while (child) { + if (child.localName === 'summary') { + bool = child === node; + break; + } + child = child.nextElementSibling; + } + return bool; + } + return false; + } + default: { + if ( + KEYS_NODE_FOCUSABLE.has(localName) && + !(node.disabled || node.hasAttribute('disabled')) + ) { + return true; + } + } + } + } else if (node instanceof window.SVGElement) { + if (Number.isInteger(parseInt(node.getAttributeNS(null, 'tabindex')))) { + const ns = 'http://www.w3.org/2000/svg'; + let bool; + let refNode = node; + while (refNode.namespaceURI === ns) { + bool = KEYS_NODE_FOCUSABLE_SVG.has(refNode.localName); + if (bool) { + break; + } + if (refNode?.parentNode?.namespaceURI === ns) { + refNode = refNode.parentNode; + } else { + break; + } + } + if (bool) { + return false; + } + return true; + } + if ( + node.localName === 'a' && + (node.href || node.hasAttributeNS(null, 'href')) + ) { + return true; + } + } + return false; +}; + +/** + * Check if a node is focusable. + * NOTE: Not applied, needs fix in jsdom itself. + * @see https://github.com/whatwg/html/pull/8392 + * @see https://phabricator.services.mozilla.com/D156219 + * @see https://github.com/jsdom/jsdom/issues/3029 + * @see https://github.com/jsdom/jsdom/issues/3464 + * @param {object} node - The Element node. + * @returns {boolean} - True if the node is focusable. + */ +export const isFocusable = node => { + if (node?.nodeType !== ELEMENT_NODE) { + return false; + } + const window = node.ownerDocument.defaultView; + let refNode = node; + let res = true; + while (refNode) { + if (refNode.disabled || refNode.hasAttribute('disabled')) { + res = false; + break; + } + if (refNode.hidden || refNode.hasAttribute('hidden')) { + res = false; + } + const { contentVisibility, display, visibility } = + window.getComputedStyle(refNode); + if ( + display === 'none' || + visibility !== 'visible' || + (contentVisibility === 'hidden' && refNode !== node) + ) { + res = false; + } else { + res = true; + } + if (res && refNode?.parentNode?.nodeType === ELEMENT_NODE) { + refNode = refNode.parentNode; + } else { + break; + } + } + return res; +}; + +/** + * Get namespace URI. + * @param {string} ns - The namespace prefix. + * @param {object} node - The Element node. + * @returns {?string} - The namespace URI. + */ +export const getNamespaceURI = (ns, node) => { + if (typeof ns !== 'string') { + throw new TypeError(`Unexpected type ${getType(ns)}`); + } else if (!node?.nodeType) { + throw new TypeError(`Unexpected type ${getType(node)}`); + } + if (!ns || node.nodeType !== ELEMENT_NODE) { + return null; + } + const { attributes } = node; + let res; + for (const attr of attributes) { + const { name, namespaceURI, prefix, value } = attr; + if (name === `xmlns:${ns}`) { + res = value; + } else if (prefix === ns) { + res = namespaceURI; + } + if (res) { + break; + } + } + return res ?? null; +}; + +/** + * Check if a namespace is declared. + * @param {string} ns - The namespace. + * @param {object} node - The Element node. + * @returns {boolean} - True if the namespace is declared. + */ +export const isNamespaceDeclared = (ns = '', node = {}) => { + if (!ns || typeof ns !== 'string' || node?.nodeType !== ELEMENT_NODE) { + return false; + } + if (node.lookupNamespaceURI(ns)) { + return true; + } + const root = node.ownerDocument.documentElement; + let parent = node; + let res; + while (parent) { + res = getNamespaceURI(ns, parent); + if (res || parent === root) { + break; + } + parent = parent.parentNode; + } + return !!res; +}; + +/** + * Check if nodeA precedes and/or contains nodeB. + * @param {object} nodeA - The first Element node. + * @param {object} nodeB - The second Element node. + * @returns {boolean} - True if nodeA precedes nodeB. + */ +export const isPreceding = (nodeA, nodeB) => { + if (!nodeA?.nodeType) { + throw new TypeError(`Unexpected type ${getType(nodeA)}`); + } else if (!nodeB?.nodeType) { + throw new TypeError(`Unexpected type ${getType(nodeB)}`); + } + if (nodeA.nodeType !== ELEMENT_NODE || nodeB.nodeType !== ELEMENT_NODE) { + return false; + } + const posBit = nodeB.compareDocumentPosition(nodeA); + const res = + posBit & DOCUMENT_POSITION_PRECEDING || posBit & DOCUMENT_POSITION_CONTAINS; + return !!res; +}; + +/** + * Comparison function for sorting nodes based on document position. + * @param {object} a - The first node. + * @param {object} b - The second node. + * @returns {number} - Sort order. + */ +export const compareNodes = (a, b) => { + if (isPreceding(b, a)) { + return 1; + } + return -1; +}; + +/** + * Sort a collection of nodes. + * @param {Array.|Set.} nodes - Collection of nodes. + * @returns {Array.} - Collection of sorted nodes. + */ +export const sortNodes = (nodes = []) => { + const arr = [...nodes]; + if (arr.length > 1) { + arr.sort(compareNodes); + } + return arr; +}; + +/** + * Concat an array of nested selectors into an equivalent single selector. + * @param {Array.>} selectors - [parents, children, ...]. + * @returns {string} - The concatenated selector. + */ +export const concatNestedSelectors = selectors => { + if (!Array.isArray(selectors)) { + throw new TypeError(`Unexpected type ${getType(selectors)}`); + } + let selector = ''; + if (selectors.length) { + const revSelectors = selectors.toReversed(); + let child = verifyArray(revSelectors.shift(), 'String'); + if (child.length === 1) { + [child] = child; + } + while (revSelectors.length) { + const parentArr = verifyArray(revSelectors.shift(), 'String'); + if (!parentArr.length) { + continue; + } + let parent; + if (parentArr.length === 1) { + [parent] = parentArr; + if (!/^[>~+]/.test(parent) && /[\s>~+]/.test(parent)) { + parent = `:is(${parent})`; + } + } else { + parent = `:is(${parentArr.join(', ')})`; + } + if (selector.includes('\x26')) { + selector = selector.replace(/\x26/g, parent); + } + if (Array.isArray(child)) { + const items = []; + for (let item of child) { + if (item.includes('\x26')) { + if (/^[>~+]/.test(item)) { + item = `${parent} ${item.replace(/\x26/g, parent)} ${selector}`; + } else { + item = `${item.replace(/\x26/g, parent)} ${selector}`; + } + } else { + item = `${parent} ${item} ${selector}`; + } + items.push(item.trim()); + } + selector = items.join(', '); + } else if (revSelectors.length) { + selector = `${child} ${selector}`; + } else { + if (child.includes('\x26')) { + if (/^[>~+]/.test(child)) { + selector = `${parent} ${child.replace(/\x26/g, parent)} ${selector}`; + } else { + selector = `${child.replace(/\x26/g, parent)} ${selector}`; + } + } else { + selector = `${parent} ${child} ${selector}`; + } + } + selector = selector.trim(); + if (revSelectors.length) { + child = parentArr.length > 1 ? parentArr : parent; + } else { + break; + } + } + selector = selector.replace(/\x26/g, ':scope').trim(); + } + return selector; +}; + +/** + * Extract nested selectors from CSSRule.cssText. + * @param {string} css - CSSRule.cssText. + * @returns {Array.>} - Array of nested selectors. + */ +export const extractNestedSelectors = css => { + const ast = cssTree.parse(css, { + context: 'rule' + }); + const extractor = new SelectorExtractor(); + cssTree.walk(ast, { + enter: extractor.enter.bind(extractor), + leave: extractor.leave.bind(extractor) + }); + return extractor.selectors; +}; + +/** + * Initialize nwsapi. + * @param {object} window - The Window object. + * @param {object} document - The Document object. + * @returns {object} - The nwsapi instance. + */ +export const initNwsapi = (window, document) => { + if (!window?.DOMException) { + throw new TypeError(`Unexpected global object ${getType(window)}`); + } + if (document?.nodeType !== DOCUMENT_NODE) { + document = window.document; + } + const nw = nwsapi({ + document, + DOMException: window.DOMException + }); + nw.configure({ + LOGERRORS: false + }); + return nw; +}; + +/** + * Filter a selector for use with nwsapi. + * @param {string} selector - The selector string. + * @param {string} target - The target type. + * @returns {boolean} - True if the selector is valid for nwsapi. + */ +export const filterSelector = (selector, target) => { + const isQuerySelectorType = target === TARGET_FIRST || target === TARGET_ALL; + if ( + !selector || + typeof selector !== 'string' || + /null|undefined/.test(selector) + ) { + return false; + } + // Exclude missing close square bracket. + if (selector.includes('[')) { + const index = selector.lastIndexOf('['); + const sel = selector.substring(index); + if (sel.indexOf(']') < 0) { + return false; + } + } + // Exclude various complex or unsupported selectors. + // - selectors containing '/' + // - namespaced selectors + // - escaped selectors + // - pseudo-element selectors + // - selectors containing non-ASCII + // - selectors containing control character other than whitespace + // - attribute selectors with case flag, e.g. [attr i] + // - attribute selectors with unclosed quotes + // - empty :is() or :where() + if (selector.includes('/') || REG_EXCLUDE_BASIC.test(selector)) { + return false; + } + // Include pseudo-classes that are known to work correctly. + if (selector.includes(':')) { + let complex = false; + if (target !== isQuerySelectorType) { + complex = REG_COMPLEX.test(selector); + } + if ( + isQuerySelectorType && + REG_DESCEND.test(selector) && + !REG_SIBLING.test(selector) + ) { + return false; + } else if (!isQuerySelectorType && /:has\(/.test(selector)) { + if (!complex || REG_LOGIC_HAS_COMPOUND.test(selector)) { + return false; + } + return REG_END_WITH_HAS.test(selector); + } else if (/:(?:is|not)\(/.test(selector)) { + if (complex) { + return !REG_LOGIC_COMPLEX.test(selector); + } else { + return !REG_LOGIC_COMPOUND.test(selector); + } + } else { + return !REG_WO_LOGICAL.test(selector); + } + } + return true; +}; diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/types/index.d.ts b/vanilla/node_modules/@asamuzakjp/dom-selector/types/index.d.ts new file mode 100644 index 0000000..d6ebaa4 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/types/index.d.ts @@ -0,0 +1,14 @@ +export class DOMSelector { + constructor(window: Window, document: Document, opt?: object); + clear: () => void; + check: (selector: string, node: Element, opt?: object) => CheckResult; + matches: (selector: string, node: Element, opt?: object) => boolean; + closest: (selector: string, node: Element, opt?: object) => Element | null; + querySelector: (selector: string, node: Document | DocumentFragment | Element, opt?: object) => Element | null; + querySelectorAll: (selector: string, node: Document | DocumentFragment | Element, opt?: object) => Array; + #private; +} +export type CheckResult = { + match: boolean; + pseudoElement: string | null; +}; diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/constant.d.ts b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/constant.d.ts new file mode 100644 index 0000000..f999a78 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/constant.d.ts @@ -0,0 +1,77 @@ +export const ATRULE: "Atrule"; +export const ATTR_SELECTOR: "AttributeSelector"; +export const CLASS_SELECTOR: "ClassSelector"; +export const COMBINATOR: "Combinator"; +export const IDENT: "Identifier"; +export const ID_SELECTOR: "IdSelector"; +export const NOT_SUPPORTED_ERR: "NotSupportedError"; +export const NTH: "Nth"; +export const OPERATOR: "Operator"; +export const PS_CLASS_SELECTOR: "PseudoClassSelector"; +export const PS_ELEMENT_SELECTOR: "PseudoElementSelector"; +export const RULE: "Rule"; +export const SCOPE: "Scope"; +export const SELECTOR: "Selector"; +export const SELECTOR_LIST: "SelectorList"; +export const STRING: "String"; +export const SYNTAX_ERR: "SyntaxError"; +export const TARGET_ALL: "all"; +export const TARGET_FIRST: "first"; +export const TARGET_LINEAL: "lineal"; +export const TARGET_SELF: "self"; +export const TYPE_SELECTOR: "TypeSelector"; +export const BIT_01: 1; +export const BIT_02: 2; +export const BIT_04: 4; +export const BIT_08: 8; +export const BIT_16: 16; +export const BIT_32: 32; +export const BIT_FFFF: 65535; +export const DUO: 2; +export const HEX: 16; +export const TYPE_FROM: 8; +export const TYPE_TO: -1; +export const ELEMENT_NODE: 1; +export const TEXT_NODE: 3; +export const DOCUMENT_NODE: 9; +export const DOCUMENT_FRAGMENT_NODE: 11; +export const DOCUMENT_POSITION_PRECEDING: 2; +export const DOCUMENT_POSITION_CONTAINS: 8; +export const DOCUMENT_POSITION_CONTAINED_BY: 16; +export const SHOW_ALL: 4294967295; +export const SHOW_CONTAINER: 1281; +export const SHOW_DOCUMENT: 256; +export const SHOW_DOCUMENT_FRAGMENT: 1024; +export const SHOW_ELEMENT: 1; +export const ALPHA_NUM: "[A-Z\\d]+"; +export const CHILD_IDX: "(?:first|last|only)-(?:child|of-type)"; +export const DIGIT: "(?:0|[1-9]\\d*)"; +export const LANG_PART: "(?:-[A-Z\\d]+)*"; +export const PSEUDO_CLASS: "(?:any-)?link|(?:first|last|only)-(?:child|of-type)|checked|empty|indeterminate|read-(?:only|write)|target"; +export const ANB: "[+-]?(?:(?:0|[1-9]\\d*)n?|n)|(?:[+-]?(?:0|[1-9]\\d*))?n\\s*[+-]\\s*(?:0|[1-9]\\d*)"; +export const COMBO: "\\s?[\\s>~+]\\s?"; +export const DESCEND: "\\s?[\\s>]\\s?"; +export const SIBLING: "\\s?[+~]\\s?"; +export const LOGIC_IS: ":is\\(\\s*[^)]+\\s*\\)"; +export const N_TH: "nth-(?:last-)?(?:child|of-type)\\(\\s*(?:even|odd|[+-]?(?:(?:0|[1-9]\\d*)n?|n)|(?:[+-]?(?:0|[1-9]\\d*))?n\\s*[+-]\\s*(?:0|[1-9]\\d*))\\s*\\)"; +export const SUB_TYPE: "\\[[^|\\]]+\\]|[#.:][\\w-]+"; +export const SUB_TYPE_WO_PSEUDO: "\\[[^|\\]]+\\]|[#.][\\w-]+"; +export const TAG_TYPE: "\\*|[A-Za-z][\\w-]*"; +export const TAG_TYPE_I: "\\*|[A-Z][\\w-]*"; +export const COMPOUND: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+)"; +export const COMPOUND_L: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)"; +export const COMPOUND_I: "(?:\\*|[A-Z][\\w-]*|(?:\\*|[A-Z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+)"; +export const COMPOUND_WO_PSEUDO: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.][\\w-]+)+)"; +export const COMPLEX: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+)+))*"; +export const COMPLEX_L: "(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*"; +export const HAS_COMPOUND: "has\\([\\s>]?\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.][\\w-]+)+)\\s*\\)"; +export const LOGIC_COMPOUND: "(?:is|not)\\(\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s*,\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*\\s*\\)"; +export const LOGIC_COMPLEX: "(?:is|not)\\(\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*(?:\\s*,\\s*(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+)(?:\\s?[\\s>~+]\\s?(?:\\*|[A-Za-z][\\w-]*|(?:\\*|[A-Za-z][\\w-]*)?(?:\\[[^|\\]]+\\]|[#.:][\\w-]+|:is\\(\\s*[^)]+\\s*\\))+))*)*\\s*\\)"; +export const FORM_PARTS: readonly string[]; +export const INPUT_BUTTON: readonly string[]; +export const INPUT_CHECK: readonly string[]; +export const INPUT_DATE: readonly string[]; +export const INPUT_TEXT: readonly string[]; +export const INPUT_EDIT: readonly string[]; +export const INPUT_LTR: readonly string[]; +export const KEYS_LOGICAL: Set; diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/finder.d.ts b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/finder.d.ts new file mode 100644 index 0000000..d88572f --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/finder.d.ts @@ -0,0 +1,63 @@ +export class Finder { + constructor(window: object); + onError: (e: Error, opt?: { + noexcept?: boolean; + }) => void; + setup: (selector: string, node: object, opt?: { + check?: boolean; + noexcept?: boolean; + warn?: boolean; + }) => object; + clearResults: (all?: boolean) => void; + private _handleFocusEvent; + private _handleKeyboardEvent; + private _handleMouseEvent; + private _registerEventListeners; + private _processSelectorBranches; + private _correspond; + private _createTreeWalker; + private _getSelectorBranches; + private _getFilteredChildren; + private _collectNthChild; + private _collectNthOfType; + private _matchAnPlusB; + private _matchHasPseudoFunc; + private _evaluateHasPseudo; + private _matchLogicalPseudoFunc; + private _matchPseudoClassSelector; + private _evaluateHostPseudo; + private _evaluateHostContextPseudo; + private _matchShadowHostPseudoClass; + private _matchSelectorForElement; + private _matchSelectorForShadowRoot; + private _matchSelector; + private _matchLeaves; + private _traverseAllDescendants; + private _findDescendantNodes; + private _matchDescendantCombinator; + private _matchChildCombinator; + private _matchAdjacentSiblingCombinator; + private _matchGeneralSiblingCombinator; + private _matchCombinator; + private _traverseAndCollectNodes; + private _findPrecede; + private _findNodeWalker; + private _matchSelf; + private _findLineal; + private _findEntryNodesForPseudoElement; + private _findEntryNodesForId; + private _findEntryNodesForClass; + private _findEntryNodesForType; + private _findEntryNodesForOther; + private _findEntryNodes; + private _determineTraversalStrategy; + private _processPendingItems; + private _collectNodes; + private _getCombinedNodes; + private _matchNodeNext; + private _matchNodePrev; + private _processComplexBranchAll; + private _processComplexBranchFirst; + find: (targetType: string) => Set; + #private; +} diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/matcher.d.ts b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/matcher.d.ts new file mode 100644 index 0000000..e1966b0 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/matcher.d.ts @@ -0,0 +1,16 @@ +export function matchPseudoElementSelector(astName: string, astType: string, opt?: { + forgive?: boolean; + warn?: boolean; +}): void; +export function matchDirectionPseudoClass(ast: object, node: object): boolean; +export function matchLanguagePseudoClass(ast: object, node: object): boolean; +export function matchDisabledPseudoClass(astName: string, node: object): boolean; +export function matchReadOnlyPseudoClass(astName: string, node: object): boolean; +export function matchAttributeSelector(ast: object, node: object, opt?: { + check?: boolean; + forgive?: boolean; +}): boolean; +export function matchTypeSelector(ast: object, node: object, opt?: { + check?: boolean; + forgive?: boolean; +}): boolean; diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/parser.d.ts b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/parser.d.ts new file mode 100644 index 0000000..f0b6da4 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/parser.d.ts @@ -0,0 +1,14 @@ +export function unescapeSelector(selector?: string): string; +export function preprocess(value: string): string; +export function parseSelector(sel: string): object; +export function walkAST(ast?: object): { + branches: Array; + info: object; +}; +export function compareASTNodes(a: object, b: object): number; +export function sortAST(asts: Array): Array; +export function parseAstName(selector: string): { + prefix: string; + localName: string; +}; +export { find as findAST, generate as generateCSS } from "css-tree"; diff --git a/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/utility.d.ts b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/utility.d.ts new file mode 100644 index 0000000..fe62759 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/dom-selector/types/js/utility.d.ts @@ -0,0 +1,30 @@ +export function getType(o: object): string; +export function verifyArray(arr: any[], type: string): any[]; +export function generateException(msg: string, name: string, globalObject?: object): DOMException; +export function findNestedHas(leaf: object): object | null; +export function findLogicalWithNestedHas(leaf: object): object | null; +export function filterNodesByAnB(nodes: Array, anb: { + a: number; + b: number; + reverse?: boolean; +}): Array; +export function resolveContent(node: object): Array; +export function traverseNode(node: object, walker: object, force?: boolean): object | null; +export function isCustomElement(node: object, opt?: object): boolean; +export function getSlottedTextContent(node: object): string | null; +export function getDirectionality(node: object): string | null; +export function getLanguageAttribute(node: object): string | null; +export function isContentEditable(node: object): boolean; +export function isVisible(node: object): boolean; +export function isFocusVisible(node: object): boolean; +export function isFocusableArea(node: object): boolean; +export function isFocusable(node: object): boolean; +export function getNamespaceURI(ns: string, node: object): string | null; +export function isNamespaceDeclared(ns?: string, node?: object): boolean; +export function isPreceding(nodeA: object, nodeB: object): boolean; +export function compareNodes(a: object, b: object): number; +export function sortNodes(nodes?: Array | Set): Array; +export function concatNestedSelectors(selectors: Array>): string; +export function extractNestedSelectors(css: string): Array>; +export function initNwsapi(window: object, document: object): object; +export function filterSelector(selector: string, target: string): boolean; diff --git a/vanilla/node_modules/@asamuzakjp/nwsapi/LICENSE b/vanilla/node_modules/@asamuzakjp/nwsapi/LICENSE new file mode 100644 index 0000000..cc3621a --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/nwsapi/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2007-2019 Diego Perini (http://www.iport.it/) + +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/vanilla/node_modules/@asamuzakjp/nwsapi/README.md b/vanilla/node_modules/@asamuzakjp/nwsapi/README.md new file mode 100644 index 0000000..f74b87d --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/nwsapi/README.md @@ -0,0 +1,132 @@ +# [NWSAPI](http://dperini.github.io/nwsapi/) + +Fast CSS Selectors API Engine + +![](https://img.shields.io/npm/v/nwsapi.svg?colorB=orange&style=flat) ![](https://img.shields.io/github/tag/dperini/nwsapi.svg?style=flat) ![](https://img.shields.io/npm/dw/nwsapi.svg?style=flat) ![](https://img.shields.io/github/issues/dperini/nwsapi.svg?style=flat) + +NWSAPI is the development progress of [NWMATCHER](https://github.com/dperini/nwmatcher) aiming at [Selectors Level 4](https://www.w3.org/TR/selectors-4/) conformance. It has been completely reworked to be easily extended and maintained. It is a right-to-left selector parser and compiler written in pure Javascript with no external dependencies. It was initially thought as a cross browser library to improve event delegation and web page scraping in various frameworks but it has become a popular replacement of the native CSS selection and matching functionality in newer browsers and headless environments. + +It uses [regular expressions](https://en.wikipedia.org/wiki/Regular_expression) to parse CSS selector strings and [metaprogramming](https://en.wikipedia.org/wiki/Metaprogramming) to transforms these selector strings into Javascript function resolvers. This process is executed only once for each selector string allowing memoization of the function resolvers and achieving unmatched performances. + +## Installation + +To include NWSAPI in a standard web page: + +```html + +``` + +To include NWSAPI in a standard web page and automatically replace the native QSA: + +```html + +``` + +To use NWSAPI with Node.js: + +``` +$ npm install nwsapi +``` + +NWSAPI currently supports browsers (as a global, `NW.Dom`) and headless environments (as a CommonJS module). + + +## Supported Selectors + +Here is a list of all the CSS2/CSS3/CSS4 [Supported selectors](https://github.com/dperini/nwsapi/wiki/CSS-supported-selectors). + + +## Features and Compliance + +You can read more about NWSAPI [features and compliance](https://github.com/dperini/nwsapi/wiki/Features-and-compliance) on the wiki. + + +## API + +### DOM Selection + +#### `ancestor( selector, context, callback )` + +Returns a reference to the nearest ancestor element matching `selector`, starting at `context`. Returns `null` if no element is found. If `callback` is provided, it is invoked for the matched element. + +#### `first( selector, context, callback )` + +Returns a reference to the first element matching `selector`, starting at `context`. Returns `null` if no element matches. If `callback` is provided, it is invoked for the matched element. + +#### `match( selector, element, callback )` + +Returns `true` if `element` matches `selector`, starting at `context`; returns `false` otherwise. If `callback` is provided, it is invoked for the matched element. + +#### `select( selector, context, callback )` + +Returns an array of all the elements matching `selector`, starting at `context`; returns empty `Array` otherwise. If `callback` is provided, it is invoked for each matching element. + + +### DOM Helpers + +#### `byId( id, from )` + +Returns a reference to the first element with ID `id`, optionally filtered to descendants of the element `from`. + +#### `byTag( tag, from )` + +Returns an array of elements having the specified tag name `tag`, optionally filtered to descendants of the element `from`. + +#### `byClass( class, from )` + +Returns an array of elements having the specified class name `class`, optionally filtered to descendants of the element `from`. + + +### Engine Configuration + +#### `configure( options )` + +The following is the list of currently available configuration options, their default values and descriptions, they are boolean flags that can be set to `true` or `false`: + +* `IDS_DUPES`: true - true to allow using multiple elements having the same id, false to disallow +* `LIVECACHE`: true - true for caching both results and resolvers, false for caching only resolvers +* `MIXEDCASE`: true - true to match tag names case insensitive, false to match using case sensitive +* `LOGERRORS`: true - true to print errors and warnings to the console, false to mute both of them + + +### Examples on extending the basic functionalities + +#### `configure( { : [ true | false ] } )` + +Disable logging errors/warnings to console, disallow duplicate ids. Example: + +```js +NW.Dom.configure( { LOGERRORS: false, IDS_DUPES: false } ); +``` +NOTE: NW.Dom.configure() without parameters return the current configuration. + +#### `registerCombinator( symbol, resolver )` + +Registers a new symbol and its matching resolver in the combinators table. Example: + +```js +NW.Dom.registerCombinator( '^', 'e.parentElement' ); +``` + +#### `registerOperator( symbol, resolver )` + +Registers a new symbol and its matching resolver in the attribute operators table. Example: + +```js +NW.Dom.registerOperator( '!=', { p1: '^', p2: '$', p3: 'false' } ); +``` + +#### `registerSelector( name, rexp, func )` + +Registers a new selector, the matching RE and the resolver function, in the selectors table. Example: + +```js +NW.Dom.registerSelector('Controls', /^\:(control)(.*)/i, + (function(global) { + return function(match, source, mode, callback) { + var status = true; + source = 'if(/^(button|input|select|textarea)/i.test(e.nodeName)){' + source + '}'; + return { 'source': source, 'status': status }; + }; + })(this)); +``` diff --git a/vanilla/node_modules/@asamuzakjp/nwsapi/package.json b/vanilla/node_modules/@asamuzakjp/nwsapi/package.json new file mode 100644 index 0000000..6a44b9c --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/nwsapi/package.json @@ -0,0 +1,43 @@ +{ + "name": "@asamuzakjp/nwsapi", + "version": "2.3.9", + "description": "Fast CSS Selectors API Engine", + "homepage": "http://javascript.nwbox.com/nwsapi/", + "main": "./src/nwsapi", + "keywords": [ + "css", + "css3", + "css4", + "matcher", + "selector" + ], + "licenses": [ + { + "type": "MIT", + "url": "http://javascript.nwbox.com/nwsapi/MIT-LICENSE" + } + ], + "license": "MIT", + "author": { + "name": "Diego Perini", + "email": "diego.perini@gmail.com", + "web": "http://www.iport.it/" + }, + "maintainers": [ + { + "name": "Diego Perini", + "email": "diego.perini@gmail.com", + "web": "http://www.iport.it/" + } + ], + "bugs": { + "url": "http://github.com/dperini/nwsapi/issues" + }, + "repository": { + "type": "git", + "url": "git://github.com/dperini/nwsapi.git" + }, + "scripts": { + "lint": "eslint ./src/nwsapi.js" + } +} diff --git a/vanilla/node_modules/@asamuzakjp/nwsapi/src/nwsapi.js b/vanilla/node_modules/@asamuzakjp/nwsapi/src/nwsapi.js new file mode 100644 index 0000000..e118fd5 --- /dev/null +++ b/vanilla/node_modules/@asamuzakjp/nwsapi/src/nwsapi.js @@ -0,0 +1,1855 @@ +/** + * Forked and modified from nwsapi@2.2.2 + * - Export to cjs only + * - Remove ./modules directory + * - Remove unused exported properties + * - Remove unused pseudo-classes + * - Remove Snapshot.root and resolve document.documentElement on runtime + * - Use `let` and `const` as much as possible + * - Use `===` and `!==` + * - Fix `:nth-of-type()` + * - Fix function source for :root, :target and :indeterminate pseudo-classes + * - Fix + * - Support complex selectors within `:is()` and `:not()` + * - Add ::slotted() and ::part() to pseudo-elements list + * - Add isContentEditable() function + * - Add createMatchingParensRegex() function from upstream + * - Invalidate cache for :has() pseudo class + * - Optimize some regular expressions + */ +/* + * Copyright (C) 2007-2019 Diego Perini + * All rights reserved. + * + * nwsapi.js - Fast CSS Selectors API Engine + * + * Author: Diego Perini + * Version: 2.2.0 + * Created: 20070722 + * Release: 20220901 + * + * License: + * http://javascript.nwbox.com/nwsapi/MIT-LICENSE + * Download: + * http://javascript.nwbox.com/nwsapi/nwsapi.js + */ + +(function Export(global, factory) { + 'use strict'; + module.exports = factory; +})(this, function Factory(global, Export) { + const version = 'nwsapi-2.2.2'; + + let doc = global.document; + + /** + * Generate a regex that matches a balanced set of parentheses. + * Outermost parentheses are excluded so any amount of children can be handled. + * See https://stackoverflow.com/a/35271017 for reference + * + * @param {number} depth + * @return {string} + */ + function createMatchingParensRegex(depth = 1) { + const out = '\\([^)(]*?(?:'.repeat(depth) + '\\([^)(]*?\\)' + '[^)(]*?)*?\\)'.repeat(depth); + // remove outermost escaped parens + return out.slice(2, out.length - 2); + } + + const CFG = { + // extensions + operators: '[~*^$|]=|=', + combinators: '[\\s>+~](?=[^>+~])' + }; + + const NOT = { + // not enclosed in double/single/parens/square + doubleEnc: '(?=(?:[^"]*"[^"]*")*[^"]*$)', + singleEnc: "(?=(?:[^']*'[^']*')*[^']*$)", + parensEnc: '(?![^\\x28]*\\x29)', + squareEnc: '(?![^\\x5b]*\\x5d)' + }; + + const REX = { + // regular expressions + hasEscapes: /\\/, + hexNumbers: /^[0-9a-f]/i, + escOrQuote: /^\\|[\x22\x27]/, + regExpChar: /(?:(?!\\)[\\^$.*+?()[\]{}|/])/g, + trimSpaces: /[\r\n\f]|^\s+|\s+$/g, + commaGroup: RegExp('(\\s{0,255},\\s{0,255})' + NOT.squareEnc + NOT.parensEnc, 'g'), + splitGroup: /((?:\x28[^\x29]{0,255}\x29|\[[^\]]{0,255}\]|\\.|[^,])+)/g, + fixEscapes: /\\([0-9a-f]{1,6}\s?|.)|([\x22\x27])/gi, + combineWSP: RegExp('\\s{1,255}' + NOT.singleEnc + NOT.doubleEnc, 'g'), + tabCharWSP: RegExp('(\\s?\\t{1,255}\\s?)' + NOT.singleEnc + NOT.doubleEnc, 'g'), + pseudosWSP: RegExp('\\s{1,255}([-+])\\s{1,255}' + NOT.squareEnc, 'g') + }; + + const STD = { + combinator: /\s?([>+~])\s?/g, + apimethods: /^(?:[a-z]+|\*)\|/i, + namespaces: /(\*|[a-z]+)\|[-a-z]+/i + }; + + const GROUPS = { + // pseudo-classes requiring parameters + logicalsel: '(is|where|matches|not|has)(?:\\x28\\s?(' + createMatchingParensRegex(3) + ')\\s?\\x29)', + treestruct: '(nth(?:-last)?(?:-child|-of-type))(?:\\x28\\s?(even|odd|(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)?)\\s?(?:\\x29|$))', + // pseudo-classes not requiring parameters + locationpc: '(any-link|link|visited|target)\\b', + structural: '(root|empty|(?:(?:first|last|only)(?:-child|-of-type)))\\b', + inputstate: '(enabled|disabled|read-(?:only|write)|placeholder-shown|default)\\b', + inputvalue: '(checked|indeterminate)\\b', + // pseudo-classes for parsing only selectors + pseudoNop: '(autofill|-webkit-autofill)\\b', + // pseudo-elements starting with single colon (:) + pseudoSng: '(after|before|first-letter|first-line)\\b', + // pseudo-elements starting with double colon (::) + pseudoDbl: ':(after|before|first-letter|first-line|selection|part|placeholder|slotted|-webkit-[-a-z0-9]{2,})\\b' + }; + + const Patterns = { + // pseudo-classes + treestruct: RegExp('^:(?:' + GROUPS.treestruct + ')(.*)', 'i'), + structural: RegExp('^:(?:' + GROUPS.structural + ')(.*)', 'i'), + inputstate: RegExp('^:(?:' + GROUPS.inputstate + ')(.*)', 'i'), + inputvalue: RegExp('^:(?:' + GROUPS.inputvalue + ')(.*)', 'i'), + locationpc: RegExp('^:(?:' + GROUPS.locationpc + ')(.*)', 'i'), + logicalsel: RegExp('^:(?:' + GROUPS.logicalsel + ')(.*)', 'i'), + pseudoNop: RegExp('^:(?:' + GROUPS.pseudoNop + ')(.*)', 'i'), + pseudoSng: RegExp('^:(?:' + GROUPS.pseudoSng + ')(.*)', 'i'), + pseudoDbl: RegExp('^:(?:' + GROUPS.pseudoDbl + ')(.*)', 'i'), + // combinator symbols + children: /^\s?>\s?(.*)/, + adjacent: /^\s?\+\s?(.*)/, + relative: /^\s?~\s?(.*)/, + ancestor: /^\s+(.*)/, + // universal & namespace + universal: /^\*(.*)/, + namespace: /^(\w+|\*)?\|(.*)/ + }; + + // emulate firefox error strings + const qsNotArgs = 'Not enough arguments'; + const qsInvalid = ' is not a valid selector'; + + // detect structural pseudo-classes in selectors + const reNthElem = /(:nth(?:-last)?-child)/i; + const reNthType = /(:nth(?:-last)?-of-type)/i; + + // placeholder for global regexp + let reOptimizer; + let reValidator; + + // special handling configuration flags + const Config = { + IDS_DUPES: true, + MIXEDCASE: true, + LOGERRORS: true, + VERBOSITY: true + }; + + let NAMESPACE; + let QUIRKS_MODE; + let HTML_DOCUMENT; + + const ATTR_STD_OPS = { + '=': 1, + '^=': 1, + '$=': 1, + '|=': 1, + '*=': 1, + '~=': 1 + }; + + const HTML_TABLE = { + accept: 1, + 'accept-charset': 1, + align: 1, + alink: 1, + axis: 1, + bgcolor: 1, + charset: 1, + checked: 1, + clear: 1, + codetype: 1, + color: 1, + compact: 1, + declare: 1, + defer: 1, + dir: 1, + direction: 1, + disabled: 1, + enctype: 1, + face: 1, + frame: 1, + hreflang: 1, + 'http-equiv': 1, + lang: 1, + language: 1, + link: 1, + media: 1, + method: 1, + multiple: 1, + nohref: 1, + noresize: 1, + noshade: 1, + nowrap: 1, + readonly: 1, + rel: 1, + rev: 1, + rules: 1, + scope: 1, + scrolling: 1, + selected: 1, + shape: 1, + target: 1, + text: 1, + type: 1, + valign: 1, + valuetype: 1, + vlink: 1 + }; + + const Combinators = {}; + + const Selectors = {}; + + const Operators = { + '=': { + p1: '^', + p2: '$', + p3: 'true' + }, + '^=': { + p1: '^', + p2: '', + p3: 'true' + }, + '$=': { + p1: '', + p2: '$', + p3: 'true' + }, + '*=': { + p1: '', + p2: '', + p3: 'true' + }, + '|=': { + p1: '^', + p2: '(-|$)', + p3: 'true' + }, + '~=': { + p1: '(^|\\s)', + p2: '(\\s|$)', + p3: 'true' + } + }; + + const concatCall = function (nodes, callback) { + let i = 0; + const l = nodes.length; + const list = Array(l); + while (l > i) { + if (callback(list[i] = nodes[i]) === false) { + break; + } + ++i; + } + return list; + }; + + const concatList = function (list, nodes) { + let i = -1; + let l = nodes.length; + while (l--) { + list[list.length] = nodes[++i]; + } + return list; + }; + + let hasDupes = false; + + const documentOrder = function (a, b) { + if (!hasDupes && a === b) { + hasDupes = true; + return 0; + } + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + + const unique = function (nodes) { + let i = 0; + let j = -1; + let l = nodes.length + 1; + const list = []; + while (--l) { + if (nodes[i++] === nodes[i]) { + continue; + } + list[++j] = nodes[i - 1]; + } + hasDupes = false; + return list; + }; + + // check context for mixed content + const hasMixedCaseTagNames = function (context) { + const api = 'getElementsByTagNameNS'; + + // current host context (ownerDocument) + context = context.ownerDocument || context; + + // documentElement (root) element namespace or default html/xhtml namespace + const ns = context.documentElement && context.documentElement.namespaceURI + ? context.documentElement.namespaceURI + : 'http://www.w3.org/1999/xhtml'; + + // checking the number of non HTML nodes in the document + return (context[api]('*', '*').length - context[api](ns, '*').length) > 0; + }; + + // check if the document type is HTML + const isHTML = function (node) { + const doc = node.ownerDocument || node; + return doc.nodeType === 9 && doc.contentType === 'text/html'; + }; + + // convert single codepoint to UTF-16 encoding + const codePointToUTF16 = function (codePoint) { + // out of range, use replacement character + if (codePoint < 1 || codePoint > 0x10ffff || + (codePoint > 0xd7ff && codePoint < 0xe000)) { + return '\\ufffd'; + } + // javascript strings are UTF-16 encoded + if (codePoint < 0x10000) { + const lowHex = '000' + codePoint.toString(16); + return '\\u' + lowHex.substr(lowHex.length - 4); + } + // supplementary high + low surrogates + return '\\u' + (((codePoint - 0x10000) >> 0x0a) + 0xd800).toString(16) + + '\\u' + (((codePoint - 0x10000) % 0x400) + 0xdc00).toString(16); + }; + + // convert single codepoint to string + const stringFromCodePoint = function (codePoint) { + // out of range, use replacement character + if (codePoint < 1 || codePoint > 0x10ffff || + (codePoint > 0xd7ff && codePoint < 0xe000)) { + return '\ufffd'; + } + if (codePoint < 0x10000) { + return String.fromCharCode(codePoint); + } + return String.fromCodePoint(codePoint); + }; + + // convert escape sequence in a CSS string or identifier + // to javascript string with javascript escape sequences + const convertEscapes = function (str) { + return REX.hasEscapes.test(str) + ? str.replace(REX.fixEscapes, function (substring, p1, p2) { + // unescaped " or ' + return p2 + ? '\\' + p2 + // javascript strings are UTF-16 encoded + : REX.hexNumbers.test(p1) + ? codePointToUTF16(parseInt(p1, 16)) + // \' \" + : REX.escOrQuote.test(p1) + ? substring + // \g \h \. \# etc + : p1; + }) + : str; + }; + + // convert escape sequence in a CSS string or identifier + // to javascript string with characters representations + const unescapeIdentifier = function (str) { + return REX.hasEscapes.test(str) + ? str.replace(REX.fixEscapes, function (substring, p1, p2) { + // unescaped " or ' + return p2 || (REX.hexNumbers.test(p1) + ? stringFromCodePoint(parseInt(p1, 16)) + // \' \" + : REX.escOrQuote.test(p1) + ? substring + // \g \h \. \# etc + : p1); + }) + : str; + }; + + // empty set + const none = []; + + // cached lambdas + const matchLambdas = {}; + const selectLambdas = {}; + + // cached resolvers + let matchResolvers = {}; + let selectResolvers = {}; + + const method = { + '#': 'getElementById', + '*': 'getElementsByTagName', + '|': 'getElementsByTagNameNS', + '.': 'getElementsByClassName' + }; + + // find duplicate ids using iterative walk + const byIdRaw = function (id, context) { + let node = context; + const nodes = []; + let next = node.firstElementChild; + while ((node = next)) { + node.id === id && nodes.push(node); + if ((next = node.firstElementChild || node.nextElementSibling)) { + continue; + } + while (!next && (node = node.parentElement) && node !== context) { + next = node.nextElementSibling; + } + } + return nodes; + }; + + // context agnostic getElementById + const byId = function (id, context) { + let e; + const api = method['#']; + + // duplicates id allowed + if (Config.IDS_DUPES === false) { + if (api in context) { + e = context[api](id); + return e ? [e] : none; + } + } else if ('all' in context) { + if ((e = context.all[id])) { + if (e.nodeType === 1) { + return e.getAttribute('id') !== id ? [] : [e]; + } else if (id === 'length') { + e = context[api](id); + return e ? [e] : none; + } + const nodes = []; + for (let i = 0, l = e.length; l > i; ++i) { + if (e[i].id === id) { + nodes.push(e[i]); + } + } + return nodes.length ? nodes : none; + } else { + return none; + } + } + + return byIdRaw(id, context); + }; + + // context agnostic getElementsByTagName + const byTag = function (tag, context) { + let e; + let nodes; + const api = method['*']; + + // DOCUMENT_NODE (9) & ELEMENT_NODE (1) + if (api in context) { + return Array.prototype.slice.call(context[api](tag)); + } else { + tag = tag.toLowerCase(); + // DOCUMENT_FRAGMENT_NODE (11) + if ((e = context.firstElementChild)) { + if (!(e.nextElementSibling || tag === '*' || e.localName === tag)) { + return Array.prototype.slice.call(e[api](tag)); + } else { + nodes = []; + do { + if (tag === '*' || e.localName === tag) { + nodes.push(e); + } + concatList(nodes, e[api](tag)); + } while ((e = e.nextElementSibling)); + } + } else { + nodes = none; + } + } + return nodes; + }; + + // context agnostic getElementsByClassName + const byClass = function (cls, context) { + let e; + let nodes; + const api = method['.']; + let reCls; + // DOCUMENT_NODE (9) & ELEMENT_NODE (1) + if (api in context) { + return Array.prototype.slice.call(context[api](cls)); + } else { + // DOCUMENT_FRAGMENT_NODE (11) + if ((e = context.firstElementChild)) { + reCls = RegExp('(^|\\s)' + cls + '(\\s|$)', QUIRKS_MODE ? 'i' : ''); + if (!(e.nextElementSibling || reCls.test(e.className))) { + return Array.prototype.slice.call(e[api](cls)); + } else { + nodes = []; + do { + if (reCls.test(e.className)) { + nodes.push(e); + } + concatList(nodes, e[api](cls)); + } while ((e = e.nextElementSibling)); + } + } else nodes = none; + } + return nodes; + }; + + const compat = { + '#': function (c, n) { + REX.hasEscapes.test(n) && (n = unescapeIdentifier(n)); + return function (e, f) { + return byId(n, c); + }; + }, + '*': function (c, n) { + REX.hasEscapes.test(n) && (n = unescapeIdentifier(n)); + return function (e, f) { + return byTag(n, c); + }; + }, + '|': function (c, n) { + REX.hasEscapes.test(n) && (n = unescapeIdentifier(n)); + return function (e, f) { + return byTag(n, c); + }; + }, + '.': function (c, n) { + REX.hasEscapes.test(n) && (n = unescapeIdentifier(n)); + return function (e, f) { + return byClass(n, c); + }; + } + }; + + // namespace aware hasAttribute + // helper for XML/XHTML documents + const hasAttributeNS = function (e, name) { + let i; + let l; + const attr = e.getAttributeNames(); + name = RegExp(':?' + name + '$', HTML_DOCUMENT ? 'i' : ''); + for (i = 0, l = attr.length; l > i; ++i) { + if (name.test(attr[i])) { + return true; + } + } + return false; + }; + + // fast resolver for the :nth-child() and :nth-last-child() pseudo-classes + const nthElement = (function () { + let idx = 0; + let len = 0; + let set = 0; + let parent; + let parents = []; + let nodes = []; + return function (element, dir) { + // ensure caches are emptied after each run, invoking with dir = 2 + if (dir === 2) { + idx = 0; len = 0; set = 0; nodes = []; parents = []; parent = undefined; + return -1; + } + let e, i, j, k, l; + if (parent === element.parentElement) { + i = set; j = idx; l = len; + } else { + l = parents.length; + parent = element.parentElement; + for (i = -1, j = 0, k = l - 1; l > j; ++j, --k) { + if (parents[j] === parent) { + i = j; + break; + } + if (parents[k] === parent) { + i = k; + break; + } + } + if (i < 0) { + parents[i = l] = parent; + l = 0; nodes[i] = []; + e = (parent && parent.firstElementChild) || element; + while (e) { + nodes[i][l] = e; + if (e === element) { + j = l; + } + e = e.nextElementSibling; + ++l; + } + set = i; idx = 0; len = l; + if (l < 2) { + return l; + } + } else { + l = nodes[i].length; + set = i; + } + } + if (element !== nodes[i][j] && element !== nodes[i][j = 0]) { + for (j = 0, e = nodes[i], k = l - 1; l > j; ++j, --k) { + if (e[j] === element) { + break; + } + if (e[k] === element) { + j = k; + break; + } + } + } + idx = j + 1; len = l; + return dir ? l - j : idx; + }; + })(); + + // fast resolver for the :nth-of-type() and :nth-last-of-type() pseudo-classes + const nthOfType = (function () { + let idx = 0; + let len = 0; + let set = 0; + let parent; + let parents = []; + let nodes = []; + return function (element, dir) { + // ensure caches are emptied after each run, invoking with dir = 2 + if (dir === 2) { + idx = 0; len = 0; set = 0; nodes = []; parents = []; parent = undefined; + return -1; + } + const name = element.localName; + const nsURI = element.namespaceURI; + if (nsURI !== 'http://www.w3.org/1999/xhtml') { + idx = 0; len = 0; set = 0; nodes = []; parents = []; parent = undefined; + } + let e; + let i; + let j; + let k; + let l; + if (nodes[set] && nodes[set][name] && parent === element.parentElement) { + i = set; + j = idx; + l = len; + } else { + l = parents.length; + parent = element.parentElement; + for (i = -1, j = 0, k = l - 1; l > j; ++j, --k) { + if (parents[j] === parent) { + i = j; + break; + } + if (parents[k] === parent) { + i = k; + break; + } + } + if (i < 0 || !nodes[i][name]) { + parents[i = l] = parent; + nodes[i] || (nodes[i] = Object()); + l = 0; nodes[i][name] = []; + e = (parent && parent.firstElementChild) || element; + while (e) { + if (e === element) { + j = l; + } + if (e.localName === name && e.namespaceURI === nsURI) { + nodes[i][name][l] = e; + ++l; + } + e = e.nextElementSibling; + } + set = i; idx = j; len = l; + if (l < 2) { + return l; + } + } else { + l = nodes[i][name].length; + set = i; + } + } + if (element !== nodes[i][name][j] && element !== nodes[i][name][j = 0]) { + for (j = 0, e = nodes[i][name], k = l - 1; l > j; ++j, --k) { + if (e[j] === element) { + break; + } + if (e[k] === element) { + j = k; + break; + } + } + } + idx = j + 1; len = l; + return dir ? l - j : idx; + }; + })(); + + // check if the node is the target + const isTarget = function (node) { + const doc = node.ownerDocument || node; + const { hash } = new URL(doc.URL); + if (node.id && hash === `#${node.id}` && doc.contains(node)) { + return true; + } + return false; + }; + + // check if node is indeterminate + const isIndeterminate = function (node) { + if ((node.indeterminate && node.localName === 'input' && + node.type === 'checkbox') || + (node.localName === 'progress' && !node.hasAttribute('value'))) { + return true; + } + if (node.localName === 'input' && node.type === 'radio' && + !node.hasAttribute('checked')) { + const nodeName = node.name; + let parent = node.parentNode; + while (parent) { + if (parent.localName === 'form') { + break; + } + parent = parent.parentNode; + } + if (!parent) { + const doc = node.ownerDocument; + parent = doc.documentElement; + } + const items = parent.getElementsByTagName('input'); + const l = items.length; + let checked; + for (let i = 0; i < l; i++) { + const item = items[i]; + if (item.getAttribute('type') === 'radio') { + if (nodeName) { + if (item.getAttribute('name') === nodeName) { + checked = !!item.checked; + } + } else if (!item.hasAttribute('name')) { + checked = !!item.checked; + } + if (checked) { + break; + } + } + } + if (!checked) { + return true; + } + } + return false; + }; + + // check if node content is editable + const isContentEditable = function (node) { + let attrValue = 'inherit'; + if (node.hasAttribute('contenteditable')) { + attrValue = node.getAttribute('contenteditable'); + } + switch (attrValue) { + case '': + case 'plaintext-only': + case 'true': + return true; + case 'false': + return false; + default: + if (node.parentNode && node.parentNode.nodeType === 1) { + return isContentEditable(node.parentNode); + } + return false; + } + }; + + // build validation regexps used by the engine + const setIdentifierSyntax = function () { + // + // NOTE: SPECIAL CASES IN CSS SYNTAX PARSING RULES + // + // The https://drafts.csswg.org/css-syntax/#typedef-eof-token + // allow mangled|unclosed selector syntax at the end of selectors strings + // + // Literal equivalent hex representations of the characters: " ' ` ] ) + // + // \\x22 = " - double quotes \\x5b = [ - open square bracket + // \\x27 = ' - single quote \\x5d = ] - closed square bracket + // \\x60 = ` - back tick \\x28 = ( - open round parens + // \\x5c = \ - back slash \\x29 = ) - closed round parens + // + // using hex format prevents false matches of opened/closed instances + // pairs, coloring breakage and other editors highlightning problems. + // + + // @see https://drafts.csswg.org/css-syntax-3/#ident-token-diagram + const nonascii = '[^\\x00-\\x9f]'; + const esctoken = '\\\\(?:[^\\r\\n\\f\\da-f]|[\\da-f]{1,6}\\s{0,255})'; + const identifier = + '(?:--|-?(?:[a-z_]|' + nonascii + '|' + esctoken + '))' + + '(?:[\\w-]|' + nonascii + '|' + esctoken + ')*'; + + const pseudonames = '[-\\w]+'; + const pseudoparms = '(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)'; + const doublequote = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*(?:"|$)'; + const singlequote = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*(?:'|$)"; + + const attrparser = identifier + '|' + doublequote + '|' + singlequote; + + const attrvalues = '([\\x22\\x27]?)((?!\\3)*|(?:\\\\?.)*?)(?:\\3|$)'; + + const attributes = + '\\[' + + // attribute presence + '(?:\\*\\|)?\\s?(' + identifier + '(?::' + identifier + ')?)\\s?' + + '(?:(' + CFG.operators + ')\\s?(?:' + attrparser + '))?' + + // attribute case sensitivity + '(?:\\s?\\b(i))?\\s?' + + '(?:\\]|$)'; + + const attrmatcher = attributes.replace(attrparser, attrvalues); + + const pseudoclass = + '(?:\\x28\\s*' + + '(?:' + pseudoparms + '?)?|' + + // universal * & + // namespace *|* + '[*|]|' + + '(?:' + + '(?::' + pseudonames + '(?:\\x28' + pseudoparms + '?(?:\\x29|$))?)|' + + '(?:[.#]?' + identifier + ')|' + + '(?:' + attributes + ')' + + ')+|' + + '\\s?[>+~]\\s?|' + + '\\s?,\\s?|' + + '\\s|' + + '\\x29|$' + + ')*'; + + const standardValidator = + '(?=\\s?[^>+~(){}<])' + + '(?:' + + // universal * & + // namespace *|* + '\\*|\\||' + + '(?:[.#]?' + identifier + ')+|' + + '(?:' + attributes + ')+|' + + '(?:::?' + pseudonames + pseudoclass + ')|' + + '(?:\\s?' + CFG.combinators + '\\s?)|' + + '\\s?,\\s?|' + + '\\s?' + + ')+'; + + // the following global RE is used to return the + // deepest localName in selector strings and then + // use it to retrieve all possible matching nodes + // that will be filtered by compiled resolvers + reOptimizer = RegExp( + '(?:([.:#*]?)(' + identifier + ')' + + '(?::[-\\w]+|\\[[^\\]]+(?:\\]|$)|\\x28[^\\x29]+(?:\\x29|$))*' + + ')$', 'i'); + + // global + reValidator = RegExp(standardValidator, 'gi'); + + Patterns.id = RegExp('^#(' + identifier + ')(.*)', 'i'); + Patterns.tagName = RegExp('^(' + identifier + ')(.*)', 'i'); + Patterns.className = RegExp('^\\.(' + identifier + ')(.*)', 'i'); + Patterns.attribute = RegExp('^(?:' + attrmatcher + ')(.*)'); + }; + + // configure the engine to use special handling + const configure = function (option, clear) { + if (typeof option === 'string') { + return !!Config[option]; + } + if (typeof option !== 'object') { + return Config; + } + for (const i in option) { + Config[i] = !!option[i]; + } + // clear lambda cache + if (clear) { + matchResolvers = {}; + selectResolvers = {}; + } + setIdentifierSyntax(); + return true; + }; + + // centralized error and exceptions handling + const emit = function (message, proto) { + let err; + if (Config.VERBOSITY) { + if (global[proto]) { + err = new global[proto](message); + } else { + err = new global.DOMException(message, 'SyntaxError'); + } + throw err; + } + if (Config.LOGERRORS && console && console.log) { + console.log(message); + } + }; + + // passed to resolvers + const Snapshot = { + doc: null, + from: null, + byTag: null, + first: null, + match: null, + ancestor: null, + nthOfType: null, + nthElement: null, + hasAttributeNS: null, + isTarget: null, + isIndeterminate: null, + isContentEditable: null + }; + + // context + let lastContext; + + const switchContext = function (context, force) { + const oldDoc = doc; + doc = context.ownerDocument || context; + if (force || oldDoc !== doc) { + // force a new check for each document change + // performed before the next select operation + HTML_DOCUMENT = isHTML(doc); + QUIRKS_MODE = HTML_DOCUMENT && doc.compatMode.indexOf('CSS') < 0; + NAMESPACE = doc.documentElement && doc.documentElement.namespaceURI; + Snapshot.doc = doc; + } + Snapshot.from = context; + return context; + }; + + // selector + let lastMatched; + let lastSelected; + + const F_INIT = '"use strict";return function Resolver(c,f,x,r)'; + + const S_HEAD = 'var e,n,o,j=r.length-1,k=-1'; + const M_HEAD = 'var e,n,o'; + + const S_LOOP = 'main:while((e=c[++k]))'; + const N_LOOP = 'main:while((e=c.item(++k)))'; + const M_LOOP = 'e=c;'; + + const S_BODY = 'r[++j]=c[k];'; + const N_BODY = 'r[++j]=c.item(k);'; + const M_BODY = ''; + + const S_TAIL = 'continue main;'; + const M_TAIL = 'r=true;'; + + const S_TEST = 'if(f(c[k])){break main;}'; + const N_TEST = 'if(f(c.item(k))){break main;}'; + const M_TEST = 'f(c);'; + + let S_VARS = []; + let M_VARS = []; + + // build conditional code to check components of selector strings + const compileSelector = function (expression, source, mode, callback) { + // N is the negation pseudo-class flag + // D is the default inverted negation flag + let a; + let b; + let n; + let f; + let name; + let NS; + const N = ''; + const D = '!'; + let compat; + let expr; + let match; + let result; + let status; + let symbol; + let test; + let type; + let selector = expression; + let vars; + + // original 'select' or 'match' selector string before normalization + const selectorString = mode ? lastSelected : lastMatched; + + // isolate selector combinators/components and normalize whitespace + selector = selector.replace(STD.combinator, '$1'); // .replace(STD.whitespace, ' '); + + let selectorRecursion = true; + while (selector) { + // get namespace prefix if present or get first char of selector + symbol = STD.apimethods.test(selector) ? '|' : selector[0]; + + switch (symbol) { + // universal resolver + case '*': + match = selector.match(Patterns.universal); + if (N === '!') { + source = 'if(' + N + 'true' + '){' + source + '}'; + } + break; + // id resolver + case '#': + match = selector.match(Patterns.id); + source = 'if(' + N + '(/^' + match[1] + '$/.test(e.getAttribute("id"))' + + ')){' + source + '}'; + break; + // class name resolver + case '.': + match = selector.match(Patterns.className); + compat = (QUIRKS_MODE ? 'i' : '') + '.test(e.getAttribute("class"))'; + source = 'if(' + N + '(/(^|\\s)' + match[1] + '(\\s|$)/' + compat + + ')){' + source + '}'; + break; + // tag name resolver + case (/[_a-z]/i.test(symbol) ? symbol : undefined): + match = selector.match(Patterns.tagName); + source = 'if(' + N + '(e.localName' + + (Config.MIXEDCASE || hasMixedCaseTagNames(doc) + ? '=="' + match[1].toLowerCase() + '"' + : '=="' + match[1].toUpperCase() + '"') + + ')){' + source + '}'; + break; + // namespace resolver + case '|': + match = selector.match(Patterns.namespace); + if (match[1] === '*') { + source = 'if(' + N + 'true){' + source + '}'; + } else if (!match[1]) { + source = 'if(' + N + '(!e.namespaceURI)){' + source + '}'; + } else if (typeof match[1] === 'string' && doc.documentElement && + doc.documentElement.prefix === match[1]) { + source = 'if(' + N + '(e.namespaceURI=="' + NAMESPACE + '")){' + source + '}'; + } else { + emit('\'' + selectorString + '\'' + qsInvalid); + } + break; + // attributes resolver + case '[': + match = selector.match(Patterns.attribute); + NS = match[0].match(STD.namespaces); + name = match[1]; + expr = name.split(':'); + expr = expr.length === 2 ? expr[1] : expr[0]; + if (match[2] && !(test = Operators[match[2]])) { + emit('\'' + selectorString + '\'' + qsInvalid); + return ''; + } + if (match[4] === '') { + test = match[2] === '~=' + ? { p1: '^\\s', p2: '+$', p3: 'true' } + : match[2] in ATTR_STD_OPS && match[2] !== '~=' + ? { p1: '^', p2: '$', p3: 'true' } + : test; + } else if (match[2] === '~=' && match[4].includes(' ')) { + // whitespace separated list but value contains space + source = 'if(' + N + 'false){' + source + '}'; + break; + } else if (match[4]) { + match[4] = convertEscapes(match[4]).replace(REX.regExpChar, '\\$&'); + } + type = match[5] === 'i' || (HTML_DOCUMENT && HTML_TABLE[expr.toLowerCase()]) + ? 'i' + : ''; + source = + 'if(' + N + '(' + + (!match[2] + ? (NS ? 's.hasAttributeNS(e,"' + name + '")' : 'e.hasAttribute&&e.hasAttribute("' + name + '")') + : !match[4] && ATTR_STD_OPS[match[2]] && match[2] !== '~=' + ? 'e.getAttribute&&e.getAttribute("' + name + '")==""' + : '(/' + test.p1 + match[4] + test.p2 + '/' + type + ').test(e.getAttribute&&e.getAttribute("' + name + '"))==' + test.p3) + + ')){' + source + '}'; + break; + // *** General sibling combinator + // E ~ F (F relative sibling of E) + case '~': + match = selector.match(Patterns.relative); + source = 'n=e;while((e=e.previousElementSibling)){' + source + '}e=n;'; + break; + // *** Adjacent sibling combinator + // E + F (F adiacent sibling of E) + case '+': + match = selector.match(Patterns.adjacent); + source = 'n=e;if((e=e.previousElementSibling)){' + source + '}e=n;'; + break; + // *** Descendant combinator + // E F (E ancestor of F) + case '\x09': + case '\x20': + match = selector.match(Patterns.ancestor); + source = 'n=e;while((e=e.parentElement)){' + source + '}e=n;'; + break; + // *** Child combinator + // E > F (F children of E) + case '>': + match = selector.match(Patterns.children); + source = 'n=e;if((e=e.parentElement)){' + source + '}e=n;'; + break; + // *** user supplied combinators extensions + case (symbol in Combinators ? symbol : undefined): + // for other registered combinators extensions + match[match.length - 1] = '*'; + source = Combinators[symbol](match) + source; + break; + // *** tree-structural pseudo-classes + // :root, :empty, :first-child, :last-child, :only-child, :first-of-type, :last-of-type, :only-of-type + case ':': + if ((match = selector.match(Patterns.structural))) { + match[1] = match[1].toLowerCase(); + switch (match[1]) { + case 'root': + // there can only be one :root element, so exit the loop once found + source = 'if(' + N + '(e===s.doc.documentElement)){' + source + (mode ? 'break main;' : '') + '}'; + break; + case 'empty': + // matches elements that don't contain elements or text nodes + source = 'n=e.firstChild;while(n&&!(/1|3/).test(n.nodeType)){n=n.nextSibling}if(' + D + 'n){' + source + '}'; + break; + // *** child-indexed pseudo-classes + // :first-child, :last-child, :only-child + case 'only-child': + source = 'if(' + N + '(!e.nextElementSibling&&!e.previousElementSibling)){' + source + '}'; + break; + case 'last-child': + source = 'if(' + N + '(!e.nextElementSibling)){' + source + '}'; + break; + case 'first-child': + source = 'if(' + N + '(!e.previousElementSibling)){' + source + '}'; + break; + // *** typed child-indexed pseudo-classes + // :only-of-type, :last-of-type, :first-of-type + case 'only-of-type': + source = 'o=e.localName;' + + 'n=e;while((n=n.nextElementSibling)&&n.localName!=o);if(!n){' + + 'n=e;while((n=n.previousElementSibling)&&n.localName!=o);}if(' + D + 'n){' + source + '}'; + break; + case 'last-of-type': + source = 'n=e;o=e.localName;while((n=n.nextElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}'; + break; + case 'first-of-type': + source = 'n=e;o=e.localName;while((n=n.previousElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}'; + break; + default: + emit('\'' + selectorString + '\'' + qsInvalid); + } + // *** child-indexed & typed child-indexed pseudo-classes + // :nth-child, :nth-of-type, :nth-last-child, :nth-last-of-type + } else if ((match = selector.match(Patterns.treestruct))) { + match[1] = match[1].toLowerCase(); + switch (match[1]) { + case 'nth-child': + case 'nth-of-type': + case 'nth-last-child': + case 'nth-last-of-type': + expr = /-of-type/i.test(match[1]); + if (match[1] && match[2]) { + type = /last/i.test(match[1]); + if (match[2] === 'n') { + source = 'if(' + N + 'true){' + source + '}'; + break; + } else if (match[2] === '1') { + test = type ? 'next' : 'previous'; + source = expr + ? 'n=e;o=e.localName;' + + 'while((n=n.' + test + 'ElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}' + : 'if(' + N + '!e.' + test + 'ElementSibling){' + source + '}'; + break; + } else if (match[2] === 'even' || match[2] === '2n0' || match[2] === '2n+0' || match[2] === '2n') { + test = 'n%2==0'; + } else if (match[2] === 'odd' || match[2] === '2n1' || match[2] === '2n+1') { + test = 'n%2==1'; + } else { + f = /n/i.test(match[2]); + n = match[2].split('n'); + a = parseInt(n[0], 10) || 0; + b = parseInt(n[1], 10) || 0; + if (n[0] === '-') { + a = -1; + } + if (n[0] === '+') { + a = +1; + } + test = (b ? '(n' + (b > 0 ? '-' : '+') + Math.abs(b) + ')' : 'n') + '%' + a + '==0'; + test = a >= +1 + ? (f + ? 'n>' + (b - 1) + (Math.abs(a) !== 1 + ? '&&' + test + : '') + : 'n==' + a) + : a <= -1 + ? (f + ? 'n<' + (b + 1) + (Math.abs(a) !== 1 + ? '&&' + test + : '') + : 'n==' + a) + : a === 0 + ? (n[0] + ? 'n==' + b + : 'n>' + (b - 1)) + : 'false'; + } + expr = expr ? 'OfType' : 'Element'; + type = type ? 'true' : 'false'; + source = 'n=s.nth' + expr + '(e,' + type + ');if(' + N + '(' + test + ')){' + source + '}'; + } else { + emit('\'' + selectorString + '\'' + qsInvalid); + } + break; + default: + emit('\'' + selectorString + '\'' + qsInvalid); + } + // *** logical combination pseudo-classes + // :is( s1, [ s2, ... ]), :not( s1, [ s2, ... ]) + } else if ((match = selector.match(Patterns.logicalsel))) { + match[1] = match[1].toLowerCase(); + expr = match[2].replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, ''); + switch (match[1]) { + // FIXME: + case 'is': + case 'where': + case 'matches': + source = 'if(s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source + '}'; + break; + // FIXME: + case 'not': + source = 'if(!s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source + '}'; + break; + // FIXME: + case 'has': + // clear cache + matchResolvers = {}; + source = 'if(e.querySelector(":scope ' + expr.replace(/\x22/g, '\\"') + '")){' + source + '}'; + break; + default: + emit('\'' + selectorString + '\'' + qsInvalid); + } + // *** location pseudo-classes + // :any-link, :link, :visited, :target + } else if ((match = selector.match(Patterns.locationpc))) { + match[1] = match[1].toLowerCase(); + switch (match[1]) { + case 'any-link': + source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href")||e.visited)){' + source + '}'; + break; + case 'link': + source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href"))){' + source + '}'; + break; + // FIXME: + case 'visited': + source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href")&&e.visited)){' + source + '}'; + break; + case 'target': + source = 'if(s.isTarget(e)){' + source + '}'; + break; + default: + emit('\'' + selectorString + '\'' + qsInvalid); + } + // *** user interface and form pseudo-classes + // :enabled, :disabled, :read-only, :read-write, :placeholder-shown, :default + } else if ((match = selector.match(Patterns.inputstate))) { + match[1] = match[1].toLowerCase(); + switch (match[1]) { + // FIXME: lacks custom element support + case 'enabled': + source = 'if((("form" in e||/^optgroup$/i.test(e.localName))&&"disabled" in e &&e.disabled===false' + + ')){' + source + '}'; + break; + // FIXME: lacks custom element support + case 'disabled': + // https://html.spec.whatwg.org/#enabling-and-disabling-form-controls:-the-disabled-attribute + source = 'if((("form" in e||/^optgroup$/i.test(e.localName))&&"disabled" in e)){' + + // F is true if any of the fieldset elements in the ancestry chain has the disabled attribute specified + // L is true if the first legend element of the fieldset contains the element + 'var x=0,N=[],F=false,L=false;' + + 'if(!(/^(optgroup|option)$/i.test(e.localName))){' + + 'n=e.parentElement;' + + 'while(n){' + + 'if(n.localName==="fieldset"){' + + 'N[x++]=n;' + + 'if(n.disabled===true){' + + 'F=true;' + + 'break;' + + '}' + + '}' + + 'n=n.parentElement;' + + '}' + + 'for(var x=0;x + // assert: e.type is in double-colon format, like ::after + } else if ((match = selector.match(Patterns.pseudoDbl))) { + source = 'if(e.element&&e.type.toLowerCase()=="' + + match[0].toLowerCase() + '"){e=e.element;' + source + '}'; + // placeholder for parsed only no-op selectors + } else if ((match = selector.match(Patterns.pseudoNop))) { + source = 'if(' + N + 'false' + '){' + source + '}'; + } else { + // reset + expr = false; + status = false; + // process registered selector extensions + for (expr in Selectors) { + if ((match = selector.match(Selectors[expr].Expression))) { + result = Selectors[expr].Callback(match, source, mode, callback); + if ('match' in result) { + match = result.match; + } + vars = result.modvar; + if (mode) { + // add extra select() vars + vars && !S_VARS.includes(vars) && S_VARS.push(vars); + } else { + // add extra match() vars + vars && M_VARS.includes(vars) && M_VARS.push(vars); + } + // extension source code + source = result.source; + // extension status code + status = result.status; + // break on status error + if (status) { break; } + } + } + if (!status) { + emit('unknown pseudo-class selector \'' + selector + '\''); + return ''; + } + if (!expr) { + emit('unknown token in selector \'' + selector + '\''); + return ''; + } + } + break; + default: + selectorRecursion = false; + emit('\'' + selectorString + '\'' + qsInvalid); + } + // end of switch symbol + if (!selectorRecursion) { + break; + } + if (!match) { + emit('\'' + selectorString + '\'' + qsInvalid); + return ''; + } + + // pop last component + selector = match.pop(); + } + // end of while selector + + return source; + }; + + // compile groups or single selector strings into + // executable functions for matching or selecting + const compile = function (selector, mode, callback) { + let head = ''; let loop = ''; let macro = ''; let source = ''; let vars = ''; + + // 'mode' can be boolean or null + // true = select / false = match + // null to use collection.item() + switch (mode) { + case true: + if (selectLambdas[selector]) { + return selectLambdas[selector]; + } + macro = S_BODY + (callback ? S_TEST : '') + S_TAIL; + head = S_HEAD; + loop = S_LOOP; + break; + case false: + if (matchLambdas[selector]) { + return matchLambdas[selector]; + } + macro = M_BODY + (callback ? M_TEST : '') + M_TAIL; + head = M_HEAD; + loop = M_LOOP; + break; + case null: + if (selectLambdas[selector]) { + return selectLambdas[selector]; + } + macro = N_BODY + (callback ? N_TEST : '') + S_TAIL; + head = S_HEAD; + loop = N_LOOP; + break; + default: + } + + source = compileSelector(selector, macro, mode, callback); + + loop += (mode || mode === null) ? '{' + source + '}' : source; + + if ((mode || mode === null) && selector.includes(':nth')) { + loop += reNthElem.test(selector) ? 's.nthElement(null, 2);' : ''; + loop += reNthType.test(selector) ? 's.nthOfType(null, 2);' : ''; + } + + if (S_VARS[0] || M_VARS[0]) { + vars = ',' + (S_VARS.join(',') || M_VARS.join(',')); + S_VARS = []; + M_VARS = []; + } + + const factory = Function('s', F_INIT + '{' + head + vars + ';' + loop + 'return r;}')(Snapshot); + + return mode || mode === null ? (selectLambdas[selector] = factory) : (matchLambdas[selector] = factory); + }; + + // optimize selectors avoiding duplicated checks + const optimize = function (selector, token) { + const index = token.index; + const length = token[1].length + token[2].length; + return selector.slice(0, index) + + (' >+~'.indexOf(selector.charAt(index - 1)) > -1 + ? (':['.indexOf(selector.charAt(index + length + 1)) > -1 + ? '*' + : '') + : '') + selector.slice(index + length - (token[1] === '*' ? 1 : 0)); + }; + + // prepare factory resolvers and closure collections + const collect = function (selectors, context, callback) { + let i; + let l; + const seen = { }; + let token = ['', '*', '*']; + const optimized = selectors; + const factory = []; + const htmlset = []; + const nodeset = []; + let results = []; + let type; + + for (i = 0, l = selectors.length; l > i; ++i) { + if (!seen[selectors[i]] && (seen[selectors[i]] = true)) { + type = selectors[i].match(reOptimizer); + if (type && type[1] !== ':' && (token = type)) { + token[1] || (token[1] = '*'); + optimized[i] = optimize(optimized[i], token); + } else { + token = ['', '*', '*']; + } + } + + nodeset[i] = token[1] + token[2]; + htmlset[i] = compat[token[1]](context, token[2]); + factory[i] = compile(optimized[i], true, null); + + factory[i] + ? factory[i](htmlset[i](), callback, context, results) + : results.concat(htmlset[i]()); + } + + if (l > 1) { + results.sort(documentOrder); + hasDupes && (results = unique(results)); + } + + return { + callback, + context, + factory, + htmlset, + nodeset, + results + }; + }; + + // replace ':scope' pseudo-class with element references + const makeref = function (selectors, element) { + // DOCUMENT_NODE (9) + if (element.nodeType === 9) { + element = element.documentElement; + } + + return selectors.replace(/:scope/gi, + element.localName + + (element.id ? '#' + element.id : '') + + (element.className ? '.' + element.classList[0] : '')); + }; + + const matchAssert = function (f, element, callback) { + let r = false; + for (let i = 0, l = f.length; l > i; ++i) { + f[i](element, callback, null, false) && (r = true); + } + return r; + }; + + const matchCollect = function (selectors, callback) { + const f = []; + for (let i = 0, l = selectors.length; l > i; ++i) { + f[i] = compile(selectors[i], false, callback); + } + return { factory: f }; + }; + + // equivalent of w3c 'matches' method + const match = function _matches(selectors, element, callback) { + let expressions; + + if (element && !/:has\(/.test(selectors) && matchResolvers[selectors]) { + return matchAssert(matchResolvers[selectors].factory, element, callback); + } + + lastMatched = selectors; + + // arguments validation + if (arguments.length === 0) { + emit(qsNotArgs, 'TypeError'); + return Config.VERBOSITY ? undefined : false; + } else if (arguments[0] === '') { + emit('\'\'' + qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + + // input NULL or UNDEFINED + if (typeof selectors !== 'string') { + selectors = '' + selectors; + } + + if ((/:scope/i).test(selectors)) { + selectors = makeref(selectors, element); + } + + // normalize input string + const parsed = selectors + .replace(/\0|\\$/g, '\ufffd') + .replace(REX.combineWSP, '\x20') + .replace(REX.pseudosWSP, '$1') + .replace(REX.tabCharWSP, '\t') + .replace(REX.commaGroup, ',') + .replace(REX.trimSpaces, ''); + + // parse, validate and split possible compound selectors + if ((expressions = parsed.match(reValidator)) && expressions.join('') === parsed) { + expressions = parsed.match(REX.splitGroup); + if (parsed[parsed.length - 1] === ',') { + emit(qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + } else { + emit('\'' + selectors + '\'' + qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + + matchResolvers[selectors] = matchCollect(expressions, callback); + + return matchAssert(matchResolvers[selectors].factory, element, callback); + }; + + // equivalent of w3c 'closest' method + const ancestor = function _closest(selectors, element, callback) { + if ((/:scope/i).test(selectors)) { + selectors = makeref(selectors, element); + } + + while (element) { + if (match(selectors, element, callback)) break; + element = element.parentElement; + } + return element; + }; + + // equivalent of w3c 'querySelectorAll' method + const select = function _querySelectorAll(selectors, context, callback) { + let expressions; let nodes = []; let resolver; + + context || (context = doc); + + if (selectors) { + if ((resolver = selectResolvers[selectors])) { + if (resolver.context === context && resolver.callback === callback) { + const f = resolver.factory; + const h = resolver.htmlset; + const n = resolver.nodeset; + if (n.length > 1) { + const l = n.length; + for (let i = 0, l = n.length, list; l > i; ++i) { + list = compat[n[i][0]](context, n[i].slice(1))(); + if (f[i] !== null) { + f[i](list, callback, context, nodes); + } else { + nodes = nodes.concat(list); + } + } + if (l > 1 && nodes.length > 1) { + nodes.sort(documentOrder); + hasDupes && (nodes = unique(nodes)); + } + } else { + if (f[0]) { + nodes = f[0](h[0](), callback, context, nodes); + } else { + nodes = h[0](); + } + } + return typeof callback === 'function' + ? concatCall(nodes, callback) + : nodes; + } + } + } + + lastSelected = selectors; + + // arguments validation + if (arguments.length === 0) { + emit(qsNotArgs, 'TypeError'); + return Config.VERBOSITY ? undefined : none; + } else if (arguments[0] === '') { + emit('\'\'' + qsInvalid); + return Config.VERBOSITY ? undefined : none; + } else if (lastContext !== context) { + lastContext = switchContext(context); + } + + // input NULL or UNDEFINED + if (typeof selectors !== 'string') { + selectors = '' + selectors; + } + + if ((/:scope/i).test(selectors)) { + selectors = makeref(selectors, context); + } + + // normalize input string + const parsed = selectors + .replace(/\0|\\$/g, '\ufffd') + .replace(REX.combineWSP, '\x20') + .replace(REX.pseudosWSP, '$1') + .replace(REX.tabCharWSP, '\t') + .replace(REX.commaGroup, ',') + .replace(REX.trimSpaces, ''); + + // parse, validate and split possible compound selectors + if ((expressions = parsed.match(reValidator)) && expressions.join('') === parsed) { + expressions = parsed.match(REX.splitGroup); + if (parsed[parsed.length - 1] === ',') { + emit(qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + } else { + emit('\'' + selectors + '\'' + qsInvalid); + return Config.VERBOSITY ? undefined : false; + } + + // save/reuse factory and closure collection + selectResolvers[selectors] = collect(expressions, context, callback); + + nodes = selectResolvers[selectors].results; + + return typeof callback === 'function' + ? concatCall(nodes, callback) + : nodes; + }; + + // equivalent of w3c 'querySelector' method + const first = function _querySelector(selectors, context, callback) { + if (arguments.length === 0) { + emit(qsNotArgs, 'TypeError'); + } + return select(selectors, context, typeof callback === 'function' + ? function firstMatch(element) { + callback(element); + return false; + } + : function firstMatch() { + return false; + } + )[0] || null; + }; + + // execute the engine initialization code + const initialize = function (d) { + setIdentifierSyntax(); + lastContext = switchContext(d, true); + Snapshot.doc = doc; + Snapshot.from = doc; + Snapshot.byTag = byTag; + Snapshot.first = first; + Snapshot.match = match; + Snapshot.ancestor = ancestor; + Snapshot.nthOfType = nthOfType; + Snapshot.nthElement = nthElement; + Snapshot.hasAttributeNS = hasAttributeNS; + Snapshot.isTarget = isTarget; + Snapshot.isIndeterminate = isIndeterminate; + Snapshot.isContentEditable = isContentEditable; + }; + + initialize(doc); + + // public exported methods/objects + const Dom = { + // exported engine methods + Version: version, + configure, + match, + closest: ancestor, + first, + select + }; + + return Dom; +}); diff --git a/vanilla/node_modules/@babel/helper-string-parser/LICENSE b/vanilla/node_modules/@babel/helper-string-parser/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/vanilla/node_modules/@babel/helper-string-parser/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vanilla/node_modules/@babel/helper-string-parser/README.md b/vanilla/node_modules/@babel/helper-string-parser/README.md new file mode 100644 index 0000000..771b470 --- /dev/null +++ b/vanilla/node_modules/@babel/helper-string-parser/README.md @@ -0,0 +1,19 @@ +# @babel/helper-string-parser + +> A utility package to parse strings + +See our website [@babel/helper-string-parser](https://babeljs.io/docs/babel-helper-string-parser) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-string-parser +``` + +or using yarn: + +```sh +yarn add @babel/helper-string-parser +``` diff --git a/vanilla/node_modules/@babel/helper-string-parser/lib/index.js b/vanilla/node_modules/@babel/helper-string-parser/lib/index.js new file mode 100644 index 0000000..2d94115 --- /dev/null +++ b/vanilla/node_modules/@babel/helper-string-parser/lib/index.js @@ -0,0 +1,295 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.readCodePoint = readCodePoint; +exports.readInt = readInt; +exports.readStringContents = readStringContents; +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; +const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) +}; +const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 +}; +function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let firstInvalidLoc = null; + let chunkStart = pos; + const { + length + } = input; + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + const ch = input.charCodeAt(pos); + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + if (ch === 92) { + out += input.slice(chunkStart, pos); + const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); + if (res.ch === null && !firstInvalidLoc) { + firstInvalidLoc = { + pos, + lineStart, + curLine + }; + } else { + out += res.ch; + } + ({ + pos, + lineStart, + curLine + } = res); + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + return { + pos, + str: out, + firstInvalidLoc, + lineStart, + curLine, + containsInvalid: !!firstInvalidLoc + }; +} +function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + return ch === (type === "double" ? 34 : 39); +} +function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + const ch = input.charCodeAt(pos++); + switch (ch) { + case 110: + return res("\n"); + case 114: + return res("\r"); + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + case 116: + return res("\t"); + case 98: + return res("\b"); + case 118: + return res("\u000b"); + case 102: + return res("\f"); + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + case 10: + lineStart = pos; + ++curLine; + case 8232: + case 8233: + return res(""); + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2)); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + return res(String.fromCharCode(octal)); + } + return res(String.fromCharCode(ch)); + } +} +function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + return { + code: n, + pos + }; +} +function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + if (!allowNumSeparator) { + if (bailOnError) return { + n: null, + pos + }; + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + if (bailOnError) return { + n: null, + pos + }; + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + ++pos; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + if (val <= 9 && bailOnError) { + return { + n: null, + pos + }; + } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + ++pos; + total = total * radix + val; + } + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + return { + n: total, + pos + }; +} +function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + return { + code, + pos + }; +} + +//# sourceMappingURL=index.js.map diff --git a/vanilla/node_modules/@babel/helper-string-parser/lib/index.js.map b/vanilla/node_modules/@babel/helper-string-parser/lib/index.js.map new file mode 100644 index 0000000..cd50797 --- /dev/null +++ b/vanilla/node_modules/@babel/helper-string-parser/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isDigit","code","forbiddenNumericSeparatorSiblings","decBinOct","Set","hex","isAllowedNumericSeparatorSibling","bin","ch","oct","dec","readStringContents","type","input","pos","lineStart","curLine","errors","initialPos","initialLineStart","initialCurLine","out","firstInvalidLoc","chunkStart","length","unterminated","slice","charCodeAt","isStringEnd","res","readEscapedChar","str","containsInvalid","inTemplate","throwOnInvalid","readHexChar","String","fromCharCode","readCodePoint","fromCodePoint","strictNumericEscape","startPos","match","exec","octalStr","octal","parseInt","next","len","forceLen","n","readInt","invalidEscapeSequence","radix","allowNumSeparator","bailOnError","start","forbiddenSiblings","isAllowedSibling","invalid","total","i","e","Infinity","val","prev","numericSeparatorInEscapeSequence","Number","isNaN","has","unexpectedNumericSeparator","_isDigit","invalidDigit","indexOf","invalidCodePoint"],"sources":["../src/index.ts"],"sourcesContent":["// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// The following character codes are forbidden from being\n// an immediate sibling of NumericLiteralSeparator _\nconst forbiddenNumericSeparatorSiblings = {\n decBinOct: new Set([\n charCodes.dot,\n charCodes.uppercaseB,\n charCodes.uppercaseE,\n charCodes.uppercaseO,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseB,\n charCodes.lowercaseE,\n charCodes.lowercaseO,\n ]),\n hex: new Set([\n charCodes.dot,\n charCodes.uppercaseX,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseX,\n ]),\n};\n\nconst isAllowedNumericSeparatorSibling = {\n // 0 - 1\n bin: (ch: number) => ch === charCodes.digit0 || ch === charCodes.digit1,\n\n // 0 - 7\n oct: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit7,\n\n // 0 - 9\n dec: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit9,\n\n // 0 - 9, A - F, a - f,\n hex: (ch: number) =>\n (ch >= charCodes.digit0 && ch <= charCodes.digit9) ||\n (ch >= charCodes.uppercaseA && ch <= charCodes.uppercaseF) ||\n (ch >= charCodes.lowercaseA && ch <= charCodes.lowercaseF),\n};\n\nexport type StringContentsErrorHandlers = EscapedCharErrorHandlers & {\n unterminated(\n initialPos: number,\n initialLineStart: number,\n initialCurLine: number,\n ): void;\n};\n\nexport function readStringContents(\n type: \"single\" | \"double\" | \"template\",\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n errors: StringContentsErrorHandlers,\n) {\n const initialPos = pos;\n const initialLineStart = lineStart;\n const initialCurLine = curLine;\n\n let out = \"\";\n let firstInvalidLoc = null;\n let chunkStart = pos;\n const { length } = input;\n for (;;) {\n if (pos >= length) {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n out += input.slice(chunkStart, pos);\n break;\n }\n const ch = input.charCodeAt(pos);\n if (isStringEnd(type, ch, input, pos)) {\n out += input.slice(chunkStart, pos);\n break;\n }\n if (ch === charCodes.backslash) {\n out += input.slice(chunkStart, pos);\n const res = readEscapedChar(\n input,\n pos,\n lineStart,\n curLine,\n type === \"template\",\n errors,\n );\n if (res.ch === null && !firstInvalidLoc) {\n firstInvalidLoc = { pos, lineStart, curLine };\n } else {\n out += res.ch;\n }\n ({ pos, lineStart, curLine } = res);\n chunkStart = pos;\n } else if (\n ch === charCodes.lineSeparator ||\n ch === charCodes.paragraphSeparator\n ) {\n ++pos;\n ++curLine;\n lineStart = pos;\n } else if (ch === charCodes.lineFeed || ch === charCodes.carriageReturn) {\n if (type === \"template\") {\n out += input.slice(chunkStart, pos) + \"\\n\";\n ++pos;\n if (\n ch === charCodes.carriageReturn &&\n input.charCodeAt(pos) === charCodes.lineFeed\n ) {\n ++pos;\n }\n ++curLine;\n chunkStart = lineStart = pos;\n } else {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n }\n } else {\n ++pos;\n }\n }\n return process.env.BABEL_8_BREAKING\n ? { pos, str: out, firstInvalidLoc, lineStart, curLine }\n : {\n pos,\n str: out,\n firstInvalidLoc,\n lineStart,\n curLine,\n containsInvalid: !!firstInvalidLoc,\n };\n}\n\nfunction isStringEnd(\n type: \"single\" | \"double\" | \"template\",\n ch: number,\n input: string,\n pos: number,\n) {\n if (type === \"template\") {\n return (\n ch === charCodes.graveAccent ||\n (ch === charCodes.dollarSign &&\n input.charCodeAt(pos + 1) === charCodes.leftCurlyBrace)\n );\n }\n return (\n ch === (type === \"double\" ? charCodes.quotationMark : charCodes.apostrophe)\n );\n}\n\ntype EscapedCharErrorHandlers = HexCharErrorHandlers &\n CodePointErrorHandlers & {\n strictNumericEscape(pos: number, lineStart: number, curLine: number): void;\n };\n\nfunction readEscapedChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n inTemplate: boolean,\n errors: EscapedCharErrorHandlers,\n) {\n const throwOnInvalid = !inTemplate;\n pos++; // skip '\\'\n\n const res = (ch: string | null) => ({ pos, ch, lineStart, curLine });\n\n const ch = input.charCodeAt(pos++);\n switch (ch) {\n case charCodes.lowercaseN:\n return res(\"\\n\");\n case charCodes.lowercaseR:\n return res(\"\\r\");\n case charCodes.lowercaseX: {\n let code;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 2,\n false,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCharCode(code));\n }\n case charCodes.lowercaseU: {\n let code;\n ({ code, pos } = readCodePoint(\n input,\n pos,\n lineStart,\n curLine,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCodePoint(code));\n }\n case charCodes.lowercaseT:\n return res(\"\\t\");\n case charCodes.lowercaseB:\n return res(\"\\b\");\n case charCodes.lowercaseV:\n return res(\"\\u000b\");\n case charCodes.lowercaseF:\n return res(\"\\f\");\n case charCodes.carriageReturn:\n if (input.charCodeAt(pos) === charCodes.lineFeed) {\n ++pos;\n }\n // fall through\n case charCodes.lineFeed:\n lineStart = pos;\n ++curLine;\n // fall through\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return res(\"\");\n case charCodes.digit8:\n case charCodes.digit9:\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(pos - 1, lineStart, curLine);\n }\n // fall through\n default:\n if (ch >= charCodes.digit0 && ch <= charCodes.digit7) {\n const startPos = pos - 1;\n const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));\n\n let octalStr = match[0];\n\n let octal = parseInt(octalStr, 8);\n if (octal > 255) {\n octalStr = octalStr.slice(0, -1);\n octal = parseInt(octalStr, 8);\n }\n pos += octalStr.length - 1;\n const next = input.charCodeAt(pos);\n if (\n octalStr !== \"0\" ||\n next === charCodes.digit8 ||\n next === charCodes.digit9\n ) {\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(startPos, lineStart, curLine);\n }\n }\n\n return res(String.fromCharCode(octal));\n }\n\n return res(String.fromCharCode(ch));\n }\n}\n\ntype HexCharErrorHandlers = IntErrorHandlers & {\n invalidEscapeSequence(pos: number, lineStart: number, curLine: number): void;\n};\n\n// Used to read character escape sequences ('\\x', '\\u').\nfunction readHexChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n len: number,\n forceLen: boolean,\n throwOnInvalid: boolean,\n errors: HexCharErrorHandlers,\n) {\n const initialPos = pos;\n let n;\n ({ n, pos } = readInt(\n input,\n pos,\n lineStart,\n curLine,\n 16,\n len,\n forceLen,\n false,\n errors,\n /* bailOnError */ !throwOnInvalid,\n ));\n if (n === null) {\n if (throwOnInvalid) {\n errors.invalidEscapeSequence(initialPos, lineStart, curLine);\n } else {\n pos = initialPos - 1;\n }\n }\n return { code: n, pos };\n}\n\nexport type IntErrorHandlers = {\n numericSeparatorInEscapeSequence(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n unexpectedNumericSeparator(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n // It can return \"true\" to indicate that the error was handled\n // and the int parsing should continue.\n invalidDigit(\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n ): boolean;\n};\n\nexport function readInt(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n len: number | undefined,\n forceLen: boolean,\n allowNumSeparator: boolean | \"bail\",\n errors: IntErrorHandlers,\n bailOnError: boolean,\n) {\n const start = pos;\n const forbiddenSiblings =\n radix === 16\n ? forbiddenNumericSeparatorSiblings.hex\n : forbiddenNumericSeparatorSiblings.decBinOct;\n const isAllowedSibling =\n radix === 16\n ? isAllowedNumericSeparatorSibling.hex\n : radix === 10\n ? isAllowedNumericSeparatorSibling.dec\n : radix === 8\n ? isAllowedNumericSeparatorSibling.oct\n : isAllowedNumericSeparatorSibling.bin;\n\n let invalid = false;\n let total = 0;\n\n for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {\n const code = input.charCodeAt(pos);\n let val;\n\n if (code === charCodes.underscore && allowNumSeparator !== \"bail\") {\n const prev = input.charCodeAt(pos - 1);\n const next = input.charCodeAt(pos + 1);\n\n if (!allowNumSeparator) {\n if (bailOnError) return { n: null, pos };\n errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);\n } else if (\n Number.isNaN(next) ||\n !isAllowedSibling(next) ||\n forbiddenSiblings.has(prev) ||\n forbiddenSiblings.has(next)\n ) {\n if (bailOnError) return { n: null, pos };\n errors.unexpectedNumericSeparator(pos, lineStart, curLine);\n }\n\n // Ignore this _ character\n ++pos;\n continue;\n }\n\n if (code >= charCodes.lowercaseA) {\n val = code - charCodes.lowercaseA + charCodes.lineFeed;\n } else if (code >= charCodes.uppercaseA) {\n val = code - charCodes.uppercaseA + charCodes.lineFeed;\n } else if (charCodes.isDigit(code)) {\n val = code - charCodes.digit0; // 0-9\n } else {\n val = Infinity;\n }\n if (val >= radix) {\n // If we found a digit which is too big, errors.invalidDigit can return true to avoid\n // breaking the loop (this is used for error recovery).\n if (val <= 9 && bailOnError) {\n return { n: null, pos };\n } else if (\n val <= 9 &&\n errors.invalidDigit(pos, lineStart, curLine, radix)\n ) {\n val = 0;\n } else if (forceLen) {\n val = 0;\n invalid = true;\n } else {\n break;\n }\n }\n ++pos;\n total = total * radix + val;\n }\n if (pos === start || (len != null && pos - start !== len) || invalid) {\n return { n: null, pos };\n }\n\n return { n: total, pos };\n}\n\nexport type CodePointErrorHandlers = HexCharErrorHandlers & {\n invalidCodePoint(pos: number, lineStart: number, curLine: number): void;\n};\n\nexport function readCodePoint(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n throwOnInvalid: boolean,\n errors: CodePointErrorHandlers,\n) {\n const ch = input.charCodeAt(pos);\n let code;\n\n if (ch === charCodes.leftCurlyBrace) {\n ++pos;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n input.indexOf(\"}\", pos) - pos,\n true,\n throwOnInvalid,\n errors,\n ));\n ++pos;\n if (code !== null && code > 0x10ffff) {\n if (throwOnInvalid) {\n errors.invalidCodePoint(pos, lineStart, curLine);\n } else {\n return { code: null, pos };\n }\n }\n } else {\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 4,\n false,\n throwOnInvalid,\n errors,\n ));\n }\n return { code, pos };\n}\n"],"mappings":";;;;;;;;eAAA,SAASA,OAAOA,CAACC,IAAI,EAAE;EACrB,OAAOA,IAAI,MAAU,IAAIA,IAAI,MAAU;AACzC,CAAC;AAID,MAAMC,iCAAiC,GAAG;EACxCC,SAAS,EAAE,IAAIC,GAAG,CAAS,kCAS1B,CAAC;EACFC,GAAG,EAAE,IAAID,GAAG,CAAS,iBAKpB;AACH,CAAC;AAED,MAAME,gCAAgC,GAAG;EAEvCC,GAAG,EAAGC,EAAU,IAAKA,EAAE,OAAqB,IAAIA,EAAE,OAAqB;EAGvEC,GAAG,EAAGD,EAAU,IAAKA,EAAE,MAAoB,IAAIA,EAAE,MAAoB;EAGrEE,GAAG,EAAGF,EAAU,IAAKA,EAAE,MAAoB,IAAIA,EAAE,MAAoB;EAGrEH,GAAG,EAAGG,EAAU,IACbA,EAAE,MAAoB,IAAIA,EAAE,MAAoB,IAChDA,EAAE,MAAwB,IAAIA,EAAE,MAAyB,IACzDA,EAAE,MAAwB,IAAIA,EAAE;AACrC,CAAC;AAUM,SAASG,kBAAkBA,CAChCC,IAAsC,EACtCC,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfC,MAAmC,EACnC;EACA,MAAMC,UAAU,GAAGJ,GAAG;EACtB,MAAMK,gBAAgB,GAAGJ,SAAS;EAClC,MAAMK,cAAc,GAAGJ,OAAO;EAE9B,IAAIK,GAAG,GAAG,EAAE;EACZ,IAAIC,eAAe,GAAG,IAAI;EAC1B,IAAIC,UAAU,GAAGT,GAAG;EACpB,MAAM;IAAEU;EAAO,CAAC,GAAGX,KAAK;EACxB,SAAS;IACP,IAAIC,GAAG,IAAIU,MAAM,EAAE;MACjBP,MAAM,CAACQ,YAAY,CAACP,UAAU,EAAEC,gBAAgB,EAAEC,cAAc,CAAC;MACjEC,GAAG,IAAIR,KAAK,CAACa,KAAK,CAACH,UAAU,EAAET,GAAG,CAAC;MACnC;IACF;IACA,MAAMN,EAAE,GAAGK,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC;IAChC,IAAIc,WAAW,CAAChB,IAAI,EAAEJ,EAAE,EAAEK,KAAK,EAAEC,GAAG,CAAC,EAAE;MACrCO,GAAG,IAAIR,KAAK,CAACa,KAAK,CAACH,UAAU,EAAET,GAAG,CAAC;MACnC;IACF;IACA,IAAIN,EAAE,OAAwB,EAAE;MAC9Ba,GAAG,IAAIR,KAAK,CAACa,KAAK,CAACH,UAAU,EAAET,GAAG,CAAC;MACnC,MAAMe,GAAG,GAAGC,eAAe,CACzBjB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACPJ,IAAI,KAAK,UAAU,EACnBK,MACF,CAAC;MACD,IAAIY,GAAG,CAACrB,EAAE,KAAK,IAAI,IAAI,CAACc,eAAe,EAAE;QACvCA,eAAe,GAAG;UAAER,GAAG;UAAEC,SAAS;UAAEC;QAAQ,CAAC;MAC/C,CAAC,MAAM;QACLK,GAAG,IAAIQ,GAAG,CAACrB,EAAE;MACf;MACA,CAAC;QAAEM,GAAG;QAAEC,SAAS;QAAEC;MAAQ,CAAC,GAAGa,GAAG;MAClCN,UAAU,GAAGT,GAAG;IAClB,CAAC,MAAM,IACLN,EAAE,SAA4B,IAC9BA,EAAE,SAAiC,EACnC;MACA,EAAEM,GAAG;MACL,EAAEE,OAAO;MACTD,SAAS,GAAGD,GAAG;IACjB,CAAC,MAAM,IAAIN,EAAE,OAAuB,IAAIA,EAAE,OAA6B,EAAE;MACvE,IAAII,IAAI,KAAK,UAAU,EAAE;QACvBS,GAAG,IAAIR,KAAK,CAACa,KAAK,CAACH,UAAU,EAAET,GAAG,CAAC,GAAG,IAAI;QAC1C,EAAEA,GAAG;QACL,IACEN,EAAE,OAA6B,IAC/BK,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC,OAAuB,EAC5C;UACA,EAAEA,GAAG;QACP;QACA,EAAEE,OAAO;QACTO,UAAU,GAAGR,SAAS,GAAGD,GAAG;MAC9B,CAAC,MAAM;QACLG,MAAM,CAACQ,YAAY,CAACP,UAAU,EAAEC,gBAAgB,EAAEC,cAAc,CAAC;MACnE;IACF,CAAC,MAAM;MACL,EAAEN,GAAG;IACP;EACF;EACA,OAEI;IACEA,GAAG;IACHiB,GAAG,EAAEV,GAAG;IACRC,eAAe;IACfP,SAAS;IACTC,OAAO;IACPgB,eAAe,EAAE,CAAC,CAACV;EACrB,CAAC;AACP;AAEA,SAASM,WAAWA,CAClBhB,IAAsC,EACtCJ,EAAU,EACVK,KAAa,EACbC,GAAW,EACX;EACA,IAAIF,IAAI,KAAK,UAAU,EAAE;IACvB,OACEJ,EAAE,OAA0B,IAC3BA,EAAE,OAAyB,IAC1BK,KAAK,CAACc,UAAU,CAACb,GAAG,GAAG,CAAC,CAAC,QAA8B;EAE7D;EACA,OACEN,EAAE,MAAMI,IAAI,KAAK,QAAQ,UAAiD,CAAC;AAE/E;AAOA,SAASkB,eAAeA,CACtBjB,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfiB,UAAmB,EACnBhB,MAAgC,EAChC;EACA,MAAMiB,cAAc,GAAG,CAACD,UAAU;EAClCnB,GAAG,EAAE;EAEL,MAAMe,GAAG,GAAIrB,EAAiB,KAAM;IAAEM,GAAG;IAAEN,EAAE;IAAEO,SAAS;IAAEC;EAAQ,CAAC,CAAC;EAEpE,MAAMR,EAAE,GAAGK,KAAK,CAACc,UAAU,CAACb,GAAG,EAAE,CAAC;EAClC,QAAQN,EAAE;IACR;MACE,OAAOqB,GAAG,CAAC,IAAI,CAAC;IAClB;MACE,OAAOA,GAAG,CAAC,IAAI,CAAC;IAClB;MAA2B;QACzB,IAAI5B,IAAI;QACR,CAAC;UAAEA,IAAI;UAAEa;QAAI,CAAC,GAAGqB,WAAW,CAC1BtB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACP,CAAC,EACD,KAAK,EACLkB,cAAc,EACdjB,MACF,CAAC;QACD,OAAOY,GAAG,CAAC5B,IAAI,KAAK,IAAI,GAAG,IAAI,GAAGmC,MAAM,CAACC,YAAY,CAACpC,IAAI,CAAC,CAAC;MAC9D;IACA;MAA2B;QACzB,IAAIA,IAAI;QACR,CAAC;UAAEA,IAAI;UAAEa;QAAI,CAAC,GAAGwB,aAAa,CAC5BzB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACPkB,cAAc,EACdjB,MACF,CAAC;QACD,OAAOY,GAAG,CAAC5B,IAAI,KAAK,IAAI,GAAG,IAAI,GAAGmC,MAAM,CAACG,aAAa,CAACtC,IAAI,CAAC,CAAC;MAC/D;IACA;MACE,OAAO4B,GAAG,CAAC,IAAI,CAAC;IAClB;MACE,OAAOA,GAAG,CAAC,IAAI,CAAC;IAClB;MACE,OAAOA,GAAG,CAAC,QAAQ,CAAC;IACtB;MACE,OAAOA,GAAG,CAAC,IAAI,CAAC;IAClB;MACE,IAAIhB,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC,OAAuB,EAAE;QAChD,EAAEA,GAAG;MACP;IAEF;MACEC,SAAS,GAAGD,GAAG;MACf,EAAEE,OAAO;IAEX;IACA;MACE,OAAOa,GAAG,CAAC,EAAE,CAAC;IAChB;IACA;MACE,IAAII,UAAU,EAAE;QACd,OAAOJ,GAAG,CAAC,IAAI,CAAC;MAClB,CAAC,MAAM;QACLZ,MAAM,CAACuB,mBAAmB,CAAC1B,GAAG,GAAG,CAAC,EAAEC,SAAS,EAAEC,OAAO,CAAC;MACzD;IAEF;MACE,IAAIR,EAAE,MAAoB,IAAIA,EAAE,MAAoB,EAAE;QACpD,MAAMiC,QAAQ,GAAG3B,GAAG,GAAG,CAAC;QACxB,MAAM4B,KAAK,GAAG,SAAS,CAACC,IAAI,CAAC9B,KAAK,CAACa,KAAK,CAACe,QAAQ,EAAE3B,GAAG,GAAG,CAAC,CAAC,CAAC;QAE5D,IAAI8B,QAAQ,GAAGF,KAAK,CAAC,CAAC,CAAC;QAEvB,IAAIG,KAAK,GAAGC,QAAQ,CAACF,QAAQ,EAAE,CAAC,CAAC;QACjC,IAAIC,KAAK,GAAG,GAAG,EAAE;UACfD,QAAQ,GAAGA,QAAQ,CAAClB,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;UAChCmB,KAAK,GAAGC,QAAQ,CAACF,QAAQ,EAAE,CAAC,CAAC;QAC/B;QACA9B,GAAG,IAAI8B,QAAQ,CAACpB,MAAM,GAAG,CAAC;QAC1B,MAAMuB,IAAI,GAAGlC,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC;QAClC,IACE8B,QAAQ,KAAK,GAAG,IAChBG,IAAI,OAAqB,IACzBA,IAAI,OAAqB,EACzB;UACA,IAAId,UAAU,EAAE;YACd,OAAOJ,GAAG,CAAC,IAAI,CAAC;UAClB,CAAC,MAAM;YACLZ,MAAM,CAACuB,mBAAmB,CAACC,QAAQ,EAAE1B,SAAS,EAAEC,OAAO,CAAC;UAC1D;QACF;QAEA,OAAOa,GAAG,CAACO,MAAM,CAACC,YAAY,CAACQ,KAAK,CAAC,CAAC;MACxC;MAEA,OAAOhB,GAAG,CAACO,MAAM,CAACC,YAAY,CAAC7B,EAAE,CAAC,CAAC;EACvC;AACF;AAOA,SAAS2B,WAAWA,CAClBtB,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfgC,GAAW,EACXC,QAAiB,EACjBf,cAAuB,EACvBjB,MAA4B,EAC5B;EACA,MAAMC,UAAU,GAAGJ,GAAG;EACtB,IAAIoC,CAAC;EACL,CAAC;IAAEA,CAAC;IAAEpC;EAAI,CAAC,GAAGqC,OAAO,CACnBtC,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACP,EAAE,EACFgC,GAAG,EACHC,QAAQ,EACR,KAAK,EACLhC,MAAM,EACY,CAACiB,cACrB,CAAC;EACD,IAAIgB,CAAC,KAAK,IAAI,EAAE;IACd,IAAIhB,cAAc,EAAE;MAClBjB,MAAM,CAACmC,qBAAqB,CAAClC,UAAU,EAAEH,SAAS,EAAEC,OAAO,CAAC;IAC9D,CAAC,MAAM;MACLF,GAAG,GAAGI,UAAU,GAAG,CAAC;IACtB;EACF;EACA,OAAO;IAAEjB,IAAI,EAAEiD,CAAC;IAAEpC;EAAI,CAAC;AACzB;AAuBO,SAASqC,OAAOA,CACrBtC,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfqC,KAAa,EACbL,GAAuB,EACvBC,QAAiB,EACjBK,iBAAmC,EACnCrC,MAAwB,EACxBsC,WAAoB,EACpB;EACA,MAAMC,KAAK,GAAG1C,GAAG;EACjB,MAAM2C,iBAAiB,GACrBJ,KAAK,KAAK,EAAE,GACRnD,iCAAiC,CAACG,GAAG,GACrCH,iCAAiC,CAACC,SAAS;EACjD,MAAMuD,gBAAgB,GACpBL,KAAK,KAAK,EAAE,GACR/C,gCAAgC,CAACD,GAAG,GACpCgD,KAAK,KAAK,EAAE,GACV/C,gCAAgC,CAACI,GAAG,GACpC2C,KAAK,KAAK,CAAC,GACT/C,gCAAgC,CAACG,GAAG,GACpCH,gCAAgC,CAACC,GAAG;EAE9C,IAAIoD,OAAO,GAAG,KAAK;EACnB,IAAIC,KAAK,GAAG,CAAC;EAEb,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEC,CAAC,GAAGd,GAAG,IAAI,IAAI,GAAGe,QAAQ,GAAGf,GAAG,EAAEa,CAAC,GAAGC,CAAC,EAAE,EAAED,CAAC,EAAE;IAC5D,MAAM5D,IAAI,GAAGY,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC;IAClC,IAAIkD,GAAG;IAEP,IAAI/D,IAAI,OAAyB,IAAIqD,iBAAiB,KAAK,MAAM,EAAE;MACjE,MAAMW,IAAI,GAAGpD,KAAK,CAACc,UAAU,CAACb,GAAG,GAAG,CAAC,CAAC;MACtC,MAAMiC,IAAI,GAAGlC,KAAK,CAACc,UAAU,CAACb,GAAG,GAAG,CAAC,CAAC;MAEtC,IAAI,CAACwC,iBAAiB,EAAE;QACtB,IAAIC,WAAW,EAAE,OAAO;UAAEL,CAAC,EAAE,IAAI;UAAEpC;QAAI,CAAC;QACxCG,MAAM,CAACiD,gCAAgC,CAACpD,GAAG,EAAEC,SAAS,EAAEC,OAAO,CAAC;MAClE,CAAC,MAAM,IACLmD,MAAM,CAACC,KAAK,CAACrB,IAAI,CAAC,IAClB,CAACW,gBAAgB,CAACX,IAAI,CAAC,IACvBU,iBAAiB,CAACY,GAAG,CAACJ,IAAI,CAAC,IAC3BR,iBAAiB,CAACY,GAAG,CAACtB,IAAI,CAAC,EAC3B;QACA,IAAIQ,WAAW,EAAE,OAAO;UAAEL,CAAC,EAAE,IAAI;UAAEpC;QAAI,CAAC;QACxCG,MAAM,CAACqD,0BAA0B,CAACxD,GAAG,EAAEC,SAAS,EAAEC,OAAO,CAAC;MAC5D;MAGA,EAAEF,GAAG;MACL;IACF;IAEA,IAAIb,IAAI,MAAwB,EAAE;MAChC+D,GAAG,GAAG/D,IAAI,KAAuB,KAAqB;IACxD,CAAC,MAAM,IAAIA,IAAI,MAAwB,EAAE;MACvC+D,GAAG,GAAG/D,IAAI,KAAuB,KAAqB;IACxD,CAAC,MAAM,IAAIsE,QAAA,CAAkBtE,IAAI,CAAC,EAAE;MAClC+D,GAAG,GAAG/D,IAAI,KAAmB;IAC/B,CAAC,MAAM;MACL+D,GAAG,GAAGD,QAAQ;IAChB;IACA,IAAIC,GAAG,IAAIX,KAAK,EAAE;MAGhB,IAAIW,GAAG,IAAI,CAAC,IAAIT,WAAW,EAAE;QAC3B,OAAO;UAAEL,CAAC,EAAE,IAAI;UAAEpC;QAAI,CAAC;MACzB,CAAC,MAAM,IACLkD,GAAG,IAAI,CAAC,IACR/C,MAAM,CAACuD,YAAY,CAAC1D,GAAG,EAAEC,SAAS,EAAEC,OAAO,EAAEqC,KAAK,CAAC,EACnD;QACAW,GAAG,GAAG,CAAC;MACT,CAAC,MAAM,IAAIf,QAAQ,EAAE;QACnBe,GAAG,GAAG,CAAC;QACPL,OAAO,GAAG,IAAI;MAChB,CAAC,MAAM;QACL;MACF;IACF;IACA,EAAE7C,GAAG;IACL8C,KAAK,GAAGA,KAAK,GAAGP,KAAK,GAAGW,GAAG;EAC7B;EACA,IAAIlD,GAAG,KAAK0C,KAAK,IAAKR,GAAG,IAAI,IAAI,IAAIlC,GAAG,GAAG0C,KAAK,KAAKR,GAAI,IAAIW,OAAO,EAAE;IACpE,OAAO;MAAET,CAAC,EAAE,IAAI;MAAEpC;IAAI,CAAC;EACzB;EAEA,OAAO;IAAEoC,CAAC,EAAEU,KAAK;IAAE9C;EAAI,CAAC;AAC1B;AAMO,SAASwB,aAAaA,CAC3BzB,KAAa,EACbC,GAAW,EACXC,SAAiB,EACjBC,OAAe,EACfkB,cAAuB,EACvBjB,MAA8B,EAC9B;EACA,MAAMT,EAAE,GAAGK,KAAK,CAACc,UAAU,CAACb,GAAG,CAAC;EAChC,IAAIb,IAAI;EAER,IAAIO,EAAE,QAA6B,EAAE;IACnC,EAAEM,GAAG;IACL,CAAC;MAAEb,IAAI;MAAEa;IAAI,CAAC,GAAGqB,WAAW,CAC1BtB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACPH,KAAK,CAAC4D,OAAO,CAAC,GAAG,EAAE3D,GAAG,CAAC,GAAGA,GAAG,EAC7B,IAAI,EACJoB,cAAc,EACdjB,MACF,CAAC;IACD,EAAEH,GAAG;IACL,IAAIb,IAAI,KAAK,IAAI,IAAIA,IAAI,GAAG,QAAQ,EAAE;MACpC,IAAIiC,cAAc,EAAE;QAClBjB,MAAM,CAACyD,gBAAgB,CAAC5D,GAAG,EAAEC,SAAS,EAAEC,OAAO,CAAC;MAClD,CAAC,MAAM;QACL,OAAO;UAAEf,IAAI,EAAE,IAAI;UAAEa;QAAI,CAAC;MAC5B;IACF;EACF,CAAC,MAAM;IACL,CAAC;MAAEb,IAAI;MAAEa;IAAI,CAAC,GAAGqB,WAAW,CAC1BtB,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,OAAO,EACP,CAAC,EACD,KAAK,EACLkB,cAAc,EACdjB,MACF,CAAC;EACH;EACA,OAAO;IAAEhB,IAAI;IAAEa;EAAI,CAAC;AACtB","ignoreList":[]} \ No newline at end of file diff --git a/vanilla/node_modules/@babel/helper-string-parser/package.json b/vanilla/node_modules/@babel/helper-string-parser/package.json new file mode 100644 index 0000000..c4c86e4 --- /dev/null +++ b/vanilla/node_modules/@babel/helper-string-parser/package.json @@ -0,0 +1,31 @@ +{ + "name": "@babel/helper-string-parser", + "version": "7.27.1", + "description": "A utility package to parse strings", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-helper-string-parser" + }, + "homepage": "https://babel.dev/docs/en/next/babel-helper-string-parser", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.js", + "devDependencies": { + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "author": "The Babel Team (https://babel.dev/team)", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/vanilla/node_modules/@babel/helper-validator-identifier/LICENSE b/vanilla/node_modules/@babel/helper-validator-identifier/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/vanilla/node_modules/@babel/helper-validator-identifier/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vanilla/node_modules/@babel/helper-validator-identifier/README.md b/vanilla/node_modules/@babel/helper-validator-identifier/README.md new file mode 100644 index 0000000..05c19e6 --- /dev/null +++ b/vanilla/node_modules/@babel/helper-validator-identifier/README.md @@ -0,0 +1,19 @@ +# @babel/helper-validator-identifier + +> Validate identifier/keywords name + +See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/babel-helper-validator-identifier) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/helper-validator-identifier +``` + +or using yarn: + +```sh +yarn add @babel/helper-validator-identifier +``` diff --git a/vanilla/node_modules/@babel/helper-validator-identifier/lib/identifier.js b/vanilla/node_modules/@babel/helper-validator-identifier/lib/identifier.js new file mode 100644 index 0000000..b12e6e4 --- /dev/null +++ b/vanilla/node_modules/@babel/helper-validator-identifier/lib/identifier.js @@ -0,0 +1,70 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIdentifierChar = isIdentifierChar; +exports.isIdentifierName = isIdentifierName; +exports.isIdentifierStart = isIdentifierStart; +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088f\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5c\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdc-\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7dc\ua7f1-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1add\u1ae0-\u1aeb\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; +function isInAstralSet(code, set) { + let pos = 0x10000; + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + return false; +} +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes); +} +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} +function isIdentifierName(name) { + let isFirst = true; + for (let i = 0; i < name.length; i++) { + let cp = name.charCodeAt(i); + if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) { + const trail = name.charCodeAt(++i); + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + if (isFirst) { + isFirst = false; + if (!isIdentifierStart(cp)) { + return false; + } + } else if (!isIdentifierChar(cp)) { + return false; + } + } + return !isFirst; +} + +//# sourceMappingURL=identifier.js.map diff --git a/vanilla/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map b/vanilla/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map new file mode 100644 index 0000000..71d32ff --- /dev/null +++ b/vanilla/node_modules/@babel/helper-validator-identifier/lib/identifier.js.map @@ -0,0 +1 @@ +{"version":3,"names":["nonASCIIidentifierStartChars","nonASCIIidentifierChars","nonASCIIidentifierStart","RegExp","nonASCIIidentifier","astralIdentifierStartCodes","astralIdentifierCodes","isInAstralSet","code","set","pos","i","length","isIdentifierStart","test","String","fromCharCode","isIdentifierChar","isIdentifierName","name","isFirst","cp","charCodeAt","trail"],"sources":["../src/identifier.ts"],"sourcesContent":["// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.cjs`.\n\n/* prettier-ignore */\nlet nonASCIIidentifierStartChars = \"\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u0870-\\u0887\\u0889-\\u088f\\u08a0-\\u08c9\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c5c\\u0c5d\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cdc-\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d04-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e86-\\u0e8a\\u0e8c-\\u0ea3\\u0ea5\\u0ea7-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u1711\\u171f-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4c\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c8a\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7dc\\ua7f1-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\";\n/* prettier-ignore */\nlet nonASCIIidentifierChars = \"\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u0897-\\u089f\\u08ca-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3c\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0cf3\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ece\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u180f-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf-\\u1add\\u1ae0-\\u1aeb\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1dff\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\u30fb\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\\uff65\";\n\nconst nonASCIIidentifierStart = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.cjs`.\n/* prettier-ignore */\nconst astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489];\n/* prettier-ignore */\nconst astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n let pos = 0x10000;\n for (let i = 0, length = set.length; i < length; i += 2) {\n pos += set[i];\n if (pos > code) return false;\n\n pos += set[i + 1];\n if (pos >= code) return true;\n }\n return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return (\n code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n );\n }\n return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n if (code < charCodes.digit0) return code === charCodes.dollarSign;\n if (code < charCodes.colon) return true;\n if (code < charCodes.uppercaseA) return false;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n }\n return (\n isInAstralSet(code, astralIdentifierStartCodes) ||\n isInAstralSet(code, astralIdentifierCodes)\n );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n let isFirst = true;\n for (let i = 0; i < name.length; i++) {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = name.charCodeAt(i);\n if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n const trail = name.charCodeAt(++i);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n if (isFirst) {\n isFirst = false;\n if (!isIdentifierStart(cp)) {\n return false;\n }\n } else if (!isIdentifierChar(cp)) {\n return false;\n }\n }\n return !isFirst;\n}\n"],"mappings":";;;;;;;;AAaA,IAAIA,4BAA4B,GAAG,spIAAspI;AAEzrI,IAAIC,uBAAuB,GAAG,4lFAA4lF;AAE1nF,MAAMC,uBAAuB,GAAG,IAAIC,MAAM,CACxC,GAAG,GAAGH,4BAA4B,GAAG,GACvC,CAAC;AACD,MAAMI,kBAAkB,GAAG,IAAID,MAAM,CACnC,GAAG,GAAGH,4BAA4B,GAAGC,uBAAuB,GAAG,GACjE,CAAC;AAEDD,4BAA4B,GAAGC,uBAAuB,GAAG,IAAI;AAQ7D,MAAMI,0BAA0B,GAAG,CAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,GAAG,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,IAAI,EAAC,EAAE,EAAC,EAAE,EAAC,IAAI,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,GAAG,EAAC,IAAI,EAAC,EAAE,EAAC,IAAI,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,IAAI,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,IAAI,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,IAAI,EAAC,KAAK,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,GAAG,EAAC,IAAI,EAAC,GAAG,EAAC,IAAI,EAAC,IAAI,EAAC,CAAC,EAAC,IAAI,CAAC;AAEjnD,MAAMC,qBAAqB,GAAG,CAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,KAAK,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,KAAK,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,IAAI,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,EAAE,EAAC,EAAE,EAAC,GAAG,EAAC,EAAE,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,GAAG,EAAC,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC,IAAI,EAAC,CAAC,EAAC,MAAM,EAAC,GAAG,CAAC;AAK52B,SAASC,aAAaA,CAACC,IAAY,EAAEC,GAAsB,EAAW;EACpE,IAAIC,GAAG,GAAG,OAAO;EACjB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEC,MAAM,GAAGH,GAAG,CAACG,MAAM,EAAED,CAAC,GAAGC,MAAM,EAAED,CAAC,IAAI,CAAC,EAAE;IACvDD,GAAG,IAAID,GAAG,CAACE,CAAC,CAAC;IACb,IAAID,GAAG,GAAGF,IAAI,EAAE,OAAO,KAAK;IAE5BE,GAAG,IAAID,GAAG,CAACE,CAAC,GAAG,CAAC,CAAC;IACjB,IAAID,GAAG,IAAIF,IAAI,EAAE,OAAO,IAAI;EAC9B;EACA,OAAO,KAAK;AACd;AAIO,SAASK,iBAAiBA,CAACL,IAAY,EAAW;EACvD,IAAIA,IAAI,KAAuB,EAAE,OAAOA,IAAI,OAAyB;EACrE,IAAIA,IAAI,MAAwB,EAAE,OAAO,IAAI;EAC7C,IAAIA,IAAI,KAAuB,EAAE,OAAOA,IAAI,OAAyB;EACrE,IAAIA,IAAI,OAAwB,EAAE,OAAO,IAAI;EAC7C,IAAIA,IAAI,IAAI,MAAM,EAAE;IAClB,OACEA,IAAI,IAAI,IAAI,IAAIN,uBAAuB,CAACY,IAAI,CAACC,MAAM,CAACC,YAAY,CAACR,IAAI,CAAC,CAAC;EAE3E;EACA,OAAOD,aAAa,CAACC,IAAI,EAAEH,0BAA0B,CAAC;AACxD;AAIO,SAASY,gBAAgBA,CAACT,IAAY,EAAW;EACtD,IAAIA,IAAI,KAAmB,EAAE,OAAOA,IAAI,OAAyB;EACjE,IAAIA,IAAI,KAAkB,EAAE,OAAO,IAAI;EACvC,IAAIA,IAAI,KAAuB,EAAE,OAAO,KAAK;EAC7C,IAAIA,IAAI,MAAwB,EAAE,OAAO,IAAI;EAC7C,IAAIA,IAAI,KAAuB,EAAE,OAAOA,IAAI,OAAyB;EACrE,IAAIA,IAAI,OAAwB,EAAE,OAAO,IAAI;EAC7C,IAAIA,IAAI,IAAI,MAAM,EAAE;IAClB,OAAOA,IAAI,IAAI,IAAI,IAAIJ,kBAAkB,CAACU,IAAI,CAACC,MAAM,CAACC,YAAY,CAACR,IAAI,CAAC,CAAC;EAC3E;EACA,OACED,aAAa,CAACC,IAAI,EAAEH,0BAA0B,CAAC,IAC/CE,aAAa,CAACC,IAAI,EAAEF,qBAAqB,CAAC;AAE9C;AAIO,SAASY,gBAAgBA,CAACC,IAAY,EAAW;EACtD,IAAIC,OAAO,GAAG,IAAI;EAClB,KAAK,IAAIT,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGQ,IAAI,CAACP,MAAM,EAAED,CAAC,EAAE,EAAE;IAKpC,IAAIU,EAAE,GAAGF,IAAI,CAACG,UAAU,CAACX,CAAC,CAAC;IAC3B,IAAI,CAACU,EAAE,GAAG,MAAM,MAAM,MAAM,IAAIV,CAAC,GAAG,CAAC,GAAGQ,IAAI,CAACP,MAAM,EAAE;MACnD,MAAMW,KAAK,GAAGJ,IAAI,CAACG,UAAU,CAAC,EAAEX,CAAC,CAAC;MAClC,IAAI,CAACY,KAAK,GAAG,MAAM,MAAM,MAAM,EAAE;QAC/BF,EAAE,GAAG,OAAO,IAAI,CAACA,EAAE,GAAG,KAAK,KAAK,EAAE,CAAC,IAAIE,KAAK,GAAG,KAAK,CAAC;MACvD;IACF;IACA,IAAIH,OAAO,EAAE;MACXA,OAAO,GAAG,KAAK;MACf,IAAI,CAACP,iBAAiB,CAACQ,EAAE,CAAC,EAAE;QAC1B,OAAO,KAAK;MACd;IACF,CAAC,MAAM,IAAI,CAACJ,gBAAgB,CAACI,EAAE,CAAC,EAAE;MAChC,OAAO,KAAK;IACd;EACF;EACA,OAAO,CAACD,OAAO;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/vanilla/node_modules/@babel/helper-validator-identifier/lib/index.js b/vanilla/node_modules/@babel/helper-validator-identifier/lib/index.js new file mode 100644 index 0000000..76b2282 --- /dev/null +++ b/vanilla/node_modules/@babel/helper-validator-identifier/lib/index.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return _identifier.isIdentifierChar; + } +}); +Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return _identifier.isIdentifierName; + } +}); +Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return _identifier.isIdentifierStart; + } +}); +Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return _keyword.isKeyword; + } +}); +Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return _keyword.isReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindOnlyReservedWord; + } +}); +Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictBindReservedWord; + } +}); +Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return _keyword.isStrictReservedWord; + } +}); +var _identifier = require("./identifier.js"); +var _keyword = require("./keyword.js"); + +//# sourceMappingURL=index.js.map diff --git a/vanilla/node_modules/@babel/helper-validator-identifier/lib/index.js.map b/vanilla/node_modules/@babel/helper-validator-identifier/lib/index.js.map new file mode 100644 index 0000000..d985f3b --- /dev/null +++ b/vanilla/node_modules/@babel/helper-validator-identifier/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_identifier","require","_keyword"],"sources":["../src/index.ts"],"sourcesContent":["export {\n isIdentifierName,\n isIdentifierChar,\n isIdentifierStart,\n} from \"./identifier.ts\";\nexport {\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"./keyword.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,WAAA,GAAAC,OAAA;AAKA,IAAAC,QAAA,GAAAD,OAAA","ignoreList":[]} \ No newline at end of file diff --git a/vanilla/node_modules/@babel/helper-validator-identifier/lib/keyword.js b/vanilla/node_modules/@babel/helper-validator-identifier/lib/keyword.js new file mode 100644 index 0000000..054cf84 --- /dev/null +++ b/vanilla/node_modules/@babel/helper-validator-identifier/lib/keyword.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isKeyword = isKeyword; +exports.isReservedWord = isReservedWord; +exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; +exports.isStrictBindReservedWord = isStrictBindReservedWord; +exports.isStrictReservedWord = isStrictReservedWord; +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +} +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} +function isKeyword(word) { + return keywords.has(word); +} + +//# sourceMappingURL=keyword.js.map diff --git a/vanilla/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map b/vanilla/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map new file mode 100644 index 0000000..3471f78 --- /dev/null +++ b/vanilla/node_modules/@babel/helper-validator-identifier/lib/keyword.js.map @@ -0,0 +1 @@ +{"version":3,"names":["reservedWords","keyword","strict","strictBind","keywords","Set","reservedWordsStrictSet","reservedWordsStrictBindSet","isReservedWord","word","inModule","isStrictReservedWord","has","isStrictBindOnlyReservedWord","isStrictBindReservedWord","isKeyword"],"sources":["../src/keyword.ts"],"sourcesContent":["const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n"],"mappings":";;;;;;;;;;AAAA,MAAMA,aAAa,GAAG;EACpBC,OAAO,EAAE,CACP,OAAO,EACP,MAAM,EACN,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,EACT,IAAI,EACJ,MAAM,EACN,SAAS,EACT,KAAK,EACL,UAAU,EACV,IAAI,EACJ,QAAQ,EACR,QAAQ,EACR,OAAO,EACP,KAAK,EACL,KAAK,EACL,OAAO,EACP,OAAO,EACP,MAAM,EACN,KAAK,EACL,MAAM,EACN,OAAO,EACP,OAAO,EACP,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,MAAM,EACN,OAAO,EACP,IAAI,EACJ,YAAY,EACZ,QAAQ,EACR,MAAM,EACN,QAAQ,CACT;EACDC,MAAM,EAAE,CACN,YAAY,EACZ,WAAW,EACX,KAAK,EACL,SAAS,EACT,SAAS,EACT,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,OAAO,CACR;EACDC,UAAU,EAAE,CAAC,MAAM,EAAE,WAAW;AAClC,CAAC;AACD,MAAMC,QAAQ,GAAG,IAAIC,GAAG,CAACL,aAAa,CAACC,OAAO,CAAC;AAC/C,MAAMK,sBAAsB,GAAG,IAAID,GAAG,CAACL,aAAa,CAACE,MAAM,CAAC;AAC5D,MAAMK,0BAA0B,GAAG,IAAIF,GAAG,CAACL,aAAa,CAACG,UAAU,CAAC;AAK7D,SAASK,cAAcA,CAACC,IAAY,EAAEC,QAAiB,EAAW;EACvE,OAAQA,QAAQ,IAAID,IAAI,KAAK,OAAO,IAAKA,IAAI,KAAK,MAAM;AAC1D;AAOO,SAASE,oBAAoBA,CAACF,IAAY,EAAEC,QAAiB,EAAW;EAC7E,OAAOF,cAAc,CAACC,IAAI,EAAEC,QAAQ,CAAC,IAAIJ,sBAAsB,CAACM,GAAG,CAACH,IAAI,CAAC;AAC3E;AAMO,SAASI,4BAA4BA,CAACJ,IAAY,EAAW;EAClE,OAAOF,0BAA0B,CAACK,GAAG,CAACH,IAAI,CAAC;AAC7C;AAOO,SAASK,wBAAwBA,CACtCL,IAAY,EACZC,QAAiB,EACR;EACT,OACEC,oBAAoB,CAACF,IAAI,EAAEC,QAAQ,CAAC,IAAIG,4BAA4B,CAACJ,IAAI,CAAC;AAE9E;AAEO,SAASM,SAASA,CAACN,IAAY,EAAW;EAC/C,OAAOL,QAAQ,CAACQ,GAAG,CAACH,IAAI,CAAC;AAC3B","ignoreList":[]} \ No newline at end of file diff --git a/vanilla/node_modules/@babel/helper-validator-identifier/package.json b/vanilla/node_modules/@babel/helper-validator-identifier/package.json new file mode 100644 index 0000000..1aea38d --- /dev/null +++ b/vanilla/node_modules/@babel/helper-validator-identifier/package.json @@ -0,0 +1,31 @@ +{ + "name": "@babel/helper-validator-identifier", + "version": "7.28.5", + "description": "Validate identifier/keywords name", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-helper-validator-identifier" + }, + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.js", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "devDependencies": { + "@unicode/unicode-17.0.0": "^1.6.10", + "charcodes": "^0.2.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "author": "The Babel Team (https://babel.dev/team)", + "type": "commonjs" +} \ No newline at end of file diff --git a/vanilla/node_modules/@babel/parser/CHANGELOG.md b/vanilla/node_modules/@babel/parser/CHANGELOG.md new file mode 100644 index 0000000..b3840ac --- /dev/null +++ b/vanilla/node_modules/@babel/parser/CHANGELOG.md @@ -0,0 +1,1073 @@ +# Changelog + +> **Tags:** +> - :boom: [Breaking Change] +> - :eyeglasses: [Spec Compliance] +> - :rocket: [New Feature] +> - :bug: [Bug Fix] +> - :memo: [Documentation] +> - :house: [Internal] +> - :nail_care: [Polish] + +> Semver Policy: https://github.com/babel/babel/tree/main/packages/babel-parser#semver + +_Note: Gaps between patch versions are faulty, broken or test releases._ + +See the [Babel Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md) for the pre-6.8.0 version Changelog. + +## 6.17.1 (2017-05-10) + +### :bug: Bug Fix + * Fix typo in flow spread operator error (Brian Ng) + * Fixed invalid number literal parsing ([#473](https://github.com/babel/babylon/pull/473)) (Alex Kuzmenko) + * Fix number parser ([#433](https://github.com/babel/babylon/pull/433)) (Alex Kuzmenko) + * Ensure non pattern shorthand props are checked for reserved words ([#479](https://github.com/babel/babylon/pull/479)) (Brian Ng) + * Remove jsx context when parsing arrow functions ([#475](https://github.com/babel/babylon/pull/475)) (Brian Ng) + * Allow super in class properties ([#499](https://github.com/babel/babylon/pull/499)) (Brian Ng) + * Allow flow class field to be named constructor ([#510](https://github.com/babel/babylon/pull/510)) (Brian Ng) + +## 6.17.0 (2017-04-20) + +### :bug: Bug Fix + * Cherry-pick #418 to 6.x ([#476](https://github.com/babel/babylon/pull/476)) (Sebastian McKenzie) + * Add support for invalid escapes in tagged templates ([#274](https://github.com/babel/babylon/pull/274)) (Kevin Gibbons) + * Throw error if new.target is used outside of a function ([#402](https://github.com/babel/babylon/pull/402)) (Brian Ng) + * Fix parsing of class properties ([#351](https://github.com/babel/babylon/pull/351)) (Kevin Gibbons) + * Fix parsing yield with dynamicImport ([#383](https://github.com/babel/babylon/pull/383)) (Brian Ng) + * Ensure consistent start args for parseParenItem ([#386](https://github.com/babel/babylon/pull/386)) (Brian Ng) + +## 7.0.0-beta.8 (2017-04-04) + +### New Feature +* Add support for flow type spread (#418) (Conrad Buck) +* Allow statics in flow interfaces (#427) (Brian Ng) + +### Bug Fix +* Fix predicate attachment to match flow parser (#428) (Brian Ng) +* Add extra.raw back to JSXText and JSXAttribute (#344) (Alex Rattray) +* Fix rest parameters with array and objects (#424) (Brian Ng) +* Fix number parser (#433) (Alex Kuzmenko) + +### Docs +* Fix CONTRIBUTING.md [skip ci] (#432) (Alex Kuzmenko) + +### Internal +* Use babel-register script when running babel smoke tests (#442) (Brian Ng) + +## 7.0.0-beta.7 (2017-03-22) + +### Spec Compliance +* Remove babylon plugin for template revision since it's stage-4 (#426) (Henry Zhu) + +### Bug Fix + +* Fix push-pop logic in flow (#405) (Daniel Tschinder) + +## 7.0.0-beta.6 (2017-03-21) + +### New Feature +* Add support for invalid escapes in tagged templates (#274) (Kevin Gibbons) + +### Polish +* Improves error message when super is called outside of constructor (#408) (Arshabh Kumar Agarwal) + +### Docs + +* [7.0] Moved value field in spec from ObjectMember to ObjectProperty as ObjectMethod's don't have it (#415) [skip ci] (James Browning) + +## 7.0.0-beta.5 (2017-03-21) + +### Bug Fix +* Throw error if new.target is used outside of a function (#402) (Brian Ng) +* Fix parsing of class properties (#351) (Kevin Gibbons) + +### Other + * Test runner: Detect extra property in 'actual' but not in 'expected'. (#407) (Andy) + * Optimize travis builds (#419) (Daniel Tschinder) + * Update codecov to 2.0 (#412) (Daniel Tschinder) + * Fix spec for ClassMethod: It doesn't have a function, it *is* a function. (#406) [skip ci] (Andy) + * Changed Non-existent RestPattern to RestElement which is what is actually parsed (#409) [skip ci] (James Browning) + * Upgrade flow to 0.41 (Daniel Tschinder) + * Fix watch command (#403) (Brian Ng) + * Update yarn lock (Daniel Tschinder) + * Fix watch command (#403) (Brian Ng) + * chore(package): update flow-bin to version 0.41.0 (#395) (greenkeeper[bot]) + * Add estree test for correct order of directives (Daniel Tschinder) + * Add DoExpression to spec (#364) (Alex Kuzmenko) + * Mention cloning of repository in CONTRIBUTING.md (#391) [skip ci] (Sumedh Nimkarde) + * Explain how to run only one test (#389) [skip ci] (Aaron Ang) + + ## 7.0.0-beta.4 (2017-03-01) + +* Don't consume async when checking for async func decl (#377) (Brian Ng) +* add `ranges` option [skip ci] (Henry Zhu) +* Don't parse class properties without initializers when classProperties is disabled and Flow is enabled (#300) (Andrew Levine) + +## 7.0.0-beta.3 (2017-02-28) + +- [7.0] Change RestProperty/SpreadProperty to RestElement/SpreadElement (#384) +- Merge changes from 6.x + +## 7.0.0-beta.2 (2017-02-20) + +- estree: correctly change literals in all cases (#368) (Daniel Tschinder) + +## 7.0.0-beta.1 (2017-02-20) + +- Fix negative number literal typeannotations (#366) (Daniel Tschinder) +- Update contributing with more test info [skip ci] (#355) (Brian Ng) + +## 7.0.0-beta.0 (2017-02-15) + +- Reintroduce Variance node (#333) (Daniel Tschinder) +- Rename NumericLiteralTypeAnnotation to NumberLiteralTypeAnnotation (#332) (Charles Pick) +- [7.0] Remove ForAwaitStatement, add await flag to ForOfStatement (#349) (Brandon Dail) +- chore(package): update ava to version 0.18.0 (#345) (greenkeeper[bot]) +- chore(package): update babel-plugin-istanbul to version 4.0.0 (#350) (greenkeeper[bot]) +- Change location of ObjectTypeIndexer to match flow (#228) (Daniel Tschinder) +- Rename flow AST Type ExistentialTypeParam to ExistsTypeAnnotation (#322) (Toru Kobayashi) +- Revert "Temporary rollback for erroring on trailing comma with spread (#154)" (#290) (Daniel Tschinder) +- Remove classConstructorCall plugin (#291) (Brian Ng) +- Update yarn.lock (Daniel Tschinder) +- Update cross-env to 3.x (Daniel Tschinder) +- [7.0] Remove node 0.10, 0.12 and 5 from Travis (#284) (Sergey Rubanov) +- Remove `String.fromCodePoint` shim (#279) (Mathias Bynens) + +## 6.16.1 (2017-02-23) + +### :bug: Regression + +- Revert "Fix export default async function to be FunctionDeclaration" ([#375](https://github.com/babel/babylon/pull/375)) + +Need to modify Babel for this AST node change, so moving to 7.0. + +- Revert "Don't parse class properties without initializers when classProperties plugin is disabled, and Flow is enabled" ([#376](https://github.com/babel/babylon/pull/376)) + +[react-native](https://github.com/facebook/react-native/issues/12542) broke with this so we reverted. + +## 6.16.0 (2017-02-23) + +### :rocket: New Feature + +***ESTree*** compatibility as plugin ([#277](https://github.com/babel/babylon/pull/277)) (Daniel Tschinder) + +We finally introduce a new compatibility layer for ESTree. To put babylon into ESTree-compatible mode the new plugin `estree` can be enabled. In this mode the parser will output an AST that is compliant to the specs of [ESTree](https://github.com/estree/estree/) + +We highly recommend everyone who uses babylon outside of babel to use this plugin. This will make it much easier for users to switch between different ESTree-compatible parsers. We so far tested several projects with different parsers and exchanged their parser to babylon and in nearly all cases it worked out of the box. Some other estree-compatible parsers include `acorn`, `esprima`, `espree`, `flow-parser`, etc. + +To enable `estree` mode simply add the plugin in the config: +```json +{ + "plugins": [ "estree" ] +} +``` + +If you want to migrate your project from non-ESTree mode to ESTree, have a look at our [Readme](https://github.com/babel/babylon/#output), where all deviations are mentioned. + +Add a parseExpression public method ([#213](https://github.com/babel/babylon/pull/213)) (jeromew) + +Babylon exports a new function to parse a single expression + +```js +import { parseExpression } from 'babylon'; + +const ast = parseExpression('x || y && z', options); +``` + +The returned AST will only consist of the expression. The options are the same as for `parse()` + +Add startLine option ([#346](https://github.com/babel/babylon/pull/346)) (Raphael Mu) + +A new option was added to babylon allowing to change the initial linenumber for the first line which is usually `1`. +Changing this for example to `100` will make line `1` of the input source to be marked as line `100`, line `2` as `101`, line `3` as `102`, ... + +Function predicate declaration ([#103](https://github.com/babel/babylon/pull/103)) (Panagiotis Vekris) + +Added support for function predicates which flow introduced in version 0.33.0 + +```js +declare function is_number(x: mixed): boolean %checks(typeof x === "number"); +``` + +Allow imports in declare module ([#315](https://github.com/babel/babylon/pull/315)) (Daniel Tschinder) + +Added support for imports within module declarations which flow introduced in version 0.37.0 + +```js +declare module "C" { + import type { DT } from "D"; + declare export type CT = { D: DT }; +} +``` + +### :eyeglasses: Spec Compliance + +Forbid semicolons after decorators in classes ([#352](https://github.com/babel/babylon/pull/352)) (Kevin Gibbons) + +This example now correctly throws an error when there is a semicolon after the decorator: + +```js +class A { +@a; +foo(){} +} +``` + +Keywords are not allowed as local specifier ([#307](https://github.com/babel/babylon/pull/307)) (Daniel Tschinder) + +Using keywords in imports is not allowed anymore: + +```js +import { default } from "foo"; +import { a as debugger } from "foo"; +``` + +Do not allow overwritting of primitive types ([#314](https://github.com/babel/babylon/pull/314)) (Daniel Tschinder) + +In flow it is now forbidden to overwrite the primitive types `"any"`, `"mixed"`, `"empty"`, `"bool"`, `"boolean"`, `"number"`, `"string"`, `"void"` and `"null"` with your own type declaration. + +Disallow import type { type a } from … ([#305](https://github.com/babel/babylon/pull/305)) (Daniel Tschinder) + +The following code now correctly throws an error + +```js +import type { type a } from "foo"; +``` + +Don't parse class properties without initializers when classProperties is disabled and Flow is enabled ([#300](https://github.com/babel/babylon/pull/300)) (Andrew Levine) + +Ensure that you enable the `classProperties` plugin in order to enable correct parsing of class properties. Prior to this version it was possible to parse them by enabling the `flow` plugin but this was not intended the behaviour. + +If you enable the flow plugin you can only define the type of the class properties, but not initialize them. + +Fix export default async function to be FunctionDeclaration ([#324](https://github.com/babel/babylon/pull/324)) (Daniel Tschinder) + +Parsing the following code now returns a `FunctionDeclaration` AST node instead of `FunctionExpression`. + +```js +export default async function bar() {}; +``` + +### :nail_care: Polish + +Improve error message on attempt to destructure named import ([#288](https://github.com/babel/babylon/pull/288)) (Brian Ng) + +### :bug: Bug Fix + +Fix negative number literal typeannotations ([#366](https://github.com/babel/babylon/pull/366)) (Daniel Tschinder) + +Ensure takeDecorators is called on exported class ([#358](https://github.com/babel/babylon/pull/358)) (Brian Ng) + +ESTree: correctly change literals in all cases ([#368](https://github.com/babel/babylon/pull/368)) (Daniel Tschinder) + +Correctly convert RestProperty to Assignable ([#339](https://github.com/babel/babylon/pull/339)) (Daniel Tschinder) + +Fix #321 by allowing question marks in type params ([#338](https://github.com/babel/babylon/pull/338)) (Daniel Tschinder) + +Fix #336 by correctly setting arrow-param ([#337](https://github.com/babel/babylon/pull/337)) (Daniel Tschinder) + +Fix parse error when destructuring `set` with default value ([#317](https://github.com/babel/babylon/pull/317)) (Brian Ng) + +Fix ObjectTypeCallProperty static ([#298](https://github.com/babel/babylon/pull/298)) (Dan Harper) + + +### :house: Internal + +Fix generator-method-with-computed-name spec ([#360](https://github.com/babel/babylon/pull/360)) (Alex Rattray) + +Fix flow type-parameter-declaration test with unintended semantic ([#361](https://github.com/babel/babylon/pull/361)) (Alex Rattray) + +Cleanup and splitup parser functions ([#295](https://github.com/babel/babylon/pull/295)) (Daniel Tschinder) + +chore(package): update flow-bin to version 0.38.0 ([#313](https://github.com/babel/babylon/pull/313)) (greenkeeper[bot]) + +Call inner function instead of 1:1 copy to plugin ([#294](https://github.com/babel/babylon/pull/294)) (Daniel Tschinder) + +Update eslint-config-babel to the latest version 🚀 ([#299](https://github.com/babel/babylon/pull/299)) (greenkeeper[bot]) + +Update eslint-config-babel to the latest version 🚀 ([#293](https://github.com/babel/babylon/pull/293)) (greenkeeper[bot]) + +devDeps: remove eslint-plugin-babel ([#292](https://github.com/babel/babylon/pull/292)) (Kai Cataldo) + +Correct indent eslint rule config ([#276](https://github.com/babel/babylon/pull/276)) (Daniel Tschinder) + +Fail tests that have expected.json and throws-option ([#285](https://github.com/babel/babylon/pull/285)) (Daniel Tschinder) + +### :memo: Documentation + +Update contributing with more test info [skip ci] ([#355](https://github.com/babel/babylon/pull/355)) (Brian Ng) + +Update API documentation ([#330](https://github.com/babel/babylon/pull/330)) (Timothy Gu) + +Added keywords to package.json ([#323](https://github.com/babel/babylon/pull/323)) (Dmytro) + +AST spec: fix casing of `RegExpLiteral` ([#318](https://github.com/babel/babylon/pull/318)) (Mathias Bynens) + +## 6.15.0 (2017-01-10) + +### :eyeglasses: Spec Compliance + +Add support for Flow shorthand import type ([#267](https://github.com/babel/babylon/pull/267)) (Jeff Morrison) + +This change implements flows new shorthand import syntax +and where previously you had to write this code: + +```js +import {someValue} from "blah"; +import type {someType} from "blah"; +import typeof {someOtherValue} from "blah"; +``` + +you can now write it like this: + +```js +import { + someValue, + type someType, + typeof someOtherValue, +} from "blah"; +``` + +For more information look at [this](https://github.com/facebook/flow/pull/2890) pull request. + +flow: allow leading pipes in all positions ([#256](https://github.com/babel/babylon/pull/256)) (Vladimir Kurchatkin) + +This change now allows a leading pipe everywhere types can be used: +```js +var f = (x): | 1 | 2 => 1; +``` + +Throw error when exporting non-declaration ([#241](https://github.com/babel/babylon/pull/241)) (Kai Cataldo) + +Previously babylon parsed the following exports, although they are not valid: +```js +export typeof foo; +export new Foo(); +export function() {}; +export for (;;); +export while(foo); +``` + +### :bug: Bug Fix + +Don't set inType flag when parsing property names ([#266](https://github.com/babel/babylon/pull/266)) (Vladimir Kurchatkin) + +This fixes parsing of this case: + +```js +const map = { + [age <= 17] : 'Too young' +}; +``` + +Fix source location for JSXEmptyExpression nodes (fixes #248) ([#249](https://github.com/babel/babylon/pull/249)) (James Long) + +The following case produced an invalid AST +```js +
{/* foo */}
+``` + +Use fromCodePoint to convert high value unicode entities ([#243](https://github.com/babel/babylon/pull/243)) (Ryan Duffy) + +When high value unicode entities (e.g. 💩) were used in the input source code they are now correctly encoded in the resulting AST. + +Rename folder to avoid Windows-illegal characters ([#281](https://github.com/babel/babylon/pull/281)) (Ryan Plant) + +Allow this.state.clone() when parsing decorators ([#262](https://github.com/babel/babylon/pull/262)) (Alex Rattray) + +### :house: Internal + +User external-helpers ([#254](https://github.com/babel/babylon/pull/254)) (Daniel Tschinder) + +Add watch script for dev ([#234](https://github.com/babel/babylon/pull/234)) (Kai Cataldo) + +Freeze current plugins list for "*" option, and remove from README.md ([#245](https://github.com/babel/babylon/pull/245)) (Andrew Levine) + +Prepare tests for multiple fixture runners. ([#240](https://github.com/babel/babylon/pull/240)) (Daniel Tschinder) + +Add some test coverage for decorators stage-0 plugin ([#250](https://github.com/babel/babylon/pull/250)) (Andrew Levine) + +Refactor tokenizer types file ([#263](https://github.com/babel/babylon/pull/263)) (Sven SAULEAU) + +Update eslint-config-babel to the latest version 🚀 ([#273](https://github.com/babel/babylon/pull/273)) (greenkeeper[bot]) + +chore(package): update rollup to version 0.41.0 ([#272](https://github.com/babel/babylon/pull/272)) (greenkeeper[bot]) + +chore(package): update flow-bin to version 0.37.0 ([#255](https://github.com/babel/babylon/pull/255)) (greenkeeper[bot]) + +## 6.14.1 (2016-11-17) + +### :bug: Bug Fix + +Allow `"plugins": ["*"]` ([#229](https://github.com/babel/babylon/pull/229)) (Daniel Tschinder) + +```js +{ + "plugins": ["*"] +} +``` + +Will include all parser plugins instead of specifying each one individually. Useful for tools like babel-eslint, jscodeshift, and ast-explorer. + +## 6.14.0 (2016-11-16) + +### :eyeglasses: Spec Compliance + +Throw error for reserved words `enum` and `await` ([#195](https://github.com/babel/babylon/pull/195)) (Kai Cataldo) + +[11.6.2.2 Future Reserved Words](http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words) + +Babylon will throw for more reserved words such as `enum` or `await` (in strict mode). + +``` +class enum {} // throws +class await {} // throws in strict mode (module) +``` + +Optional names for function types and object type indexers ([#197](https://github.com/babel/babylon/pull/197)) (Gabe Levi) + +So where you used to have to write + +```js +type A = (x: string, y: boolean) => number; +type B = (z: string) => number; +type C = { [key: string]: number }; +``` + +you can now write (with flow 0.34.0) + +```js +type A = (string, boolean) => number; +type B = string => number; +type C = { [string]: number }; +``` + +Parse flow nested array type annotations like `number[][]` ([#219](https://github.com/babel/babylon/pull/219)) (Bernhard Häussner) + +Supports these form now of specifying array types: + +```js +var a: number[][][][]; +var b: string[][]; +``` + +### :bug: Bug Fix + +Correctly eat semicolon at the end of `DelcareModuleExports` ([#223](https://github.com/babel/babylon/pull/223)) (Daniel Tschinder) + +``` +declare module "foo" { declare module.exports: number } +declare module "foo" { declare module.exports: number; } // also allowed now +``` + +### :house: Internal + + * Count Babel tests towards Babylon code coverage ([#182](https://github.com/babel/babylon/pull/182)) (Moti Zilberman) + * Fix strange line endings ([#214](https://github.com/babel/babylon/pull/214)) (Thomas Grainger) + * Add node 7 (Daniel Tschinder) + * chore(package): update flow-bin to version 0.34.0 ([#204](https://github.com/babel/babylon/pull/204)) (Greenkeeper) + +## v6.13.1 (2016-10-26) + +### :nail_care: Polish + +- Use rollup for bundling to speed up startup time ([#190](https://github.com/babel/babylon/pull/190)) ([@drewml](https://github.com/DrewML)) + +```js +const babylon = require('babylon'); +const ast = babylon.parse('var foo = "lol";'); +``` + +With that test case, there was a ~95ms savings by removing the need for node to build/traverse the dependency graph. + +**Without bundling** +![image](https://cloud.githubusercontent.com/assets/5233399/19420264/3133497e-93ad-11e6-9a6a-2da59c4f5c13.png) + +**With bundling** +![image](https://cloud.githubusercontent.com/assets/5233399/19420267/388f556e-93ad-11e6-813e-7c5c396be322.png) + +- add clean command [skip ci] ([#201](https://github.com/babel/babylon/pull/201)) (Henry Zhu) +- add ForAwaitStatement (async generator already added) [skip ci] ([#196](https://github.com/babel/babylon/pull/196)) (Henry Zhu) + +## v6.13.0 (2016-10-21) + +### :eyeglasses: Spec Compliance + +Property variance type annotations for Flow plugin ([#161](https://github.com/babel/babylon/pull/161)) (Sam Goldman) + +> See https://flowtype.org/docs/variance.html for more information + +```js +type T = { +p: T }; +interface T { -p: T }; +declare class T { +[k:K]: V }; +class T { -[k:K]: V }; +class C2 { +p: T = e }; +``` + +Raise error on duplicate definition of __proto__ ([#183](https://github.com/babel/babylon/pull/183)) (Moti Zilberman) + +```js +({ __proto__: 1, __proto__: 2 }) // Throws an error now +``` + +### :bug: Bug Fix + +Flow: Allow class properties to be named `static` ([#184](https://github.com/babel/babylon/pull/184)) (Moti Zilberman) + +```js +declare class A { + static: T; +} +``` + +Allow "async" as identifier for object literal property shorthand ([#187](https://github.com/babel/babylon/pull/187)) (Andrew Levine) + +```js +var foo = { async, bar }; +``` + +### :nail_care: Polish + +Fix flowtype and add inType to state ([#189](https://github.com/babel/babylon/pull/189)) (Daniel Tschinder) + +> This improves the performance slightly (because of hidden classes) + +### :house: Internal + +Fix .gitattributes line ending setting ([#191](https://github.com/babel/babylon/pull/191)) (Moti Zilberman) + +Increase test coverage ([#175](https://github.com/babel/babylon/pull/175) (Moti Zilberman) + +Readd missin .eslinignore for IDEs (Daniel Tschinder) + +Error on missing expected.json fixture in CI ([#188](https://github.com/babel/babylon/pull/188)) (Moti Zilberman) + +Add .gitattributes and .editorconfig for LF line endings ([#179](https://github.com/babel/babylon/pull/179)) (Moti Zilberman) + +Fixes two tests that are failing after the merge of #172 ([#177](https://github.com/babel/babylon/pull/177)) (Moti Zilberman) + +## v6.12.0 (2016-10-14) + +### :eyeglasses: Spec Compliance + +Implement import() syntax ([#163](https://github.com/babel/babylon/pull/163)) (Jordan Gensler) + +#### Dynamic Import + +- Proposal Repo: https://github.com/domenic/proposal-dynamic-import +- Championed by [@domenic](https://github.com/domenic) +- stage-2 +- [sept-28 tc39 notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2016-09/sept-28.md#113a-import) + +> This repository contains a proposal for adding a "function-like" import() module loading syntactic form to JavaScript + +```js +import(`./section-modules/${link.dataset.entryModule}.js`) +.then(module => { + module.loadPageInto(main); +}) +``` + +Add EmptyTypeAnnotation ([#171](https://github.com/babel/babylon/pull/171)) (Sam Goldman) + +#### EmptyTypeAnnotation + +Just wasn't covered before. + +```js +type T = empty; +``` + +### :bug: Bug Fix + +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels) + +```js +// was failing due to sparse array +export const { foo: [ ,, qux7 ] } = bar; +``` + +Allow keyword in Flow object declaration property names with type parameters ([#146](https://github.com/babel/babylon/pull/146)) (Dan Harper) + +```js +declare class X { + foobar(): void; + static foobar(): void; +} +``` + +Allow keyword in object/class property names with Flow type parameters ([#145](https://github.com/babel/babylon/pull/145)) (Dan Harper) + +```js +class Foo { + delete(item: T): T { + return item; + } +} +``` + +Allow typeAnnotations for yield expressions ([#174](https://github.com/babel/babylon/pull/174))) (Daniel Tschinder) + +```js +function *foo() { + const x = (yield 5: any); +} +``` + +### :nail_care: Polish + +Annotate more errors with expected token ([#172](https://github.com/babel/babylon/pull/172))) (Moti Zilberman) + +```js +// Unexpected token, expected ; (1:6) +{ set 1 } +``` + +### :house: Internal + +Remove kcheck ([#173](https://github.com/babel/babylon/pull/173))) (Daniel Tschinder) + +Also run flow, linting, babel tests on separate instances (add back node 0.10) + +## v6.11.6 (2016-10-12) + +### :bug: Bug Fix/Regression + +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels) + +```js +// was failing with `Cannot read property 'type' of null` because of null identifiers +export const { foo: [ ,, qux7 ] } = bar; +``` + +## v6.11.5 (2016-10-12) + +### :eyeglasses: Spec Compliance + +Fix: Check for duplicate named exports in exported destructuring assignments ([#144](https://github.com/babel/babylon/pull/144)) (Kai Cataldo) + +```js +// `foo` has already been exported. Exported identifiers must be unique. (2:20) +export function foo() {}; +export const { a: [{foo}] } = bar; +``` + +Fix: Check for duplicate named exports in exported rest elements/properties ([#164](https://github.com/babel/babylon/pull/164)) (Kai Cataldo) + +```js +// `foo` has already been exported. Exported identifiers must be unique. (2:22) +export const foo = 1; +export const [bar, ...foo] = baz; +``` + +### :bug: Bug Fix + +Fix: Allow identifier `async` for default param in arrow expression ([#165](https://github.com/babel/babylon/pull/165)) (Kai Cataldo) + +```js +// this is ok now +const test = ({async = true}) => {}; +``` + +### :nail_care: Polish + +Babylon will now print out the token it's expecting if there's a `SyntaxError` ([#150](https://github.com/babel/babylon/pull/150)) (Daniel Tschinder) + +```bash +# So in the case of a missing ending curly (`}`) +Module build failed: SyntaxError: Unexpected token, expected } (30:0) + 28 | } + 29 | +> 30 | + | ^ +``` + +## v6.11.4 (2016-10-03) + +Temporary rollback for erroring on trailing comma with spread (#154) (Henry Zhu) + +## v6.11.3 (2016-10-01) + +### :eyeglasses: Spec Compliance + +Add static errors for object rest (#149) ([@danez](https://github.com/danez)) + +> https://github.com/sebmarkbage/ecmascript-rest-spread + +Object rest copies the *rest* of properties from the right hand side `obj` starting from the left to right. + +```js +let { x, y, ...z } = { x: 1, y: 2, z: 3 }; +// x = 1 +// y = 2 +// z = { z: 3 } +``` + +#### New Syntax Errors: + +**SyntaxError**: The rest element has to be the last element when destructuring (1:10) +```bash +> 1 | let { ...x, y, z } = { x: 1, y: 2, z: 3}; + | ^ +# Previous behavior: +# x = { x: 1, y: 2, z: 3 } +# y = 2 +# z = 3 +``` + +Before, this was just a more verbose way of shallow copying `obj` since it doesn't actually do what you think. + +**SyntaxError**: Cannot have multiple rest elements when destructuring (1:13) + +```bash +> 1 | let { x, ...y, ...z } = { x: 1, y: 2, z: 3}; + | ^ +# Previous behavior: +# x = 1 +# y = { y: 2, z: 3 } +# z = { y: 2, z: 3 } +``` + +Before y and z would just be the same value anyway so there is no reason to need to have both. + +**SyntaxError**: A trailing comma is not permitted after the rest element (1:16) + +```js +let { x, y, ...z, } = obj; +``` + +The rationale for this is that the use case for trailing comma is that you can add something at the end without affecting the line above. Since a RestProperty always has to be the last property it doesn't make sense. + +--- + +get / set are valid property names in default assignment (#142) ([@jezell](https://github.com/jezell)) + +```js +// valid +function something({ set = null, get = null }) {} +``` + +## v6.11.2 (2016-09-23) + +### Bug Fix + +- [#139](https://github.com/babel/babylon/issues/139) Don't do the duplicate check if not an identifier (#140) @hzoo + +```js +// regression with duplicate export check +SyntaxError: ./typography.js: `undefined` has already been exported. Exported identifiers must be unique. (22:13) + 20 | + 21 | export const { rhythm } = typography; +> 22 | export const { TypographyStyle } = typography +``` + +Bail out for now, and make a change to account for destructuring in the next release. + +## 6.11.1 (2016-09-22) + +### Bug Fix +- [#137](https://github.com/babel/babylon/pull/137) - Fix a regression with duplicate exports - it was erroring on all keys in `Object.prototype`. @danez + +```javascript +export toString from './toString'; +``` + +```bash +`toString` has already been exported. Exported identifiers must be unique. (1:7) +> 1 | export toString from './toString'; + | ^ + 2 | +``` + +## 6.11.0 (2016-09-22) + +### Spec Compliance (will break CI) + +- Disallow duplicate named exports ([#107](https://github.com/babel/babylon/pull/107)) @kaicataldo + +```js +// Only one default export allowed per module. (2:9) +export default function() {}; +export { foo as default }; + +// Only one default export allowed per module. (2:0) +export default {}; +export default function() {}; + +// `Foo` has already been exported. Exported identifiers must be unique. (2:0) +export { Foo }; +export class Foo {}; +``` + +### New Feature (Syntax) + +- Add support for computed class property names ([#121](https://github.com/babel/babylon/pull/121)) @motiz88 + +```js +// AST +interface ClassProperty <: Node { + type: "ClassProperty"; + key: Identifier; + value: Expression; + computed: boolean; // added +} +``` + +```js +// with "plugins": ["classProperties"] +class Foo { + [x] + ['y'] +} + +class Bar { + [p] + [m] () {} +} + ``` + +### Bug Fix + +- Fix `static` property falling through in the declare class Flow AST ([#135](https://github.com/babel/babylon/pull/135)) @danharper + +```js +declare class X { + a: number; + static b: number; // static + c: number; // this was being marked as static in the AST as well +} +``` + +### Polish + +- Rephrase "assigning/binding to rvalue" errors to include context ([#119](https://github.com/babel/babylon/pull/119)) @motiz88 + +```js +// Used to error with: +// SyntaxError: Assigning to rvalue (1:0) + +// Now: +// Invalid left-hand side in assignment expression (1:0) +3 = 4 + +// Invalid left-hand side in for-in statement (1:5) +for (+i in {}); +``` + +### Internal + +- Fix call to `this.parseMaybeAssign` with correct arguments ([#133](https://github.com/babel/babylon/pull/133)) @danez +- Add semver note to changelog ([#131](https://github.com/babel/babylon/pull/131)) @hzoo + +## 6.10.0 (2016-09-19) + +> We plan to include some spec compliance bugs in patch versions. An example was the multiple default exports issue. + +### Spec Compliance + +* Implement ES2016 check for simple parameter list in strict mode ([#106](https://github.com/babel/babylon/pull/106)) (Timothy Gu) + +> It is a Syntax Error if ContainsUseStrict of FunctionBody is true and IsSimpleParameterList of FormalParameters is false. https://tc39.github.io/ecma262/2016/#sec-function-definitions-static-semantics-early-errors + +More Context: [tc39-notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2015-07/july-29.md#611-the-scope-of-use-strict-with-respect-to-destructuring-in-parameter-lists) + +For example: + +```js +// this errors because it uses destructuring and default parameters +// in a function with a "use strict" directive +function a([ option1, option2 ] = []) { + "use strict"; +} + ``` + +The solution would be to use a top level "use strict" or to remove the destructuring or default parameters when using a function + "use strict" or to. + +### New Feature + +* Exact object type annotations for Flow plugin ([#104](https://github.com/babel/babylon/pull/104)) (Basil Hosmer) + +Added to flow in https://github.com/facebook/flow/commit/c710c40aa2a115435098d6c0dfeaadb023cd39b8 + +Looks like: + +```js +var a : {| x: number, y: string |} = { x: 0, y: 'foo' }; +``` + +### Bug Fixes + +* Include `typeParameter` location in `ArrowFunctionExpression` ([#126](https://github.com/babel/babylon/pull/126)) (Daniel Tschinder) +* Error on invalid flow type annotation with default assignment ([#122](https://github.com/babel/babylon/pull/122)) (Dan Harper) +* Fix Flow return types on arrow functions ([#124](https://github.com/babel/babylon/pull/124)) (Dan Harper) + +### Misc + +* Add tests for export extensions ([#127](https://github.com/babel/babylon/pull/127)) (Daniel Tschinder) +* Fix Contributing guidelines [skip ci] (Daniel Tschinder) + +## 6.9.2 (2016-09-09) + +The only change is to remove the `babel-runtime` dependency by compiling with Babel's ES2015 loose mode. So using babylon standalone should be smaller. + +## 6.9.1 (2016-08-23) + +This release contains mainly small bugfixes but also updates babylons default mode to es2017. The features for `exponentiationOperator`, `asyncFunctions` and `trailingFunctionCommas` which previously needed to be activated via plugin are now enabled by default and the plugins are now no-ops. + +### Bug Fixes + +- Fix issues with default object params in async functions ([#96](https://github.com/babel/babylon/pull/96)) @danez +- Fix issues with flow-types and async function ([#95](https://github.com/babel/babylon/pull/95)) @danez +- Fix arrow functions with destructuring, types & default value ([#94](https://github.com/babel/babylon/pull/94)) @danharper +- Fix declare class with qualified type identifier ([#97](https://github.com/babel/babylon/pull/97)) @danez +- Remove exponentiationOperator, asyncFunctions, trailingFunctionCommas plugins and enable them by default ([#98](https://github.com/babel/babylon/pull/98)) @danez + +## 6.9.0 (2016-08-16) + +### New syntax support + +- Add JSX spread children ([#42](https://github.com/babel/babylon/pull/42)) @calebmer + +(Be aware that React is not going to support this syntax) + +```js +
+ {...todos.map(todo => )} +
+``` + +- Add support for declare module.exports ([#72](https://github.com/babel/babylon/pull/72)) @danez + +```js +declare module "foo" { + declare module.exports: {} +} +``` + +### New Features + +- If supplied, attach filename property to comment node loc. ([#80](https://github.com/babel/babylon/pull/80)) @divmain +- Add identifier name to node loc field ([#90](https://github.com/babel/babylon/pull/90)) @kittens + +### Bug Fixes + +- Fix exponential operator to behave according to spec ([#75](https://github.com/babel/babylon/pull/75)) @danez +- Fix lookahead to not add comments to arrays which are not cloned ([#76](https://github.com/babel/babylon/pull/76)) @danez +- Fix accidental fall-through in Flow type parsing. ([#82](https://github.com/babel/babylon/pull/82)) @xiemaisi +- Only allow declares inside declare module ([#73](https://github.com/babel/babylon/pull/73)) @danez +- Small fix for parsing type parameter declarations ([#83](https://github.com/babel/babylon/pull/83)) @gabelevi +- Fix arrow param locations with flow types ([#57](https://github.com/babel/babylon/pull/57)) @danez +- Fixes SyntaxError position with flow optional type ([#65](https://github.com/babel/babylon/pull/65)) @danez + +### Internal + +- Add codecoverage to tests @danez +- Fix tests to not save expected output if we expect the test to fail @danez +- Make a shallow clone of babel for testing @danez +- chore(package): update cross-env to version 2.0.0 ([#77](https://github.com/babel/babylon/pull/77)) @greenkeeperio-bot +- chore(package): update ava to version 0.16.0 ([#86](https://github.com/babel/babylon/pull/86)) @greenkeeperio-bot +- chore(package): update babel-plugin-istanbul to version 2.0.0 ([#89](https://github.com/babel/babylon/pull/89)) @greenkeeperio-bot +- chore(package): update nyc to version 8.0.0 ([#88](https://github.com/babel/babylon/pull/88)) @greenkeeperio-bot + +## 6.8.4 (2016-07-06) + +### Bug Fixes + +- Fix the location of params, when flow and default value used ([#68](https://github.com/babel/babylon/pull/68)) @danez + +## 6.8.3 (2016-07-02) + +### Bug Fixes + +- Fix performance regression introduced in 6.8.2 with conditionals ([#63](https://github.com/babel/babylon/pull/63)) @danez + +## 6.8.2 (2016-06-24) + +### Bug Fixes + +- Fix parse error with yielding jsx elements in generators `function* it() { yield ; }` ([#31](https://github.com/babel/babylon/pull/31)) @eldereal +- When cloning nodes do not clone its comments ([#24](https://github.com/babel/babylon/pull/24)) @danez +- Fix parse errors when using arrow functions with an spread element and return type `(...props): void => {}` ([#10](https://github.com/babel/babylon/pull/10)) @danez +- Fix leading comments added from previous node ([#23](https://github.com/babel/babylon/pull/23)) @danez +- Fix parse errors with flow's optional arguments `(arg?) => {}` ([#19](https://github.com/babel/babylon/pull/19)) @danez +- Support negative numeric type literals @kittens +- Remove line terminator restriction after await keyword @kittens +- Remove grouped type arrow restriction as it seems flow no longer has it @kittens +- Fix parse error with generic methods that have the name `get` or `set` `class foo { get() {} }` ([#55](https://github.com/babel/babylon/pull/55)) @vkurchatkin +- Fix parse error with arrow functions that have flow type parameter declarations `(x: T): T => x;` ([#54](https://github.com/babel/babylon/pull/54)) @gabelevi + +### Documentation + +- Document AST differences from ESTree ([#41](https://github.com/babel/babylon/pull/41)) @nene +- Move ast spec from babel/babel ([#46](https://github.com/babel/babylon/pull/46)) @hzoo + +### Internal + +- Enable skipped tests ([#16](https://github.com/babel/babylon/pull/16)) @danez +- Add script to test latest version of babylon with babel ([#21](https://github.com/babel/babylon/pull/21)) @danez +- Upgrade test runner ava @kittens +- Add missing generate-identifier-regex script @kittens +- Rename parser context types @kittens +- Add node v6 to travis testing @hzoo +- Update to Unicode v9 ([#45](https://github.com/babel/babylon/pull/45)) @mathiasbynens + +## 6.8.1 (2016-06-06) + +### New Feature + +- Parse type parameter declarations with defaults like `type Foo = T` + +### Bug Fixes +- Type parameter declarations need 1 or more type parameters. +- The existential type `*` is not a valid type parameter. +- The existential type `*` is a primary type + +### Spec Compliance +- The param list for type parameter declarations now consists of `TypeParameter` nodes +- New `TypeParameter` AST Node (replaces using the `Identifier` node before) + +``` +interface TypeParameter <: Node { + bound: TypeAnnotation; + default: TypeAnnotation; + name: string; + variance: "plus" | "minus"; +} +``` + +## 6.8.0 (2016-05-02) + +#### New Feature + +##### Parse Method Parameter Decorators ([#12](https://github.com/babel/babylon/pull/12)) + +> [Method Parameter Decorators](https://goo.gl/8MmCMG) is now a TC39 [stage 0 proposal](https://github.com/tc39/ecma262/blob/master/stage0.md). + +Examples: + +```js +class Foo { + constructor(@foo() x, @bar({ a: 123 }) @baz() y) {} +} + +export default function func(@foo() x, @bar({ a: 123 }) @baz() y) {} + +var obj = { + method(@foo() x, @bar({ a: 123 }) @baz() y) {} +}; +``` + +##### Parse for-await statements (w/ `asyncGenerators` plugin) ([#17](https://github.com/babel/babylon/pull/17)) + +There is also a new node type, `ForAwaitStatement`. + +> [Async generators and for-await](https://github.com/tc39/proposal-async-iteration) are now a [stage 2 proposal](https://github.com/tc39/ecma262#current-proposals). + +Example: + +```js +async function f() { + for await (let x of y); +} +``` diff --git a/vanilla/node_modules/@babel/parser/LICENSE b/vanilla/node_modules/@babel/parser/LICENSE new file mode 100644 index 0000000..d4c7fc5 --- /dev/null +++ b/vanilla/node_modules/@babel/parser/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2014 by various contributors (see AUTHORS) + +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/vanilla/node_modules/@babel/parser/README.md b/vanilla/node_modules/@babel/parser/README.md new file mode 100644 index 0000000..a9463e8 --- /dev/null +++ b/vanilla/node_modules/@babel/parser/README.md @@ -0,0 +1,19 @@ +# @babel/parser + +> A JavaScript parser + +See our website [@babel/parser](https://babeljs.io/docs/babel-parser) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20parser%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/parser +``` + +or using yarn: + +```sh +yarn add @babel/parser --dev +``` diff --git a/vanilla/node_modules/@babel/parser/bin/babel-parser.js b/vanilla/node_modules/@babel/parser/bin/babel-parser.js new file mode 100755 index 0000000..4808c5e --- /dev/null +++ b/vanilla/node_modules/@babel/parser/bin/babel-parser.js @@ -0,0 +1,15 @@ +#!/usr/bin/env node +/* eslint-disable no-var, unicorn/prefer-node-protocol */ + +var parser = require(".."); +var fs = require("fs"); + +var filename = process.argv[2]; +if (!filename) { + console.error("no filename specified"); +} else { + var file = fs.readFileSync(filename, "utf8"); + var ast = parser.parse(file); + + console.log(JSON.stringify(ast, null, " ")); +} diff --git a/vanilla/node_modules/@babel/parser/lib/index.js b/vanilla/node_modules/@babel/parser/lib/index.js new file mode 100644 index 0000000..fa6628c --- /dev/null +++ b/vanilla/node_modules/@babel/parser/lib/index.js @@ -0,0 +1,14582 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +function _objectWithoutPropertiesLoose(r, e) { + if (null == r) return {}; + var t = {}; + for (var n in r) if ({}.hasOwnProperty.call(r, n)) { + if (-1 !== e.indexOf(n)) continue; + t[n] = r[n]; + } + return t; +} +class Position { + constructor(line, col, index) { + this.line = void 0; + this.column = void 0; + this.index = void 0; + this.line = line; + this.column = col; + this.index = index; + } +} +class SourceLocation { + constructor(start, end) { + this.start = void 0; + this.end = void 0; + this.filename = void 0; + this.identifierName = void 0; + this.start = start; + this.end = end; + } +} +function createPositionWithColumnOffset(position, columnOffset) { + const { + line, + column, + index + } = position; + return new Position(line, column + columnOffset, index + columnOffset); +} +const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"; +var ModuleErrors = { + ImportMetaOutsideModule: { + message: `import.meta may appear only with 'sourceType: "module"'`, + code + }, + ImportOutsideModule: { + message: `'import' and 'export' may appear only with 'sourceType: "module"'`, + code + } +}; +const NodeDescriptions = { + ArrayPattern: "array destructuring pattern", + AssignmentExpression: "assignment expression", + AssignmentPattern: "assignment expression", + ArrowFunctionExpression: "arrow function expression", + ConditionalExpression: "conditional expression", + CatchClause: "catch clause", + ForOfStatement: "for-of statement", + ForInStatement: "for-in statement", + ForStatement: "for-loop", + FormalParameters: "function parameter list", + Identifier: "identifier", + ImportSpecifier: "import specifier", + ImportDefaultSpecifier: "import default specifier", + ImportNamespaceSpecifier: "import namespace specifier", + ObjectPattern: "object destructuring pattern", + ParenthesizedExpression: "parenthesized expression", + RestElement: "rest element", + UpdateExpression: { + true: "prefix operation", + false: "postfix operation" + }, + VariableDeclarator: "variable declaration", + YieldExpression: "yield expression" +}; +const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type]; +var StandardErrors = { + AccessorIsGenerator: ({ + kind + }) => `A ${kind}ter cannot be a generator.`, + ArgumentsInClass: "'arguments' is only allowed in functions and class methods.", + AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.", + AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.", + AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.", + AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.", + AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.", + AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.", + BadGetterArity: "A 'get' accessor must not have any formal parameters.", + BadSetterArity: "A 'set' accessor must have exactly one formal parameter.", + BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.", + ConstructorClassField: "Classes may not have a field named 'constructor'.", + ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.", + ConstructorIsAccessor: "Class constructor may not be an accessor.", + ConstructorIsAsync: "Constructor can't be an async function.", + ConstructorIsGenerator: "Constructor can't be a generator.", + DeclarationMissingInitializer: ({ + kind + }) => `Missing initializer in ${kind} declaration.`, + DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.", + DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.", + DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.", + DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", + DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.", + DecoratorSemicolon: "Decorators must not be followed by a semicolon.", + DecoratorStaticBlock: "Decorators can't be used with a static block.", + DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.', + DeletePrivateField: "Deleting a private field is not allowed.", + DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.", + DuplicateConstructor: "Duplicate constructor in the same class.", + DuplicateDefaultExport: "Only one default export allowed per module.", + DuplicateExport: ({ + exportName + }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`, + DuplicateProto: "Redefinition of __proto__ property.", + DuplicateRegExpFlags: "Duplicate regular expression flag.", + ElementAfterRest: "Rest element must be last element.", + EscapedCharNotAnIdentifier: "Invalid Unicode escape.", + ExportBindingIsString: ({ + localName, + exportName + }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`, + ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.", + ForInOfLoopInitializer: ({ + type + }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`, + ForInUsing: "For-in loop may not start with 'using' declaration.", + ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.", + ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.", + GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.", + IllegalBreakContinue: ({ + type + }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`, + IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.", + IllegalReturn: "'return' outside of function.", + ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.", + ImportBindingIsString: ({ + importName + }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`, + ImportCallArity: `\`import()\` requires exactly one or two arguments.`, + ImportCallNotNewExpression: "Cannot use new with import(...).", + ImportCallSpreadArgument: "`...` is not allowed in `import()`.", + ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.", + ImportReflectionHasAssertion: "`import module x` cannot have assertions.", + ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.', + IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.", + InvalidBigIntLiteral: "Invalid BigIntLiteral.", + InvalidCodePoint: "Code point out of bounds.", + InvalidCoverDiscardElement: "'void' must be followed by an expression when not used in a binding position.", + InvalidCoverInitializedName: "Invalid shorthand property initializer.", + InvalidDecimal: "Invalid decimal.", + InvalidDigit: ({ + radix + }) => `Expected number in radix ${radix}.`, + InvalidEscapeSequence: "Bad character escape sequence.", + InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.", + InvalidEscapedReservedWord: ({ + reservedWord + }) => `Escape sequence in keyword ${reservedWord}.`, + InvalidIdentifier: ({ + identifierName + }) => `Invalid identifier ${identifierName}.`, + InvalidLhs: ({ + ancestor + }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`, + InvalidLhsBinding: ({ + ancestor + }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`, + InvalidLhsOptionalChaining: ({ + ancestor + }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`, + InvalidNumber: "Invalid number.", + InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.", + InvalidOrUnexpectedToken: ({ + unexpected + }) => `Unexpected character '${unexpected}'.`, + InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.", + InvalidPrivateFieldResolution: ({ + identifierName + }) => `Private name #${identifierName} is not defined.`, + InvalidPropertyBindingPattern: "Binding member expression.", + InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.", + InvalidRestAssignmentPattern: "Invalid rest operator's argument.", + LabelRedeclaration: ({ + labelName + }) => `Label '${labelName}' is already declared.`, + LetInLexicalBinding: "'let' is disallowed as a lexically bound name.", + LineTerminatorBeforeArrow: "No line break is allowed before '=>'.", + MalformedRegExpFlags: "Invalid regular expression flag.", + MissingClassName: "A class name is required.", + MissingEqInAssignment: "Only '=' operator can be used for specifying default value.", + MissingSemicolon: "Missing semicolon.", + MissingPlugin: ({ + missingPlugin + }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, + MissingOneOfPlugins: ({ + missingPlugin + }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, + MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.", + MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.", + ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.", + ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.", + ModuleAttributesWithDuplicateKeys: ({ + key + }) => `Duplicate key "${key}" is not allowed in module attributes.`, + ModuleExportNameHasLoneSurrogate: ({ + surrogateCharCode + }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`, + ModuleExportUndefined: ({ + localName + }) => `Export '${localName}' is not defined.`, + MultipleDefaultsInSwitch: "Multiple default clauses.", + NewlineAfterThrow: "Illegal newline after throw.", + NoCatchOrFinally: "Missing catch or finally clause.", + NumberIdentifier: "Identifier directly after number.", + NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.", + ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.", + OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.", + OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.", + OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.", + ParamDupe: "Argument name clash.", + PatternHasAccessor: "Object pattern can't contain getter or setter.", + PatternHasMethod: "Object pattern can't contain methods.", + PrivateInExpectedIn: ({ + identifierName + }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`, + PrivateNameRedeclaration: ({ + identifierName + }) => `Duplicate private name #${identifierName}.`, + RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + RecordNoProto: "'__proto__' is not allowed in Record expressions.", + RestTrailingComma: "Unexpected trailing comma after rest element.", + SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.", + SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.", + SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.', + StaticPrototype: "Classes may not have static property named prototype.", + SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?", + SuperPrivateField: "Private fields can't be accessed on super.", + TrailingDecorator: "Decorators must be attached to a class element.", + TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.", + UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.', + UnexpectedDigitAfterHash: "Unexpected digit after hash token.", + UnexpectedImportExport: "'import' and 'export' may only appear at the top level.", + UnexpectedKeyword: ({ + keyword + }) => `Unexpected keyword '${keyword}'.`, + UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.", + UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.", + UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.", + UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.", + UnexpectedPrivateField: "Unexpected private name.", + UnexpectedReservedWord: ({ + reservedWord + }) => `Unexpected reserved word '${reservedWord}'.`, + UnexpectedSuper: "'super' is only allowed in object methods and classes.", + UnexpectedToken: ({ + expected, + unexpected + }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`, + UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.", + UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.", + UnexpectedVoidPattern: "Unexpected void binding.", + UnsupportedBind: "Binding should be performed on object property.", + UnsupportedDecoratorExport: "A decorated export must export a class declaration.", + UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.", + UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.", + UnsupportedMetaProperty: ({ + target, + onlyValidPropertyName + }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`, + UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.", + UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.", + UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).", + UnterminatedComment: "Unterminated comment.", + UnterminatedRegExp: "Unterminated regular expression.", + UnterminatedString: "Unterminated string constant.", + UnterminatedTemplate: "Unterminated template.", + UsingDeclarationExport: "Using declaration cannot be exported.", + UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.", + VarRedeclaration: ({ + identifierName + }) => `Identifier '${identifierName}' has already been declared.`, + VoidPatternCatchClauseParam: "A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.", + VoidPatternInitializer: "A void binding may not have an initializer.", + YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.", + YieldInParameter: "Yield expression is not allowed in formal parameters.", + YieldNotInGeneratorFunction: "'yield' is only allowed within generator functions.", + ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0." +}; +var StrictModeErrors = { + StrictDelete: "Deleting local variable in strict mode.", + StrictEvalArguments: ({ + referenceName + }) => `Assigning to '${referenceName}' in strict mode.`, + StrictEvalArgumentsBinding: ({ + bindingName + }) => `Binding '${bindingName}' in strict mode.`, + StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.", + StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.", + StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.", + StrictWith: "'with' in strict mode." +}; +var ParseExpressionErrors = { + ParseExpressionEmptyInput: "Unexpected parseExpression() input: The input is empty or contains only comments.", + ParseExpressionExpectsEOF: ({ + unexpected + }) => `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(unexpected)}\`.` +}; +const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]); +var PipelineOperatorErrors = Object.assign({ + PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.", + PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.', + PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.", + PipeTopicUnconfiguredToken: ({ + token + }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`, + PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.", + PipeUnparenthesizedBody: ({ + type + }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({ + type + })}; please wrap it in parentheses.` +}, { + PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.', + PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.", + PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.", + PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.", + PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.", + PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.' +}); +const _excluded = ["message"]; +function defineHidden(obj, key, value) { + Object.defineProperty(obj, key, { + enumerable: false, + configurable: true, + value + }); +} +function toParseErrorConstructor({ + toMessage, + code, + reasonCode, + syntaxPlugin +}) { + const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins"; + const oldReasonCodes = { + AccessorCannotDeclareThisParameter: "AccesorCannotDeclareThisParameter", + AccessorCannotHaveTypeParameters: "AccesorCannotHaveTypeParameters", + ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference", + SetAccessorCannotHaveOptionalParameter: "SetAccesorCannotHaveOptionalParameter", + SetAccessorCannotHaveRestParameter: "SetAccesorCannotHaveRestParameter", + SetAccessorCannotHaveReturnType: "SetAccesorCannotHaveReturnType" + }; + if (oldReasonCodes[reasonCode]) { + reasonCode = oldReasonCodes[reasonCode]; + } + return function constructor(loc, details) { + const error = new SyntaxError(); + error.code = code; + error.reasonCode = reasonCode; + error.loc = loc; + error.pos = loc.index; + error.syntaxPlugin = syntaxPlugin; + if (hasMissingPlugin) { + error.missingPlugin = details.missingPlugin; + } + defineHidden(error, "clone", function clone(overrides = {}) { + var _overrides$loc; + const { + line, + column, + index + } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc; + return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details)); + }); + defineHidden(error, "details", details); + Object.defineProperty(error, "message", { + configurable: true, + get() { + const message = `${toMessage(details)} (${loc.line}:${loc.column})`; + this.message = message; + return message; + }, + set(value) { + Object.defineProperty(this, "message", { + value, + writable: true + }); + } + }); + return error; + }; +} +function ParseErrorEnum(argument, syntaxPlugin) { + if (Array.isArray(argument)) { + return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]); + } + const ParseErrorConstructors = {}; + for (const reasonCode of Object.keys(argument)) { + const template = argument[reasonCode]; + const _ref = typeof template === "string" ? { + message: () => template + } : typeof template === "function" ? { + message: template + } : template, + { + message + } = _ref, + rest = _objectWithoutPropertiesLoose(_ref, _excluded); + const toMessage = typeof message === "string" ? () => message : message; + ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({ + code: "BABEL_PARSER_SYNTAX_ERROR", + reasonCode, + toMessage + }, syntaxPlugin ? { + syntaxPlugin + } : {}, rest)); + } + return ParseErrorConstructors; +} +const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum(ParseExpressionErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors)); +function createDefaultOptions() { + return { + sourceType: "script", + sourceFilename: undefined, + startIndex: 0, + startColumn: 0, + startLine: 1, + allowAwaitOutsideFunction: false, + allowReturnOutsideFunction: false, + allowNewTargetOutsideFunction: false, + allowImportExportEverywhere: false, + allowSuperOutsideMethod: false, + allowUndeclaredExports: false, + allowYieldOutsideFunction: false, + plugins: [], + strictMode: undefined, + ranges: false, + tokens: false, + createImportExpressions: false, + createParenthesizedExpressions: false, + errorRecovery: false, + attachComment: true, + annexB: true + }; +} +function getOptions(opts) { + const options = createDefaultOptions(); + if (opts == null) { + return options; + } + if (opts.annexB != null && opts.annexB !== false) { + throw new Error("The `annexB` option can only be set to `false`."); + } + for (const key of Object.keys(options)) { + if (opts[key] != null) options[key] = opts[key]; + } + if (options.startLine === 1) { + if (opts.startIndex == null && options.startColumn > 0) { + options.startIndex = options.startColumn; + } else if (opts.startColumn == null && options.startIndex > 0) { + options.startColumn = options.startIndex; + } + } else if (opts.startColumn == null || opts.startIndex == null) { + if (opts.startIndex != null) { + throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`."); + } + } + if (options.sourceType === "commonjs") { + if (opts.allowAwaitOutsideFunction != null) { + throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`."); + } + if (opts.allowReturnOutsideFunction != null) { + throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`."); + } + if (opts.allowNewTargetOutsideFunction != null) { + throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`."); + } + } + return options; +} +const { + defineProperty +} = Object; +const toUnenumerable = (object, key) => { + if (object) { + defineProperty(object, key, { + enumerable: false, + value: object[key] + }); + } +}; +function toESTreeLocation(node) { + toUnenumerable(node.loc.start, "index"); + toUnenumerable(node.loc.end, "index"); + return node; +} +var estree = superClass => class ESTreeParserMixin extends superClass { + parse() { + const file = toESTreeLocation(super.parse()); + if (this.optionFlags & 256) { + file.tokens = file.tokens.map(toESTreeLocation); + } + return file; + } + parseRegExpLiteral({ + pattern, + flags + }) { + let regex = null; + try { + regex = new RegExp(pattern, flags); + } catch (_) {} + const node = this.estreeParseLiteral(regex); + node.regex = { + pattern, + flags + }; + return node; + } + parseBigIntLiteral(value) { + let bigInt; + try { + bigInt = BigInt(value); + } catch (_unused) { + bigInt = null; + } + const node = this.estreeParseLiteral(bigInt); + node.bigint = String(node.value || value); + return node; + } + parseDecimalLiteral(value) { + const decimal = null; + const node = this.estreeParseLiteral(decimal); + node.decimal = String(node.value || value); + return node; + } + estreeParseLiteral(value) { + return this.parseLiteral(value, "Literal"); + } + parseStringLiteral(value) { + return this.estreeParseLiteral(value); + } + parseNumericLiteral(value) { + return this.estreeParseLiteral(value); + } + parseNullLiteral() { + return this.estreeParseLiteral(null); + } + parseBooleanLiteral(value) { + return this.estreeParseLiteral(value); + } + estreeParseChainExpression(node, endLoc) { + const chain = this.startNodeAtNode(node); + chain.expression = node; + return this.finishNodeAt(chain, "ChainExpression", endLoc); + } + directiveToStmt(directive) { + const expression = directive.value; + delete directive.value; + this.castNodeTo(expression, "Literal"); + expression.raw = expression.extra.raw; + expression.value = expression.extra.expressionValue; + const stmt = this.castNodeTo(directive, "ExpressionStatement"); + stmt.expression = expression; + stmt.directive = expression.extra.rawValue; + delete expression.extra; + return stmt; + } + fillOptionalPropertiesForTSESLint(node) {} + cloneEstreeStringLiteral(node) { + const { + start, + end, + loc, + range, + raw, + value + } = node; + const cloned = Object.create(node.constructor.prototype); + cloned.type = "Literal"; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.raw = raw; + cloned.value = value; + return cloned; + } + initFunction(node, isAsync) { + super.initFunction(node, isAsync); + node.expression = false; + } + checkDeclaration(node) { + if (node != null && this.isObjectProperty(node)) { + this.checkDeclaration(node.value); + } else { + super.checkDeclaration(node); + } + } + getObjectOrClassMethodParams(method) { + return method.value.params; + } + isValidDirective(stmt) { + var _stmt$expression$extr; + return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized); + } + parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { + super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse); + const directiveStatements = node.directives.map(d => this.directiveToStmt(d)); + node.body = directiveStatements.concat(node.body); + delete node.directives; + } + parsePrivateName() { + const node = super.parsePrivateName(); + if (!this.getPluginOption("estree", "classFeatures")) { + return node; + } + return this.convertPrivateNameToPrivateIdentifier(node); + } + convertPrivateNameToPrivateIdentifier(node) { + const name = super.getPrivateNameSV(node); + delete node.id; + node.name = name; + return this.castNodeTo(node, "PrivateIdentifier"); + } + isPrivateName(node) { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.isPrivateName(node); + } + return node.type === "PrivateIdentifier"; + } + getPrivateNameSV(node) { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.getPrivateNameSV(node); + } + return node.name; + } + parseLiteral(value, type) { + const node = super.parseLiteral(value, type); + node.raw = node.extra.raw; + delete node.extra; + return node; + } + parseFunctionBody(node, allowExpression, isMethod = false) { + super.parseFunctionBody(node, allowExpression, isMethod); + node.expression = node.body.type !== "BlockStatement"; + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + let funcNode = this.startNode(); + funcNode.kind = node.kind; + funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + delete funcNode.kind; + const { + typeParameters + } = node; + if (typeParameters) { + delete node.typeParameters; + funcNode.typeParameters = typeParameters; + this.resetStartLocationFromNode(funcNode, typeParameters); + } + const valueNode = this.castNodeTo(funcNode, "FunctionExpression"); + node.value = valueNode; + if (type === "ClassPrivateMethod") { + node.computed = false; + } + if (type === "ObjectMethod") { + if (node.kind === "method") { + node.kind = "init"; + } + node.shorthand = false; + return this.finishNode(node, "Property"); + } else { + return this.finishNode(node, "MethodDefinition"); + } + } + nameIsConstructor(key) { + if (key.type === "Literal") return key.value === "constructor"; + return super.nameIsConstructor(key); + } + parseClassProperty(...args) { + const propertyNode = super.parseClassProperty(...args); + if (!this.getPluginOption("estree", "classFeatures")) { + return propertyNode; + } + this.castNodeTo(propertyNode, "PropertyDefinition"); + return propertyNode; + } + parseClassPrivateProperty(...args) { + const propertyNode = super.parseClassPrivateProperty(...args); + if (!this.getPluginOption("estree", "classFeatures")) { + return propertyNode; + } + this.castNodeTo(propertyNode, "PropertyDefinition"); + propertyNode.computed = false; + return propertyNode; + } + parseClassAccessorProperty(node) { + const accessorPropertyNode = super.parseClassAccessorProperty(node); + if (!this.getPluginOption("estree", "classFeatures")) { + return accessorPropertyNode; + } + if (accessorPropertyNode.abstract && this.hasPlugin("typescript")) { + delete accessorPropertyNode.abstract; + this.castNodeTo(accessorPropertyNode, "TSAbstractAccessorProperty"); + } else { + this.castNodeTo(accessorPropertyNode, "AccessorProperty"); + } + return accessorPropertyNode; + } + parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { + const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); + if (node) { + node.kind = "init"; + this.castNodeTo(node, "Property"); + } + return node; + } + finishObjectProperty(node) { + node.kind = "init"; + return this.finishNode(node, "Property"); + } + isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) { + return type === "Property" ? "value" : super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding); + } + isAssignable(node, isBinding) { + if (node != null && this.isObjectProperty(node)) { + return this.isAssignable(node.value, isBinding); + } + return super.isAssignable(node, isBinding); + } + toAssignable(node, isLHS = false) { + if (node != null && this.isObjectProperty(node)) { + const { + key, + value + } = node; + if (this.isPrivateName(key)) { + this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); + } + this.toAssignable(value, isLHS); + } else { + super.toAssignable(node, isLHS); + } + } + toAssignableObjectExpressionProp(prop, isLast, isLHS) { + if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) { + this.raise(Errors.PatternHasAccessor, prop.key); + } else if (prop.type === "Property" && prop.method) { + this.raise(Errors.PatternHasMethod, prop.key); + } else { + super.toAssignableObjectExpressionProp(prop, isLast, isLHS); + } + } + finishCallExpression(unfinished, optional) { + const node = super.finishCallExpression(unfinished, optional); + if (node.callee.type === "Import") { + var _ref, _ref2; + this.castNodeTo(node, "ImportExpression"); + node.source = node.arguments[0]; + node.options = (_ref = node.arguments[1]) != null ? _ref : null; + node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null; + delete node.arguments; + delete node.callee; + } else if (node.type === "OptionalCallExpression") { + this.castNodeTo(node, "CallExpression"); + } else { + node.optional = false; + } + return node; + } + toReferencedArguments(node) { + if (node.type === "ImportExpression") { + return; + } + super.toReferencedArguments(node); + } + parseExport(unfinished, decorators) { + const exportStartLoc = this.state.lastTokStartLoc; + const node = super.parseExport(unfinished, decorators); + switch (node.type) { + case "ExportAllDeclaration": + node.exported = null; + break; + case "ExportNamedDeclaration": + if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") { + this.castNodeTo(node, "ExportAllDeclaration"); + node.exported = node.specifiers[0].exported; + delete node.specifiers; + } + case "ExportDefaultDeclaration": + { + var _declaration$decorato; + const { + declaration + } = node; + if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) { + this.resetStartLocation(node, exportStartLoc); + } + } + break; + } + return node; + } + stopParseSubscript(base, state) { + const node = super.stopParseSubscript(base, state); + if (state.optionalChainMember) { + return this.estreeParseChainExpression(node, base.loc.end); + } + return node; + } + parseMember(base, startLoc, state, computed, optional) { + const node = super.parseMember(base, startLoc, state, computed, optional); + if (node.type === "OptionalMemberExpression") { + this.castNodeTo(node, "MemberExpression"); + } else { + node.optional = false; + } + return node; + } + isOptionalMemberExpression(node) { + if (node.type === "ChainExpression") { + return node.expression.type === "MemberExpression"; + } + return super.isOptionalMemberExpression(node); + } + hasPropertyAsPrivateName(node) { + if (node.type === "ChainExpression") { + node = node.expression; + } + return super.hasPropertyAsPrivateName(node); + } + isObjectProperty(node) { + return node.type === "Property" && node.kind === "init" && !node.method; + } + isObjectMethod(node) { + return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set"); + } + castNodeTo(node, type) { + const result = super.castNodeTo(node, type); + this.fillOptionalPropertiesForTSESLint(result); + return result; + } + cloneIdentifier(node) { + const cloned = super.cloneIdentifier(node); + this.fillOptionalPropertiesForTSESLint(cloned); + return cloned; + } + cloneStringLiteral(node) { + if (node.type === "Literal") { + return this.cloneEstreeStringLiteral(node); + } + return super.cloneStringLiteral(node); + } + finishNodeAt(node, type, endLoc) { + return toESTreeLocation(super.finishNodeAt(node, type, endLoc)); + } + finishNode(node, type) { + const result = super.finishNode(node, type); + this.fillOptionalPropertiesForTSESLint(result); + return result; + } + resetStartLocation(node, startLoc) { + super.resetStartLocation(node, startLoc); + toESTreeLocation(node); + } + resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { + super.resetEndLocation(node, endLoc); + toESTreeLocation(node); + } +}; +class TokContext { + constructor(token, preserveSpace) { + this.token = void 0; + this.preserveSpace = void 0; + this.token = token; + this.preserveSpace = !!preserveSpace; + } +} +const types = { + brace: new TokContext("{"), + j_oTag: new TokContext("...", true) +}; +types.template = new TokContext("`", true); +const beforeExpr = true; +const startsExpr = true; +const isLoop = true; +const isAssign = true; +const prefix = true; +const postfix = true; +class ExportedTokenType { + constructor(label, conf = {}) { + this.label = void 0; + this.keyword = void 0; + this.beforeExpr = void 0; + this.startsExpr = void 0; + this.rightAssociative = void 0; + this.isLoop = void 0; + this.isAssign = void 0; + this.prefix = void 0; + this.postfix = void 0; + this.binop = void 0; + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.rightAssociative = !!conf.rightAssociative; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop != null ? conf.binop : null; + this.updateContext = null; + } +} +const keywords$1 = new Map(); +function createKeyword(name, options = {}) { + options.keyword = name; + const token = createToken(name, options); + keywords$1.set(name, token); + return token; +} +function createBinop(name, binop) { + return createToken(name, { + beforeExpr, + binop + }); +} +let tokenTypeCounter = -1; +const tokenTypes = []; +const tokenLabels = []; +const tokenBinops = []; +const tokenBeforeExprs = []; +const tokenStartsExprs = []; +const tokenPrefixes = []; +function createToken(name, options = {}) { + var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix; + ++tokenTypeCounter; + tokenLabels.push(name); + tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1); + tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false); + tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false); + tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false); + tokenTypes.push(new ExportedTokenType(name, options)); + return tokenTypeCounter; +} +function createKeywordLike(name, options = {}) { + var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2; + ++tokenTypeCounter; + keywords$1.set(name, tokenTypeCounter); + tokenLabels.push(name); + tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1); + tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false); + tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false); + tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false); + tokenTypes.push(new ExportedTokenType("name", options)); + return tokenTypeCounter; +} +const tt = { + bracketL: createToken("[", { + beforeExpr, + startsExpr + }), + bracketHashL: createToken("#[", { + beforeExpr, + startsExpr + }), + bracketBarL: createToken("[|", { + beforeExpr, + startsExpr + }), + bracketR: createToken("]"), + bracketBarR: createToken("|]"), + braceL: createToken("{", { + beforeExpr, + startsExpr + }), + braceBarL: createToken("{|", { + beforeExpr, + startsExpr + }), + braceHashL: createToken("#{", { + beforeExpr, + startsExpr + }), + braceR: createToken("}"), + braceBarR: createToken("|}"), + parenL: createToken("(", { + beforeExpr, + startsExpr + }), + parenR: createToken(")"), + comma: createToken(",", { + beforeExpr + }), + semi: createToken(";", { + beforeExpr + }), + colon: createToken(":", { + beforeExpr + }), + doubleColon: createToken("::", { + beforeExpr + }), + dot: createToken("."), + question: createToken("?", { + beforeExpr + }), + questionDot: createToken("?."), + arrow: createToken("=>", { + beforeExpr + }), + template: createToken("template"), + ellipsis: createToken("...", { + beforeExpr + }), + backQuote: createToken("`", { + startsExpr + }), + dollarBraceL: createToken("${", { + beforeExpr, + startsExpr + }), + templateTail: createToken("...`", { + startsExpr + }), + templateNonTail: createToken("...${", { + beforeExpr, + startsExpr + }), + at: createToken("@"), + hash: createToken("#", { + startsExpr + }), + interpreterDirective: createToken("#!..."), + eq: createToken("=", { + beforeExpr, + isAssign + }), + assign: createToken("_=", { + beforeExpr, + isAssign + }), + slashAssign: createToken("_=", { + beforeExpr, + isAssign + }), + xorAssign: createToken("_=", { + beforeExpr, + isAssign + }), + moduloAssign: createToken("_=", { + beforeExpr, + isAssign + }), + incDec: createToken("++/--", { + prefix, + postfix, + startsExpr + }), + bang: createToken("!", { + beforeExpr, + prefix, + startsExpr + }), + tilde: createToken("~", { + beforeExpr, + prefix, + startsExpr + }), + doubleCaret: createToken("^^", { + startsExpr + }), + doubleAt: createToken("@@", { + startsExpr + }), + pipeline: createBinop("|>", 0), + nullishCoalescing: createBinop("??", 1), + logicalOR: createBinop("||", 1), + logicalAND: createBinop("&&", 2), + bitwiseOR: createBinop("|", 3), + bitwiseXOR: createBinop("^", 4), + bitwiseAND: createBinop("&", 5), + equality: createBinop("==/!=/===/!==", 6), + lt: createBinop("/<=/>=", 7), + gt: createBinop("/<=/>=", 7), + relational: createBinop("/<=/>=", 7), + bitShift: createBinop("<>/>>>", 8), + bitShiftL: createBinop("<>/>>>", 8), + bitShiftR: createBinop("<>/>>>", 8), + plusMin: createToken("+/-", { + beforeExpr, + binop: 9, + prefix, + startsExpr + }), + modulo: createToken("%", { + binop: 10, + startsExpr + }), + star: createToken("*", { + binop: 10 + }), + slash: createBinop("/", 10), + exponent: createToken("**", { + beforeExpr, + binop: 11, + rightAssociative: true + }), + _in: createKeyword("in", { + beforeExpr, + binop: 7 + }), + _instanceof: createKeyword("instanceof", { + beforeExpr, + binop: 7 + }), + _break: createKeyword("break"), + _case: createKeyword("case", { + beforeExpr + }), + _catch: createKeyword("catch"), + _continue: createKeyword("continue"), + _debugger: createKeyword("debugger"), + _default: createKeyword("default", { + beforeExpr + }), + _else: createKeyword("else", { + beforeExpr + }), + _finally: createKeyword("finally"), + _function: createKeyword("function", { + startsExpr + }), + _if: createKeyword("if"), + _return: createKeyword("return", { + beforeExpr + }), + _switch: createKeyword("switch"), + _throw: createKeyword("throw", { + beforeExpr, + prefix, + startsExpr + }), + _try: createKeyword("try"), + _var: createKeyword("var"), + _const: createKeyword("const"), + _with: createKeyword("with"), + _new: createKeyword("new", { + beforeExpr, + startsExpr + }), + _this: createKeyword("this", { + startsExpr + }), + _super: createKeyword("super", { + startsExpr + }), + _class: createKeyword("class", { + startsExpr + }), + _extends: createKeyword("extends", { + beforeExpr + }), + _export: createKeyword("export"), + _import: createKeyword("import", { + startsExpr + }), + _null: createKeyword("null", { + startsExpr + }), + _true: createKeyword("true", { + startsExpr + }), + _false: createKeyword("false", { + startsExpr + }), + _typeof: createKeyword("typeof", { + beforeExpr, + prefix, + startsExpr + }), + _void: createKeyword("void", { + beforeExpr, + prefix, + startsExpr + }), + _delete: createKeyword("delete", { + beforeExpr, + prefix, + startsExpr + }), + _do: createKeyword("do", { + isLoop, + beforeExpr + }), + _for: createKeyword("for", { + isLoop + }), + _while: createKeyword("while", { + isLoop + }), + _as: createKeywordLike("as", { + startsExpr + }), + _assert: createKeywordLike("assert", { + startsExpr + }), + _async: createKeywordLike("async", { + startsExpr + }), + _await: createKeywordLike("await", { + startsExpr + }), + _defer: createKeywordLike("defer", { + startsExpr + }), + _from: createKeywordLike("from", { + startsExpr + }), + _get: createKeywordLike("get", { + startsExpr + }), + _let: createKeywordLike("let", { + startsExpr + }), + _meta: createKeywordLike("meta", { + startsExpr + }), + _of: createKeywordLike("of", { + startsExpr + }), + _sent: createKeywordLike("sent", { + startsExpr + }), + _set: createKeywordLike("set", { + startsExpr + }), + _source: createKeywordLike("source", { + startsExpr + }), + _static: createKeywordLike("static", { + startsExpr + }), + _using: createKeywordLike("using", { + startsExpr + }), + _yield: createKeywordLike("yield", { + startsExpr + }), + _asserts: createKeywordLike("asserts", { + startsExpr + }), + _checks: createKeywordLike("checks", { + startsExpr + }), + _exports: createKeywordLike("exports", { + startsExpr + }), + _global: createKeywordLike("global", { + startsExpr + }), + _implements: createKeywordLike("implements", { + startsExpr + }), + _intrinsic: createKeywordLike("intrinsic", { + startsExpr + }), + _infer: createKeywordLike("infer", { + startsExpr + }), + _is: createKeywordLike("is", { + startsExpr + }), + _mixins: createKeywordLike("mixins", { + startsExpr + }), + _proto: createKeywordLike("proto", { + startsExpr + }), + _require: createKeywordLike("require", { + startsExpr + }), + _satisfies: createKeywordLike("satisfies", { + startsExpr + }), + _keyof: createKeywordLike("keyof", { + startsExpr + }), + _readonly: createKeywordLike("readonly", { + startsExpr + }), + _unique: createKeywordLike("unique", { + startsExpr + }), + _abstract: createKeywordLike("abstract", { + startsExpr + }), + _declare: createKeywordLike("declare", { + startsExpr + }), + _enum: createKeywordLike("enum", { + startsExpr + }), + _module: createKeywordLike("module", { + startsExpr + }), + _namespace: createKeywordLike("namespace", { + startsExpr + }), + _interface: createKeywordLike("interface", { + startsExpr + }), + _type: createKeywordLike("type", { + startsExpr + }), + _opaque: createKeywordLike("opaque", { + startsExpr + }), + name: createToken("name", { + startsExpr + }), + placeholder: createToken("%%", { + startsExpr + }), + string: createToken("string", { + startsExpr + }), + num: createToken("num", { + startsExpr + }), + bigint: createToken("bigint", { + startsExpr + }), + decimal: createToken("decimal", { + startsExpr + }), + regexp: createToken("regexp", { + startsExpr + }), + privateName: createToken("#name", { + startsExpr + }), + eof: createToken("eof"), + jsxName: createToken("jsxName"), + jsxText: createToken("jsxText", { + beforeExpr + }), + jsxTagStart: createToken("jsxTagStart", { + startsExpr + }), + jsxTagEnd: createToken("jsxTagEnd") +}; +function tokenIsIdentifier(token) { + return token >= 93 && token <= 133; +} +function tokenKeywordOrIdentifierIsKeyword(token) { + return token <= 92; +} +function tokenIsKeywordOrIdentifier(token) { + return token >= 58 && token <= 133; +} +function tokenIsLiteralPropertyName(token) { + return token >= 58 && token <= 137; +} +function tokenComesBeforeExpression(token) { + return tokenBeforeExprs[token]; +} +function tokenCanStartExpression(token) { + return tokenStartsExprs[token]; +} +function tokenIsAssignment(token) { + return token >= 29 && token <= 33; +} +function tokenIsFlowInterfaceOrTypeOrOpaque(token) { + return token >= 129 && token <= 131; +} +function tokenIsLoop(token) { + return token >= 90 && token <= 92; +} +function tokenIsKeyword(token) { + return token >= 58 && token <= 92; +} +function tokenIsOperator(token) { + return token >= 39 && token <= 59; +} +function tokenIsPostfix(token) { + return token === 34; +} +function tokenIsPrefix(token) { + return tokenPrefixes[token]; +} +function tokenIsTSTypeOperator(token) { + return token >= 121 && token <= 123; +} +function tokenIsTSDeclarationStart(token) { + return token >= 124 && token <= 130; +} +function tokenLabelName(token) { + return tokenLabels[token]; +} +function tokenOperatorPrecedence(token) { + return tokenBinops[token]; +} +function tokenIsRightAssociative(token) { + return token === 57; +} +function tokenIsTemplate(token) { + return token >= 24 && token <= 25; +} +function getExportedToken(token) { + return tokenTypes[token]; +} +tokenTypes[8].updateContext = context => { + context.pop(); +}; +tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => { + context.push(types.brace); +}; +tokenTypes[22].updateContext = context => { + if (context[context.length - 1] === types.template) { + context.pop(); + } else { + context.push(types.template); + } +}; +tokenTypes[143].updateContext = context => { + context.push(types.j_expr, types.j_oTag); +}; +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088f\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5c\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdc-\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7dc\ua7f1-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1add\u1ae0-\u1aeb\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; +function isInAstralSet(code, set) { + let pos = 0x10000; + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + return false; +} +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes); +} +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +} +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} +function isKeyword(word) { + return keywords.has(word); +} +function isIteratorStart(current, next, next2) { + return current === 64 && next === 64 && isIdentifierStart(next2); +} +const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]); +function canBeReservedWord(word) { + return reservedWordLikeSet.has(word); +} +class Scope { + constructor(flags) { + this.flags = 0; + this.names = new Map(); + this.firstLexicalName = ""; + this.flags = flags; + } +} +class ScopeHandler { + constructor(parser, inModule) { + this.parser = void 0; + this.scopeStack = []; + this.inModule = void 0; + this.undefinedExports = new Map(); + this.parser = parser; + this.inModule = inModule; + } + get inTopLevel() { + return (this.currentScope().flags & 1) > 0; + } + get inFunction() { + return (this.currentVarScopeFlags() & 2) > 0; + } + get allowSuper() { + return (this.currentThisScopeFlags() & 16) > 0; + } + get allowDirectSuper() { + return (this.currentThisScopeFlags() & 32) > 0; + } + get allowNewTarget() { + return (this.currentThisScopeFlags() & 512) > 0; + } + get inClass() { + return (this.currentThisScopeFlags() & 64) > 0; + } + get inClassAndNotInNonArrowFunction() { + const flags = this.currentThisScopeFlags(); + return (flags & 64) > 0 && (flags & 2) === 0; + } + get inStaticBlock() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & 128) { + return true; + } + if (flags & (1667 | 64)) { + return false; + } + } + } + get inNonArrowFunction() { + return (this.currentThisScopeFlags() & 2) > 0; + } + get inBareCaseStatement() { + return (this.currentScope().flags & 256) > 0; + } + get treatFunctionsAsVar() { + return this.treatFunctionsAsVarInScope(this.currentScope()); + } + createScope(flags) { + return new Scope(flags); + } + enter(flags) { + this.scopeStack.push(this.createScope(flags)); + } + exit() { + const scope = this.scopeStack.pop(); + return scope.flags; + } + treatFunctionsAsVarInScope(scope) { + return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1); + } + declareName(name, bindingType, loc) { + let scope = this.currentScope(); + if (bindingType & 8 || bindingType & 16) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + let type = scope.names.get(name) || 0; + if (bindingType & 16) { + type = type | 4; + } else { + if (!scope.firstLexicalName) { + scope.firstLexicalName = name; + } + type = type | 2; + } + scope.names.set(name, type); + if (bindingType & 8) { + this.maybeExportDefined(scope, name); + } + } else if (bindingType & 4) { + for (let i = this.scopeStack.length - 1; i >= 0; --i) { + scope = this.scopeStack[i]; + this.checkRedeclarationInScope(scope, name, bindingType, loc); + scope.names.set(name, (scope.names.get(name) || 0) | 1); + this.maybeExportDefined(scope, name); + if (scope.flags & 1667) break; + } + } + if (this.parser.inModule && scope.flags & 1) { + this.undefinedExports.delete(name); + } + } + maybeExportDefined(scope, name) { + if (this.parser.inModule && scope.flags & 1) { + this.undefinedExports.delete(name); + } + } + checkRedeclarationInScope(scope, name, bindingType, loc) { + if (this.isRedeclaredInScope(scope, name, bindingType)) { + this.parser.raise(Errors.VarRedeclaration, loc, { + identifierName: name + }); + } + } + isRedeclaredInScope(scope, name, bindingType) { + if (!(bindingType & 1)) return false; + if (bindingType & 8) { + return scope.names.has(name); + } + const type = scope.names.get(name) || 0; + if (bindingType & 16) { + return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0; + } + return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0; + } + checkLocalExport(id) { + const { + name + } = id; + const topLevelScope = this.scopeStack[0]; + if (!topLevelScope.names.has(name)) { + this.undefinedExports.set(name, id.loc.start); + } + } + currentScope() { + return this.scopeStack[this.scopeStack.length - 1]; + } + currentVarScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & 1667) { + return flags; + } + } + } + currentThisScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & (1667 | 64) && !(flags & 4)) { + return flags; + } + } + } +} +class FlowScope extends Scope { + constructor(...args) { + super(...args); + this.declareFunctions = new Set(); + } +} +class FlowScopeHandler extends ScopeHandler { + createScope(flags) { + return new FlowScope(flags); + } + declareName(name, bindingType, loc) { + const scope = this.currentScope(); + if (bindingType & 2048) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + this.maybeExportDefined(scope, name); + scope.declareFunctions.add(name); + return; + } + super.declareName(name, bindingType, loc); + } + isRedeclaredInScope(scope, name, bindingType) { + if (super.isRedeclaredInScope(scope, name, bindingType)) return true; + if (bindingType & 2048 && !scope.declareFunctions.has(name)) { + const type = scope.names.get(name); + return (type & 4) > 0 || (type & 2) > 0; + } + return false; + } + checkLocalExport(id) { + if (!this.scopeStack[0].declareFunctions.has(id.name)) { + super.checkLocalExport(id); + } + } +} +const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]); +const FlowErrors = ParseErrorEnum`flow`({ + AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.", + AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.", + AssignReservedType: ({ + reservedType + }) => `Cannot overwrite reserved type ${reservedType}.`, + DeclareClassElement: "The `declare` modifier can only appear on class fields.", + DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.", + DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.", + EnumBooleanMemberNotInitialized: ({ + memberName, + enumName + }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`, + EnumDuplicateMemberName: ({ + memberName, + enumName + }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`, + EnumInconsistentMemberValues: ({ + enumName + }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`, + EnumInvalidExplicitType: ({ + invalidEnumType, + enumName + }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, + EnumInvalidExplicitTypeUnknownSupplied: ({ + enumName + }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, + EnumInvalidMemberInitializerPrimaryType: ({ + enumName, + memberName, + explicitType + }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`, + EnumInvalidMemberInitializerSymbolType: ({ + enumName, + memberName + }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`, + EnumInvalidMemberInitializerUnknownType: ({ + enumName, + memberName + }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`, + EnumInvalidMemberName: ({ + enumName, + memberName, + suggestion + }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`, + EnumNumberMemberNotInitialized: ({ + enumName, + memberName + }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`, + EnumStringMemberInconsistentlyInitialized: ({ + enumName + }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`, + GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.", + ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.", + ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.", + InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.", + InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.", + InexactVariance: "Explicit inexact syntax cannot have variance.", + InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.", + MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.", + NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.", + NestedFlowComment: "Cannot have a flow comment inside another flow comment.", + PatternIsOptional: Object.assign({ + message: "A binding pattern parameter cannot be optional in an implementation signature." + }, { + reasonCode: "OptionalBindingPattern" + }), + SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.", + SpreadVariance: "Spread properties cannot have variance.", + ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.", + ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.", + ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.", + ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.", + ThisParamNoDefault: "The `this` parameter may not have a default value.", + TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.", + UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.", + UnexpectedReservedType: ({ + reservedType + }) => `Unexpected reserved type ${reservedType}.`, + UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.", + UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.", + UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.", + UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".', + UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.", + UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of ` async () => {}`, use `async () => {}`.", + UnsupportedDeclareExportKind: ({ + unsupportedExportKind, + suggestion + }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`, + UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.", + UnterminatedFlowComment: "Unterminated flow-comment." +}); +function isEsModuleType(bodyElement) { + return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration"); +} +function hasTypeImportKind(node) { + return node.importKind === "type" || node.importKind === "typeof"; +} +const exportSuggestions = { + const: "declare export var", + let: "declare export var", + type: "export type", + interface: "export interface" +}; +function partition(list, test) { + const list1 = []; + const list2 = []; + for (let i = 0; i < list.length; i++) { + (test(list[i], i, list) ? list1 : list2).push(list[i]); + } + return [list1, list2]; +} +const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; +var flow = superClass => class FlowParserMixin extends superClass { + constructor(...args) { + super(...args); + this.flowPragma = undefined; + } + getScopeHandler() { + return FlowScopeHandler; + } + shouldParseTypes() { + return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; + } + finishToken(type, val) { + if (type !== 134 && type !== 13 && type !== 28) { + if (this.flowPragma === undefined) { + this.flowPragma = null; + } + } + super.finishToken(type, val); + } + addComment(comment) { + if (this.flowPragma === undefined) { + const matches = FLOW_PRAGMA_REGEX.exec(comment.value); + if (!matches) ;else if (matches[1] === "flow") { + this.flowPragma = "flow"; + } else if (matches[1] === "noflow") { + this.flowPragma = "noflow"; + } else { + throw new Error("Unexpected flow pragma"); + } + } + super.addComment(comment); + } + flowParseTypeInitialiser(tok) { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(tok || 14); + const type = this.flowParseType(); + this.state.inType = oldInType; + return type; + } + flowParsePredicate() { + const node = this.startNode(); + const moduloLoc = this.state.startLoc; + this.next(); + this.expectContextual(110); + if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) { + this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc); + } + if (this.eat(10)) { + node.value = super.parseExpression(); + this.expect(11); + return this.finishNode(node, "DeclaredPredicate"); + } else { + return this.finishNode(node, "InferredPredicate"); + } + } + flowParseTypeAndPredicateInitialiser() { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(14); + let type = null; + let predicate = null; + if (this.match(54)) { + this.state.inType = oldInType; + predicate = this.flowParsePredicate(); + } else { + type = this.flowParseType(); + this.state.inType = oldInType; + if (this.match(54)) { + predicate = this.flowParsePredicate(); + } + } + return [type, predicate]; + } + flowParseDeclareClass(node) { + this.next(); + this.flowParseInterfaceish(node, true); + return this.finishNode(node, "DeclareClass"); + } + flowParseDeclareFunction(node) { + this.next(); + const id = node.id = this.parseIdentifier(); + const typeNode = this.startNode(); + const typeContainer = this.startNode(); + if (this.match(47)) { + typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + typeNode.typeParameters = null; + } + this.expect(10); + const tmp = this.flowParseFunctionTypeParams(); + typeNode.params = tmp.params; + typeNode.rest = tmp.rest; + typeNode.this = tmp._this; + this.expect(11); + [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); + id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); + this.resetEndLocation(id); + this.semicolon(); + this.scope.declareName(node.id.name, 2048, node.id.loc.start); + return this.finishNode(node, "DeclareFunction"); + } + flowParseDeclare(node, insideModule) { + if (this.match(80)) { + return this.flowParseDeclareClass(node); + } else if (this.match(68)) { + return this.flowParseDeclareFunction(node); + } else if (this.match(74)) { + return this.flowParseDeclareVariable(node); + } else if (this.eatContextual(127)) { + if (this.match(16)) { + return this.flowParseDeclareModuleExports(node); + } else { + if (insideModule) { + this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc); + } + return this.flowParseDeclareModule(node); + } + } else if (this.isContextual(130)) { + return this.flowParseDeclareTypeAlias(node); + } else if (this.isContextual(131)) { + return this.flowParseDeclareOpaqueType(node); + } else if (this.isContextual(129)) { + return this.flowParseDeclareInterface(node); + } else if (this.match(82)) { + return this.flowParseDeclareExportDeclaration(node, insideModule); + } + throw this.unexpected(); + } + flowParseDeclareVariable(node) { + this.next(); + node.id = this.flowParseTypeAnnotatableIdentifier(true); + this.scope.declareName(node.id.name, 5, node.id.loc.start); + this.semicolon(); + return this.finishNode(node, "DeclareVariable"); + } + flowParseDeclareModule(node) { + this.scope.enter(0); + if (this.match(134)) { + node.id = super.parseExprAtom(); + } else { + node.id = this.parseIdentifier(); + } + const bodyNode = node.body = this.startNode(); + const body = bodyNode.body = []; + this.expect(5); + while (!this.match(8)) { + const bodyNode = this.startNode(); + if (this.match(83)) { + this.next(); + if (!this.isContextual(130) && !this.match(87)) { + this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc); + } + body.push(super.parseImport(bodyNode)); + } else { + this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule); + body.push(this.flowParseDeclare(bodyNode, true)); + } + } + this.scope.exit(); + this.expect(8); + this.finishNode(bodyNode, "BlockStatement"); + let kind = null; + let hasModuleExport = false; + body.forEach(bodyElement => { + if (isEsModuleType(bodyElement)) { + if (kind === "CommonJS") { + this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); + } + kind = "ES"; + } else if (bodyElement.type === "DeclareModuleExports") { + if (hasModuleExport) { + this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement); + } + if (kind === "ES") { + this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); + } + kind = "CommonJS"; + hasModuleExport = true; + } + }); + node.kind = kind || "CommonJS"; + return this.finishNode(node, "DeclareModule"); + } + flowParseDeclareExportDeclaration(node, insideModule) { + this.expect(82); + if (this.eat(65)) { + if (this.match(68) || this.match(80)) { + node.declaration = this.flowParseDeclare(this.startNode()); + } else { + node.declaration = this.flowParseType(); + this.semicolon(); + } + node.default = true; + return this.finishNode(node, "DeclareExportDeclaration"); + } else { + if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) { + const label = this.state.value; + throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, { + unsupportedExportKind: label, + suggestion: exportSuggestions[label] + }); + } + if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) { + node.declaration = this.flowParseDeclare(this.startNode()); + node.default = false; + return this.finishNode(node, "DeclareExportDeclaration"); + } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) { + node = this.parseExport(node, null); + if (node.type === "ExportNamedDeclaration") { + node.default = false; + delete node.exportKind; + return this.castNodeTo(node, "DeclareExportDeclaration"); + } else { + return this.castNodeTo(node, "DeclareExportAllDeclaration"); + } + } + } + throw this.unexpected(); + } + flowParseDeclareModuleExports(node) { + this.next(); + this.expectContextual(111); + node.typeAnnotation = this.flowParseTypeAnnotation(); + this.semicolon(); + return this.finishNode(node, "DeclareModuleExports"); + } + flowParseDeclareTypeAlias(node) { + this.next(); + const finished = this.flowParseTypeAlias(node); + this.castNodeTo(finished, "DeclareTypeAlias"); + return finished; + } + flowParseDeclareOpaqueType(node) { + this.next(); + const finished = this.flowParseOpaqueType(node, true); + this.castNodeTo(finished, "DeclareOpaqueType"); + return finished; + } + flowParseDeclareInterface(node) { + this.next(); + this.flowParseInterfaceish(node, false); + return this.finishNode(node, "DeclareInterface"); + } + flowParseInterfaceish(node, isClass) { + node.id = this.flowParseRestrictedIdentifier(!isClass, true); + this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.extends = []; + if (this.eat(81)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (!isClass && this.eat(12)); + } + if (isClass) { + node.implements = []; + node.mixins = []; + if (this.eatContextual(117)) { + do { + node.mixins.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + if (this.eatContextual(113)) { + do { + node.implements.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + } + node.body = this.flowParseObjectType({ + allowStatic: isClass, + allowExact: false, + allowSpread: false, + allowProto: isClass, + allowInexact: false + }); + } + flowParseInterfaceExtends() { + const node = this.startNode(); + node.id = this.flowParseQualifiedTypeIdentifier(); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + return this.finishNode(node, "InterfaceExtends"); + } + flowParseInterface(node) { + this.flowParseInterfaceish(node, false); + return this.finishNode(node, "InterfaceDeclaration"); + } + checkNotUnderscore(word) { + if (word === "_") { + this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc); + } + } + checkReservedType(word, startLoc, declaration) { + if (!reservedTypes.has(word)) return; + this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, { + reservedType: word + }); + } + flowParseRestrictedIdentifier(liberal, declaration) { + this.checkReservedType(this.state.value, this.state.startLoc, declaration); + return this.parseIdentifier(liberal); + } + flowParseTypeAlias(node) { + node.id = this.flowParseRestrictedIdentifier(false, true); + this.scope.declareName(node.id.name, 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.right = this.flowParseTypeInitialiser(29); + this.semicolon(); + return this.finishNode(node, "TypeAlias"); + } + flowParseOpaqueType(node, declare) { + this.expectContextual(130); + node.id = this.flowParseRestrictedIdentifier(true, true); + this.scope.declareName(node.id.name, 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.supertype = null; + if (this.match(14)) { + node.supertype = this.flowParseTypeInitialiser(14); + } + node.impltype = null; + if (!declare) { + node.impltype = this.flowParseTypeInitialiser(29); + } + this.semicolon(); + return this.finishNode(node, "OpaqueType"); + } + flowParseTypeParameter(requireDefault = false) { + const nodeStartLoc = this.state.startLoc; + const node = this.startNode(); + const variance = this.flowParseVariance(); + const ident = this.flowParseTypeAnnotatableIdentifier(); + node.name = ident.name; + node.variance = variance; + node.bound = ident.typeAnnotation; + if (this.match(29)) { + this.eat(29); + node.default = this.flowParseType(); + } else { + if (requireDefault) { + this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc); + } + } + return this.finishNode(node, "TypeParameter"); + } + flowParseTypeParameterDeclaration() { + const oldInType = this.state.inType; + const node = this.startNode(); + node.params = []; + this.state.inType = true; + if (this.match(47) || this.match(143)) { + this.next(); + } else { + this.unexpected(); + } + let defaultRequired = false; + do { + const typeParameter = this.flowParseTypeParameter(defaultRequired); + node.params.push(typeParameter); + if (typeParameter.default) { + defaultRequired = true; + } + if (!this.match(48)) { + this.expect(12); + } + } while (!this.match(48)); + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterDeclaration"); + } + flowInTopLevelContext(cb) { + if (this.curContext() !== types.brace) { + const oldContext = this.state.context; + this.state.context = [oldContext[0]]; + try { + return cb(); + } finally { + this.state.context = oldContext; + } + } else { + return cb(); + } + } + flowParseTypeParameterInstantiationInExpression() { + if (this.reScan_lt() !== 47) return; + return this.flowParseTypeParameterInstantiation(); + } + flowParseTypeParameterInstantiation() { + const node = this.startNode(); + const oldInType = this.state.inType; + this.state.inType = true; + node.params = []; + this.flowInTopLevelContext(() => { + this.expect(47); + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = false; + while (!this.match(48)) { + node.params.push(this.flowParseType()); + if (!this.match(48)) { + this.expect(12); + } + } + this.state.noAnonFunctionType = oldNoAnonFunctionType; + }); + this.state.inType = oldInType; + if (!this.state.inType && this.curContext() === types.brace) { + this.reScan_lt_gt(); + } + this.expect(48); + return this.finishNode(node, "TypeParameterInstantiation"); + } + flowParseTypeParameterInstantiationCallOrNew() { + if (this.reScan_lt() !== 47) return null; + const node = this.startNode(); + const oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expect(47); + while (!this.match(48)) { + node.params.push(this.flowParseTypeOrImplicitInstantiation()); + if (!this.match(48)) { + this.expect(12); + } + } + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + flowParseInterfaceType() { + const node = this.startNode(); + this.expectContextual(129); + node.extends = []; + if (this.eat(81)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + node.body = this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: false, + allowProto: false, + allowInexact: false + }); + return this.finishNode(node, "InterfaceTypeAnnotation"); + } + flowParseObjectPropertyKey() { + return this.match(135) || this.match(134) ? super.parseExprAtom() : this.parseIdentifier(true); + } + flowParseObjectTypeIndexer(node, isStatic, variance) { + node.static = isStatic; + if (this.lookahead().type === 14) { + node.id = this.flowParseObjectPropertyKey(); + node.key = this.flowParseTypeInitialiser(); + } else { + node.id = null; + node.key = this.flowParseType(); + } + this.expect(3); + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + return this.finishNode(node, "ObjectTypeIndexer"); + } + flowParseObjectTypeInternalSlot(node, isStatic) { + node.static = isStatic; + node.id = this.flowParseObjectPropertyKey(); + this.expect(3); + this.expect(3); + if (this.match(47) || this.match(10)) { + node.method = true; + node.optional = false; + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); + } else { + node.method = false; + if (this.eat(17)) { + node.optional = true; + } + node.value = this.flowParseTypeInitialiser(); + } + return this.finishNode(node, "ObjectTypeInternalSlot"); + } + flowParseObjectTypeMethodish(node) { + node.params = []; + node.rest = null; + node.typeParameters = null; + node.this = null; + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + this.expect(10); + if (this.match(78)) { + node.this = this.flowParseFunctionTypeParam(true); + node.this.name = null; + if (!this.match(11)) { + this.expect(12); + } + } + while (!this.match(11) && !this.match(21)) { + node.params.push(this.flowParseFunctionTypeParam(false)); + if (!this.match(11)) { + this.expect(12); + } + } + if (this.eat(21)) { + node.rest = this.flowParseFunctionTypeParam(false); + } + this.expect(11); + node.returnType = this.flowParseTypeInitialiser(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + flowParseObjectTypeCallProperty(node, isStatic) { + const valueNode = this.startNode(); + node.static = isStatic; + node.value = this.flowParseObjectTypeMethodish(valueNode); + return this.finishNode(node, "ObjectTypeCallProperty"); + } + flowParseObjectType({ + allowStatic, + allowExact, + allowSpread, + allowProto, + allowInexact + }) { + const oldInType = this.state.inType; + this.state.inType = true; + const nodeStart = this.startNode(); + nodeStart.callProperties = []; + nodeStart.properties = []; + nodeStart.indexers = []; + nodeStart.internalSlots = []; + let endDelim; + let exact; + let inexact = false; + if (allowExact && this.match(6)) { + this.expect(6); + endDelim = 9; + exact = true; + } else { + this.expect(5); + endDelim = 8; + exact = false; + } + nodeStart.exact = exact; + while (!this.match(endDelim)) { + let isStatic = false; + let protoStartLoc = null; + let inexactStartLoc = null; + const node = this.startNode(); + if (allowProto && this.isContextual(118)) { + const lookahead = this.lookahead(); + if (lookahead.type !== 14 && lookahead.type !== 17) { + this.next(); + protoStartLoc = this.state.startLoc; + allowStatic = false; + } + } + if (allowStatic && this.isContextual(106)) { + const lookahead = this.lookahead(); + if (lookahead.type !== 14 && lookahead.type !== 17) { + this.next(); + isStatic = true; + } + } + const variance = this.flowParseVariance(); + if (this.eat(0)) { + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (this.eat(0)) { + if (variance) { + this.unexpected(variance.loc.start); + } + nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic)); + } else { + nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance)); + } + } else if (this.match(10) || this.match(47)) { + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.unexpected(variance.loc.start); + } + nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic)); + } else { + let kind = "init"; + if (this.isContextual(99) || this.isContextual(104)) { + const lookahead = this.lookahead(); + if (tokenIsLiteralPropertyName(lookahead.type)) { + kind = this.state.value; + this.next(); + } + } + const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact); + if (propOrInexact === null) { + inexact = true; + inexactStartLoc = this.state.lastTokStartLoc; + } else { + nodeStart.properties.push(propOrInexact); + } + } + this.flowObjectTypeSemicolon(); + if (inexactStartLoc && !this.match(8) && !this.match(9)) { + this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc); + } + } + this.expect(endDelim); + if (allowSpread) { + nodeStart.inexact = inexact; + } + const out = this.finishNode(nodeStart, "ObjectTypeAnnotation"); + this.state.inType = oldInType; + return out; + } + flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) { + if (this.eat(21)) { + const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9); + if (isInexactToken) { + if (!allowSpread) { + this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc); + } else if (!allowInexact) { + this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc); + } + if (variance) { + this.raise(FlowErrors.InexactVariance, variance); + } + return null; + } + if (!allowSpread) { + this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc); + } + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.raise(FlowErrors.SpreadVariance, variance); + } + node.argument = this.flowParseType(); + return this.finishNode(node, "ObjectTypeSpreadProperty"); + } else { + node.key = this.flowParseObjectPropertyKey(); + node.static = isStatic; + node.proto = protoStartLoc != null; + node.kind = kind; + let optional = false; + if (this.match(47) || this.match(10)) { + node.method = true; + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.unexpected(variance.loc.start); + } + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); + if (kind === "get" || kind === "set") { + this.flowCheckGetterSetterParams(node); + } + if (!allowSpread && node.key.name === "constructor" && node.value.this) { + this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this); + } + } else { + if (kind !== "init") this.unexpected(); + node.method = false; + if (this.eat(17)) { + optional = true; + } + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + } + node.optional = optional; + return this.finishNode(node, "ObjectTypeProperty"); + } + } + flowCheckGetterSetterParams(property) { + const paramCount = property.kind === "get" ? 0 : 1; + const length = property.value.params.length + (property.value.rest ? 1 : 0); + if (property.value.this) { + this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this); + } + if (length !== paramCount) { + this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property); + } + if (property.kind === "set" && property.value.rest) { + this.raise(Errors.BadSetterRestParameter, property); + } + } + flowObjectTypeSemicolon() { + if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) { + this.unexpected(); + } + } + flowParseQualifiedTypeIdentifier(startLoc, id) { + startLoc != null ? startLoc : startLoc = this.state.startLoc; + let node = id || this.flowParseRestrictedIdentifier(true); + while (this.eat(16)) { + const node2 = this.startNodeAt(startLoc); + node2.qualification = node; + node2.id = this.flowParseRestrictedIdentifier(true); + node = this.finishNode(node2, "QualifiedTypeIdentifier"); + } + return node; + } + flowParseGenericType(startLoc, id) { + const node = this.startNodeAt(startLoc); + node.typeParameters = null; + node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } + return this.finishNode(node, "GenericTypeAnnotation"); + } + flowParseTypeofType() { + const node = this.startNode(); + this.expect(87); + node.argument = this.flowParsePrimaryType(); + return this.finishNode(node, "TypeofTypeAnnotation"); + } + flowParseTupleType() { + const node = this.startNode(); + node.types = []; + this.expect(0); + while (this.state.pos < this.length && !this.match(3)) { + node.types.push(this.flowParseType()); + if (this.match(3)) break; + this.expect(12); + } + this.expect(3); + return this.finishNode(node, "TupleTypeAnnotation"); + } + flowParseFunctionTypeParam(first) { + let name = null; + let optional = false; + let typeAnnotation = null; + const node = this.startNode(); + const lh = this.lookahead(); + const isThis = this.state.type === 78; + if (lh.type === 14 || lh.type === 17) { + if (isThis && !first) { + this.raise(FlowErrors.ThisParamMustBeFirst, node); + } + name = this.parseIdentifier(isThis); + if (this.eat(17)) { + optional = true; + if (isThis) { + this.raise(FlowErrors.ThisParamMayNotBeOptional, node); + } + } + typeAnnotation = this.flowParseTypeInitialiser(); + } else { + typeAnnotation = this.flowParseType(); + } + node.name = name; + node.optional = optional; + node.typeAnnotation = typeAnnotation; + return this.finishNode(node, "FunctionTypeParam"); + } + reinterpretTypeAsFunctionTypeParam(type) { + const node = this.startNodeAt(type.loc.start); + node.name = null; + node.optional = false; + node.typeAnnotation = type; + return this.finishNode(node, "FunctionTypeParam"); + } + flowParseFunctionTypeParams(params = []) { + let rest = null; + let _this = null; + if (this.match(78)) { + _this = this.flowParseFunctionTypeParam(true); + _this.name = null; + if (!this.match(11)) { + this.expect(12); + } + } + while (!this.match(11) && !this.match(21)) { + params.push(this.flowParseFunctionTypeParam(false)); + if (!this.match(11)) { + this.expect(12); + } + } + if (this.eat(21)) { + rest = this.flowParseFunctionTypeParam(false); + } + return { + params, + rest, + _this + }; + } + flowIdentToTypeAnnotation(startLoc, node, id) { + switch (id.name) { + case "any": + return this.finishNode(node, "AnyTypeAnnotation"); + case "bool": + case "boolean": + return this.finishNode(node, "BooleanTypeAnnotation"); + case "mixed": + return this.finishNode(node, "MixedTypeAnnotation"); + case "empty": + return this.finishNode(node, "EmptyTypeAnnotation"); + case "number": + return this.finishNode(node, "NumberTypeAnnotation"); + case "string": + return this.finishNode(node, "StringTypeAnnotation"); + case "symbol": + return this.finishNode(node, "SymbolTypeAnnotation"); + default: + this.checkNotUnderscore(id.name); + return this.flowParseGenericType(startLoc, id); + } + } + flowParsePrimaryType() { + const startLoc = this.state.startLoc; + const node = this.startNode(); + let tmp; + let type; + let isGroupedType = false; + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + switch (this.state.type) { + case 5: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: true, + allowProto: false, + allowInexact: true + }); + case 6: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: true, + allowSpread: true, + allowProto: false, + allowInexact: false + }); + case 0: + this.state.noAnonFunctionType = false; + type = this.flowParseTupleType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + return type; + case 47: + { + const node = this.startNode(); + node.typeParameters = this.flowParseTypeParameterDeclaration(); + this.expect(10); + tmp = this.flowParseFunctionTypeParams(); + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(11); + this.expect(19); + node.returnType = this.flowParseType(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + case 10: + { + const node = this.startNode(); + this.next(); + if (!this.match(11) && !this.match(21)) { + if (tokenIsIdentifier(this.state.type) || this.match(78)) { + const token = this.lookahead().type; + isGroupedType = token !== 17 && token !== 14; + } else { + isGroupedType = true; + } + } + if (isGroupedType) { + this.state.noAnonFunctionType = false; + type = this.flowParseType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) { + this.expect(11); + return type; + } else { + this.eat(12); + } + } + if (type) { + tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]); + } else { + tmp = this.flowParseFunctionTypeParams(); + } + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(11); + this.expect(19); + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + } + case 134: + return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation"); + case 85: + case 86: + node.value = this.match(85); + this.next(); + return this.finishNode(node, "BooleanLiteralTypeAnnotation"); + case 53: + if (this.state.value === "-") { + this.next(); + if (this.match(135)) { + return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node); + } + if (this.match(136)) { + return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node); + } + throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc); + } + throw this.unexpected(); + case 135: + return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); + case 136: + return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation"); + case 88: + this.next(); + return this.finishNode(node, "VoidTypeAnnotation"); + case 84: + this.next(); + return this.finishNode(node, "NullLiteralTypeAnnotation"); + case 78: + this.next(); + return this.finishNode(node, "ThisTypeAnnotation"); + case 55: + this.next(); + return this.finishNode(node, "ExistsTypeAnnotation"); + case 87: + return this.flowParseTypeofType(); + default: + if (tokenIsKeyword(this.state.type)) { + const label = tokenLabelName(this.state.type); + this.next(); + return super.createIdentifier(node, label); + } else if (tokenIsIdentifier(this.state.type)) { + if (this.isContextual(129)) { + return this.flowParseInterfaceType(); + } + return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier()); + } + } + throw this.unexpected(); + } + flowParsePostfixType() { + const startLoc = this.state.startLoc; + let type = this.flowParsePrimaryType(); + let seenOptionalIndexedAccess = false; + while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startLoc); + const optional = this.eat(18); + seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional; + this.expect(0); + if (!optional && this.match(3)) { + node.elementType = type; + this.next(); + type = this.finishNode(node, "ArrayTypeAnnotation"); + } else { + node.objectType = type; + node.indexType = this.flowParseType(); + this.expect(3); + if (seenOptionalIndexedAccess) { + node.optional = optional; + type = this.finishNode(node, "OptionalIndexedAccessType"); + } else { + type = this.finishNode(node, "IndexedAccessType"); + } + } + } + return type; + } + flowParsePrefixType() { + const node = this.startNode(); + if (this.eat(17)) { + node.typeAnnotation = this.flowParsePrefixType(); + return this.finishNode(node, "NullableTypeAnnotation"); + } else { + return this.flowParsePostfixType(); + } + } + flowParseAnonFunctionWithoutParens() { + const param = this.flowParsePrefixType(); + if (!this.state.noAnonFunctionType && this.eat(19)) { + const node = this.startNodeAt(param.loc.start); + node.params = [this.reinterpretTypeAsFunctionTypeParam(param)]; + node.rest = null; + node.this = null; + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + } + return param; + } + flowParseIntersectionType() { + const node = this.startNode(); + this.eat(45); + const type = this.flowParseAnonFunctionWithoutParens(); + node.types = [type]; + while (this.eat(45)) { + node.types.push(this.flowParseAnonFunctionWithoutParens()); + } + return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); + } + flowParseUnionType() { + const node = this.startNode(); + this.eat(43); + const type = this.flowParseIntersectionType(); + node.types = [type]; + while (this.eat(43)) { + node.types.push(this.flowParseIntersectionType()); + } + return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); + } + flowParseType() { + const oldInType = this.state.inType; + this.state.inType = true; + const type = this.flowParseUnionType(); + this.state.inType = oldInType; + return type; + } + flowParseTypeOrImplicitInstantiation() { + if (this.state.type === 132 && this.state.value === "_") { + const startLoc = this.state.startLoc; + const node = this.parseIdentifier(); + return this.flowParseGenericType(startLoc, node); + } else { + return this.flowParseType(); + } + } + flowParseTypeAnnotation() { + const node = this.startNode(); + node.typeAnnotation = this.flowParseTypeInitialiser(); + return this.finishNode(node, "TypeAnnotation"); + } + flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) { + const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); + if (this.match(14)) { + ident.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(ident); + } + return ident; + } + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); + return node.expression; + } + flowParseVariance() { + let variance = null; + if (this.match(53)) { + variance = this.startNode(); + if (this.state.value === "+") { + variance.kind = "plus"; + } else { + variance.kind = "minus"; + } + this.next(); + return this.finishNode(variance, "Variance"); + } + return variance; + } + parseFunctionBody(node, allowExpressionBody, isMethod = false) { + if (allowExpressionBody) { + this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod)); + return; + } + super.parseFunctionBody(node, false, isMethod); + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(14)) { + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; + } + return super.parseFunctionBodyAndFinish(node, type, isMethod); + } + parseStatementLike(flags) { + if (this.state.strict && this.isContextual(129)) { + const lookahead = this.lookahead(); + if (tokenIsKeywordOrIdentifier(lookahead.type)) { + const node = this.startNode(); + this.next(); + return this.flowParseInterface(node); + } + } else if (this.isContextual(126)) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + const stmt = super.parseStatementLike(flags); + if (this.flowPragma === undefined && !this.isValidDirective(stmt)) { + this.flowPragma = null; + } + return stmt; + } + parseExpressionStatement(node, expr, decorators) { + if (expr.type === "Identifier") { + if (expr.name === "declare") { + if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) { + return this.flowParseDeclare(node); + } + } else if (tokenIsIdentifier(this.state.type)) { + if (expr.name === "interface") { + return this.flowParseInterface(node); + } else if (expr.name === "type") { + return this.flowParseTypeAlias(node); + } else if (expr.name === "opaque") { + return this.flowParseOpaqueType(node, false); + } + } + } + return super.parseExpressionStatement(node, expr, decorators); + } + shouldParseExportDeclaration() { + const { + type + } = this.state; + if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) { + return !this.state.containsEsc; + } + return super.shouldParseExportDeclaration(); + } + isExportDefaultSpecifier() { + const { + type + } = this.state; + if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) { + return this.state.containsEsc; + } + return super.isExportDefaultSpecifier(); + } + parseExportDefaultExpression() { + if (this.isContextual(126)) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + return super.parseExportDefaultExpression(); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (!this.match(17)) return expr; + if (this.state.maybeInArrowParameters) { + const nextCh = this.lookaheadCharCode(); + if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) { + this.setOptionalParametersError(refExpressionErrors); + return expr; + } + } + this.expect(17); + const state = this.state.clone(); + const originalNoArrowAt = this.state.noArrowAt; + const node = this.startNodeAt(startLoc); + let { + consequent, + failed + } = this.tryParseConditionalConsequent(); + let [valid, invalid] = this.getArrowLikeExpressions(consequent); + if (failed || invalid.length > 0) { + const noArrowAt = [...originalNoArrowAt]; + if (invalid.length > 0) { + this.state = state; + this.state.noArrowAt = noArrowAt; + for (let i = 0; i < invalid.length; i++) { + noArrowAt.push(invalid[i].start); + } + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + [valid, invalid] = this.getArrowLikeExpressions(consequent); + } + if (failed && valid.length > 1) { + this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc); + } + if (failed && valid.length === 1) { + this.state = state; + noArrowAt.push(valid[0].start); + this.state.noArrowAt = noArrowAt; + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + } + } + this.getArrowLikeExpressions(consequent, true); + this.state.noArrowAt = originalNoArrowAt; + this.expect(14); + node.test = expr; + node.consequent = consequent; + node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined)); + return this.finishNode(node, "ConditionalExpression"); + } + tryParseConditionalConsequent() { + this.state.noArrowParamsConversionAt.push(this.state.start); + const consequent = this.parseMaybeAssignAllowIn(); + const failed = !this.match(14); + this.state.noArrowParamsConversionAt.pop(); + return { + consequent, + failed + }; + } + getArrowLikeExpressions(node, disallowInvalid) { + const stack = [node]; + const arrows = []; + while (stack.length !== 0) { + const node = stack.pop(); + if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") { + if (node.typeParameters || !node.returnType) { + this.finishArrowValidation(node); + } else { + arrows.push(node); + } + stack.push(node.body); + } else if (node.type === "ConditionalExpression") { + stack.push(node.consequent); + stack.push(node.alternate); + } + } + if (disallowInvalid) { + arrows.forEach(node => this.finishArrowValidation(node)); + return [arrows, []]; + } + return partition(arrows, node => node.params.every(param => this.isAssignable(param, true))); + } + finishArrowValidation(node) { + var _node$extra; + this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false); + this.scope.enter(514 | 4); + super.checkParams(node, false, true); + this.scope.exit(); + } + forwardNoArrowParamsConversionAt(node, parse) { + let result; + if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) { + this.state.noArrowParamsConversionAt.push(this.state.start); + result = parse(); + this.state.noArrowParamsConversionAt.pop(); + } else { + result = parse(); + } + return result; + } + parseParenItem(node, startLoc) { + const newNode = super.parseParenItem(node, startLoc); + if (this.eat(17)) { + newNode.optional = true; + this.resetEndLocation(node); + } + if (this.match(14)) { + const typeCastNode = this.startNodeAt(startLoc); + typeCastNode.expression = newNode; + typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TypeCastExpression"); + } + return newNode; + } + assertModuleNodeAllowed(node) { + if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") { + return; + } + super.assertModuleNodeAllowed(node); + } + parseExportDeclaration(node) { + if (this.isContextual(130)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + if (this.match(5)) { + node.specifiers = this.parseExportSpecifiers(true); + super.parseExportFrom(node); + return null; + } else { + return this.flowParseTypeAlias(declarationNode); + } + } else if (this.isContextual(131)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseOpaqueType(declarationNode, false); + } else if (this.isContextual(129)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseInterface(declarationNode); + } else if (this.isContextual(126)) { + node.exportKind = "value"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(declarationNode); + } else { + return super.parseExportDeclaration(node); + } + } + eatExportStar(node) { + if (super.eatExportStar(node)) return true; + if (this.isContextual(130) && this.lookahead().type === 55) { + node.exportKind = "type"; + this.next(); + this.next(); + return true; + } + return false; + } + maybeParseExportNamespaceSpecifier(node) { + const { + startLoc + } = this.state; + const hasNamespace = super.maybeParseExportNamespaceSpecifier(node); + if (hasNamespace && node.exportKind === "type") { + this.unexpected(startLoc); + } + return hasNamespace; + } + parseClassId(node, isStatement, optionalId) { + super.parseClassId(node, isStatement, optionalId); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + } + parseClassMember(classBody, member, state) { + const { + startLoc + } = this.state; + if (this.isContextual(125)) { + if (super.parseClassMemberFromModifier(classBody, member)) { + return; + } + member.declare = true; + } + super.parseClassMember(classBody, member, state); + if (member.declare) { + if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") { + this.raise(FlowErrors.DeclareClassElement, startLoc); + } else if (member.value) { + this.raise(FlowErrors.DeclareClassFieldInitializer, member.value); + } + } + } + isIterator(word) { + return word === "iterator" || word === "asyncIterator"; + } + readIterator() { + const word = super.readWord1(); + const fullWord = "@@" + word; + if (!this.isIterator(word) || !this.state.inType) { + this.raise(Errors.InvalidIdentifier, this.state.curPosition(), { + identifierName: fullWord + }); + } + this.finishToken(132, fullWord); + } + getTokenFromCode(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 123 && next === 124) { + this.finishOp(6, 2); + } else if (this.state.inType && (code === 62 || code === 60)) { + this.finishOp(code === 62 ? 48 : 47, 1); + } else if (this.state.inType && code === 63) { + if (next === 46) { + this.finishOp(18, 2); + } else { + this.finishOp(17, 1); + } + } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) { + this.state.pos += 2; + this.readIterator(); + } else { + super.getTokenFromCode(code); + } + } + isAssignable(node, isBinding) { + if (node.type === "TypeCastExpression") { + return this.isAssignable(node.expression, isBinding); + } else { + return super.isAssignable(node, isBinding); + } + } + toAssignable(node, isLHS = false) { + if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") { + node.left = this.typeCastToParameter(node.left); + } + super.toAssignable(node, isLHS); + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + for (let i = 0; i < exprList.length; i++) { + const expr = exprList[i]; + if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") { + exprList[i] = this.typeCastToParameter(expr); + } + } + super.toAssignableList(exprList, trailingCommaLoc, isLHS); + } + toReferencedList(exprList, isParenthesizedExpr) { + for (let i = 0; i < exprList.length; i++) { + var _expr$extra; + const expr = exprList[i]; + if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { + this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation); + } + } + return exprList; + } + parseArrayLike(close, isTuple, refExpressionErrors) { + const node = super.parseArrayLike(close, isTuple, refExpressionErrors); + if (refExpressionErrors != null && !this.state.maybeInArrowParameters) { + this.toReferencedList(node.elements); + } + return node; + } + isValidLVal(type, disallowCallExpression, isParenthesized, binding) { + return type === "TypeCastExpression" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding); + } + parseClassProperty(node) { + if (this.match(14)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + return super.parseClassProperty(node); + } + parseClassPrivateProperty(node) { + if (this.match(14)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + return super.parseClassPrivateProperty(node); + } + isClassMethod() { + return this.match(47) || super.isClassMethod(); + } + isClassProperty() { + return this.match(14) || super.isClassProperty(); + } + isNonstaticConstructor(method) { + return !this.match(14) && super.isNonstaticConstructor(method); + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + if (method.variance) { + this.unexpected(method.variance.loc.start); + } + delete method.variance; + if (this.match(47)) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + if (method.params && isConstructor) { + const params = method.params; + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(FlowErrors.ThisParamBannedInConstructor, method); + } + } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) { + const params = method.value.params; + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(FlowErrors.ThisParamBannedInConstructor, method); + } + } + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + if (method.variance) { + this.unexpected(method.variance.loc.start); + } + delete method.variance; + if (this.match(47)) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + parseClassSuper(node) { + super.parseClassSuper(node); + if (node.superClass && (this.match(47) || this.match(51))) { + node.superTypeParameters = this.flowParseTypeParameterInstantiationInExpression(); + } + if (this.isContextual(113)) { + this.next(); + const implemented = node.implements = []; + do { + const node = this.startNode(); + node.id = this.flowParseRestrictedIdentifier(true); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + implemented.push(this.finishNode(node, "ClassImplements")); + } while (this.eat(12)); + } + } + checkGetterSetterParams(method) { + super.checkGetterSetterParams(method); + const params = this.getObjectOrClassMethodParams(method); + if (params.length > 0) { + const param = params[0]; + if (this.isThisParam(param) && method.kind === "get") { + this.raise(FlowErrors.GetterMayNotHaveThisParam, param); + } else if (this.isThisParam(param)) { + this.raise(FlowErrors.SetterMayNotHaveThisParam, param); + } + } + } + parsePropertyNamePrefixOperator(node) { + node.variance = this.flowParseVariance(); + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + if (prop.variance) { + this.unexpected(prop.variance.loc.start); + } + delete prop.variance; + let typeParameters; + if (this.match(47) && !isAccessor) { + typeParameters = this.flowParseTypeParameterDeclaration(); + if (!this.match(10)) this.unexpected(); + } + const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + if (typeParameters) { + (result.value || result).typeParameters = typeParameters; + } + return result; + } + parseFunctionParamType(param) { + if (this.eat(17)) { + if (param.type !== "Identifier") { + this.raise(FlowErrors.PatternIsOptional, param); + } + if (this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamMayNotBeOptional, param); + } + param.optional = true; + } + if (this.match(14)) { + param.typeAnnotation = this.flowParseTypeAnnotation(); + } else if (this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamAnnotationRequired, param); + } + if (this.match(29) && this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamNoDefault, param); + } + this.resetEndLocation(param); + return param; + } + parseMaybeDefault(startLoc, left) { + const node = super.parseMaybeDefault(startLoc, left); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation); + } + return node; + } + checkImportReflection(node) { + super.checkImportReflection(node); + if (node.module && node.importKind !== "value") { + this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); + } + } + parseImportSpecifierLocal(node, specifier, type) { + specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier(); + node.specifiers.push(this.finishImportSpecifier(specifier, type)); + } + isPotentialImportPhase(isExport) { + if (super.isPotentialImportPhase(isExport)) return true; + if (this.isContextual(130)) { + if (!isExport) return true; + const ch = this.lookaheadCharCode(); + return ch === 123 || ch === 42; + } + return !isExport && this.isContextual(87); + } + applyImportPhase(node, isExport, phase, loc) { + super.applyImportPhase(node, isExport, phase, loc); + if (isExport) { + if (!phase && this.match(65)) { + return; + } + node.exportKind = phase === "type" ? phase : "value"; + } else { + if (phase === "type" && this.match(55)) this.unexpected(); + node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; + } + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + const firstIdent = specifier.imported; + let specifierTypeKind = null; + if (firstIdent.type === "Identifier") { + if (firstIdent.name === "type") { + specifierTypeKind = "type"; + } else if (firstIdent.name === "typeof") { + specifierTypeKind = "typeof"; + } + } + let isBinding = false; + if (this.isContextual(93) && !this.isLookaheadContextual("as")) { + const as_ident = this.parseIdentifier(true); + if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) { + specifier.imported = as_ident; + specifier.importKind = specifierTypeKind; + specifier.local = this.cloneIdentifier(as_ident); + } else { + specifier.imported = firstIdent; + specifier.importKind = null; + specifier.local = this.parseIdentifier(); + } + } else { + if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) { + specifier.imported = this.parseIdentifier(true); + specifier.importKind = specifierTypeKind; + } else { + if (importedIsString) { + throw this.raise(Errors.ImportBindingIsString, specifier, { + importName: firstIdent.value + }); + } + specifier.imported = firstIdent; + specifier.importKind = null; + } + if (this.eatContextual(93)) { + specifier.local = this.parseIdentifier(); + } else { + isBinding = true; + specifier.local = this.cloneIdentifier(specifier.imported); + } + } + const specifierIsTypeImport = hasTypeImportKind(specifier); + if (isInTypeOnlyImport && specifierIsTypeImport) { + this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier); + } + if (isInTypeOnlyImport || specifierIsTypeImport) { + this.checkReservedType(specifier.local.name, specifier.local.loc.start, true); + } + if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) { + this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true); + } + return this.finishImportSpecifier(specifier, "ImportSpecifier"); + } + parseBindingAtom() { + switch (this.state.type) { + case 78: + return this.parseIdentifier(true); + default: + return super.parseBindingAtom(); + } + } + parseFunctionParams(node, isConstructor) { + const kind = node.kind; + if (kind !== "get" && kind !== "set" && this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.parseFunctionParams(node, isConstructor); + } + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + if (this.match(14)) { + decl.id.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(decl.id); + } + } + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(14)) { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + node.returnType = this.flowParseTypeAnnotation(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + } + return super.parseAsyncArrowFromCallExpression(node, call); + } + shouldParseAsyncArrow() { + return this.match(14) || super.shouldParseAsyncArrow(); + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + var _jsx; + let state = null; + let jsx; + if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + const currentContext = context[context.length - 1]; + if (currentContext === types.j_oTag || currentContext === types.j_expr) { + context.pop(); + } + } + if ((_jsx = jsx) != null && _jsx.error || this.match(47)) { + var _jsx2, _jsx3; + state = state || this.state.clone(); + let typeParameters; + const arrow = this.tryParse(abort => { + var _arrowExpression$extr; + typeParameters = this.flowParseTypeParameterDeclaration(); + const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => { + const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + this.resetStartLocationFromNode(result, typeParameters); + return result; + }); + if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort(); + const expr = this.maybeUnwrapTypeCastExpression(arrowExpression); + if (expr.type !== "ArrowFunctionExpression") abort(); + expr.typeParameters = typeParameters; + this.resetStartLocationFromNode(expr, typeParameters); + return arrowExpression; + }, state); + let arrowExpression = null; + if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") { + if (!arrow.error && !arrow.aborted) { + if (arrow.node.async) { + this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters); + } + return arrow.node; + } + arrowExpression = arrow.node; + } + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + if (arrowExpression) { + this.state = arrow.failState; + return arrowExpression; + } + if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error; + if (arrow.thrown) throw arrow.error; + throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters); + } + return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + } + parseArrow(node) { + if (this.match(14)) { + const result = this.tryParse(() => { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + if (this.canInsertSemicolon()) this.unexpected(); + if (!this.match(19)) this.unexpected(); + return typeNode; + }); + if (result.thrown) return null; + if (result.error) this.state = result.failState; + node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null; + } + return super.parseArrow(node); + } + shouldParseArrow(params) { + return this.match(14) || super.shouldParseArrow(params); + } + setArrowFunctionParameters(node, params) { + if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) { + node.params = params; + } else { + super.setArrowFunctionParameters(node, params); + } + } + checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { + if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) { + return; + } + for (let i = 0; i < node.params.length; i++) { + if (this.isThisParam(node.params[i]) && i > 0) { + this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]); + } + } + super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged); + } + parseParenAndDistinguishExpression(canBeArrow) { + return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start))); + } + parseSubscripts(base, startLoc, noCalls) { + if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) { + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + node.arguments = super.parseCallExpressionArguments(); + base = this.finishNode(node, "CallExpression"); + } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) { + const state = this.state.clone(); + const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state); + if (!arrow.error && !arrow.aborted) return arrow.node; + const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state); + if (result.node && !result.error) return result.node; + if (arrow.node) { + this.state = arrow.failState; + return arrow.node; + } + if (result.node) { + this.state = result.failState; + return result.node; + } + throw arrow.error || result.error; + } + return super.parseSubscripts(base, startLoc, noCalls); + } + parseSubscript(base, startLoc, noCalls, subscriptState) { + if (this.match(18) && this.isLookaheadToken_lt()) { + subscriptState.optionalChainMember = true; + if (noCalls) { + subscriptState.stop = true; + return base; + } + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + node.typeArguments = this.flowParseTypeParameterInstantiationInExpression(); + this.expect(10); + node.arguments = this.parseCallExpressionArguments(); + node.optional = true; + return this.finishCallExpression(node, true); + } else if (!noCalls && this.shouldParseTypes() && (this.match(47) || this.match(51))) { + const node = this.startNodeAt(startLoc); + node.callee = base; + const result = this.tryParse(() => { + node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); + this.expect(10); + node.arguments = super.parseCallExpressionArguments(); + if (subscriptState.optionalChainMember) { + node.optional = false; + } + return this.finishCallExpression(node, subscriptState.optionalChainMember); + }); + if (result.node) { + if (result.error) this.state = result.failState; + return result.node; + } + } + return super.parseSubscript(base, startLoc, noCalls, subscriptState); + } + parseNewCallee(node) { + super.parseNewCallee(node); + let targs = null; + if (this.shouldParseTypes() && this.match(47)) { + targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node; + } + node.typeArguments = targs; + } + parseAsyncArrowWithTypeParameters(startLoc) { + const node = this.startNodeAt(startLoc); + this.parseFunctionParams(node, false); + if (!this.parseArrow(node)) return; + return super.parseArrowExpression(node, undefined, true); + } + readToken_mult_modulo(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 42 && next === 47 && this.state.hasFlowComment) { + this.state.hasFlowComment = false; + this.state.pos += 2; + this.nextToken(); + return; + } + super.readToken_mult_modulo(code); + } + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 124 && next === 125) { + this.finishOp(9, 2); + return; + } + super.readToken_pipe_amp(code); + } + parseTopLevel(file, program) { + const fileNode = super.parseTopLevel(file, program); + if (this.state.hasFlowComment) { + this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition()); + } + return fileNode; + } + skipBlockComment() { + if (this.hasPlugin("flowComments") && this.skipFlowComment()) { + if (this.state.hasFlowComment) { + throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc); + } + this.hasFlowCommentCompletion(); + const commentSkip = this.skipFlowComment(); + if (commentSkip) { + this.state.pos += commentSkip; + this.state.hasFlowComment = true; + } + return; + } + return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/"); + } + skipFlowComment() { + const { + pos + } = this.state; + let shiftToFirstNonWhiteSpace = 2; + while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) { + shiftToFirstNonWhiteSpace++; + } + const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos); + const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1); + if (ch2 === 58 && ch3 === 58) { + return shiftToFirstNonWhiteSpace + 2; + } + if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") { + return shiftToFirstNonWhiteSpace + 12; + } + if (ch2 === 58 && ch3 !== 58) { + return shiftToFirstNonWhiteSpace; + } + return false; + } + hasFlowCommentCompletion() { + const end = this.input.indexOf("*/", this.state.pos); + if (end === -1) { + throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); + } + } + flowEnumErrorBooleanMemberNotInitialized(loc, { + enumName, + memberName + }) { + this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, { + memberName, + enumName + }); + } + flowEnumErrorInvalidMemberInitializer(loc, enumContext) { + return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext); + } + flowEnumErrorNumberMemberNotInitialized(loc, details) { + this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details); + } + flowEnumErrorStringMemberInconsistentlyInitialized(node, details) { + this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details); + } + flowEnumMemberInit() { + const startLoc = this.state.startLoc; + const endOfInit = () => this.match(12) || this.match(8); + switch (this.state.type) { + case 135: + { + const literal = this.parseNumericLiteral(this.state.value); + if (endOfInit()) { + return { + type: "number", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + case 134: + { + const literal = this.parseStringLiteral(this.state.value); + if (endOfInit()) { + return { + type: "string", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + case 85: + case 86: + { + const literal = this.parseBooleanLiteral(this.match(85)); + if (endOfInit()) { + return { + type: "boolean", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + default: + return { + type: "invalid", + loc: startLoc + }; + } + } + flowEnumMemberRaw() { + const loc = this.state.startLoc; + const id = this.parseIdentifier(true); + const init = this.eat(29) ? this.flowEnumMemberInit() : { + type: "none", + loc + }; + return { + id, + init + }; + } + flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) { + const { + explicitType + } = context; + if (explicitType === null) { + return; + } + if (explicitType !== expectedType) { + this.flowEnumErrorInvalidMemberInitializer(loc, context); + } + } + flowEnumMembers({ + enumName, + explicitType + }) { + const seenNames = new Set(); + const members = { + booleanMembers: [], + numberMembers: [], + stringMembers: [], + defaultedMembers: [] + }; + let hasUnknownMembers = false; + while (!this.match(8)) { + if (this.eat(21)) { + hasUnknownMembers = true; + break; + } + const memberNode = this.startNode(); + const { + id, + init + } = this.flowEnumMemberRaw(); + const memberName = id.name; + if (memberName === "") { + continue; + } + if (/^[a-z]/.test(memberName)) { + this.raise(FlowErrors.EnumInvalidMemberName, id, { + memberName, + suggestion: memberName[0].toUpperCase() + memberName.slice(1), + enumName + }); + } + if (seenNames.has(memberName)) { + this.raise(FlowErrors.EnumDuplicateMemberName, id, { + memberName, + enumName + }); + } + seenNames.add(memberName); + const context = { + enumName, + explicitType, + memberName + }; + memberNode.id = id; + switch (init.type) { + case "boolean": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean"); + memberNode.init = init.value; + members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); + break; + } + case "number": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number"); + memberNode.init = init.value; + members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); + break; + } + case "string": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string"); + memberNode.init = init.value; + members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); + break; + } + case "invalid": + { + throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context); + } + case "none": + { + switch (explicitType) { + case "boolean": + this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context); + break; + case "number": + this.flowEnumErrorNumberMemberNotInitialized(init.loc, context); + break; + default: + members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember")); + } + } + } + if (!this.match(8)) { + this.expect(12); + } + } + return { + members, + hasUnknownMembers + }; + } + flowEnumStringMembers(initializedMembers, defaultedMembers, { + enumName + }) { + if (initializedMembers.length === 0) { + return defaultedMembers; + } else if (defaultedMembers.length === 0) { + return initializedMembers; + } else if (defaultedMembers.length > initializedMembers.length) { + for (const member of initializedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { + enumName + }); + } + return defaultedMembers; + } else { + for (const member of defaultedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { + enumName + }); + } + return initializedMembers; + } + } + flowEnumParseExplicitType({ + enumName + }) { + if (!this.eatContextual(102)) return null; + if (!tokenIsIdentifier(this.state.type)) { + throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, { + enumName + }); + } + const { + value + } = this.state; + this.next(); + if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { + this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, { + enumName, + invalidEnumType: value + }); + } + return value; + } + flowEnumBody(node, id) { + const enumName = id.name; + const nameLoc = id.loc.start; + const explicitType = this.flowEnumParseExplicitType({ + enumName + }); + this.expect(5); + const { + members, + hasUnknownMembers + } = this.flowEnumMembers({ + enumName, + explicitType + }); + node.hasUnknownMembers = hasUnknownMembers; + switch (explicitType) { + case "boolean": + node.explicitType = true; + node.members = members.booleanMembers; + this.expect(8); + return this.finishNode(node, "EnumBooleanBody"); + case "number": + node.explicitType = true; + node.members = members.numberMembers; + this.expect(8); + return this.finishNode(node, "EnumNumberBody"); + case "string": + node.explicitType = true; + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + case "symbol": + node.members = members.defaultedMembers; + this.expect(8); + return this.finishNode(node, "EnumSymbolBody"); + default: + { + const empty = () => { + node.members = []; + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + }; + node.explicitType = false; + const boolsLen = members.booleanMembers.length; + const numsLen = members.numberMembers.length; + const strsLen = members.stringMembers.length; + const defaultedLen = members.defaultedMembers.length; + if (!boolsLen && !numsLen && !strsLen && !defaultedLen) { + return empty(); + } else if (!boolsLen && !numsLen) { + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, { + enumName, + memberName: member.id.name + }); + } + node.members = members.booleanMembers; + this.expect(8); + return this.finishNode(node, "EnumBooleanBody"); + } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, { + enumName, + memberName: member.id.name + }); + } + node.members = members.numberMembers; + this.expect(8); + return this.finishNode(node, "EnumNumberBody"); + } else { + this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, { + enumName + }); + return empty(); + } + } + } + } + flowParseEnumDeclaration(node) { + const id = this.parseIdentifier(); + node.id = id; + node.body = this.flowEnumBody(this.startNode(), id); + return this.finishNode(node, "EnumDeclaration"); + } + jsxParseOpeningElementAfterName(node) { + if (this.shouldParseTypes()) { + if (this.match(47) || this.match(51)) { + node.typeArguments = this.flowParseTypeParameterInstantiationInExpression(); + } + } + return super.jsxParseOpeningElementAfterName(node); + } + isLookaheadToken_lt() { + const next = this.nextTokenStart(); + if (this.input.charCodeAt(next) === 60) { + const afterNext = this.input.charCodeAt(next + 1); + return afterNext !== 60 && afterNext !== 61; + } + return false; + } + reScan_lt_gt() { + const { + type + } = this.state; + if (type === 47) { + this.state.pos -= 1; + this.readToken_lt(); + } else if (type === 48) { + this.state.pos -= 1; + this.readToken_gt(); + } + } + reScan_lt() { + const { + type + } = this.state; + if (type === 51) { + this.state.pos -= 2; + this.finishOp(47, 1); + return 47; + } + return type; + } + maybeUnwrapTypeCastExpression(node) { + return node.type === "TypeCastExpression" ? node.expression : node; + } +}; +const entities = { + __proto__: null, + quot: "\u0022", + amp: "&", + apos: "\u0027", + lt: "<", + gt: ">", + nbsp: "\u00A0", + iexcl: "\u00A1", + cent: "\u00A2", + pound: "\u00A3", + curren: "\u00A4", + yen: "\u00A5", + brvbar: "\u00A6", + sect: "\u00A7", + uml: "\u00A8", + copy: "\u00A9", + ordf: "\u00AA", + laquo: "\u00AB", + not: "\u00AC", + shy: "\u00AD", + reg: "\u00AE", + macr: "\u00AF", + deg: "\u00B0", + plusmn: "\u00B1", + sup2: "\u00B2", + sup3: "\u00B3", + acute: "\u00B4", + micro: "\u00B5", + para: "\u00B6", + middot: "\u00B7", + cedil: "\u00B8", + sup1: "\u00B9", + ordm: "\u00BA", + raquo: "\u00BB", + frac14: "\u00BC", + frac12: "\u00BD", + frac34: "\u00BE", + iquest: "\u00BF", + Agrave: "\u00C0", + Aacute: "\u00C1", + Acirc: "\u00C2", + Atilde: "\u00C3", + Auml: "\u00C4", + Aring: "\u00C5", + AElig: "\u00C6", + Ccedil: "\u00C7", + Egrave: "\u00C8", + Eacute: "\u00C9", + Ecirc: "\u00CA", + Euml: "\u00CB", + Igrave: "\u00CC", + Iacute: "\u00CD", + Icirc: "\u00CE", + Iuml: "\u00CF", + ETH: "\u00D0", + Ntilde: "\u00D1", + Ograve: "\u00D2", + Oacute: "\u00D3", + Ocirc: "\u00D4", + Otilde: "\u00D5", + Ouml: "\u00D6", + times: "\u00D7", + Oslash: "\u00D8", + Ugrave: "\u00D9", + Uacute: "\u00DA", + Ucirc: "\u00DB", + Uuml: "\u00DC", + Yacute: "\u00DD", + THORN: "\u00DE", + szlig: "\u00DF", + agrave: "\u00E0", + aacute: "\u00E1", + acirc: "\u00E2", + atilde: "\u00E3", + auml: "\u00E4", + aring: "\u00E5", + aelig: "\u00E6", + ccedil: "\u00E7", + egrave: "\u00E8", + eacute: "\u00E9", + ecirc: "\u00EA", + euml: "\u00EB", + igrave: "\u00EC", + iacute: "\u00ED", + icirc: "\u00EE", + iuml: "\u00EF", + eth: "\u00F0", + ntilde: "\u00F1", + ograve: "\u00F2", + oacute: "\u00F3", + ocirc: "\u00F4", + otilde: "\u00F5", + ouml: "\u00F6", + divide: "\u00F7", + oslash: "\u00F8", + ugrave: "\u00F9", + uacute: "\u00FA", + ucirc: "\u00FB", + uuml: "\u00FC", + yacute: "\u00FD", + thorn: "\u00FE", + yuml: "\u00FF", + OElig: "\u0152", + oelig: "\u0153", + Scaron: "\u0160", + scaron: "\u0161", + Yuml: "\u0178", + fnof: "\u0192", + circ: "\u02C6", + tilde: "\u02DC", + Alpha: "\u0391", + Beta: "\u0392", + Gamma: "\u0393", + Delta: "\u0394", + Epsilon: "\u0395", + Zeta: "\u0396", + Eta: "\u0397", + Theta: "\u0398", + Iota: "\u0399", + Kappa: "\u039A", + Lambda: "\u039B", + Mu: "\u039C", + Nu: "\u039D", + Xi: "\u039E", + Omicron: "\u039F", + Pi: "\u03A0", + Rho: "\u03A1", + Sigma: "\u03A3", + Tau: "\u03A4", + Upsilon: "\u03A5", + Phi: "\u03A6", + Chi: "\u03A7", + Psi: "\u03A8", + Omega: "\u03A9", + alpha: "\u03B1", + beta: "\u03B2", + gamma: "\u03B3", + delta: "\u03B4", + epsilon: "\u03B5", + zeta: "\u03B6", + eta: "\u03B7", + theta: "\u03B8", + iota: "\u03B9", + kappa: "\u03BA", + lambda: "\u03BB", + mu: "\u03BC", + nu: "\u03BD", + xi: "\u03BE", + omicron: "\u03BF", + pi: "\u03C0", + rho: "\u03C1", + sigmaf: "\u03C2", + sigma: "\u03C3", + tau: "\u03C4", + upsilon: "\u03C5", + phi: "\u03C6", + chi: "\u03C7", + psi: "\u03C8", + omega: "\u03C9", + thetasym: "\u03D1", + upsih: "\u03D2", + piv: "\u03D6", + ensp: "\u2002", + emsp: "\u2003", + thinsp: "\u2009", + zwnj: "\u200C", + zwj: "\u200D", + lrm: "\u200E", + rlm: "\u200F", + ndash: "\u2013", + mdash: "\u2014", + lsquo: "\u2018", + rsquo: "\u2019", + sbquo: "\u201A", + ldquo: "\u201C", + rdquo: "\u201D", + bdquo: "\u201E", + dagger: "\u2020", + Dagger: "\u2021", + bull: "\u2022", + hellip: "\u2026", + permil: "\u2030", + prime: "\u2032", + Prime: "\u2033", + lsaquo: "\u2039", + rsaquo: "\u203A", + oline: "\u203E", + frasl: "\u2044", + euro: "\u20AC", + image: "\u2111", + weierp: "\u2118", + real: "\u211C", + trade: "\u2122", + alefsym: "\u2135", + larr: "\u2190", + uarr: "\u2191", + rarr: "\u2192", + darr: "\u2193", + harr: "\u2194", + crarr: "\u21B5", + lArr: "\u21D0", + uArr: "\u21D1", + rArr: "\u21D2", + dArr: "\u21D3", + hArr: "\u21D4", + forall: "\u2200", + part: "\u2202", + exist: "\u2203", + empty: "\u2205", + nabla: "\u2207", + isin: "\u2208", + notin: "\u2209", + ni: "\u220B", + prod: "\u220F", + sum: "\u2211", + minus: "\u2212", + lowast: "\u2217", + radic: "\u221A", + prop: "\u221D", + infin: "\u221E", + ang: "\u2220", + and: "\u2227", + or: "\u2228", + cap: "\u2229", + cup: "\u222A", + int: "\u222B", + there4: "\u2234", + sim: "\u223C", + cong: "\u2245", + asymp: "\u2248", + ne: "\u2260", + equiv: "\u2261", + le: "\u2264", + ge: "\u2265", + sub: "\u2282", + sup: "\u2283", + nsub: "\u2284", + sube: "\u2286", + supe: "\u2287", + oplus: "\u2295", + otimes: "\u2297", + perp: "\u22A5", + sdot: "\u22C5", + lceil: "\u2308", + rceil: "\u2309", + lfloor: "\u230A", + rfloor: "\u230B", + lang: "\u2329", + rang: "\u232A", + loz: "\u25CA", + spades: "\u2660", + clubs: "\u2663", + hearts: "\u2665", + diams: "\u2666" +}; +const lineBreak = /\r\n|[\r\n\u2028\u2029]/; +const lineBreakG = new RegExp(lineBreak.source, "g"); +function isNewLine(code) { + switch (code) { + case 10: + case 13: + case 8232: + case 8233: + return true; + default: + return false; + } +} +function hasNewLine(input, start, end) { + for (let i = start; i < end; i++) { + if (isNewLine(input.charCodeAt(i))) { + return true; + } + } + return false; +} +const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g; +function isWhitespace(code) { + switch (code) { + case 0x0009: + case 0x000b: + case 0x000c: + case 32: + case 160: + case 5760: + case 0x2000: + case 0x2001: + case 0x2002: + case 0x2003: + case 0x2004: + case 0x2005: + case 0x2006: + case 0x2007: + case 0x2008: + case 0x2009: + case 0x200a: + case 0x202f: + case 0x205f: + case 0x3000: + case 0xfeff: + return true; + default: + return false; + } +} +const JsxErrors = ParseErrorEnum`jsx`({ + AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.", + MissingClosingTagElement: ({ + openingTagName + }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`, + MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.", + UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?", + UnexpectedToken: ({ + unexpected, + HTMLEntity + }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`, + UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.", + UnterminatedJsxContent: "Unterminated JSX contents.", + UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?" +}); +function isFragment(object) { + return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false; +} +function getQualifiedJSXName(object) { + if (object.type === "JSXIdentifier") { + return object.name; + } + if (object.type === "JSXNamespacedName") { + return object.namespace.name + ":" + object.name.name; + } + if (object.type === "JSXMemberExpression") { + return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); + } + throw new Error("Node had unexpected type: " + object.type); +} +var jsx = superClass => class JSXParserMixin extends superClass { + jsxReadToken() { + let out = ""; + let chunkStart = this.state.pos; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc); + } + const ch = this.input.charCodeAt(this.state.pos); + switch (ch) { + case 60: + case 123: + if (this.state.pos === this.state.start) { + if (ch === 60 && this.state.canStartJSXElement) { + ++this.state.pos; + this.finishToken(143); + } else { + super.getTokenFromCode(ch); + } + return; + } + out += this.input.slice(chunkStart, this.state.pos); + this.finishToken(142, out); + return; + case 38: + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + break; + case 62: + case 125: + default: + if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(true); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + } + } + jsxReadNewLine(normalizeCRLF) { + const ch = this.input.charCodeAt(this.state.pos); + let out; + ++this.state.pos; + if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + out = normalizeCRLF ? "\n" : "\r\n"; + } else { + out = String.fromCharCode(ch); + } + ++this.state.curLine; + this.state.lineStart = this.state.pos; + return out; + } + jsxReadString(quote) { + let out = ""; + let chunkStart = ++this.state.pos; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(Errors.UnterminatedString, this.state.startLoc); + } + const ch = this.input.charCodeAt(this.state.pos); + if (ch === quote) break; + if (ch === 38) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(false); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + out += this.input.slice(chunkStart, this.state.pos++); + this.finishToken(134, out); + } + jsxReadEntity() { + const startPos = ++this.state.pos; + if (this.codePointAtPos(this.state.pos) === 35) { + ++this.state.pos; + let radix = 10; + if (this.codePointAtPos(this.state.pos) === 120) { + radix = 16; + ++this.state.pos; + } + const codePoint = this.readInt(radix, undefined, false, "bail"); + if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) { + ++this.state.pos; + return String.fromCodePoint(codePoint); + } + } else { + let count = 0; + let semi = false; + while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) === 59)) { + ++this.state.pos; + } + if (semi) { + const desc = this.input.slice(startPos, this.state.pos); + const entity = entities[desc]; + ++this.state.pos; + if (entity) { + return entity; + } + } + } + this.state.pos = startPos; + return "&"; + } + jsxReadWord() { + let ch; + const start = this.state.pos; + do { + ch = this.input.charCodeAt(++this.state.pos); + } while (isIdentifierChar(ch) || ch === 45); + this.finishToken(141, this.input.slice(start, this.state.pos)); + } + jsxParseIdentifier() { + const node = this.startNode(); + if (this.match(141)) { + node.name = this.state.value; + } else if (tokenIsKeyword(this.state.type)) { + node.name = tokenLabelName(this.state.type); + } else { + this.unexpected(); + } + this.next(); + return this.finishNode(node, "JSXIdentifier"); + } + jsxParseNamespacedName() { + const startLoc = this.state.startLoc; + const name = this.jsxParseIdentifier(); + if (!this.eat(14)) return name; + const node = this.startNodeAt(startLoc); + node.namespace = name; + node.name = this.jsxParseIdentifier(); + return this.finishNode(node, "JSXNamespacedName"); + } + jsxParseElementName() { + const startLoc = this.state.startLoc; + let node = this.jsxParseNamespacedName(); + if (node.type === "JSXNamespacedName") { + return node; + } + while (this.eat(16)) { + const newNode = this.startNodeAt(startLoc); + newNode.object = node; + newNode.property = this.jsxParseIdentifier(); + node = this.finishNode(newNode, "JSXMemberExpression"); + } + return node; + } + jsxParseAttributeValue() { + let node; + switch (this.state.type) { + case 5: + node = this.startNode(); + this.setContext(types.brace); + this.next(); + node = this.jsxParseExpressionContainer(node, types.j_oTag); + if (node.expression.type === "JSXEmptyExpression") { + this.raise(JsxErrors.AttributeIsEmpty, node); + } + return node; + case 143: + case 134: + return this.parseExprAtom(); + default: + throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc); + } + } + jsxParseEmptyExpression() { + const node = this.startNodeAt(this.state.lastTokEndLoc); + return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc); + } + jsxParseSpreadChild(node) { + this.next(); + node.expression = this.parseExpression(); + this.setContext(types.j_expr); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXSpreadChild"); + } + jsxParseExpressionContainer(node, previousContext) { + if (this.match(8)) { + node.expression = this.jsxParseEmptyExpression(); + } else { + const expression = this.parseExpression(); + node.expression = expression; + } + this.setContext(previousContext); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXExpressionContainer"); + } + jsxParseAttribute() { + const node = this.startNode(); + if (this.match(5)) { + this.setContext(types.brace); + this.next(); + this.expect(21); + node.argument = this.parseMaybeAssignAllowIn(); + this.setContext(types.j_oTag); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXSpreadAttribute"); + } + node.name = this.jsxParseNamespacedName(); + node.value = this.eat(29) ? this.jsxParseAttributeValue() : null; + return this.finishNode(node, "JSXAttribute"); + } + jsxParseOpeningElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + if (this.eat(144)) { + return this.finishNode(node, "JSXOpeningFragment"); + } + node.name = this.jsxParseElementName(); + return this.jsxParseOpeningElementAfterName(node); + } + jsxParseOpeningElementAfterName(node) { + const attributes = []; + while (!this.match(56) && !this.match(144)) { + attributes.push(this.jsxParseAttribute()); + } + node.attributes = attributes; + node.selfClosing = this.eat(56); + this.expect(144); + return this.finishNode(node, "JSXOpeningElement"); + } + jsxParseClosingElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + if (this.eat(144)) { + return this.finishNode(node, "JSXClosingFragment"); + } + node.name = this.jsxParseElementName(); + this.expect(144); + return this.finishNode(node, "JSXClosingElement"); + } + jsxParseElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + const children = []; + const openingElement = this.jsxParseOpeningElementAt(startLoc); + let closingElement = null; + if (!openingElement.selfClosing) { + contents: for (;;) { + switch (this.state.type) { + case 143: + startLoc = this.state.startLoc; + this.next(); + if (this.eat(56)) { + closingElement = this.jsxParseClosingElementAt(startLoc); + break contents; + } + children.push(this.jsxParseElementAt(startLoc)); + break; + case 142: + children.push(this.parseLiteral(this.state.value, "JSXText")); + break; + case 5: + { + const node = this.startNode(); + this.setContext(types.brace); + this.next(); + if (this.match(21)) { + children.push(this.jsxParseSpreadChild(node)); + } else { + children.push(this.jsxParseExpressionContainer(node, types.j_expr)); + } + break; + } + default: + this.unexpected(); + } + } + if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) { + this.raise(JsxErrors.MissingClosingTagFragment, closingElement); + } else if (!isFragment(openingElement) && isFragment(closingElement)) { + this.raise(JsxErrors.MissingClosingTagElement, closingElement, { + openingTagName: getQualifiedJSXName(openingElement.name) + }); + } else if (!isFragment(openingElement) && !isFragment(closingElement)) { + if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { + this.raise(JsxErrors.MissingClosingTagElement, closingElement, { + openingTagName: getQualifiedJSXName(openingElement.name) + }); + } + } + } + if (isFragment(openingElement)) { + node.openingFragment = openingElement; + node.closingFragment = closingElement; + } else { + node.openingElement = openingElement; + node.closingElement = closingElement; + } + node.children = children; + if (this.match(47)) { + throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc); + } + return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement"); + } + jsxParseElement() { + const startLoc = this.state.startLoc; + this.next(); + return this.jsxParseElementAt(startLoc); + } + setContext(newContext) { + const { + context + } = this.state; + context[context.length - 1] = newContext; + } + parseExprAtom(refExpressionErrors) { + if (this.match(143)) { + return this.jsxParseElement(); + } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) { + this.replaceToken(143); + return this.jsxParseElement(); + } else { + return super.parseExprAtom(refExpressionErrors); + } + } + skipSpace() { + const curContext = this.curContext(); + if (!curContext.preserveSpace) super.skipSpace(); + } + getTokenFromCode(code) { + const context = this.curContext(); + if (context === types.j_expr) { + this.jsxReadToken(); + return; + } + if (context === types.j_oTag || context === types.j_cTag) { + if (isIdentifierStart(code)) { + this.jsxReadWord(); + return; + } + if (code === 62) { + ++this.state.pos; + this.finishToken(144); + return; + } + if ((code === 34 || code === 39) && context === types.j_oTag) { + this.jsxReadString(code); + return; + } + } + if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) { + ++this.state.pos; + this.finishToken(143); + return; + } + super.getTokenFromCode(code); + } + updateContext(prevType) { + const { + context, + type + } = this.state; + if (type === 56 && prevType === 143) { + context.splice(-2, 2, types.j_cTag); + this.state.canStartJSXElement = false; + } else if (type === 143) { + context.push(types.j_oTag); + } else if (type === 144) { + const out = context[context.length - 1]; + if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) { + context.pop(); + this.state.canStartJSXElement = context[context.length - 1] === types.j_expr; + } else { + this.setContext(types.j_expr); + this.state.canStartJSXElement = true; + } + } else { + this.state.canStartJSXElement = tokenComesBeforeExpression(type); + } + } +}; +class TypeScriptScope extends Scope { + constructor(...args) { + super(...args); + this.tsNames = new Map(); + } +} +class TypeScriptScopeHandler extends ScopeHandler { + constructor(...args) { + super(...args); + this.importsStack = []; + } + createScope(flags) { + this.importsStack.push(new Set()); + return new TypeScriptScope(flags); + } + enter(flags) { + if (flags === 1024) { + this.importsStack.push(new Set()); + } + super.enter(flags); + } + exit() { + const flags = super.exit(); + if (flags === 1024) { + this.importsStack.pop(); + } + return flags; + } + hasImport(name, allowShadow) { + const len = this.importsStack.length; + if (this.importsStack[len - 1].has(name)) { + return true; + } + if (!allowShadow && len > 1) { + for (let i = 0; i < len - 1; i++) { + if (this.importsStack[i].has(name)) return true; + } + } + return false; + } + declareName(name, bindingType, loc) { + if (bindingType & 4096) { + if (this.hasImport(name, true)) { + this.parser.raise(Errors.VarRedeclaration, loc, { + identifierName: name + }); + } + this.importsStack[this.importsStack.length - 1].add(name); + return; + } + const scope = this.currentScope(); + let type = scope.tsNames.get(name) || 0; + if (bindingType & 1024) { + this.maybeExportDefined(scope, name); + scope.tsNames.set(name, type | 16); + return; + } + super.declareName(name, bindingType, loc); + if (bindingType & 2) { + if (!(bindingType & 1)) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + this.maybeExportDefined(scope, name); + } + type = type | 1; + } + if (bindingType & 256) { + type = type | 2; + } + if (bindingType & 512) { + type = type | 4; + } + if (bindingType & 128) { + type = type | 8; + } + if (type) scope.tsNames.set(name, type); + } + isRedeclaredInScope(scope, name, bindingType) { + const type = scope.tsNames.get(name); + if ((type & 2) > 0) { + if (bindingType & 256) { + const isConst = !!(bindingType & 512); + const wasConst = (type & 4) > 0; + return isConst !== wasConst; + } + return true; + } + if (bindingType & 128 && (type & 8) > 0) { + if (scope.names.get(name) & 2) { + return !!(bindingType & 1); + } else { + return false; + } + } + if (bindingType & 2 && (type & 1) > 0) { + return true; + } + return super.isRedeclaredInScope(scope, name, bindingType); + } + checkLocalExport(id) { + const { + name + } = id; + if (this.hasImport(name)) return; + const len = this.scopeStack.length; + for (let i = len - 1; i >= 0; i--) { + const scope = this.scopeStack[i]; + const type = scope.tsNames.get(name); + if ((type & 1) > 0 || (type & 16) > 0) { + return; + } + } + super.checkLocalExport(id); + } +} +class ProductionParameterHandler { + constructor() { + this.stacks = []; + } + enter(flags) { + this.stacks.push(flags); + } + exit() { + this.stacks.pop(); + } + currentFlags() { + return this.stacks[this.stacks.length - 1]; + } + get hasAwait() { + return (this.currentFlags() & 2) > 0; + } + get hasYield() { + return (this.currentFlags() & 1) > 0; + } + get hasReturn() { + return (this.currentFlags() & 4) > 0; + } + get hasIn() { + return (this.currentFlags() & 8) > 0; + } +} +function functionFlags(isAsync, isGenerator) { + return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0); +} +class BaseParser { + constructor() { + this.sawUnambiguousESM = false; + this.ambiguousScriptDifferentAst = false; + } + sourceToOffsetPos(sourcePos) { + return sourcePos + this.startIndex; + } + offsetToSourcePos(offsetPos) { + return offsetPos - this.startIndex; + } + hasPlugin(pluginConfig) { + if (typeof pluginConfig === "string") { + return this.plugins.has(pluginConfig); + } else { + const [pluginName, pluginOptions] = pluginConfig; + if (!this.hasPlugin(pluginName)) { + return false; + } + const actualOptions = this.plugins.get(pluginName); + for (const key of Object.keys(pluginOptions)) { + if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) { + return false; + } + } + return true; + } + } + getPluginOption(plugin, name) { + var _this$plugins$get; + return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name]; + } +} +function setTrailingComments(node, comments) { + if (node.trailingComments === undefined) { + node.trailingComments = comments; + } else { + node.trailingComments.unshift(...comments); + } +} +function setLeadingComments(node, comments) { + if (node.leadingComments === undefined) { + node.leadingComments = comments; + } else { + node.leadingComments.unshift(...comments); + } +} +function setInnerComments(node, comments) { + if (node.innerComments === undefined) { + node.innerComments = comments; + } else { + node.innerComments.unshift(...comments); + } +} +function adjustInnerComments(node, elements, commentWS) { + let lastElement = null; + let i = elements.length; + while (lastElement === null && i > 0) { + lastElement = elements[--i]; + } + if (lastElement === null || lastElement.start > commentWS.start) { + setInnerComments(node, commentWS.comments); + } else { + setTrailingComments(lastElement, commentWS.comments); + } +} +class CommentsParser extends BaseParser { + addComment(comment) { + if (this.filename) comment.loc.filename = this.filename; + const { + commentsLen + } = this.state; + if (this.comments.length !== commentsLen) { + this.comments.length = commentsLen; + } + this.comments.push(comment); + this.state.commentsLen++; + } + processComment(node) { + const { + commentStack + } = this.state; + const commentStackLength = commentStack.length; + if (commentStackLength === 0) return; + let i = commentStackLength - 1; + const lastCommentWS = commentStack[i]; + if (lastCommentWS.start === node.end) { + lastCommentWS.leadingNode = node; + i--; + } + const { + start: nodeStart + } = node; + for (; i >= 0; i--) { + const commentWS = commentStack[i]; + const commentEnd = commentWS.end; + if (commentEnd > nodeStart) { + commentWS.containingNode = node; + this.finalizeComment(commentWS); + commentStack.splice(i, 1); + } else { + if (commentEnd === nodeStart) { + commentWS.trailingNode = node; + } + break; + } + } + } + finalizeComment(commentWS) { + var _node$options; + const { + comments + } = commentWS; + if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) { + if (commentWS.leadingNode !== null) { + setTrailingComments(commentWS.leadingNode, comments); + } + if (commentWS.trailingNode !== null) { + setLeadingComments(commentWS.trailingNode, comments); + } + } else { + const node = commentWS.containingNode; + const commentStart = commentWS.start; + if (this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) === 44) { + switch (node.type) { + case "ObjectExpression": + case "ObjectPattern": + adjustInnerComments(node, node.properties, commentWS); + break; + case "CallExpression": + case "OptionalCallExpression": + adjustInnerComments(node, node.arguments, commentWS); + break; + case "ImportExpression": + adjustInnerComments(node, [node.source, (_node$options = node.options) != null ? _node$options : null], commentWS); + break; + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "ObjectMethod": + case "ClassMethod": + case "ClassPrivateMethod": + adjustInnerComments(node, node.params, commentWS); + break; + case "ArrayExpression": + case "ArrayPattern": + adjustInnerComments(node, node.elements, commentWS); + break; + case "ExportNamedDeclaration": + case "ImportDeclaration": + adjustInnerComments(node, node.specifiers, commentWS); + break; + case "TSEnumDeclaration": + adjustInnerComments(node, node.members, commentWS); + break; + case "TSEnumBody": + adjustInnerComments(node, node.members, commentWS); + break; + default: + { + if (node.type === "RecordExpression") { + adjustInnerComments(node, node.properties, commentWS); + break; + } + if (node.type === "TupleExpression") { + adjustInnerComments(node, node.elements, commentWS); + break; + } + setInnerComments(node, comments); + } + } + } else { + setInnerComments(node, comments); + } + } + } + finalizeRemainingComments() { + const { + commentStack + } = this.state; + for (let i = commentStack.length - 1; i >= 0; i--) { + this.finalizeComment(commentStack[i]); + } + this.state.commentStack = []; + } + resetPreviousNodeTrailingComments(node) { + const { + commentStack + } = this.state; + const { + length + } = commentStack; + if (length === 0) return; + const commentWS = commentStack[length - 1]; + if (commentWS.leadingNode === node) { + commentWS.leadingNode = null; + } + } + takeSurroundingComments(node, start, end) { + const { + commentStack + } = this.state; + const commentStackLength = commentStack.length; + if (commentStackLength === 0) return; + let i = commentStackLength - 1; + for (; i >= 0; i--) { + const commentWS = commentStack[i]; + const commentEnd = commentWS.end; + const commentStart = commentWS.start; + if (commentStart === end) { + commentWS.leadingNode = node; + } else if (commentEnd === start) { + commentWS.trailingNode = node; + } else if (commentEnd < start) { + break; + } + } + } +} +class State { + constructor() { + this.flags = 1024; + this.startIndex = void 0; + this.curLine = void 0; + this.lineStart = void 0; + this.startLoc = void 0; + this.endLoc = void 0; + this.errors = []; + this.potentialArrowAt = -1; + this.noArrowAt = []; + this.noArrowParamsConversionAt = []; + this.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + this.labels = []; + this.commentsLen = 0; + this.commentStack = []; + this.pos = 0; + this.type = 140; + this.value = null; + this.start = 0; + this.end = 0; + this.lastTokEndLoc = null; + this.lastTokStartLoc = null; + this.context = [types.brace]; + this.firstInvalidTemplateEscapePos = null; + this.strictErrors = new Map(); + this.tokensLength = 0; + } + get strict() { + return (this.flags & 1) > 0; + } + set strict(v) { + if (v) this.flags |= 1;else this.flags &= -2; + } + init({ + strictMode, + sourceType, + startIndex, + startLine, + startColumn + }) { + this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module"; + this.startIndex = startIndex; + this.curLine = startLine; + this.lineStart = -startColumn; + this.startLoc = this.endLoc = new Position(startLine, startColumn, startIndex); + } + get maybeInArrowParameters() { + return (this.flags & 2) > 0; + } + set maybeInArrowParameters(v) { + if (v) this.flags |= 2;else this.flags &= -3; + } + get inType() { + return (this.flags & 4) > 0; + } + set inType(v) { + if (v) this.flags |= 4;else this.flags &= -5; + } + get noAnonFunctionType() { + return (this.flags & 8) > 0; + } + set noAnonFunctionType(v) { + if (v) this.flags |= 8;else this.flags &= -9; + } + get hasFlowComment() { + return (this.flags & 16) > 0; + } + set hasFlowComment(v) { + if (v) this.flags |= 16;else this.flags &= -17; + } + get isAmbientContext() { + return (this.flags & 32) > 0; + } + set isAmbientContext(v) { + if (v) this.flags |= 32;else this.flags &= -33; + } + get inAbstractClass() { + return (this.flags & 64) > 0; + } + set inAbstractClass(v) { + if (v) this.flags |= 64;else this.flags &= -65; + } + get inDisallowConditionalTypesContext() { + return (this.flags & 128) > 0; + } + set inDisallowConditionalTypesContext(v) { + if (v) this.flags |= 128;else this.flags &= -129; + } + get soloAwait() { + return (this.flags & 256) > 0; + } + set soloAwait(v) { + if (v) this.flags |= 256;else this.flags &= -257; + } + get inFSharpPipelineDirectBody() { + return (this.flags & 512) > 0; + } + set inFSharpPipelineDirectBody(v) { + if (v) this.flags |= 512;else this.flags &= -513; + } + get canStartJSXElement() { + return (this.flags & 1024) > 0; + } + set canStartJSXElement(v) { + if (v) this.flags |= 1024;else this.flags &= -1025; + } + get containsEsc() { + return (this.flags & 2048) > 0; + } + set containsEsc(v) { + if (v) this.flags |= 2048;else this.flags &= -2049; + } + get hasTopLevelAwait() { + return (this.flags & 4096) > 0; + } + set hasTopLevelAwait(v) { + if (v) this.flags |= 4096;else this.flags &= -4097; + } + curPosition() { + return new Position(this.curLine, this.pos - this.lineStart, this.pos + this.startIndex); + } + clone() { + const state = new State(); + state.flags = this.flags; + state.startIndex = this.startIndex; + state.curLine = this.curLine; + state.lineStart = this.lineStart; + state.startLoc = this.startLoc; + state.endLoc = this.endLoc; + state.errors = this.errors.slice(); + state.potentialArrowAt = this.potentialArrowAt; + state.noArrowAt = this.noArrowAt.slice(); + state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice(); + state.topicContext = this.topicContext; + state.labels = this.labels.slice(); + state.commentsLen = this.commentsLen; + state.commentStack = this.commentStack.slice(); + state.pos = this.pos; + state.type = this.type; + state.value = this.value; + state.start = this.start; + state.end = this.end; + state.lastTokEndLoc = this.lastTokEndLoc; + state.lastTokStartLoc = this.lastTokStartLoc; + state.context = this.context.slice(); + state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos; + state.strictErrors = this.strictErrors; + state.tokensLength = this.tokensLength; + return state; + } +} +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; +const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) +}; +const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 +}; +function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let firstInvalidLoc = null; + let chunkStart = pos; + const { + length + } = input; + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + const ch = input.charCodeAt(pos); + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + if (ch === 92) { + out += input.slice(chunkStart, pos); + const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); + if (res.ch === null && !firstInvalidLoc) { + firstInvalidLoc = { + pos, + lineStart, + curLine + }; + } else { + out += res.ch; + } + ({ + pos, + lineStart, + curLine + } = res); + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + return { + pos, + str: out, + firstInvalidLoc, + lineStart, + curLine, + containsInvalid: !!firstInvalidLoc + }; +} +function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + return ch === (type === "double" ? 34 : 39); +} +function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + const ch = input.charCodeAt(pos++); + switch (ch) { + case 110: + return res("\n"); + case 114: + return res("\r"); + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + case 116: + return res("\t"); + case 98: + return res("\b"); + case 118: + return res("\u000b"); + case 102: + return res("\f"); + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + case 10: + lineStart = pos; + ++curLine; + case 8232: + case 8233: + return res(""); + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2)); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + return res(String.fromCharCode(octal)); + } + return res(String.fromCharCode(ch)); + } +} +function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + return { + code: n, + pos + }; +} +function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + if (!allowNumSeparator) { + if (bailOnError) return { + n: null, + pos + }; + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + if (bailOnError) return { + n: null, + pos + }; + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + ++pos; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + if (val <= 9 && bailOnError) { + return { + n: null, + pos + }; + } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + ++pos; + total = total * radix + val; + } + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + return { + n: total, + pos + }; +} +function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + return { + code, + pos + }; +} +function buildPosition(pos, lineStart, curLine) { + return new Position(curLine, pos - lineStart, pos); +} +const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]); +class Token { + constructor(state) { + const startIndex = state.startIndex || 0; + this.type = state.type; + this.value = state.value; + this.start = startIndex + state.start; + this.end = startIndex + state.end; + this.loc = new SourceLocation(state.startLoc, state.endLoc); + } +} +class Tokenizer extends CommentsParser { + constructor(options, input) { + super(); + this.isLookahead = void 0; + this.tokens = []; + this.errorHandlers_readInt = { + invalidDigit: (pos, lineStart, curLine, radix) => { + if (!(this.optionFlags & 2048)) return false; + this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), { + radix + }); + return true; + }, + numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence), + unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator) + }; + this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, { + invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence), + invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint) + }); + this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, { + strictNumericEscape: (pos, lineStart, curLine) => { + this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine)); + }, + unterminated: (pos, lineStart, curLine) => { + throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine)); + } + }); + this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, { + strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape), + unterminated: (pos, lineStart, curLine) => { + throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine)); + } + }); + this.state = new State(); + this.state.init(options); + this.input = input; + this.length = input.length; + this.comments = []; + this.isLookahead = false; + } + pushToken(token) { + this.tokens.length = this.state.tokensLength; + this.tokens.push(token); + ++this.state.tokensLength; + } + next() { + this.checkKeywordEscapes(); + if (this.optionFlags & 256) { + this.pushToken(new Token(this.state)); + } + this.state.lastTokEndLoc = this.state.endLoc; + this.state.lastTokStartLoc = this.state.startLoc; + this.nextToken(); + } + eat(type) { + if (this.match(type)) { + this.next(); + return true; + } else { + return false; + } + } + match(type) { + return this.state.type === type; + } + createLookaheadState(state) { + return { + pos: state.pos, + value: null, + type: state.type, + start: state.start, + end: state.end, + context: [this.curContext()], + inType: state.inType, + startLoc: state.startLoc, + lastTokEndLoc: state.lastTokEndLoc, + curLine: state.curLine, + lineStart: state.lineStart, + curPosition: state.curPosition + }; + } + lookahead() { + const old = this.state; + this.state = this.createLookaheadState(old); + this.isLookahead = true; + this.nextToken(); + this.isLookahead = false; + const curr = this.state; + this.state = old; + return curr; + } + nextTokenStart() { + return this.nextTokenStartSince(this.state.pos); + } + nextTokenStartSince(pos) { + skipWhiteSpace.lastIndex = pos; + return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos; + } + lookaheadCharCode() { + return this.lookaheadCharCodeSince(this.state.pos); + } + lookaheadCharCodeSince(pos) { + return this.input.charCodeAt(this.nextTokenStartSince(pos)); + } + nextTokenInLineStart() { + return this.nextTokenInLineStartSince(this.state.pos); + } + nextTokenInLineStartSince(pos) { + skipWhiteSpaceInLine.lastIndex = pos; + return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos; + } + lookaheadInLineCharCode() { + return this.input.charCodeAt(this.nextTokenInLineStart()); + } + codePointAtPos(pos) { + let cp = this.input.charCodeAt(pos); + if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) { + const trail = this.input.charCodeAt(pos); + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + return cp; + } + setStrict(strict) { + this.state.strict = strict; + if (strict) { + this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at)); + this.state.strictErrors.clear(); + } + } + curContext() { + return this.state.context[this.state.context.length - 1]; + } + nextToken() { + this.skipSpace(); + this.state.start = this.state.pos; + if (!this.isLookahead) this.state.startLoc = this.state.curPosition(); + if (this.state.pos >= this.length) { + this.finishToken(140); + return; + } + this.getTokenFromCode(this.codePointAtPos(this.state.pos)); + } + skipBlockComment(commentEnd) { + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + const start = this.state.pos; + const end = this.input.indexOf(commentEnd, start + 2); + if (end === -1) { + throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); + } + this.state.pos = end + commentEnd.length; + lineBreakG.lastIndex = start + 2; + while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) { + ++this.state.curLine; + this.state.lineStart = lineBreakG.lastIndex; + } + if (this.isLookahead) return; + const comment = { + type: "CommentBlock", + value: this.input.slice(start + 2, end), + start: this.sourceToOffsetPos(start), + end: this.sourceToOffsetPos(end + commentEnd.length), + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.optionFlags & 256) this.pushToken(comment); + return comment; + } + skipLineComment(startSkip) { + const start = this.state.pos; + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + let ch = this.input.charCodeAt(this.state.pos += startSkip); + if (this.state.pos < this.length) { + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + } + if (this.isLookahead) return; + const end = this.state.pos; + const value = this.input.slice(start + startSkip, end); + const comment = { + type: "CommentLine", + value, + start: this.sourceToOffsetPos(start), + end: this.sourceToOffsetPos(end), + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.optionFlags & 256) this.pushToken(comment); + return comment; + } + skipSpace() { + const spaceStart = this.state.pos; + const comments = this.optionFlags & 4096 ? [] : null; + loop: while (this.state.pos < this.length) { + const ch = this.input.charCodeAt(this.state.pos); + switch (ch) { + case 32: + case 160: + case 9: + ++this.state.pos; + break; + case 13: + if (this.input.charCodeAt(this.state.pos + 1) === 10) { + ++this.state.pos; + } + case 10: + case 8232: + case 8233: + ++this.state.pos; + ++this.state.curLine; + this.state.lineStart = this.state.pos; + break; + case 47: + switch (this.input.charCodeAt(this.state.pos + 1)) { + case 42: + { + const comment = this.skipBlockComment("*/"); + if (comment !== undefined) { + this.addComment(comment); + comments == null || comments.push(comment); + } + break; + } + case 47: + { + const comment = this.skipLineComment(2); + if (comment !== undefined) { + this.addComment(comment); + comments == null || comments.push(comment); + } + break; + } + default: + break loop; + } + break; + default: + if (isWhitespace(ch)) { + ++this.state.pos; + } else if (ch === 45 && !this.inModule && this.optionFlags & 8192) { + const pos = this.state.pos; + if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) { + const comment = this.skipLineComment(3); + if (comment !== undefined) { + this.addComment(comment); + comments == null || comments.push(comment); + } + } else { + break loop; + } + } else if (ch === 60 && !this.inModule && this.optionFlags & 8192) { + const pos = this.state.pos; + if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) { + const comment = this.skipLineComment(4); + if (comment !== undefined) { + this.addComment(comment); + comments == null || comments.push(comment); + } + } else { + break loop; + } + } else { + break loop; + } + } + } + if ((comments == null ? void 0 : comments.length) > 0) { + const end = this.state.pos; + const commentWhitespace = { + start: this.sourceToOffsetPos(spaceStart), + end: this.sourceToOffsetPos(end), + comments: comments, + leadingNode: null, + trailingNode: null, + containingNode: null + }; + this.state.commentStack.push(commentWhitespace); + } + } + finishToken(type, val) { + this.state.end = this.state.pos; + this.state.endLoc = this.state.curPosition(); + const prevType = this.state.type; + this.state.type = type; + this.state.value = val; + if (!this.isLookahead) { + this.updateContext(prevType); + } + } + replaceToken(type) { + this.state.type = type; + this.updateContext(); + } + readToken_numberSign() { + if (this.state.pos === 0 && this.readToken_interpreter()) { + return; + } + const nextPos = this.state.pos + 1; + const next = this.codePointAtPos(nextPos); + if (next >= 48 && next <= 57) { + throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition()); + } + if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) { + this.expectPlugin("recordAndTuple"); + if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") { + throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + if (next === 123) { + this.finishToken(7); + } else { + this.finishToken(1); + } + } else if (isIdentifierStart(next)) { + ++this.state.pos; + this.finishToken(139, this.readWord1(next)); + } else if (next === 92) { + ++this.state.pos; + this.finishToken(139, this.readWord1()); + } else { + this.finishOp(27, 1); + } + } + readToken_dot() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next >= 48 && next <= 57) { + this.readNumber(true); + return; + } + if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) { + this.state.pos += 3; + this.finishToken(21); + } else { + ++this.state.pos; + this.finishToken(16); + } + } + readToken_slash() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + this.finishOp(31, 2); + } else { + this.finishOp(56, 1); + } + } + readToken_interpreter() { + if (this.state.pos !== 0 || this.length < 2) return false; + let ch = this.input.charCodeAt(this.state.pos + 1); + if (ch !== 33) return false; + const start = this.state.pos; + this.state.pos += 1; + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + const value = this.input.slice(start + 2, this.state.pos); + this.finishToken(28, value); + return true; + } + readToken_mult_modulo(code) { + let type = code === 42 ? 55 : 54; + let width = 1; + let next = this.input.charCodeAt(this.state.pos + 1); + if (code === 42 && next === 42) { + width++; + next = this.input.charCodeAt(this.state.pos + 2); + type = 57; + } + if (next === 61 && !this.state.inType) { + width++; + type = code === 37 ? 33 : 30; + } + this.finishOp(type, width); + } + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === code) { + if (this.input.charCodeAt(this.state.pos + 2) === 61) { + this.finishOp(30, 3); + } else { + this.finishOp(code === 124 ? 41 : 42, 2); + } + return; + } + if (code === 124) { + if (next === 62) { + this.finishOp(39, 2); + return; + } + if (this.hasPlugin("recordAndTuple") && next === 125) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(9); + return; + } + if (this.hasPlugin("recordAndTuple") && next === 93) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(4); + return; + } + } + if (next === 61) { + this.finishOp(30, 2); + return; + } + this.finishOp(code === 124 ? 43 : 45, 1); + } + readToken_caret() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61 && !this.state.inType) { + this.finishOp(32, 2); + } else if (next === 94 && this.hasPlugin(["pipelineOperator", { + proposal: "hack", + topicToken: "^^" + }])) { + this.finishOp(37, 2); + const lookaheadCh = this.input.codePointAt(this.state.pos); + if (lookaheadCh === 94) { + this.unexpected(); + } + } else { + this.finishOp(44, 1); + } + } + readToken_atSign() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 64 && this.hasPlugin(["pipelineOperator", { + proposal: "hack", + topicToken: "@@" + }])) { + this.finishOp(38, 2); + } else { + this.finishOp(26, 1); + } + } + readToken_plus_min(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === code) { + this.finishOp(34, 2); + return; + } + if (next === 61) { + this.finishOp(30, 2); + } else { + this.finishOp(53, 1); + } + } + readToken_lt() { + const { + pos + } = this.state; + const next = this.input.charCodeAt(pos + 1); + if (next === 60) { + if (this.input.charCodeAt(pos + 2) === 61) { + this.finishOp(30, 3); + return; + } + this.finishOp(51, 2); + return; + } + if (next === 61) { + this.finishOp(49, 2); + return; + } + this.finishOp(47, 1); + } + readToken_gt() { + const { + pos + } = this.state; + const next = this.input.charCodeAt(pos + 1); + if (next === 62) { + const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(pos + size) === 61) { + this.finishOp(30, size + 1); + return; + } + this.finishOp(52, size); + return; + } + if (next === 61) { + this.finishOp(49, 2); + return; + } + this.finishOp(48, 1); + } + readToken_eq_excl(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2); + return; + } + if (code === 61 && next === 62) { + this.state.pos += 2; + this.finishToken(19); + return; + } + this.finishOp(code === 61 ? 29 : 35, 1); + } + readToken_question() { + const next = this.input.charCodeAt(this.state.pos + 1); + const next2 = this.input.charCodeAt(this.state.pos + 2); + if (next === 63) { + if (next2 === 61) { + this.finishOp(30, 3); + } else { + this.finishOp(40, 2); + } + } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) { + this.state.pos += 2; + this.finishToken(18); + } else { + ++this.state.pos; + this.finishToken(17); + } + } + getTokenFromCode(code) { + switch (code) { + case 46: + this.readToken_dot(); + return; + case 40: + ++this.state.pos; + this.finishToken(10); + return; + case 41: + ++this.state.pos; + this.finishToken(11); + return; + case 59: + ++this.state.pos; + this.finishToken(13); + return; + case 44: + ++this.state.pos; + this.finishToken(12); + return; + case 91: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(2); + } else { + ++this.state.pos; + this.finishToken(0); + } + return; + case 93: + ++this.state.pos; + this.finishToken(3); + return; + case 123: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(6); + } else { + ++this.state.pos; + this.finishToken(5); + } + return; + case 125: + ++this.state.pos; + this.finishToken(8); + return; + case 58: + if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) { + this.finishOp(15, 2); + } else { + ++this.state.pos; + this.finishToken(14); + } + return; + case 63: + this.readToken_question(); + return; + case 96: + this.readTemplateToken(); + return; + case 48: + { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 120 || next === 88) { + this.readRadixNumber(16); + return; + } + if (next === 111 || next === 79) { + this.readRadixNumber(8); + return; + } + if (next === 98 || next === 66) { + this.readRadixNumber(2); + return; + } + } + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + this.readNumber(false); + return; + case 34: + case 39: + this.readString(code); + return; + case 47: + this.readToken_slash(); + return; + case 37: + case 42: + this.readToken_mult_modulo(code); + return; + case 124: + case 38: + this.readToken_pipe_amp(code); + return; + case 94: + this.readToken_caret(); + return; + case 43: + case 45: + this.readToken_plus_min(code); + return; + case 60: + this.readToken_lt(); + return; + case 62: + this.readToken_gt(); + return; + case 61: + case 33: + this.readToken_eq_excl(code); + return; + case 126: + this.finishOp(36, 1); + return; + case 64: + this.readToken_atSign(); + return; + case 35: + this.readToken_numberSign(); + return; + case 92: + this.readWord(); + return; + default: + if (isIdentifierStart(code)) { + this.readWord(code); + return; + } + } + throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), { + unexpected: String.fromCodePoint(code) + }); + } + finishOp(type, size) { + const str = this.input.slice(this.state.pos, this.state.pos + size); + this.state.pos += size; + this.finishToken(type, str); + } + readRegexp() { + const startLoc = this.state.startLoc; + const start = this.state.start + 1; + let escaped, inClass; + let { + pos + } = this.state; + for (;; ++pos) { + if (pos >= this.length) { + throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); + } + const ch = this.input.charCodeAt(pos); + if (isNewLine(ch)) { + throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); + } + if (escaped) { + escaped = false; + } else { + if (ch === 91) { + inClass = true; + } else if (ch === 93 && inClass) { + inClass = false; + } else if (ch === 47 && !inClass) { + break; + } + escaped = ch === 92; + } + } + const content = this.input.slice(start, pos); + ++pos; + let mods = ""; + const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start); + while (pos < this.length) { + const cp = this.codePointAtPos(pos); + const char = String.fromCharCode(cp); + if (VALID_REGEX_FLAGS.has(cp)) { + if (cp === 118) { + if (mods.includes("u")) { + this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); + } + } else if (cp === 117) { + if (mods.includes("v")) { + this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); + } + } + if (mods.includes(char)) { + this.raise(Errors.DuplicateRegExpFlags, nextPos()); + } + } else if (isIdentifierChar(cp) || cp === 92) { + this.raise(Errors.MalformedRegExpFlags, nextPos()); + } else { + break; + } + ++pos; + mods += char; + } + this.state.pos = pos; + this.finishToken(138, { + pattern: content, + flags: mods + }); + } + readInt(radix, len, forceLen = false, allowNumSeparator = true) { + const { + n, + pos + } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false); + this.state.pos = pos; + return n; + } + readRadixNumber(radix) { + const start = this.state.pos; + const startLoc = this.state.curPosition(); + let isBigInt = false; + this.state.pos += 2; + const val = this.readInt(radix); + if (val == null) { + this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), { + radix + }); + } + const next = this.input.charCodeAt(this.state.pos); + if (next === 110) { + ++this.state.pos; + isBigInt = true; + } else if (next === 109) { + throw this.raise(Errors.InvalidDecimal, startLoc); + } + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); + } + if (isBigInt) { + const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, ""); + this.finishToken(136, str); + return; + } + this.finishToken(135, val); + } + readNumber(startsWithDot) { + const start = this.state.pos; + const startLoc = this.state.curPosition(); + let isFloat = false; + let isBigInt = false; + let hasExponent = false; + let isOctal = false; + if (!startsWithDot && this.readInt(10) === null) { + this.raise(Errors.InvalidNumber, this.state.curPosition()); + } + const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; + if (hasLeadingZero) { + const integer = this.input.slice(start, this.state.pos); + this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc); + if (!this.state.strict) { + const underscorePos = integer.indexOf("_"); + if (underscorePos > 0) { + this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos)); + } + } + isOctal = hasLeadingZero && !/[89]/.test(integer); + } + let next = this.input.charCodeAt(this.state.pos); + if (next === 46 && !isOctal) { + ++this.state.pos; + this.readInt(10); + isFloat = true; + next = this.input.charCodeAt(this.state.pos); + } + if ((next === 69 || next === 101) && !isOctal) { + next = this.input.charCodeAt(++this.state.pos); + if (next === 43 || next === 45) { + ++this.state.pos; + } + if (this.readInt(10) === null) { + this.raise(Errors.InvalidOrMissingExponent, startLoc); + } + isFloat = true; + hasExponent = true; + next = this.input.charCodeAt(this.state.pos); + } + if (next === 110) { + if (isFloat || hasLeadingZero) { + this.raise(Errors.InvalidBigIntLiteral, startLoc); + } + ++this.state.pos; + isBigInt = true; + } + if (next === 109) { + this.expectPlugin("decimal", this.state.curPosition()); + if (hasExponent || hasLeadingZero) { + this.raise(Errors.InvalidDecimal, startLoc); + } + ++this.state.pos; + var isDecimal = true; + } + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); + } + const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, ""); + if (isBigInt) { + this.finishToken(136, str); + return; + } + if (isDecimal) { + this.finishToken(137, str); + return; + } + const val = isOctal ? parseInt(str, 8) : parseFloat(str); + this.finishToken(135, val); + } + readCodePoint(throwOnInvalid) { + const { + code, + pos + } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint); + this.state.pos = pos; + return code; + } + readString(quote) { + const { + str, + pos, + curLine, + lineStart + } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string); + this.state.pos = pos + 1; + this.state.lineStart = lineStart; + this.state.curLine = curLine; + this.finishToken(134, str); + } + readTemplateContinuation() { + if (!this.match(8)) { + this.unexpected(null, 8); + } + this.state.pos--; + this.readTemplateToken(); + } + readTemplateToken() { + const opening = this.input[this.state.pos]; + const { + str, + firstInvalidLoc, + pos, + curLine, + lineStart + } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template); + this.state.pos = pos + 1; + this.state.lineStart = lineStart; + this.state.curLine = curLine; + if (firstInvalidLoc) { + this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, this.sourceToOffsetPos(firstInvalidLoc.pos)); + } + if (this.input.codePointAt(pos) === 96) { + this.finishToken(24, firstInvalidLoc ? null : opening + str + "`"); + } else { + this.state.pos++; + this.finishToken(25, firstInvalidLoc ? null : opening + str + "${"); + } + } + recordStrictModeErrors(toParseError, at) { + const index = at.index; + if (this.state.strict && !this.state.strictErrors.has(index)) { + this.raise(toParseError, at); + } else { + this.state.strictErrors.set(index, [toParseError, at]); + } + } + readWord1(firstCode) { + this.state.containsEsc = false; + let word = ""; + const start = this.state.pos; + let chunkStart = this.state.pos; + if (firstCode !== undefined) { + this.state.pos += firstCode <= 0xffff ? 1 : 2; + } + while (this.state.pos < this.length) { + const ch = this.codePointAtPos(this.state.pos); + if (isIdentifierChar(ch)) { + this.state.pos += ch <= 0xffff ? 1 : 2; + } else if (ch === 92) { + this.state.containsEsc = true; + word += this.input.slice(chunkStart, this.state.pos); + const escStart = this.state.curPosition(); + const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; + if (this.input.charCodeAt(++this.state.pos) !== 117) { + this.raise(Errors.MissingUnicodeEscape, this.state.curPosition()); + chunkStart = this.state.pos - 1; + continue; + } + ++this.state.pos; + const esc = this.readCodePoint(true); + if (esc !== null) { + if (!identifierCheck(esc)) { + this.raise(Errors.EscapedCharNotAnIdentifier, escStart); + } + word += String.fromCodePoint(esc); + } + chunkStart = this.state.pos; + } else { + break; + } + } + return word + this.input.slice(chunkStart, this.state.pos); + } + readWord(firstCode) { + const word = this.readWord1(firstCode); + const type = keywords$1.get(word); + if (type !== undefined) { + this.finishToken(type, tokenLabelName(type)); + } else { + this.finishToken(132, word); + } + } + checkKeywordEscapes() { + const { + type + } = this.state; + if (tokenIsKeyword(type) && this.state.containsEsc) { + this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, { + reservedWord: tokenLabelName(type) + }); + } + } + raise(toParseError, at, details = {}) { + const loc = at instanceof Position ? at : at.loc.start; + const error = toParseError(loc, details); + if (!(this.optionFlags & 2048)) throw error; + if (!this.isLookahead) this.state.errors.push(error); + return error; + } + raiseOverwrite(toParseError, at, details = {}) { + const loc = at instanceof Position ? at : at.loc.start; + const pos = loc.index; + const errors = this.state.errors; + for (let i = errors.length - 1; i >= 0; i--) { + const error = errors[i]; + if (error.loc.index === pos) { + return errors[i] = toParseError(loc, details); + } + if (error.loc.index < pos) break; + } + return this.raise(toParseError, at, details); + } + updateContext(prevType) {} + unexpected(loc, type) { + throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, { + expected: type ? tokenLabelName(type) : null + }); + } + expectPlugin(pluginName, loc) { + if (this.hasPlugin(pluginName)) { + return true; + } + throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, { + missingPlugin: [pluginName] + }); + } + expectOnePlugin(pluginNames) { + if (!pluginNames.some(name => this.hasPlugin(name))) { + throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, { + missingPlugin: pluginNames + }); + } + } + errorBuilder(error) { + return (pos, lineStart, curLine) => { + this.raise(error, buildPosition(pos, lineStart, curLine)); + }; + } +} +class ClassScope { + constructor() { + this.privateNames = new Set(); + this.loneAccessors = new Map(); + this.undefinedPrivateNames = new Map(); + } +} +class ClassScopeHandler { + constructor(parser) { + this.parser = void 0; + this.stack = []; + this.undefinedPrivateNames = new Map(); + this.parser = parser; + } + current() { + return this.stack[this.stack.length - 1]; + } + enter() { + this.stack.push(new ClassScope()); + } + exit() { + const oldClassScope = this.stack.pop(); + const current = this.current(); + for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) { + if (current) { + if (!current.undefinedPrivateNames.has(name)) { + current.undefinedPrivateNames.set(name, loc); + } + } else { + this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { + identifierName: name + }); + } + } + } + declarePrivateName(name, elementType, loc) { + const { + privateNames, + loneAccessors, + undefinedPrivateNames + } = this.current(); + let redefined = privateNames.has(name); + if (elementType & 3) { + const accessor = redefined && loneAccessors.get(name); + if (accessor) { + const oldStatic = accessor & 4; + const newStatic = elementType & 4; + const oldKind = accessor & 3; + const newKind = elementType & 3; + redefined = oldKind === newKind || oldStatic !== newStatic; + if (!redefined) loneAccessors.delete(name); + } else if (!redefined) { + loneAccessors.set(name, elementType); + } + } + if (redefined) { + this.parser.raise(Errors.PrivateNameRedeclaration, loc, { + identifierName: name + }); + } + privateNames.add(name); + undefinedPrivateNames.delete(name); + } + usePrivateName(name, loc) { + let classScope; + for (classScope of this.stack) { + if (classScope.privateNames.has(name)) return; + } + if (classScope) { + classScope.undefinedPrivateNames.set(name, loc); + } else { + this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { + identifierName: name + }); + } + } +} +class ExpressionScope { + constructor(type = 0) { + this.type = type; + } + canBeArrowParameterDeclaration() { + return this.type === 2 || this.type === 1; + } + isCertainlyParameterDeclaration() { + return this.type === 3; + } +} +class ArrowHeadParsingScope extends ExpressionScope { + constructor(type) { + super(type); + this.declarationErrors = new Map(); + } + recordDeclarationError(ParsingErrorClass, at) { + const index = at.index; + this.declarationErrors.set(index, [ParsingErrorClass, at]); + } + clearDeclarationError(index) { + this.declarationErrors.delete(index); + } + iterateErrors(iterator) { + this.declarationErrors.forEach(iterator); + } +} +class ExpressionScopeHandler { + constructor(parser) { + this.parser = void 0; + this.stack = [new ExpressionScope()]; + this.parser = parser; + } + enter(scope) { + this.stack.push(scope); + } + exit() { + this.stack.pop(); + } + recordParameterInitializerError(toParseError, node) { + const origin = node.loc.start; + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + while (!scope.isCertainlyParameterDeclaration()) { + if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(toParseError, origin); + } else { + return; + } + scope = stack[--i]; + } + this.parser.raise(toParseError, origin); + } + recordArrowParameterBindingError(error, node) { + const { + stack + } = this; + const scope = stack[stack.length - 1]; + const origin = node.loc.start; + if (scope.isCertainlyParameterDeclaration()) { + this.parser.raise(error, origin); + } else if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(error, origin); + } else { + return; + } + } + recordAsyncArrowParametersError(at) { + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + while (scope.canBeArrowParameterDeclaration()) { + if (scope.type === 2) { + scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at); + } + scope = stack[--i]; + } + } + validateAsPattern() { + const { + stack + } = this; + const currentScope = stack[stack.length - 1]; + if (!currentScope.canBeArrowParameterDeclaration()) return; + currentScope.iterateErrors(([toParseError, loc]) => { + this.parser.raise(toParseError, loc); + let i = stack.length - 2; + let scope = stack[i]; + while (scope.canBeArrowParameterDeclaration()) { + scope.clearDeclarationError(loc.index); + scope = stack[--i]; + } + }); + } +} +function newParameterDeclarationScope() { + return new ExpressionScope(3); +} +function newArrowHeadScope() { + return new ArrowHeadParsingScope(1); +} +function newAsyncArrowScope() { + return new ArrowHeadParsingScope(2); +} +function newExpressionScope() { + return new ExpressionScope(); +} +class UtilParser extends Tokenizer { + addExtra(node, key, value, enumerable = true) { + if (!node) return; + let { + extra + } = node; + if (extra == null) { + extra = {}; + node.extra = extra; + } + if (enumerable) { + extra[key] = value; + } else { + Object.defineProperty(extra, key, { + enumerable, + value + }); + } + } + isContextual(token) { + return this.state.type === token && !this.state.containsEsc; + } + isUnparsedContextual(nameStart, name) { + if (this.input.startsWith(name, nameStart)) { + const nextCh = this.input.charCodeAt(nameStart + name.length); + return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800); + } + return false; + } + isLookaheadContextual(name) { + const next = this.nextTokenStart(); + return this.isUnparsedContextual(next, name); + } + eatContextual(token) { + if (this.isContextual(token)) { + this.next(); + return true; + } + return false; + } + expectContextual(token, toParseError) { + if (!this.eatContextual(token)) { + if (toParseError != null) { + throw this.raise(toParseError, this.state.startLoc); + } + this.unexpected(null, token); + } + } + canInsertSemicolon() { + return this.match(140) || this.match(8) || this.hasPrecedingLineBreak(); + } + hasPrecedingLineBreak() { + return hasNewLine(this.input, this.offsetToSourcePos(this.state.lastTokEndLoc.index), this.state.start); + } + hasFollowingLineBreak() { + return hasNewLine(this.input, this.state.end, this.nextTokenStart()); + } + isLineTerminator() { + return this.eat(13) || this.canInsertSemicolon(); + } + semicolon(allowAsi = true) { + if (allowAsi ? this.isLineTerminator() : this.eat(13)) return; + this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc); + } + expect(type, loc) { + if (!this.eat(type)) { + this.unexpected(loc, type); + } + } + tryParse(fn, oldState = this.state.clone()) { + const abortSignal = { + node: null + }; + try { + const node = fn((node = null) => { + abortSignal.node = node; + throw abortSignal; + }); + if (this.state.errors.length > oldState.errors.length) { + const failState = this.state; + this.state = oldState; + this.state.tokensLength = failState.tokensLength; + return { + node, + error: failState.errors[oldState.errors.length], + thrown: false, + aborted: false, + failState + }; + } + return { + node: node, + error: null, + thrown: false, + aborted: false, + failState: null + }; + } catch (error) { + const failState = this.state; + this.state = oldState; + if (error instanceof SyntaxError) { + return { + node: null, + error, + thrown: true, + aborted: false, + failState + }; + } + if (error === abortSignal) { + return { + node: abortSignal.node, + error: null, + thrown: false, + aborted: true, + failState + }; + } + throw error; + } + } + checkExpressionErrors(refExpressionErrors, andThrow) { + if (!refExpressionErrors) return false; + const { + shorthandAssignLoc, + doubleProtoLoc, + privateKeyLoc, + optionalParametersLoc, + voidPatternLoc + } = refExpressionErrors; + const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc || !!voidPatternLoc; + if (!andThrow) { + return hasErrors; + } + if (shorthandAssignLoc != null) { + this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); + } + if (doubleProtoLoc != null) { + this.raise(Errors.DuplicateProto, doubleProtoLoc); + } + if (privateKeyLoc != null) { + this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); + } + if (optionalParametersLoc != null) { + this.unexpected(optionalParametersLoc); + } + if (voidPatternLoc != null) { + this.raise(Errors.InvalidCoverDiscardElement, voidPatternLoc); + } + } + isLiteralPropertyName() { + return tokenIsLiteralPropertyName(this.state.type); + } + isPrivateName(node) { + return node.type === "PrivateName"; + } + getPrivateNameSV(node) { + return node.id.name; + } + hasPropertyAsPrivateName(node) { + return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property); + } + isObjectProperty(node) { + return node.type === "ObjectProperty"; + } + isObjectMethod(node) { + return node.type === "ObjectMethod"; + } + initializeScopes(inModule = this.options.sourceType === "module") { + const oldLabels = this.state.labels; + this.state.labels = []; + const oldExportedIdentifiers = this.exportedIdentifiers; + this.exportedIdentifiers = new Set(); + const oldInModule = this.inModule; + this.inModule = inModule; + const oldScope = this.scope; + const ScopeHandler = this.getScopeHandler(); + this.scope = new ScopeHandler(this, inModule); + const oldProdParam = this.prodParam; + this.prodParam = new ProductionParameterHandler(); + const oldClassScope = this.classScope; + this.classScope = new ClassScopeHandler(this); + const oldExpressionScope = this.expressionScope; + this.expressionScope = new ExpressionScopeHandler(this); + return () => { + this.state.labels = oldLabels; + this.exportedIdentifiers = oldExportedIdentifiers; + this.inModule = oldInModule; + this.scope = oldScope; + this.prodParam = oldProdParam; + this.classScope = oldClassScope; + this.expressionScope = oldExpressionScope; + }; + } + enterInitialScopes() { + let paramFlags = 0; + if (this.inModule || this.optionFlags & 1) { + paramFlags |= 2; + } + if (this.optionFlags & 32) { + paramFlags |= 1; + } + const isCommonJS = !this.inModule && this.options.sourceType === "commonjs"; + if (isCommonJS || this.optionFlags & 2) { + paramFlags |= 4; + } + this.prodParam.enter(paramFlags); + let scopeFlags = isCommonJS ? 514 : 1; + if (this.optionFlags & 4) { + scopeFlags |= 512; + } + this.scope.enter(scopeFlags); + } + checkDestructuringPrivate(refExpressionErrors) { + const { + privateKeyLoc + } = refExpressionErrors; + if (privateKeyLoc !== null) { + this.expectPlugin("destructuringPrivate", privateKeyLoc); + } + } +} +class ExpressionErrors { + constructor() { + this.shorthandAssignLoc = null; + this.doubleProtoLoc = null; + this.privateKeyLoc = null; + this.optionalParametersLoc = null; + this.voidPatternLoc = null; + } +} +class Node { + constructor(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + this.loc = new SourceLocation(loc); + if ((parser == null ? void 0 : parser.optionFlags) & 128) this.range = [pos, 0]; + if (parser != null && parser.filename) this.loc.filename = parser.filename; + } +} +const NodePrototype = Node.prototype; +NodePrototype.__clone = function () { + const newNode = new Node(undefined, this.start, this.loc.start); + const keys = Object.keys(this); + for (let i = 0, length = keys.length; i < length; i++) { + const key = keys[i]; + if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") { + newNode[key] = this[key]; + } + } + return newNode; +}; +class NodeUtils extends UtilParser { + startNode() { + const loc = this.state.startLoc; + return new Node(this, loc.index, loc); + } + startNodeAt(loc) { + return new Node(this, loc.index, loc); + } + startNodeAtNode(type) { + return this.startNodeAt(type.loc.start); + } + finishNode(node, type) { + return this.finishNodeAt(node, type, this.state.lastTokEndLoc); + } + finishNodeAt(node, type, endLoc) { + node.type = type; + node.end = endLoc.index; + node.loc.end = endLoc; + if (this.optionFlags & 128) node.range[1] = endLoc.index; + if (this.optionFlags & 4096) { + this.processComment(node); + } + return node; + } + resetStartLocation(node, startLoc) { + node.start = startLoc.index; + node.loc.start = startLoc; + if (this.optionFlags & 128) node.range[0] = startLoc.index; + } + resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { + node.end = endLoc.index; + node.loc.end = endLoc; + if (this.optionFlags & 128) node.range[1] = endLoc.index; + } + resetStartLocationFromNode(node, locationNode) { + this.resetStartLocation(node, locationNode.loc.start); + } + castNodeTo(node, type) { + node.type = type; + return node; + } + cloneIdentifier(node) { + const { + type, + start, + end, + loc, + range, + name + } = node; + const cloned = Object.create(NodePrototype); + cloned.type = type; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.name = name; + if (node.extra) cloned.extra = node.extra; + return cloned; + } + cloneStringLiteral(node) { + const { + type, + start, + end, + loc, + range, + extra + } = node; + const cloned = Object.create(NodePrototype); + cloned.type = type; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.extra = extra; + cloned.value = node.value; + return cloned; + } +} +const unwrapParenthesizedExpression = node => { + return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; +}; +class LValParser extends NodeUtils { + toAssignable(node, isLHS = false) { + var _node$extra, _node$extra3; + let parenthesized = undefined; + if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) { + parenthesized = unwrapParenthesizedExpression(node); + if (isLHS) { + if (parenthesized.type === "Identifier") { + this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node); + } else if (parenthesized.type !== "CallExpression" && parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) { + this.raise(Errors.InvalidParenthesizedAssignment, node); + } + } else { + this.raise(Errors.InvalidParenthesizedAssignment, node); + } + } + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + case "VoidPattern": + break; + case "ObjectExpression": + this.castNodeTo(node, "ObjectPattern"); + for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) { + var _node$extra2; + const prop = node.properties[i]; + const isLast = i === last; + this.toAssignableObjectExpressionProp(prop, isLast, isLHS); + if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) { + this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc); + } + } + break; + case "ObjectProperty": + { + const { + key, + value + } = node; + if (this.isPrivateName(key)) { + this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); + } + this.toAssignable(value, isLHS); + break; + } + case "SpreadElement": + { + throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller."); + } + case "ArrayExpression": + this.castNodeTo(node, "ArrayPattern"); + this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS); + break; + case "AssignmentExpression": + if (node.operator !== "=") { + this.raise(Errors.MissingEqInAssignment, node.left.loc.end); + } + this.castNodeTo(node, "AssignmentPattern"); + delete node.operator; + if (node.left.type === "VoidPattern") { + this.raise(Errors.VoidPatternInitializer, node.left); + } + this.toAssignable(node.left, isLHS); + break; + case "ParenthesizedExpression": + this.toAssignable(parenthesized, isLHS); + break; + } + } + toAssignableObjectExpressionProp(prop, isLast, isLHS) { + if (prop.type === "ObjectMethod") { + this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key); + } else if (prop.type === "SpreadElement") { + this.castNodeTo(prop, "RestElement"); + const arg = prop.argument; + this.checkToRestConversion(arg, false); + this.toAssignable(arg, isLHS); + if (!isLast) { + this.raise(Errors.RestTrailingComma, prop); + } + } else { + this.toAssignable(prop, isLHS); + } + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + const end = exprList.length - 1; + for (let i = 0; i <= end; i++) { + const elt = exprList[i]; + if (!elt) continue; + this.toAssignableListItem(exprList, i, isLHS); + if (elt.type === "RestElement") { + if (i < end) { + this.raise(Errors.RestTrailingComma, elt); + } else if (trailingCommaLoc) { + this.raise(Errors.RestTrailingComma, trailingCommaLoc); + } + } + } + } + toAssignableListItem(exprList, index, isLHS) { + const node = exprList[index]; + if (node.type === "SpreadElement") { + this.castNodeTo(node, "RestElement"); + const arg = node.argument; + this.checkToRestConversion(arg, true); + this.toAssignable(arg, isLHS); + } else { + this.toAssignable(node, isLHS); + } + } + isAssignable(node, isBinding) { + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + case "VoidPattern": + return true; + case "ObjectExpression": + { + const last = node.properties.length - 1; + return node.properties.every((prop, i) => { + return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop); + }); + } + case "ObjectProperty": + return this.isAssignable(node.value); + case "SpreadElement": + return this.isAssignable(node.argument); + case "ArrayExpression": + return node.elements.every(element => element === null || this.isAssignable(element)); + case "AssignmentExpression": + return node.operator === "="; + case "ParenthesizedExpression": + return this.isAssignable(node.expression); + case "MemberExpression": + case "OptionalMemberExpression": + return !isBinding; + default: + return false; + } + } + toReferencedList(exprList, isParenthesizedExpr) { + return exprList; + } + toReferencedListDeep(exprList, isParenthesizedExpr) { + this.toReferencedList(exprList, isParenthesizedExpr); + for (const expr of exprList) { + if ((expr == null ? void 0 : expr.type) === "ArrayExpression") { + this.toReferencedListDeep(expr.elements); + } + } + } + parseSpread(refExpressionErrors) { + const node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined); + return this.finishNode(node, "SpreadElement"); + } + parseRestBinding() { + const node = this.startNode(); + this.next(); + const argument = this.parseBindingAtom(); + if (argument.type === "VoidPattern") { + this.raise(Errors.UnexpectedVoidPattern, argument); + } + node.argument = argument; + return this.finishNode(node, "RestElement"); + } + parseBindingAtom() { + switch (this.state.type) { + case 0: + { + const node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(3, 93, 1); + return this.finishNode(node, "ArrayPattern"); + } + case 5: + return this.parseObjectLike(8, true); + case 88: + return this.parseVoidPattern(null); + } + return this.parseIdentifier(); + } + parseBindingList(close, closeCharCode, flags) { + const allowEmpty = flags & 1; + const elts = []; + let first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + } + if (allowEmpty && this.match(12)) { + elts.push(null); + } else if (this.eat(close)) { + break; + } else if (this.match(21)) { + let rest = this.parseRestBinding(); + if (this.hasPlugin("flow") || flags & 2) { + rest = this.parseFunctionParamType(rest); + } + elts.push(rest); + if (!this.checkCommaAfterRest(closeCharCode)) { + this.expect(close); + break; + } + } else { + const decorators = []; + if (flags & 2) { + if (this.match(26) && this.hasPlugin("decorators")) { + this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc); + } + while (this.match(26)) { + decorators.push(this.parseDecorator()); + } + } + elts.push(this.parseBindingElement(flags, decorators)); + } + } + return elts; + } + parseBindingRestProperty(prop) { + this.next(); + if (this.hasPlugin("discardBinding") && this.match(88)) { + prop.argument = this.parseVoidPattern(null); + this.raise(Errors.UnexpectedVoidPattern, prop.argument); + } else { + prop.argument = this.parseIdentifier(); + } + this.checkCommaAfterRest(125); + return this.finishNode(prop, "RestElement"); + } + parseBindingProperty() { + const { + type, + startLoc + } = this.state; + if (type === 21) { + return this.parseBindingRestProperty(this.startNode()); + } + const prop = this.startNode(); + if (type === 139) { + this.expectPlugin("destructuringPrivate", startLoc); + this.classScope.usePrivateName(this.state.value, startLoc); + prop.key = this.parsePrivateName(); + } else { + this.parsePropertyName(prop); + } + prop.method = false; + return this.parseObjPropValue(prop, startLoc, false, false, true, false); + } + parseBindingElement(flags, decorators) { + const left = this.parseMaybeDefault(); + if (this.hasPlugin("flow") || flags & 2) { + this.parseFunctionParamType(left); + } + if (decorators.length) { + left.decorators = decorators; + this.resetStartLocationFromNode(left, decorators[0]); + } + const elt = this.parseMaybeDefault(left.loc.start, left); + return elt; + } + parseFunctionParamType(param) { + return param; + } + parseMaybeDefault(startLoc, left) { + startLoc != null ? startLoc : startLoc = this.state.startLoc; + left = left != null ? left : this.parseBindingAtom(); + if (!this.eat(29)) return left; + const node = this.startNodeAt(startLoc); + if (left.type === "VoidPattern") { + this.raise(Errors.VoidPatternInitializer, left); + } + node.left = left; + node.right = this.parseMaybeAssignAllowIn(); + return this.finishNode(node, "AssignmentPattern"); + } + isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) { + switch (type) { + case "AssignmentPattern": + return "left"; + case "RestElement": + return "argument"; + case "ObjectProperty": + return "value"; + case "ParenthesizedExpression": + return "expression"; + case "ArrayPattern": + return "elements"; + case "ObjectPattern": + return "properties"; + case "VoidPattern": + return true; + case "CallExpression": + if (!disallowCallExpression && !this.state.strict && this.optionFlags & 8192) { + return true; + } + } + return false; + } + isOptionalMemberExpression(expression) { + return expression.type === "OptionalMemberExpression"; + } + checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false, disallowCallExpression = false) { + var _expression$extra; + const type = expression.type; + if (this.isObjectMethod(expression)) return; + const isOptionalMemberExpression = this.isOptionalMemberExpression(expression); + if (isOptionalMemberExpression || type === "MemberExpression") { + if (isOptionalMemberExpression) { + this.expectPlugin("optionalChainingAssign", expression.loc.start); + if (ancestor.type !== "AssignmentExpression") { + this.raise(Errors.InvalidLhsOptionalChaining, expression, { + ancestor + }); + } + } + if (binding !== 64) { + this.raise(Errors.InvalidPropertyBindingPattern, expression); + } + return; + } + if (type === "Identifier") { + this.checkIdentifier(expression, binding, strictModeChanged); + const { + name + } = expression; + if (checkClashes) { + if (checkClashes.has(name)) { + this.raise(Errors.ParamDupe, expression); + } else { + checkClashes.add(name); + } + } + return; + } else if (type === "VoidPattern" && ancestor.type === "CatchClause") { + this.raise(Errors.VoidPatternCatchClauseParam, expression); + } + const unwrappedExpression = unwrapParenthesizedExpression(expression); + disallowCallExpression || (disallowCallExpression = unwrappedExpression.type === "CallExpression" && (unwrappedExpression.callee.type === "Import" || unwrappedExpression.callee.type === "Super")); + const validity = this.isValidLVal(type, disallowCallExpression, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding); + if (validity === true) return; + if (validity === false) { + const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding; + this.raise(ParseErrorClass, expression, { + ancestor + }); + return; + } + let key, isParenthesizedExpression; + if (typeof validity === "string") { + key = validity; + isParenthesizedExpression = type === "ParenthesizedExpression"; + } else { + [key, isParenthesizedExpression] = validity; + } + const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? { + type + } : ancestor; + const val = expression[key]; + if (Array.isArray(val)) { + for (const child of val) { + if (child) { + this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, true); + } + } + } else if (val) { + this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, disallowCallExpression); + } + } + checkIdentifier(at, bindingType, strictModeChanged = false) { + if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) { + if (bindingType === 64) { + this.raise(Errors.StrictEvalArguments, at, { + referenceName: at.name + }); + } else { + this.raise(Errors.StrictEvalArgumentsBinding, at, { + bindingName: at.name + }); + } + } + if (bindingType & 8192 && at.name === "let") { + this.raise(Errors.LetInLexicalBinding, at); + } + if (!(bindingType & 64)) { + this.declareNameFromIdentifier(at, bindingType); + } + } + declareNameFromIdentifier(identifier, binding) { + this.scope.declareName(identifier.name, binding, identifier.loc.start); + } + checkToRestConversion(node, allowPattern) { + switch (node.type) { + case "ParenthesizedExpression": + this.checkToRestConversion(node.expression, allowPattern); + break; + case "Identifier": + case "MemberExpression": + break; + case "ArrayExpression": + case "ObjectExpression": + if (allowPattern) break; + default: + this.raise(Errors.InvalidRestAssignmentPattern, node); + } + } + checkCommaAfterRest(close) { + if (!this.match(12)) { + return false; + } + this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc); + return true; + } +} +const keywordAndTSRelationalOperator = /in(?:stanceof)?|as|satisfies/y; +function nonNull(x) { + if (x == null) { + throw new Error(`Unexpected ${x} value.`); + } + return x; +} +function assert(x) { + if (!x) { + throw new Error("Assert fail"); + } +} +const TSErrors = ParseErrorEnum`typescript`({ + AbstractMethodHasImplementation: ({ + methodName + }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`, + AbstractPropertyHasInitializer: ({ + propertyName + }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`, + AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.", + AccessorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.", + AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.", + ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.", + ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.", + ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.", + ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.", + DeclareAccessor: ({ + kind + }) => `'declare' is not allowed in ${kind}ters.`, + DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.", + DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.", + DuplicateAccessibilityModifier: ({ + modifier + }) => `Accessibility modifier already seen: '${modifier}'.`, + DuplicateModifier: ({ + modifier + }) => `Duplicate modifier: '${modifier}'.`, + EmptyHeritageClauseType: ({ + token + }) => `'${token}' list cannot be empty.`, + EmptyTypeArguments: "Type argument list cannot be empty.", + EmptyTypeParameters: "Type parameter list cannot be empty.", + ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.", + ImportAliasHasImportType: "An import alias can not use 'import type'.", + ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier", + IncompatibleModifiers: ({ + modifiers + }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`, + IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.", + IndexSignatureHasAccessibility: ({ + modifier + }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`, + IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.", + IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.", + IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.", + InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.", + InvalidHeritageClauseType: ({ + token + }) => `'${token}' list can only include identifiers or qualified-names with optional type arguments.`, + InvalidModifierOnAwaitUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on an await using declaration.`, + InvalidModifierOnTypeMember: ({ + modifier + }) => `'${modifier}' modifier cannot appear on a type member.`, + InvalidModifierOnTypeParameter: ({ + modifier + }) => `'${modifier}' modifier cannot appear on a type parameter.`, + InvalidModifierOnTypeParameterPositions: ({ + modifier + }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`, + InvalidModifierOnUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on a using declaration.`, + InvalidModifiersOrder: ({ + orderedModifiers + }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`, + InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.", + InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.", + MissingInterfaceName: "'interface' declarations must be followed by an identifier.", + NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.", + NonClassMethodPropertyHasAbstractModifier: "'abstract' modifier can only appear on a class, method, or property declaration.", + OptionalTypeBeforeRequired: "A required element cannot follow an optional element.", + OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.", + PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", + PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.", + PrivateElementHasAccessibility: ({ + modifier + }) => `Private elements cannot have an accessibility modifier ('${modifier}').`, + ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.", + ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `() => ...`.", + ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.", + SetAccessorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.", + SetAccessorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.", + SetAccessorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.", + SingleTypeParameterWithoutTrailingComma: ({ + typeParameterName + }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`, + StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.", + TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).", + TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.", + TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.", + TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.", + UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.", + UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.", + UnexpectedTypeAnnotation: "Did not expect a type annotation here.", + UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.", + UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.", + UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.", + UnsupportedSignatureParameterKind: ({ + type + }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`, + UsingDeclarationInAmbientContext: kind => `'${kind}' declarations are not allowed in ambient contexts.` +}); +function keywordTypeFromName(value) { + switch (value) { + case "any": + return "TSAnyKeyword"; + case "boolean": + return "TSBooleanKeyword"; + case "bigint": + return "TSBigIntKeyword"; + case "never": + return "TSNeverKeyword"; + case "number": + return "TSNumberKeyword"; + case "object": + return "TSObjectKeyword"; + case "string": + return "TSStringKeyword"; + case "symbol": + return "TSSymbolKeyword"; + case "undefined": + return "TSUndefinedKeyword"; + case "unknown": + return "TSUnknownKeyword"; + default: + return undefined; + } +} +function tsIsAccessModifier(modifier) { + return modifier === "private" || modifier === "public" || modifier === "protected"; +} +function tsIsVarianceAnnotations(modifier) { + return modifier === "in" || modifier === "out"; +} +var typescript = superClass => class TypeScriptParserMixin extends superClass { + constructor(...args) { + super(...args); + this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, { + allowedModifiers: ["in", "out"], + disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameter + }); + this.tsParseConstModifier = this.tsParseModifiers.bind(this, { + allowedModifiers: ["const"], + disallowedModifiers: ["in", "out"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions + }); + this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, { + allowedModifiers: ["in", "out", "const"], + disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameter + }); + } + getScopeHandler() { + return TypeScriptScopeHandler; + } + tsIsIdentifier() { + return tokenIsIdentifier(this.state.type); + } + tsTokenCanFollowModifier() { + return this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(139) || this.isLiteralPropertyName(); + } + tsNextTokenOnSameLineAndCanFollowModifier() { + this.next(); + if (this.hasPrecedingLineBreak()) { + return false; + } + return this.tsTokenCanFollowModifier(); + } + tsNextTokenCanFollowModifier() { + if (this.match(106)) { + this.next(); + return this.tsTokenCanFollowModifier(); + } + return this.tsNextTokenOnSameLineAndCanFollowModifier(); + } + tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock, hasSeenStaticModifier) { + if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) { + return undefined; + } + const modifier = this.state.value; + if (allowedModifiers.includes(modifier)) { + if (hasSeenStaticModifier && this.match(106)) { + return undefined; + } + if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { + return undefined; + } + if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { + return modifier; + } + } + return undefined; + } + tsParseModifiers({ + allowedModifiers, + disallowedModifiers, + stopOnStartOfClassStaticBlock, + errorTemplate = TSErrors.InvalidModifierOnTypeMember + }, modified) { + const enforceOrder = (loc, modifier, before, after) => { + if (modifier === before && modified[after]) { + this.raise(TSErrors.InvalidModifiersOrder, loc, { + orderedModifiers: [before, after] + }); + } + }; + const incompatible = (loc, modifier, mod1, mod2) => { + if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) { + this.raise(TSErrors.IncompatibleModifiers, loc, { + modifiers: [mod1, mod2] + }); + } + }; + for (;;) { + const { + startLoc + } = this.state; + const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock, modified.static); + if (!modifier) break; + if (tsIsAccessModifier(modifier)) { + if (modified.accessibility) { + this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, { + modifier + }); + } else { + enforceOrder(startLoc, modifier, modifier, "override"); + enforceOrder(startLoc, modifier, modifier, "static"); + enforceOrder(startLoc, modifier, modifier, "readonly"); + modified.accessibility = modifier; + } + } else if (tsIsVarianceAnnotations(modifier)) { + if (modified[modifier]) { + this.raise(TSErrors.DuplicateModifier, startLoc, { + modifier + }); + } + modified[modifier] = true; + enforceOrder(startLoc, modifier, "in", "out"); + } else { + if (hasOwnProperty.call(modified, modifier)) { + this.raise(TSErrors.DuplicateModifier, startLoc, { + modifier + }); + } else { + enforceOrder(startLoc, modifier, "static", "readonly"); + enforceOrder(startLoc, modifier, "static", "override"); + enforceOrder(startLoc, modifier, "override", "readonly"); + enforceOrder(startLoc, modifier, "abstract", "override"); + incompatible(startLoc, modifier, "declare", "override"); + incompatible(startLoc, modifier, "static", "abstract"); + } + modified[modifier] = true; + } + if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) { + this.raise(errorTemplate, startLoc, { + modifier + }); + } + } + } + tsIsListTerminator(kind) { + switch (kind) { + case "EnumMembers": + case "TypeMembers": + return this.match(8); + case "HeritageClauseElement": + return this.match(5); + case "TupleElementTypes": + return this.match(3); + case "TypeParametersOrArguments": + return this.match(48); + } + } + tsParseList(kind, parseElement) { + const result = []; + while (!this.tsIsListTerminator(kind)) { + result.push(parseElement()); + } + return result; + } + tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) { + return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos)); + } + tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) { + const result = []; + let trailingCommaPos = -1; + for (;;) { + if (this.tsIsListTerminator(kind)) { + break; + } + trailingCommaPos = -1; + const element = parseElement(); + if (element == null) { + return undefined; + } + result.push(element); + if (this.eat(12)) { + trailingCommaPos = this.state.lastTokStartLoc.index; + continue; + } + if (this.tsIsListTerminator(kind)) { + break; + } + if (expectSuccess) { + this.expect(12); + } + return undefined; + } + if (refTrailingCommaPos) { + refTrailingCommaPos.value = trailingCommaPos; + } + return result; + } + tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) { + if (!skipFirstToken) { + if (bracket) { + this.expect(0); + } else { + this.expect(47); + } + } + const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos); + if (bracket) { + this.expect(3); + } else { + this.expect(48); + } + return result; + } + tsParseImportType() { + const node = this.startNode(); + this.expect(83); + this.expect(10); + if (!this.match(134)) { + this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc); + node.argument = super.parseExprAtom(); + } else { + node.argument = this.parseStringLiteral(this.state.value); + } + if (this.eat(12)) { + node.options = this.tsParseImportTypeOptions(); + } else { + node.options = null; + } + this.expect(11); + if (this.eat(16)) { + node.qualifier = this.tsParseEntityName(1 | 2); + } + if (this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSImportType"); + } + tsParseImportTypeOptions() { + const node = this.startNode(); + this.expect(5); + const withProperty = this.startNode(); + if (this.isContextual(76)) { + withProperty.method = false; + withProperty.key = this.parseIdentifier(true); + withProperty.computed = false; + withProperty.shorthand = false; + } else { + this.unexpected(null, 76); + } + this.expect(14); + withProperty.value = this.tsParseImportTypeWithPropertyValue(); + node.properties = [this.finishObjectProperty(withProperty)]; + this.eat(12); + this.expect(8); + return this.finishNode(node, "ObjectExpression"); + } + tsParseImportTypeWithPropertyValue() { + const node = this.startNode(); + const properties = []; + this.expect(5); + while (!this.match(8)) { + const type = this.state.type; + if (tokenIsIdentifier(type) || type === 134) { + properties.push(super.parsePropertyDefinition(null)); + } else { + this.unexpected(); + } + this.eat(12); + } + node.properties = properties; + this.next(); + return this.finishNode(node, "ObjectExpression"); + } + tsParseEntityName(flags) { + let entity; + if (flags & 1 && this.match(78)) { + if (flags & 2) { + entity = this.parseIdentifier(true); + } else { + const node = this.startNode(); + this.next(); + entity = this.finishNode(node, "ThisExpression"); + } + } else { + entity = this.parseIdentifier(!!(flags & 1)); + } + while (this.eat(16)) { + const node = this.startNodeAtNode(entity); + node.left = entity; + node.right = this.parseIdentifier(!!(flags & 1)); + entity = this.finishNode(node, "TSQualifiedName"); + } + return entity; + } + tsParseTypeReference() { + const node = this.startNode(); + node.typeName = this.tsParseEntityName(1); + if (!this.hasPrecedingLineBreak() && this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeReference"); + } + tsParseThisTypePredicate(lhs) { + this.next(); + const node = this.startNodeAtNode(lhs); + node.parameterName = lhs; + node.typeAnnotation = this.tsParseTypeAnnotation(false); + node.asserts = false; + return this.finishNode(node, "TSTypePredicate"); + } + tsParseThisTypeNode() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSThisType"); + } + tsParseTypeQuery() { + const node = this.startNode(); + this.expect(87); + if (this.match(83)) { + node.exprName = this.tsParseImportType(); + } else { + node.exprName = this.tsParseEntityName(1 | 2); + } + if (!this.hasPrecedingLineBreak() && this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeQuery"); + } + tsParseTypeParameter(parseModifiers) { + const node = this.startNode(); + parseModifiers(node); + node.name = this.tsParseTypeParameterName(); + node.constraint = this.tsEatThenParseType(81); + node.default = this.tsEatThenParseType(29); + return this.finishNode(node, "TSTypeParameter"); + } + tsTryParseTypeParameters(parseModifiers) { + if (this.match(47)) { + return this.tsParseTypeParameters(parseModifiers); + } + } + tsParseTypeParameters(parseModifiers) { + const node = this.startNode(); + if (this.match(47) || this.match(143)) { + this.next(); + } else { + this.unexpected(); + } + const refTrailingCommaPos = { + value: -1 + }; + node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos); + if (node.params.length === 0) { + this.raise(TSErrors.EmptyTypeParameters, node); + } + if (refTrailingCommaPos.value !== -1) { + this.addExtra(node, "trailingComma", refTrailingCommaPos.value); + } + return this.finishNode(node, "TSTypeParameterDeclaration"); + } + tsFillSignature(returnToken, signature) { + const returnTokenRequired = returnToken === 19; + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + this.expect(10); + signature[paramsKey] = this.tsParseBindingListForSignature(); + if (returnTokenRequired) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } else if (this.match(returnToken)) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } + } + tsParseBindingListForSignature() { + const list = super.parseBindingList(11, 41, 2); + for (const pattern of list) { + const { + type + } = pattern; + if (type === "AssignmentPattern" || type === "TSParameterProperty") { + this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, { + type + }); + } + } + return list; + } + tsParseTypeMemberSemicolon() { + if (!this.eat(12) && !this.isLineTerminator()) { + this.expect(13); + } + } + tsParseSignatureMember(kind, node) { + this.tsFillSignature(14, node); + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, kind); + } + tsIsUnambiguouslyIndexSignature() { + this.next(); + if (tokenIsIdentifier(this.state.type)) { + this.next(); + return this.match(14); + } + return false; + } + tsTryParseIndexSignature(node) { + if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { + return; + } + this.expect(0); + const id = this.parseIdentifier(); + id.typeAnnotation = this.tsParseTypeAnnotation(); + this.resetEndLocation(id); + this.expect(3); + node.parameters = [id]; + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, "TSIndexSignature"); + } + tsParsePropertyOrMethodSignature(node, readonly) { + if (this.eat(17)) node.optional = true; + if (this.match(10) || this.match(47)) { + if (readonly) { + this.raise(TSErrors.ReadonlyForMethodSignature, node); + } + const method = node; + if (method.kind && this.match(47)) { + this.raise(TSErrors.AccessorCannotHaveTypeParameters, this.state.curPosition()); + } + this.tsFillSignature(14, method); + this.tsParseTypeMemberSemicolon(); + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + if (method.kind === "get") { + if (method[paramsKey].length > 0) { + this.raise(Errors.BadGetterArity, this.state.curPosition()); + if (this.isThisParam(method[paramsKey][0])) { + this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition()); + } + } + } else if (method.kind === "set") { + if (method[paramsKey].length !== 1) { + this.raise(Errors.BadSetterArity, this.state.curPosition()); + } else { + const firstParameter = method[paramsKey][0]; + if (this.isThisParam(firstParameter)) { + this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition()); + } + if (firstParameter.type === "Identifier" && firstParameter.optional) { + this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, this.state.curPosition()); + } + if (firstParameter.type === "RestElement") { + this.raise(TSErrors.SetAccessorCannotHaveRestParameter, this.state.curPosition()); + } + } + if (method[returnTypeKey]) { + this.raise(TSErrors.SetAccessorCannotHaveReturnType, method[returnTypeKey]); + } + } else { + method.kind = "method"; + } + return this.finishNode(method, "TSMethodSignature"); + } else { + const property = node; + if (readonly) property.readonly = true; + const type = this.tsTryParseTypeAnnotation(); + if (type) property.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(property, "TSPropertySignature"); + } + } + tsParseTypeMember() { + const node = this.startNode(); + if (this.match(10) || this.match(47)) { + return this.tsParseSignatureMember("TSCallSignatureDeclaration", node); + } + if (this.match(77)) { + const id = this.startNode(); + this.next(); + if (this.match(10) || this.match(47)) { + return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node); + } else { + node.key = this.createIdentifier(id, "new"); + return this.tsParsePropertyOrMethodSignature(node, false); + } + } + this.tsParseModifiers({ + allowedModifiers: ["readonly"], + disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"] + }, node); + const idx = this.tsTryParseIndexSignature(node); + if (idx) { + return idx; + } + super.parsePropertyName(node); + if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) { + node.kind = node.key.name; + super.parsePropertyName(node); + if (!this.match(10) && !this.match(47)) { + this.unexpected(null, 10); + } + } + return this.tsParsePropertyOrMethodSignature(node, !!node.readonly); + } + tsParseTypeLiteral() { + const node = this.startNode(); + node.members = this.tsParseObjectTypeMembers(); + return this.finishNode(node, "TSTypeLiteral"); + } + tsParseObjectTypeMembers() { + this.expect(5); + const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); + this.expect(8); + return members; + } + tsIsStartOfMappedType() { + this.next(); + if (this.eat(53)) { + return this.isContextual(122); + } + if (this.isContextual(122)) { + this.next(); + } + if (!this.match(0)) { + return false; + } + this.next(); + if (!this.tsIsIdentifier()) { + return false; + } + this.next(); + return this.match(58); + } + tsParseMappedType() { + const node = this.startNode(); + this.expect(5); + if (this.match(53)) { + node.readonly = this.state.value; + this.next(); + this.expectContextual(122); + } else if (this.eatContextual(122)) { + node.readonly = true; + } + this.expect(0); + const typeParameter = this.startNode(); + typeParameter.name = this.tsParseTypeParameterName(); + typeParameter.constraint = this.tsExpectThenParseType(58); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + node.nameType = this.eatContextual(93) ? this.tsParseType() : null; + this.expect(3); + if (this.match(53)) { + node.optional = this.state.value; + this.next(); + this.expect(17); + } else if (this.eat(17)) { + node.optional = true; + } + node.typeAnnotation = this.tsTryParseType(); + this.semicolon(); + this.expect(8); + return this.finishNode(node, "TSMappedType"); + } + tsParseTupleType() { + const node = this.startNode(); + node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false); + let seenOptionalElement = false; + node.elementTypes.forEach(elementNode => { + const { + type + } = elementNode; + if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) { + this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode); + } + seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType"); + }); + return this.finishNode(node, "TSTupleType"); + } + tsParseTupleElementType() { + const restStartLoc = this.state.startLoc; + const rest = this.eat(21); + const { + startLoc + } = this.state; + let labeled; + let label; + let optional; + let type; + const isWord = tokenIsKeywordOrIdentifier(this.state.type); + const chAfterWord = isWord ? this.lookaheadCharCode() : null; + if (chAfterWord === 58) { + labeled = true; + optional = false; + label = this.parseIdentifier(true); + this.expect(14); + type = this.tsParseType(); + } else if (chAfterWord === 63) { + optional = true; + const wordName = this.state.value; + const typeOrLabel = this.tsParseNonArrayType(); + if (this.lookaheadCharCode() === 58) { + labeled = true; + label = this.createIdentifier(this.startNodeAt(startLoc), wordName); + this.expect(17); + this.expect(14); + type = this.tsParseType(); + } else { + labeled = false; + type = typeOrLabel; + this.expect(17); + } + } else { + type = this.tsParseType(); + optional = this.eat(17); + labeled = this.eat(14); + } + if (labeled) { + let labeledNode; + if (label) { + labeledNode = this.startNodeAt(startLoc); + labeledNode.optional = optional; + labeledNode.label = label; + labeledNode.elementType = type; + if (this.eat(17)) { + labeledNode.optional = true; + this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc); + } + } else { + labeledNode = this.startNodeAt(startLoc); + labeledNode.optional = optional; + this.raise(TSErrors.InvalidTupleMemberLabel, type); + labeledNode.label = type; + labeledNode.elementType = this.tsParseType(); + } + type = this.finishNode(labeledNode, "TSNamedTupleMember"); + } else if (optional) { + const optionalTypeNode = this.startNodeAt(startLoc); + optionalTypeNode.typeAnnotation = type; + type = this.finishNode(optionalTypeNode, "TSOptionalType"); + } + if (rest) { + const restNode = this.startNodeAt(restStartLoc); + restNode.typeAnnotation = type; + type = this.finishNode(restNode, "TSRestType"); + } + return type; + } + tsParseParenthesizedType() { + const node = this.startNode(); + this.expect(10); + node.typeAnnotation = this.tsParseType(); + this.expect(11); + return this.finishNode(node, "TSParenthesizedType"); + } + tsParseFunctionOrConstructorType(type, abstract) { + const node = this.startNode(); + if (type === "TSConstructorType") { + node.abstract = !!abstract; + if (abstract) this.next(); + this.next(); + } + this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node)); + return this.finishNode(node, type); + } + tsParseLiteralTypeNode() { + const node = this.startNode(); + switch (this.state.type) { + case 135: + case 136: + case 134: + case 85: + case 86: + node.literal = super.parseExprAtom(); + break; + default: + this.unexpected(); + } + return this.finishNode(node, "TSLiteralType"); + } + tsParseTemplateLiteralType() { + const node = this.startNode(); + node.literal = super.parseTemplate(false); + return this.finishNode(node, "TSLiteralType"); + } + parseTemplateSubstitution() { + if (this.state.inType) return this.tsParseType(); + return super.parseTemplateSubstitution(); + } + tsParseThisTypeOrThisTypePredicate() { + const thisKeyword = this.tsParseThisTypeNode(); + if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { + return this.tsParseThisTypePredicate(thisKeyword); + } else { + return thisKeyword; + } + } + tsParseNonArrayType() { + switch (this.state.type) { + case 134: + case 135: + case 136: + case 85: + case 86: + return this.tsParseLiteralTypeNode(); + case 53: + if (this.state.value === "-") { + const node = this.startNode(); + const nextToken = this.lookahead(); + if (nextToken.type !== 135 && nextToken.type !== 136) { + this.unexpected(); + } + node.literal = this.parseMaybeUnary(); + return this.finishNode(node, "TSLiteralType"); + } + break; + case 78: + return this.tsParseThisTypeOrThisTypePredicate(); + case 87: + return this.tsParseTypeQuery(); + case 83: + return this.tsParseImportType(); + case 5: + return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); + case 0: + return this.tsParseTupleType(); + case 10: + return this.tsParseParenthesizedType(); + case 25: + case 24: + return this.tsParseTemplateLiteralType(); + default: + { + const { + type + } = this.state; + if (tokenIsIdentifier(type) || type === 88 || type === 84) { + const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value); + if (nodeType !== undefined && this.lookaheadCharCode() !== 46) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, nodeType); + } + return this.tsParseTypeReference(); + } + } + } + throw this.unexpected(); + } + tsParseArrayTypeOrHigher() { + const { + startLoc + } = this.state; + let type = this.tsParseNonArrayType(); + while (!this.hasPrecedingLineBreak() && this.eat(0)) { + if (this.match(3)) { + const node = this.startNodeAt(startLoc); + node.elementType = type; + this.expect(3); + type = this.finishNode(node, "TSArrayType"); + } else { + const node = this.startNodeAt(startLoc); + node.objectType = type; + node.indexType = this.tsParseType(); + this.expect(3); + type = this.finishNode(node, "TSIndexedAccessType"); + } + } + return type; + } + tsParseTypeOperator() { + const node = this.startNode(); + const operator = this.state.value; + this.next(); + node.operator = operator; + node.typeAnnotation = this.tsParseTypeOperatorOrHigher(); + if (operator === "readonly") { + this.tsCheckTypeAnnotationForReadOnly(node); + } + return this.finishNode(node, "TSTypeOperator"); + } + tsCheckTypeAnnotationForReadOnly(node) { + switch (node.typeAnnotation.type) { + case "TSTupleType": + case "TSArrayType": + return; + default: + this.raise(TSErrors.UnexpectedReadonly, node); + } + } + tsParseInferType() { + const node = this.startNode(); + this.expectContextual(115); + const typeParameter = this.startNode(); + typeParameter.name = this.tsParseTypeParameterName(); + typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType()); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + return this.finishNode(node, "TSInferType"); + } + tsParseConstraintForInferType() { + if (this.eat(81)) { + const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType()); + if (this.state.inDisallowConditionalTypesContext || !this.match(17)) { + return constraint; + } + } + } + tsParseTypeOperatorOrHigher() { + const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc; + return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher()); + } + tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { + const node = this.startNode(); + const hasLeadingOperator = this.eat(operator); + const types = []; + do { + types.push(parseConstituentType()); + } while (this.eat(operator)); + if (types.length === 1 && !hasLeadingOperator) { + return types[0]; + } + node.types = types; + return this.finishNode(node, kind); + } + tsParseIntersectionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45); + } + tsParseUnionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43); + } + tsIsStartOfFunctionType() { + if (this.match(47)) { + return true; + } + return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); + } + tsSkipParameterStart() { + if (tokenIsIdentifier(this.state.type) || this.match(78)) { + this.next(); + return true; + } + if (this.match(5)) { + const { + errors + } = this.state; + const previousErrorCount = errors.length; + try { + this.parseObjectLike(8, true); + return errors.length === previousErrorCount; + } catch (_unused) { + return false; + } + } + if (this.match(0)) { + this.next(); + const { + errors + } = this.state; + const previousErrorCount = errors.length; + try { + super.parseBindingList(3, 93, 1); + return errors.length === previousErrorCount; + } catch (_unused2) { + return false; + } + } + return false; + } + tsIsUnambiguouslyStartOfFunctionType() { + this.next(); + if (this.match(11) || this.match(21)) { + return true; + } + if (this.tsSkipParameterStart()) { + if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) { + return true; + } + if (this.match(11)) { + this.next(); + if (this.match(19)) { + return true; + } + } + } + return false; + } + tsParseTypeOrTypePredicateAnnotation(returnToken) { + return this.tsInType(() => { + const t = this.startNode(); + this.expect(returnToken); + const node = this.startNode(); + const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this)); + if (asserts && this.match(78)) { + let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); + if (thisTypePredicate.type === "TSThisType") { + node.parameterName = thisTypePredicate; + node.asserts = true; + node.typeAnnotation = null; + thisTypePredicate = this.finishNode(node, "TSTypePredicate"); + } else { + this.resetStartLocationFromNode(thisTypePredicate, node); + thisTypePredicate.asserts = true; + } + t.typeAnnotation = thisTypePredicate; + return this.finishNode(t, "TSTypeAnnotation"); + } + const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); + if (!typePredicateVariable) { + if (!asserts) { + return this.tsParseTypeAnnotation(false, t); + } + node.parameterName = this.parseIdentifier(); + node.asserts = asserts; + node.typeAnnotation = null; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + } + const type = this.tsParseTypeAnnotation(false); + node.parameterName = typePredicateVariable; + node.typeAnnotation = type; + node.asserts = asserts; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + }); + } + tsTryParseTypeOrTypePredicateAnnotation() { + if (this.match(14)) { + return this.tsParseTypeOrTypePredicateAnnotation(14); + } + } + tsTryParseTypeAnnotation() { + if (this.match(14)) { + return this.tsParseTypeAnnotation(); + } + } + tsTryParseType() { + return this.tsEatThenParseType(14); + } + tsParseTypePredicatePrefix() { + const id = this.parseIdentifier(); + if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { + this.next(); + return id; + } + } + tsParseTypePredicateAsserts() { + if (this.state.type !== 109) { + return false; + } + const containsEsc = this.state.containsEsc; + this.next(); + if (!tokenIsIdentifier(this.state.type) && !this.match(78)) { + return false; + } + if (containsEsc) { + this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, { + reservedWord: "asserts" + }); + } + return true; + } + tsParseTypeAnnotation(eatColon = true, t = this.startNode()) { + this.tsInType(() => { + if (eatColon) this.expect(14); + t.typeAnnotation = this.tsParseType(); + }); + return this.finishNode(t, "TSTypeAnnotation"); + } + tsParseType() { + assert(this.state.inType); + const type = this.tsParseNonConditionalType(); + if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) { + return type; + } + const node = this.startNodeAtNode(type); + node.checkType = type; + node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType()); + this.expect(17); + node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + this.expect(14); + node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + return this.finishNode(node, "TSConditionalType"); + } + isAbstractConstructorSignature() { + return this.isContextual(124) && this.isLookaheadContextual("new"); + } + tsParseNonConditionalType() { + if (this.tsIsStartOfFunctionType()) { + return this.tsParseFunctionOrConstructorType("TSFunctionType"); + } + if (this.match(77)) { + return this.tsParseFunctionOrConstructorType("TSConstructorType"); + } else if (this.isAbstractConstructorSignature()) { + return this.tsParseFunctionOrConstructorType("TSConstructorType", true); + } + return this.tsParseUnionTypeOrHigher(); + } + tsParseTypeAssertion() { + if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { + this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc); + } + const node = this.startNode(); + node.typeAnnotation = this.tsInType(() => { + this.next(); + return this.match(75) ? this.tsParseTypeReference() : this.tsParseType(); + }); + this.expect(48); + node.expression = this.parseMaybeUnary(); + return this.finishNode(node, "TSTypeAssertion"); + } + tsParseHeritageClause(token) { + const originalStartLoc = this.state.startLoc; + const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => { + const node = this.startNode(); + node.expression = this.tsParseEntityName(1 | 2); + if (this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSExpressionWithTypeArguments"); + }); + if (!delimitedList.length) { + this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, { + token + }); + } + return delimitedList; + } + tsParseInterfaceDeclaration(node, properties = {}) { + if (this.hasFollowingLineBreak()) return null; + this.expectContextual(129); + if (properties.declare) node.declare = true; + if (tokenIsIdentifier(this.state.type)) { + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, 130); + } else { + node.id = null; + this.raise(TSErrors.MissingInterfaceName, this.state.startLoc); + } + node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); + if (this.eat(81)) { + node.extends = this.tsParseHeritageClause("extends"); + } + const body = this.startNode(); + body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this)); + node.body = this.finishNode(body, "TSInterfaceBody"); + return this.finishNode(node, "TSInterfaceDeclaration"); + } + tsParseTypeAliasDeclaration(node) { + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, 2); + node.typeAnnotation = this.tsInType(() => { + node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers); + this.expect(29); + if (this.isContextual(114) && this.lookaheadCharCode() !== 46) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSIntrinsicKeyword"); + } + return this.tsParseType(); + }); + this.semicolon(); + return this.finishNode(node, "TSTypeAliasDeclaration"); + } + tsInTopLevelContext(cb) { + if (this.curContext() !== types.brace) { + const oldContext = this.state.context; + this.state.context = [oldContext[0]]; + try { + return cb(); + } finally { + this.state.context = oldContext; + } + } else { + return cb(); + } + } + tsInType(cb) { + const oldInType = this.state.inType; + this.state.inType = true; + try { + return cb(); + } finally { + this.state.inType = oldInType; + } + } + tsInDisallowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; + this.state.inDisallowConditionalTypesContext = true; + try { + return cb(); + } finally { + this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsInAllowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; + this.state.inDisallowConditionalTypesContext = false; + try { + return cb(); + } finally { + this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsEatThenParseType(token) { + if (this.match(token)) { + return this.tsNextThenParseType(); + } + } + tsExpectThenParseType(token) { + return this.tsInType(() => { + this.expect(token); + return this.tsParseType(); + }); + } + tsNextThenParseType() { + return this.tsInType(() => { + this.next(); + return this.tsParseType(); + }); + } + tsParseEnumMember() { + const node = this.startNode(); + node.id = this.match(134) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true); + if (this.eat(29)) { + node.initializer = super.parseMaybeAssignAllowIn(); + } + return this.finishNode(node, "TSEnumMember"); + } + tsParseEnumDeclaration(node, properties = {}) { + if (properties.const) node.const = true; + if (properties.declare) node.declare = true; + this.expectContextual(126); + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, node.const ? 8971 : 8459); + this.expect(5); + node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); + this.expect(8); + return this.finishNode(node, "TSEnumDeclaration"); + } + tsParseEnumBody() { + const node = this.startNode(); + this.expect(5); + node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); + this.expect(8); + return this.finishNode(node, "TSEnumBody"); + } + tsParseModuleBlock() { + const node = this.startNode(); + this.scope.enter(0); + this.expect(5); + super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8); + this.scope.exit(); + return this.finishNode(node, "TSModuleBlock"); + } + tsParseModuleOrNamespaceDeclaration(node, nested = false) { + node.id = this.parseIdentifier(); + if (!nested) { + this.checkIdentifier(node.id, 1024); + } + if (this.eat(16)) { + const inner = this.startNode(); + this.tsParseModuleOrNamespaceDeclaration(inner, true); + node.body = inner; + } else { + this.scope.enter(1024); + this.prodParam.enter(0); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + tsParseAmbientExternalModuleDeclaration(node) { + if (this.isContextual(112)) { + node.kind = "global"; + node.global = true; + node.id = this.parseIdentifier(); + } else if (this.match(134)) { + node.kind = "module"; + node.id = super.parseStringLiteral(this.state.value); + } else { + this.unexpected(); + } + if (this.match(5)) { + this.scope.enter(1024); + this.prodParam.enter(0); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } else { + this.semicolon(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) { + node.isExport = isExport || false; + node.id = maybeDefaultIdentifier || this.parseIdentifier(); + this.checkIdentifier(node.id, 4096); + this.expect(29); + const moduleReference = this.tsParseModuleReference(); + if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") { + this.raise(TSErrors.ImportAliasHasImportType, moduleReference); + } + node.moduleReference = moduleReference; + this.semicolon(); + return this.finishNode(node, "TSImportEqualsDeclaration"); + } + tsIsExternalModuleReference() { + return this.isContextual(119) && this.lookaheadCharCode() === 40; + } + tsParseModuleReference() { + return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(0); + } + tsParseExternalModuleReference() { + const node = this.startNode(); + this.expectContextual(119); + this.expect(10); + if (!this.match(134)) { + this.unexpected(); + } + node.expression = super.parseExprAtom(); + this.expect(11); + this.sawUnambiguousESM = true; + return this.finishNode(node, "TSExternalModuleReference"); + } + tsLookAhead(f) { + const state = this.state.clone(); + const res = f(); + this.state = state; + return res; + } + tsTryParseAndCatch(f) { + const result = this.tryParse(abort => f() || abort()); + if (result.aborted || !result.node) return; + if (result.error) this.state = result.failState; + return result.node; + } + tsTryParse(f) { + const state = this.state.clone(); + const result = f(); + if (result !== undefined && result !== false) { + return result; + } + this.state = state; + } + tsTryParseDeclare(node) { + if (this.isLineTerminator()) { + return; + } + const startType = this.state.type; + return this.tsInAmbientContext(() => { + switch (startType) { + case 68: + node.declare = true; + return super.parseFunctionStatement(node, false, false); + case 80: + node.declare = true; + return this.parseClass(node, true, false); + case 126: + return this.tsParseEnumDeclaration(node, { + declare: true + }); + case 112: + return this.tsParseAmbientExternalModuleDeclaration(node); + case 100: + if (this.state.containsEsc) { + return; + } + case 75: + case 74: + if (!this.match(75) || !this.isLookaheadContextual("enum")) { + node.declare = true; + return this.parseVarStatement(node, this.state.value, true); + } + this.expect(75); + return this.tsParseEnumDeclaration(node, { + const: true, + declare: true + }); + case 107: + if (this.isUsing()) { + this.raise(TSErrors.InvalidModifierOnUsingDeclaration, this.state.startLoc, "declare"); + node.declare = true; + return this.parseVarStatement(node, "using", true); + } + break; + case 96: + if (this.isAwaitUsing()) { + this.raise(TSErrors.InvalidModifierOnAwaitUsingDeclaration, this.state.startLoc, "declare"); + node.declare = true; + this.next(); + return this.parseVarStatement(node, "await using", true); + } + break; + case 129: + { + const result = this.tsParseInterfaceDeclaration(node, { + declare: true + }); + if (result) return result; + } + default: + if (tokenIsIdentifier(startType)) { + return this.tsParseDeclaration(node, this.state.type, true, null); + } + } + }); + } + tsTryParseExportDeclaration() { + return this.tsParseDeclaration(this.startNode(), this.state.type, true, null); + } + tsParseDeclaration(node, type, next, decorators) { + switch (type) { + case 124: + if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) { + return this.tsParseAbstractDeclaration(node, decorators); + } + break; + case 127: + if (this.tsCheckLineTerminator(next)) { + if (this.match(134)) { + return this.tsParseAmbientExternalModuleDeclaration(node); + } else if (tokenIsIdentifier(this.state.type)) { + node.kind = "module"; + return this.tsParseModuleOrNamespaceDeclaration(node); + } + } + break; + case 128: + if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { + node.kind = "namespace"; + return this.tsParseModuleOrNamespaceDeclaration(node); + } + break; + case 130: + if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { + return this.tsParseTypeAliasDeclaration(node); + } + break; + } + } + tsCheckLineTerminator(next) { + if (next) { + if (this.hasFollowingLineBreak()) return false; + this.next(); + return true; + } + return !this.isLineTerminator(); + } + tsTryParseGenericAsyncArrowFunction(startLoc) { + if (!this.match(47)) return; + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = true; + const res = this.tsTryParseAndCatch(() => { + const node = this.startNodeAt(startLoc); + node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + super.parseFunctionParams(node); + node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation(); + this.expect(19); + return node; + }); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + if (!res) return; + return super.parseArrowExpression(res, null, true); + } + tsParseTypeArgumentsInExpression() { + if (this.reScan_lt() !== 47) return; + return this.tsParseTypeArguments(); + } + tsParseTypeArguments() { + const node = this.startNode(); + node.params = this.tsInType(() => this.tsInTopLevelContext(() => { + this.expect(47); + return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this)); + })); + if (node.params.length === 0) { + this.raise(TSErrors.EmptyTypeArguments, node); + } else if (!this.state.inType && this.curContext() === types.brace) { + this.reScan_lt_gt(); + } + this.expect(48); + return this.finishNode(node, "TSTypeParameterInstantiation"); + } + tsIsDeclarationStart() { + return tokenIsTSDeclarationStart(this.state.type); + } + isExportDefaultSpecifier() { + if (this.tsIsDeclarationStart()) return false; + return super.isExportDefaultSpecifier(); + } + parseBindingElement(flags, decorators) { + const startLoc = decorators.length ? decorators[0].loc.start : this.state.startLoc; + const modified = {}; + this.tsParseModifiers({ + allowedModifiers: ["public", "private", "protected", "override", "readonly"] + }, modified); + const accessibility = modified.accessibility; + const override = modified.override; + const readonly = modified.readonly; + if (!(flags & 4) && (accessibility || readonly || override)) { + this.raise(TSErrors.UnexpectedParameterModifier, startLoc); + } + const left = this.parseMaybeDefault(); + if (flags & 2) { + this.parseFunctionParamType(left); + } + const elt = this.parseMaybeDefault(left.loc.start, left); + if (accessibility || readonly || override) { + const pp = this.startNodeAt(startLoc); + if (decorators.length) { + pp.decorators = decorators; + } + if (accessibility) pp.accessibility = accessibility; + if (readonly) pp.readonly = readonly; + if (override) pp.override = override; + if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { + this.raise(TSErrors.UnsupportedParameterPropertyKind, pp); + } + pp.parameter = elt; + return this.finishNode(pp, "TSParameterProperty"); + } + if (decorators.length) { + left.decorators = decorators; + } + return elt; + } + isSimpleParameter(node) { + return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node); + } + tsDisallowOptionalPattern(node) { + for (const param of node.params) { + if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) { + this.raise(TSErrors.PatternIsOptional, param); + } + } + } + setArrowFunctionParameters(node, params, trailingCommaLoc) { + super.setArrowFunctionParameters(node, params, trailingCommaLoc); + this.tsDisallowOptionalPattern(node); + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(14)) { + node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14); + } + const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined; + if (bodilessType && !this.match(5) && this.isLineTerminator()) { + return this.finishNode(node, bodilessType); + } + if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) { + this.raise(TSErrors.DeclareFunctionHasImplementation, node); + if (node.declare) { + return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod); + } + } + this.tsDisallowOptionalPattern(node); + return super.parseFunctionBodyAndFinish(node, type, isMethod); + } + registerFunctionStatementId(node) { + if (!node.body && node.id) { + this.checkIdentifier(node.id, 1024); + } else { + super.registerFunctionStatementId(node); + } + } + tsCheckForInvalidTypeCasts(items) { + items.forEach(node => { + if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") { + this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation); + } + }); + } + toReferencedList(exprList, isInParens) { + this.tsCheckForInvalidTypeCasts(exprList); + return exprList; + } + parseArrayLike(close, isTuple, refExpressionErrors) { + const node = super.parseArrayLike(close, isTuple, refExpressionErrors); + if (node.type === "ArrayExpression") { + this.tsCheckForInvalidTypeCasts(node.elements); + } + return node; + } + parseSubscript(base, startLoc, noCalls, state) { + if (!this.hasPrecedingLineBreak() && this.match(35)) { + this.state.canStartJSXElement = false; + this.next(); + const nonNullExpression = this.startNodeAt(startLoc); + nonNullExpression.expression = base; + return this.finishNode(nonNullExpression, "TSNonNullExpression"); + } + let isOptionalCall = false; + if (this.match(18) && this.lookaheadCharCode() === 60) { + if (noCalls) { + state.stop = true; + return base; + } + state.optionalChainMember = isOptionalCall = true; + this.next(); + } + if (this.match(47) || this.match(51)) { + let missingParenErrorLoc; + const result = this.tsTryParseAndCatch(() => { + if (!noCalls && this.atPossibleAsyncArrow(base)) { + const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc); + if (asyncArrowFn) { + state.stop = true; + return asyncArrowFn; + } + } + const typeArguments = this.tsParseTypeArgumentsInExpression(); + if (!typeArguments) return; + if (isOptionalCall && !this.match(10)) { + missingParenErrorLoc = this.state.curPosition(); + return; + } + if (tokenIsTemplate(this.state.type)) { + const result = super.parseTaggedTemplateExpression(base, startLoc, state); + result.typeParameters = typeArguments; + return result; + } + if (!noCalls && this.eat(10)) { + const node = this.startNodeAt(startLoc); + node.callee = base; + node.arguments = this.parseCallExpressionArguments(); + this.tsCheckForInvalidTypeCasts(node.arguments); + node.typeParameters = typeArguments; + if (state.optionalChainMember) { + node.optional = isOptionalCall; + } + return this.finishCallExpression(node, state.optionalChainMember); + } + const tokenType = this.state.type; + if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenType !== 93 && tokenType !== 120 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) { + return; + } + const node = this.startNodeAt(startLoc); + node.expression = base; + node.typeParameters = typeArguments; + return this.finishNode(node, "TSInstantiationExpression"); + }); + if (missingParenErrorLoc) { + this.unexpected(missingParenErrorLoc, 10); + } + if (result) { + if (result.type === "TSInstantiationExpression") { + if (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40) { + this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc); + } + if (!this.match(16) && !this.match(18)) { + result.expression = super.stopParseSubscript(base, state); + } + } + return result; + } + } + return super.parseSubscript(base, startLoc, noCalls, state); + } + parseNewCallee(node) { + var _callee$extra; + super.parseNewCallee(node); + const { + callee + } = node; + if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) { + node.typeParameters = callee.typeParameters; + node.callee = callee.expression; + } + } + parseExprOp(left, leftStartLoc, minPrec) { + let isSatisfies; + if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) { + const node = this.startNodeAt(leftStartLoc); + node.expression = left; + node.typeAnnotation = this.tsInType(() => { + this.next(); + if (this.match(75)) { + if (isSatisfies) { + this.raise(Errors.UnexpectedKeyword, this.state.startLoc, { + keyword: "const" + }); + } + return this.tsParseTypeReference(); + } + return this.tsParseType(); + }); + this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression"); + this.reScan_lt_gt(); + return this.parseExprOp(node, leftStartLoc, minPrec); + } + return super.parseExprOp(left, leftStartLoc, minPrec); + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (!this.state.isAmbientContext) { + super.checkReservedWord(word, startLoc, checkKeywords, isBinding); + } + } + checkImportReflection(node) { + super.checkImportReflection(node); + if (node.module && node.importKind !== "value") { + this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); + } + } + checkDuplicateExports() {} + isPotentialImportPhase(isExport) { + if (super.isPotentialImportPhase(isExport)) return true; + if (this.isContextual(130)) { + const ch = this.lookaheadCharCode(); + return isExport ? ch === 123 || ch === 42 : ch !== 61; + } + return !isExport && this.isContextual(87); + } + applyImportPhase(node, isExport, phase, loc) { + super.applyImportPhase(node, isExport, phase, loc); + if (isExport) { + node.exportKind = phase === "type" ? "type" : "value"; + } else { + node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; + } + } + parseImport(node) { + if (this.match(134)) { + node.importKind = "value"; + return super.parseImport(node); + } + let importNode; + if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) { + node.importKind = "value"; + return this.tsParseImportEqualsDeclaration(node); + } else if (this.isContextual(130)) { + const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false); + if (this.lookaheadCharCode() === 61) { + return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier); + } else { + importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier); + } + } else { + importNode = super.parseImport(node); + } + if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") { + this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode); + } + return importNode; + } + parseExport(node, decorators) { + if (this.match(83)) { + const nodeImportEquals = node; + this.next(); + let maybeDefaultIdentifier = null; + if (this.isContextual(130) && this.isPotentialImportPhase(false)) { + maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false); + } else { + nodeImportEquals.importKind = "value"; + } + const declaration = this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true); + return declaration; + } else if (this.eat(29)) { + const assign = node; + assign.expression = super.parseExpression(); + this.semicolon(); + this.sawUnambiguousESM = true; + return this.finishNode(assign, "TSExportAssignment"); + } else if (this.eatContextual(93)) { + const decl = node; + this.expectContextual(128); + decl.id = this.parseIdentifier(); + this.semicolon(); + return this.finishNode(decl, "TSNamespaceExportDeclaration"); + } else { + return super.parseExport(node, decorators); + } + } + isAbstractClass() { + return this.isContextual(124) && this.isLookaheadContextual("class"); + } + parseExportDefaultExpression() { + if (this.isAbstractClass()) { + const cls = this.startNode(); + this.next(); + cls.abstract = true; + return this.parseClass(cls, true, true); + } + if (this.match(129)) { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + } + return super.parseExportDefaultExpression(); + } + parseVarStatement(node, kind, allowMissingInitializer = false) { + const { + isAmbientContext + } = this.state; + const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext); + if (!isAmbientContext) return declaration; + if (!node.declare && (kind === "using" || kind === "await using")) { + this.raiseOverwrite(TSErrors.UsingDeclarationInAmbientContext, node, kind); + return declaration; + } + for (const { + id, + init + } of declaration.declarations) { + if (!init) continue; + if (kind === "var" || kind === "let" || !!id.typeAnnotation) { + this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init); + } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) { + this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference, init); + } + } + return declaration; + } + parseStatementContent(flags, decorators) { + if (!this.state.containsEsc) { + switch (this.state.type) { + case 75: + { + if (this.isLookaheadContextual("enum")) { + const node = this.startNode(); + this.expect(75); + return this.tsParseEnumDeclaration(node, { + const: true + }); + } + break; + } + case 124: + case 125: + { + if (this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()) { + const token = this.state.type; + const node = this.startNode(); + this.next(); + const declaration = token === 125 ? this.tsTryParseDeclare(node) : this.tsParseAbstractDeclaration(node, decorators); + if (declaration) { + if (token === 125) { + declaration.declare = true; + } + return declaration; + } else { + node.expression = this.createIdentifier(this.startNodeAt(node.loc.start), token === 125 ? "declare" : "abstract"); + this.semicolon(false); + return this.finishNode(node, "ExpressionStatement"); + } + } + break; + } + case 126: + return this.tsParseEnumDeclaration(this.startNode()); + case 112: + { + const nextCh = this.lookaheadCharCode(); + if (nextCh === 123) { + const node = this.startNode(); + return this.tsParseAmbientExternalModuleDeclaration(node); + } + break; + } + case 129: + { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + break; + } + case 127: + { + if (this.nextTokenIsIdentifierOrStringLiteralOnSameLine()) { + const node = this.startNode(); + this.next(); + return this.tsParseDeclaration(node, 127, false, decorators); + } + break; + } + case 128: + { + if (this.nextTokenIsIdentifierOnSameLine()) { + const node = this.startNode(); + this.next(); + return this.tsParseDeclaration(node, 128, false, decorators); + } + break; + } + case 130: + { + if (this.nextTokenIsIdentifierOnSameLine()) { + const node = this.startNode(); + this.next(); + return this.tsParseTypeAliasDeclaration(node); + } + break; + } + } + } + return super.parseStatementContent(flags, decorators); + } + parseAccessModifier() { + return this.tsParseModifier(["public", "protected", "private"]); + } + tsHasSomeModifiers(member, modifiers) { + return modifiers.some(modifier => { + if (tsIsAccessModifier(modifier)) { + return member.accessibility === modifier; + } + return !!member[modifier]; + }); + } + tsIsStartOfStaticBlocks() { + return this.isContextual(106) && this.lookaheadCharCode() === 123; + } + parseClassMember(classBody, member, state) { + const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"]; + this.tsParseModifiers({ + allowedModifiers: modifiers, + disallowedModifiers: ["in", "out"], + stopOnStartOfClassStaticBlock: true, + errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions + }, member); + const callParseClassMemberWithIsStatic = () => { + if (this.tsIsStartOfStaticBlocks()) { + this.next(); + this.next(); + if (this.tsHasSomeModifiers(member, modifiers)) { + this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition()); + } + super.parseClassStaticBlock(classBody, member); + } else { + this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static); + } + }; + if (member.declare) { + this.tsInAmbientContext(callParseClassMemberWithIsStatic); + } else { + callParseClassMemberWithIsStatic(); + } + } + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const idx = this.tsTryParseIndexSignature(member); + if (idx) { + classBody.body.push(idx); + if (member.abstract) { + this.raise(TSErrors.IndexSignatureHasAbstract, member); + } + if (member.accessibility) { + this.raise(TSErrors.IndexSignatureHasAccessibility, member, { + modifier: member.accessibility + }); + } + if (member.declare) { + this.raise(TSErrors.IndexSignatureHasDeclare, member); + } + if (member.override) { + this.raise(TSErrors.IndexSignatureHasOverride, member); + } + return; + } + if (!this.state.inAbstractClass && member.abstract) { + this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member); + } + if (member.override) { + if (!state.hadSuperClass) { + this.raise(TSErrors.OverrideNotInSubClass, member); + } + } + super.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + parsePostMemberNameModifiers(methodOrProp) { + const optional = this.eat(17); + if (optional) methodOrProp.optional = true; + if (methodOrProp.readonly && this.match(10)) { + this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp); + } + if (methodOrProp.declare && this.match(10)) { + this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp); + } + } + shouldParseExportDeclaration() { + if (this.tsIsDeclarationStart()) return true; + return super.shouldParseExportDeclaration(); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (!this.match(17)) return expr; + if (this.state.maybeInArrowParameters) { + const nextCh = this.lookaheadCharCode(); + if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) { + this.setOptionalParametersError(refExpressionErrors); + return expr; + } + } + return super.parseConditional(expr, startLoc, refExpressionErrors); + } + parseParenItem(node, startLoc) { + const newNode = super.parseParenItem(node, startLoc); + if (this.eat(17)) { + newNode.optional = true; + this.resetEndLocation(node); + } + if (this.match(14)) { + const typeCastNode = this.startNodeAt(startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TSTypeCastExpression"); + } + return node; + } + parseExportDeclaration(node) { + if (!this.state.isAmbientContext && this.isContextual(125)) { + return this.tsInAmbientContext(() => this.parseExportDeclaration(node)); + } + const startLoc = this.state.startLoc; + const isDeclare = this.eatContextual(125); + if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) { + throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc); + } + const isIdentifier = tokenIsIdentifier(this.state.type); + const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node); + if (!declaration) return null; + if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) { + node.exportKind = "type"; + } + if (isDeclare && declaration.type !== "TSImportEqualsDeclaration") { + this.resetStartLocation(declaration, startLoc); + declaration.declare = true; + } + return declaration; + } + parseClassId(node, isStatement, optionalId, bindingType) { + if ((!isStatement || optionalId) && this.isContextual(113)) { + return; + } + super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331); + const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); + if (typeParameters) node.typeParameters = typeParameters; + } + parseClassPropertyAnnotation(node) { + if (!node.optional) { + if (this.eat(35)) { + node.definite = true; + } else if (this.eat(17)) { + node.optional = true; + } + } + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + } + parseClassProperty(node) { + this.parseClassPropertyAnnotation(node); + if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) { + this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc); + } + if (node.abstract && this.match(29)) { + const { + key + } = node; + this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, { + propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]` + }); + } + return super.parseClassProperty(node); + } + parseClassPrivateProperty(node) { + if (node.abstract) { + this.raise(TSErrors.PrivateElementHasAbstract, node); + } + if (node.accessibility) { + this.raise(TSErrors.PrivateElementHasAccessibility, node, { + modifier: node.accessibility + }); + } + this.parseClassPropertyAnnotation(node); + return super.parseClassPrivateProperty(node); + } + parseClassAccessorProperty(node) { + this.parseClassPropertyAnnotation(node); + if (node.optional) { + this.raise(TSErrors.AccessorCannotBeOptional, node); + } + return super.parseClassAccessorProperty(node); + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters && isConstructor) { + this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters); + } + const { + declare = false, + kind + } = method; + if (declare && (kind === "get" || kind === "set")) { + this.raise(TSErrors.DeclareAccessor, method, { + kind + }); + } + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + declareClassPrivateMethodInScope(node, kind) { + if (node.type === "TSDeclareMethod") return; + if (node.type === "MethodDefinition" && node.value.body == null) { + return; + } + super.declareClassPrivateMethodInScope(node, kind); + } + parseClassSuper(node) { + super.parseClassSuper(node); + if (node.superClass) { + if (node.superClass.type === "TSInstantiationExpression") { + const tsInstantiationExpression = node.superClass; + const superClass = tsInstantiationExpression.expression; + this.takeSurroundingComments(superClass, superClass.start, superClass.end); + const superTypeArguments = tsInstantiationExpression.typeParameters; + this.takeSurroundingComments(superTypeArguments, superTypeArguments.start, superTypeArguments.end); + node.superClass = superClass; + node.superTypeParameters = superTypeArguments; + } else if (this.match(47) || this.match(51)) { + node.superTypeParameters = this.tsParseTypeArgumentsInExpression(); + } + } + if (this.eatContextual(113)) { + node.implements = this.tsParseHeritageClause("implements"); + } + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) prop.typeParameters = typeParameters; + return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + } + parseFunctionParams(node, isConstructor) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) node.typeParameters = typeParameters; + super.parseFunctionParams(node, isConstructor); + } + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) { + decl.definite = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) { + decl.id.typeAnnotation = type; + this.resetEndLocation(decl.id); + } + } + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(14)) { + node.returnType = this.tsParseTypeAnnotation(); + } + return super.parseAsyncArrowFromCallExpression(node, call); + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2; + let state; + let jsx; + let typeCast; + if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + const currentContext = context[context.length - 1]; + if (currentContext === types.j_oTag || currentContext === types.j_expr) { + context.pop(); + } + } + if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) { + return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + } + if (!state || state === this.state) state = this.state.clone(); + let typeParameters; + const arrow = this.tryParse(abort => { + var _expr$extra, _typeParameters; + typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { + abort(); + } + if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) { + this.resetStartLocationFromNode(expr, typeParameters); + } + expr.typeParameters = typeParameters; + return expr; + }, state); + if (!arrow.error && !arrow.aborted) { + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow.node; + } + if (!jsx) { + assert(!this.hasPlugin("jsx")); + typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!typeCast.error) return typeCast.node; + } + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + if (arrow.node) { + this.state = arrow.failState; + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow.node; + } + if ((_typeCast = typeCast) != null && _typeCast.node) { + this.state = typeCast.failState; + return typeCast.node; + } + throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error); + } + reportReservedArrowTypeParam(node) { + var _node$extra2; + if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra2 = node.extra) != null && _node$extra2.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { + this.raise(TSErrors.ReservedArrowTypeParam, node); + } + } + parseMaybeUnary(refExpressionErrors, sawUnary) { + if (!this.hasPlugin("jsx") && this.match(47)) { + return this.tsParseTypeAssertion(); + } + return super.parseMaybeUnary(refExpressionErrors, sawUnary); + } + parseArrow(node) { + if (this.match(14)) { + const result = this.tryParse(abort => { + const returnType = this.tsParseTypeOrTypePredicateAnnotation(14); + if (this.canInsertSemicolon() || !this.match(19)) abort(); + return returnType; + }); + if (result.aborted) return; + if (!result.thrown) { + if (result.error) this.state = result.failState; + node.returnType = result.node; + } + } + return super.parseArrow(node); + } + parseFunctionParamType(param) { + if (this.eat(17)) { + param.optional = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) param.typeAnnotation = type; + this.resetEndLocation(param); + return param; + } + isAssignable(node, isBinding) { + switch (node.type) { + case "TSTypeCastExpression": + return this.isAssignable(node.expression, isBinding); + case "TSParameterProperty": + return true; + default: + return super.isAssignable(node, isBinding); + } + } + toAssignable(node, isLHS = false) { + switch (node.type) { + case "ParenthesizedExpression": + this.toAssignableParenthesizedExpression(node, isLHS); + break; + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + if (isLHS) { + this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node); + } else { + this.raise(TSErrors.UnexpectedTypeCastInParameter, node); + } + this.toAssignable(node.expression, isLHS); + break; + case "AssignmentExpression": + if (!isLHS && node.left.type === "TSTypeCastExpression") { + node.left = this.typeCastToParameter(node.left); + } + default: + super.toAssignable(node, isLHS); + } + } + toAssignableParenthesizedExpression(node, isLHS) { + switch (node.expression.type) { + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + case "ParenthesizedExpression": + this.toAssignable(node.expression, isLHS); + break; + default: + super.toAssignable(node, isLHS); + } + } + checkToRestConversion(node, allowPattern) { + switch (node.type) { + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + this.checkToRestConversion(node.expression, false); + break; + default: + super.checkToRestConversion(node, allowPattern); + } + } + isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) { + switch (type) { + case "TSTypeCastExpression": + return true; + case "TSParameterProperty": + return "parameter"; + case "TSNonNullExpression": + return "expression"; + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true]; + default: + return super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding); + } + } + parseBindingAtom() { + if (this.state.type === 78) { + return this.parseIdentifier(true); + } + return super.parseBindingAtom(); + } + parseMaybeDecoratorArguments(expr, startLoc) { + if (this.match(47) || this.match(51)) { + const typeArguments = this.tsParseTypeArgumentsInExpression(); + if (this.match(10)) { + const call = super.parseMaybeDecoratorArguments(expr, startLoc); + call.typeParameters = typeArguments; + return call; + } + this.unexpected(null, 10); + } + return super.parseMaybeDecoratorArguments(expr, startLoc); + } + checkCommaAfterRest(close) { + if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) { + this.next(); + return false; + } + return super.checkCommaAfterRest(close); + } + isClassMethod() { + return this.match(47) || super.isClassMethod(); + } + isClassProperty() { + return this.match(35) || this.match(14) || super.isClassProperty(); + } + parseMaybeDefault(startLoc, left) { + const node = super.parseMaybeDefault(startLoc, left); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation); + } + return node; + } + getTokenFromCode(code) { + if (this.state.inType) { + if (code === 62) { + this.finishOp(48, 1); + return; + } + if (code === 60) { + this.finishOp(47, 1); + return; + } + } + super.getTokenFromCode(code); + } + reScan_lt_gt() { + const { + type + } = this.state; + if (type === 47) { + this.state.pos -= 1; + this.readToken_lt(); + } else if (type === 48) { + this.state.pos -= 1; + this.readToken_gt(); + } + } + reScan_lt() { + const { + type + } = this.state; + if (type === 51) { + this.state.pos -= 2; + this.finishOp(47, 1); + return 47; + } + return type; + } + toAssignableListItem(exprList, index, isLHS) { + const node = exprList[index]; + if (node.type === "TSTypeCastExpression") { + exprList[index] = this.typeCastToParameter(node); + } + super.toAssignableListItem(exprList, index, isLHS); + } + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); + return node.expression; + } + shouldParseArrow(params) { + if (this.match(14)) { + return params.every(expr => this.isAssignable(expr, true)); + } + return super.shouldParseArrow(params); + } + shouldParseAsyncArrow() { + return this.match(14) || super.shouldParseAsyncArrow(); + } + canHaveLeadingDecorator() { + return super.canHaveLeadingDecorator() || this.isAbstractClass(); + } + jsxParseOpeningElementAfterName(node) { + if (this.match(47) || this.match(51)) { + const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression()); + if (typeArguments) { + node.typeParameters = typeArguments; + } + } + return super.jsxParseOpeningElementAfterName(node); + } + getGetterSetterExpectedParamCount(method) { + const baseCount = super.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + const firstParam = params[0]; + const hasContextParam = firstParam && this.isThisParam(firstParam); + return hasContextParam ? baseCount + 1 : baseCount; + } + parseCatchClauseParam() { + const param = super.parseCatchClauseParam(); + const type = this.tsTryParseTypeAnnotation(); + if (type) { + param.typeAnnotation = type; + this.resetEndLocation(param); + } + return param; + } + tsInAmbientContext(cb) { + const { + isAmbientContext: oldIsAmbientContext, + strict: oldStrict + } = this.state; + this.state.isAmbientContext = true; + this.state.strict = false; + try { + return cb(); + } finally { + this.state.isAmbientContext = oldIsAmbientContext; + this.state.strict = oldStrict; + } + } + parseClass(node, isStatement, optionalId) { + const oldInAbstractClass = this.state.inAbstractClass; + this.state.inAbstractClass = !!node.abstract; + try { + return super.parseClass(node, isStatement, optionalId); + } finally { + this.state.inAbstractClass = oldInAbstractClass; + } + } + tsParseAbstractDeclaration(node, decorators) { + if (this.match(80)) { + node.abstract = true; + return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false)); + } else if (this.isContextual(129)) { + if (!this.hasFollowingLineBreak()) { + node.abstract = true; + this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifier, node); + return this.tsParseInterfaceDeclaration(node); + } else { + return null; + } + } + throw this.unexpected(null, 80); + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) { + const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + if (method.abstract || method.type === "TSAbstractMethodDefinition") { + const hasEstreePlugin = this.hasPlugin("estree"); + const methodFn = hasEstreePlugin ? method.value : method; + if (methodFn.body) { + const { + key + } = method; + this.raise(TSErrors.AbstractMethodHasImplementation, method, { + methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]` + }); + } + } + return method; + } + tsParseTypeParameterName() { + const typeName = this.parseIdentifier(); + return typeName.name; + } + shouldParseAsAmbientContext() { + return !!this.getPluginOption("typescript", "dts"); + } + parse() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + return super.parse(); + } + getExpression() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + return super.getExpression(); + } + parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { + if (!isString && isMaybeTypeOnly) { + this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport); + return this.finishNode(node, "ExportSpecifier"); + } + node.exportKind = "value"; + return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly); + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + if (!importedIsString && isMaybeTypeOnly) { + this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport); + return this.finishNode(specifier, "ImportSpecifier"); + } + specifier.importKind = "value"; + return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096); + } + parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) { + const leftOfAsKey = isImport ? "imported" : "local"; + const rightOfAsKey = isImport ? "local" : "exported"; + let leftOfAs = node[leftOfAsKey]; + let rightOfAs; + let hasTypeSpecifier = false; + let canParseAsKeyword = true; + const loc = leftOfAs.loc.start; + if (this.isContextual(93)) { + const firstAs = this.parseIdentifier(); + if (this.isContextual(93)) { + const secondAs = this.parseIdentifier(); + if (tokenIsKeywordOrIdentifier(this.state.type)) { + hasTypeSpecifier = true; + leftOfAs = firstAs; + rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + canParseAsKeyword = false; + } else { + rightOfAs = secondAs; + canParseAsKeyword = false; + } + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + canParseAsKeyword = false; + rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + } else { + hasTypeSpecifier = true; + leftOfAs = firstAs; + } + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + hasTypeSpecifier = true; + if (isImport) { + leftOfAs = this.parseIdentifier(true); + if (!this.isContextual(93)) { + this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true); + } + } else { + leftOfAs = this.parseModuleExportName(); + } + } + if (hasTypeSpecifier && isInTypeOnlyImportExport) { + this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc); + } + node[leftOfAsKey] = leftOfAs; + node[rightOfAsKey] = rightOfAs; + const kindKey = isImport ? "importKind" : "exportKind"; + node[kindKey] = hasTypeSpecifier ? "type" : "value"; + if (canParseAsKeyword && this.eatContextual(93)) { + node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + } + if (!node[rightOfAsKey]) { + node[rightOfAsKey] = this.cloneIdentifier(node[leftOfAsKey]); + } + if (isImport) { + this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096); + } + } + fillOptionalPropertiesForTSESLint(node) { + var _node$directive, _node$decorators, _node$optional, _node$typeAnnotation, _node$accessibility, _node$decorators2, _node$override, _node$readonly, _node$static, _node$declare, _node$returnType, _node$typeParameters, _node$optional2, _node$optional3, _node$accessibility2, _node$readonly2, _node$static2, _node$declare2, _node$definite, _node$readonly3, _node$typeAnnotation2, _node$accessibility3, _node$decorators3, _node$override2, _node$optional4, _node$id, _node$abstract, _node$declare3, _node$decorators4, _node$implements, _node$superTypeArgume, _node$typeParameters2, _node$declare4, _node$definite2, _node$const, _node$declare5, _node$computed, _node$qualifier, _node$options, _node$declare6, _node$extends, _node$optional5, _node$readonly4, _node$declare7, _node$global, _node$const2, _node$in, _node$out; + switch (node.type) { + case "ExpressionStatement": + (_node$directive = node.directive) != null ? _node$directive : node.directive = undefined; + return; + case "RestElement": + node.value = undefined; + case "Identifier": + case "ArrayPattern": + case "AssignmentPattern": + case "ObjectPattern": + (_node$decorators = node.decorators) != null ? _node$decorators : node.decorators = []; + (_node$optional = node.optional) != null ? _node$optional : node.optional = false; + (_node$typeAnnotation = node.typeAnnotation) != null ? _node$typeAnnotation : node.typeAnnotation = undefined; + return; + case "TSParameterProperty": + (_node$accessibility = node.accessibility) != null ? _node$accessibility : node.accessibility = undefined; + (_node$decorators2 = node.decorators) != null ? _node$decorators2 : node.decorators = []; + (_node$override = node.override) != null ? _node$override : node.override = false; + (_node$readonly = node.readonly) != null ? _node$readonly : node.readonly = false; + (_node$static = node.static) != null ? _node$static : node.static = false; + return; + case "TSEmptyBodyFunctionExpression": + node.body = null; + case "TSDeclareFunction": + case "FunctionDeclaration": + case "FunctionExpression": + case "ClassMethod": + case "ClassPrivateMethod": + (_node$declare = node.declare) != null ? _node$declare : node.declare = false; + (_node$returnType = node.returnType) != null ? _node$returnType : node.returnType = undefined; + (_node$typeParameters = node.typeParameters) != null ? _node$typeParameters : node.typeParameters = undefined; + return; + case "Property": + (_node$optional2 = node.optional) != null ? _node$optional2 : node.optional = false; + return; + case "TSMethodSignature": + case "TSPropertySignature": + (_node$optional3 = node.optional) != null ? _node$optional3 : node.optional = false; + case "TSIndexSignature": + (_node$accessibility2 = node.accessibility) != null ? _node$accessibility2 : node.accessibility = undefined; + (_node$readonly2 = node.readonly) != null ? _node$readonly2 : node.readonly = false; + (_node$static2 = node.static) != null ? _node$static2 : node.static = false; + return; + case "TSAbstractPropertyDefinition": + case "PropertyDefinition": + case "TSAbstractAccessorProperty": + case "AccessorProperty": + (_node$declare2 = node.declare) != null ? _node$declare2 : node.declare = false; + (_node$definite = node.definite) != null ? _node$definite : node.definite = false; + (_node$readonly3 = node.readonly) != null ? _node$readonly3 : node.readonly = false; + (_node$typeAnnotation2 = node.typeAnnotation) != null ? _node$typeAnnotation2 : node.typeAnnotation = undefined; + case "TSAbstractMethodDefinition": + case "MethodDefinition": + (_node$accessibility3 = node.accessibility) != null ? _node$accessibility3 : node.accessibility = undefined; + (_node$decorators3 = node.decorators) != null ? _node$decorators3 : node.decorators = []; + (_node$override2 = node.override) != null ? _node$override2 : node.override = false; + (_node$optional4 = node.optional) != null ? _node$optional4 : node.optional = false; + return; + case "ClassExpression": + (_node$id = node.id) != null ? _node$id : node.id = null; + case "ClassDeclaration": + (_node$abstract = node.abstract) != null ? _node$abstract : node.abstract = false; + (_node$declare3 = node.declare) != null ? _node$declare3 : node.declare = false; + (_node$decorators4 = node.decorators) != null ? _node$decorators4 : node.decorators = []; + (_node$implements = node.implements) != null ? _node$implements : node.implements = []; + (_node$superTypeArgume = node.superTypeArguments) != null ? _node$superTypeArgume : node.superTypeArguments = undefined; + (_node$typeParameters2 = node.typeParameters) != null ? _node$typeParameters2 : node.typeParameters = undefined; + return; + case "TSTypeAliasDeclaration": + case "VariableDeclaration": + (_node$declare4 = node.declare) != null ? _node$declare4 : node.declare = false; + return; + case "VariableDeclarator": + (_node$definite2 = node.definite) != null ? _node$definite2 : node.definite = false; + return; + case "TSEnumDeclaration": + (_node$const = node.const) != null ? _node$const : node.const = false; + (_node$declare5 = node.declare) != null ? _node$declare5 : node.declare = false; + return; + case "TSEnumMember": + (_node$computed = node.computed) != null ? _node$computed : node.computed = false; + return; + case "TSImportType": + (_node$qualifier = node.qualifier) != null ? _node$qualifier : node.qualifier = null; + (_node$options = node.options) != null ? _node$options : node.options = null; + return; + case "TSInterfaceDeclaration": + (_node$declare6 = node.declare) != null ? _node$declare6 : node.declare = false; + (_node$extends = node.extends) != null ? _node$extends : node.extends = []; + return; + case "TSMappedType": + (_node$optional5 = node.optional) != null ? _node$optional5 : node.optional = false; + (_node$readonly4 = node.readonly) != null ? _node$readonly4 : node.readonly = undefined; + return; + case "TSModuleDeclaration": + (_node$declare7 = node.declare) != null ? _node$declare7 : node.declare = false; + (_node$global = node.global) != null ? _node$global : node.global = node.kind === "global"; + return; + case "TSTypeParameter": + (_node$const2 = node.const) != null ? _node$const2 : node.const = false; + (_node$in = node.in) != null ? _node$in : node.in = false; + (_node$out = node.out) != null ? _node$out : node.out = false; + return; + } + } + chStartsBindingIdentifierAndNotRelationalOperator(ch, pos) { + if (isIdentifierStart(ch)) { + keywordAndTSRelationalOperator.lastIndex = pos; + if (keywordAndTSRelationalOperator.test(this.input)) { + const endCh = this.codePointAtPos(keywordAndTSRelationalOperator.lastIndex); + if (!isIdentifierChar(endCh) && endCh !== 92) { + return false; + } + } + return true; + } else if (ch === 92) { + return true; + } else { + return false; + } + } + nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingIdentifierAndNotRelationalOperator(nextCh, next); + } + nextTokenIsIdentifierOrStringLiteralOnSameLine() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingIdentifier(nextCh, next) || nextCh === 34 || nextCh === 39; + } +}; +function isPossiblyLiteralEnum(expression) { + if (expression.type !== "MemberExpression") return false; + const { + computed, + property + } = expression; + if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) { + return false; + } + return isUncomputedMemberExpressionChain(expression.object); +} +function isValidAmbientConstInitializer(expression, estree) { + var _expression$extra; + const { + type + } = expression; + if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) { + return false; + } + if (estree) { + if (type === "Literal") { + const { + value + } = expression; + if (typeof value === "string" || typeof value === "boolean") { + return true; + } + } + } else { + if (type === "StringLiteral" || type === "BooleanLiteral") { + return true; + } + } + if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) { + return true; + } + if (type === "TemplateLiteral" && expression.expressions.length === 0) { + return true; + } + if (isPossiblyLiteralEnum(expression)) { + return true; + } + return false; +} +function isNumber(expression, estree) { + if (estree) { + return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression); + } + return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral"; +} +function isNegativeNumber(expression, estree) { + if (expression.type === "UnaryExpression") { + const { + operator, + argument + } = expression; + if (operator === "-" && isNumber(argument, estree)) { + return true; + } + } + return false; +} +function isUncomputedMemberExpressionChain(expression) { + if (expression.type === "Identifier") return true; + if (expression.type !== "MemberExpression" || expression.computed) { + return false; + } + return isUncomputedMemberExpressionChain(expression.object); +} +const PlaceholderErrors = ParseErrorEnum`placeholders`({ + ClassNameIsRequired: "A class name is required.", + UnexpectedSpace: "Unexpected space in placeholder." +}); +var placeholders = superClass => class PlaceholdersParserMixin extends superClass { + parsePlaceholder(expectedNode) { + if (this.match(133)) { + const node = this.startNode(); + this.next(); + this.assertNoSpace(); + node.name = super.parseIdentifier(true); + this.assertNoSpace(); + this.expect(133); + return this.finishPlaceholder(node, expectedNode); + } + } + finishPlaceholder(node, expectedNode) { + let placeholder = node; + if (!placeholder.expectedNode || !placeholder.type) { + placeholder = this.finishNode(placeholder, "Placeholder"); + } + placeholder.expectedNode = expectedNode; + return placeholder; + } + getTokenFromCode(code) { + if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { + this.finishOp(133, 2); + } else { + super.getTokenFromCode(code); + } + } + parseExprAtom(refExpressionErrors) { + return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors); + } + parseIdentifier(liberal) { + return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal); + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (word !== undefined) { + super.checkReservedWord(word, startLoc, checkKeywords, isBinding); + } + } + cloneIdentifier(node) { + const cloned = super.cloneIdentifier(node); + if (cloned.type === "Placeholder") { + cloned.expectedNode = node.expectedNode; + } + return cloned; + } + cloneStringLiteral(node) { + if (node.type === "Placeholder") { + return this.cloneIdentifier(node); + } + return super.cloneStringLiteral(node); + } + parseBindingAtom() { + return this.parsePlaceholder("Pattern") || super.parseBindingAtom(); + } + isValidLVal(type, disallowCallExpression, isParenthesized, binding) { + return type === "Placeholder" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding); + } + toAssignable(node, isLHS) { + if (node && node.type === "Placeholder" && node.expectedNode === "Expression") { + node.expectedNode = "Pattern"; + } else { + super.toAssignable(node, isLHS); + } + } + chStartsBindingIdentifier(ch, pos) { + if (super.chStartsBindingIdentifier(ch, pos)) { + return true; + } + const next = this.nextTokenStart(); + if (this.input.charCodeAt(next) === 37 && this.input.charCodeAt(next + 1) === 37) { + return true; + } + return false; + } + verifyBreakContinue(node, isBreak) { + var _node$label; + if (((_node$label = node.label) == null ? void 0 : _node$label.type) === "Placeholder") return; + super.verifyBreakContinue(node, isBreak); + } + parseExpressionStatement(node, expr) { + var _expr$extra; + if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { + return super.parseExpressionStatement(node, expr); + } + if (this.match(14)) { + const stmt = node; + stmt.label = this.finishPlaceholder(expr, "Identifier"); + this.next(); + stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration(); + return this.finishNode(stmt, "LabeledStatement"); + } + this.semicolon(); + const stmtPlaceholder = node; + stmtPlaceholder.name = expr.name; + return this.finishPlaceholder(stmtPlaceholder, "Statement"); + } + parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) { + return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse); + } + parseFunctionId(requireId) { + return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId); + } + parseClass(node, isStatement, optionalId) { + const type = isStatement ? "ClassDeclaration" : "ClassExpression"; + this.next(); + const oldStrict = this.state.strict; + const placeholder = this.parsePlaceholder("Identifier"); + if (placeholder) { + if (this.match(81) || this.match(133) || this.match(5)) { + node.id = placeholder; + } else if (optionalId || !isStatement) { + node.id = null; + node.body = this.finishPlaceholder(placeholder, "ClassBody"); + return this.finishNode(node, type); + } else { + throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc); + } + } else { + this.parseClassId(node, isStatement, optionalId); + } + super.parseClassSuper(node); + node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, type); + } + parseExport(node, decorators) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseExport(node, decorators); + const node2 = node; + if (!this.isContextual(98) && !this.match(12)) { + node2.specifiers = []; + node2.source = null; + node2.declaration = this.finishPlaceholder(placeholder, "Declaration"); + return this.finishNode(node2, "ExportNamedDeclaration"); + } + this.expectPlugin("exportDefaultFrom"); + const specifier = this.startNode(); + specifier.exported = placeholder; + node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return super.parseExport(node2, decorators); + } + isExportDefaultSpecifier() { + if (this.match(65)) { + const next = this.nextTokenStart(); + if (this.isUnparsedContextual(next, "from")) { + if (this.input.startsWith(tokenLabelName(133), this.nextTokenStartSince(next + 4))) { + return true; + } + } + } + return super.isExportDefaultSpecifier(); + } + maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { + var _specifiers; + if ((_specifiers = node.specifiers) != null && _specifiers.length) { + return true; + } + return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); + } + checkExport(node) { + const { + specifiers + } = node; + if (specifiers != null && specifiers.length) { + node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder"); + } + super.checkExport(node); + node.specifiers = specifiers; + } + parseImport(node) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseImport(node); + node.specifiers = []; + if (!this.isContextual(98) && !this.match(12)) { + node.source = this.finishPlaceholder(placeholder, "StringLiteral"); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + const specifier = this.startNodeAtNode(placeholder); + specifier.local = placeholder; + node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier")); + if (this.eat(12)) { + const hasStarImport = this.maybeParseStarImportSpecifier(node); + if (!hasStarImport) this.parseNamedImportSpecifiers(node); + } + this.expectContextual(98); + node.source = this.parseImportSource(); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + parseImportSource() { + return this.parsePlaceholder("StringLiteral") || super.parseImportSource(); + } + assertNoSpace() { + if (this.state.start > this.offsetToSourcePos(this.state.lastTokEndLoc.index)) { + this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc); + } + } +}; +var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass { + parseV8Intrinsic() { + if (this.match(54)) { + const v8IntrinsicStartLoc = this.state.startLoc; + const node = this.startNode(); + this.next(); + if (tokenIsIdentifier(this.state.type)) { + const name = this.parseIdentifierName(); + const identifier = this.createIdentifier(node, name); + this.castNodeTo(identifier, "V8IntrinsicIdentifier"); + if (this.match(10)) { + return identifier; + } + } + this.unexpected(v8IntrinsicStartLoc); + } + } + parseExprAtom(refExpressionErrors) { + return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors); + } +}; +const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"]; +const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"]; +function validatePlugins(pluginsMap) { + if (pluginsMap.has("decorators")) { + if (pluginsMap.has("decorators-legacy")) { + throw new Error("Cannot use the decorators and decorators-legacy plugin together"); + } + const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport; + if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") { + throw new Error("'decoratorsBeforeExport' must be a boolean, if specified."); + } + const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized; + if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") { + throw new Error("'allowCallParenthesized' must be a boolean."); + } + } + if (pluginsMap.has("flow") && pluginsMap.has("typescript")) { + throw new Error("Cannot combine flow and typescript plugins."); + } + if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) { + throw new Error("Cannot combine placeholders and v8intrinsic plugins."); + } + if (pluginsMap.has("pipelineOperator")) { + var _pluginsMap$get2; + const proposal = pluginsMap.get("pipelineOperator").proposal; + if (!PIPELINE_PROPOSALS.includes(proposal)) { + const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", "); + throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`); + } + if (proposal === "hack") { + var _pluginsMap$get; + if (pluginsMap.has("placeholders")) { + throw new Error("Cannot combine placeholders plugin and Hack-style pipes."); + } + if (pluginsMap.has("v8intrinsic")) { + throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes."); + } + const topicToken = pluginsMap.get("pipelineOperator").topicToken; + if (!TOPIC_TOKENS.includes(topicToken)) { + const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", "); + throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`); + } + if (topicToken === "#" && ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash") { + throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`); + } + } else if (proposal === "smart" && ((_pluginsMap$get2 = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get2.syntaxType) === "hash") { + throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`); + } + } + if (pluginsMap.has("moduleAttributes")) { + if (pluginsMap.has("deprecatedImportAssert") || pluginsMap.has("importAssertions")) { + throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins."); + } + const moduleAttributesVersionPluginOption = pluginsMap.get("moduleAttributes").version; + if (moduleAttributesVersionPluginOption !== "may-2020") { + throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'."); + } + } + if (pluginsMap.has("importAssertions")) { + if (pluginsMap.has("deprecatedImportAssert")) { + throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins."); + } + } + if (pluginsMap.has("deprecatedImportAssert")) ;else if (pluginsMap.has("importAttributes") && pluginsMap.get("importAttributes").deprecatedAssertSyntax) { + pluginsMap.set("deprecatedImportAssert", {}); + } + if (pluginsMap.has("recordAndTuple")) { + const syntaxType = pluginsMap.get("recordAndTuple").syntaxType; + if (syntaxType != null) { + const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"]; + if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) { + throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", ")); + } + } + } + if (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) { + const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins."); + error.missingPlugins = "doExpressions"; + throw error; + } + if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("optionalChainingAssign").version !== "2023-07") { + throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'."); + } + if (pluginsMap.has("discardBinding") && pluginsMap.get("discardBinding").syntaxType !== "void") { + throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'."); + } +} +const mixinPlugins = { + estree, + jsx, + flow, + typescript, + v8intrinsic, + placeholders +}; +const mixinPluginNames = Object.keys(mixinPlugins); +class ExpressionParser extends LValParser { + checkProto(prop, isRecord, sawProto, refExpressionErrors) { + if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) { + return sawProto; + } + const key = prop.key; + const name = key.type === "Identifier" ? key.name : key.value; + if (name === "__proto__") { + if (isRecord) { + this.raise(Errors.RecordNoProto, key); + return true; + } + if (sawProto) { + if (refExpressionErrors) { + if (refExpressionErrors.doubleProtoLoc === null) { + refExpressionErrors.doubleProtoLoc = key.loc.start; + } + } else { + this.raise(Errors.DuplicateProto, key); + } + } + return true; + } + return sawProto; + } + shouldExitDescending(expr, potentialArrowAt) { + return expr.type === "ArrowFunctionExpression" && this.offsetToSourcePos(expr.start) === potentialArrowAt; + } + getExpression() { + this.enterInitialScopes(); + this.nextToken(); + if (this.match(140)) { + throw this.raise(Errors.ParseExpressionEmptyInput, this.state.startLoc); + } + const expr = this.parseExpression(); + if (!this.match(140)) { + throw this.raise(Errors.ParseExpressionExpectsEOF, this.state.startLoc, { + unexpected: this.input.codePointAt(this.state.start) + }); + } + this.finalizeRemainingComments(); + expr.comments = this.comments; + expr.errors = this.state.errors; + if (this.optionFlags & 256) { + expr.tokens = this.tokens; + } + return expr; + } + parseExpression(disallowIn, refExpressionErrors) { + if (disallowIn) { + return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + parseExpressionBase(refExpressionErrors) { + const startLoc = this.state.startLoc; + const expr = this.parseMaybeAssign(refExpressionErrors); + if (this.match(12)) { + const node = this.startNodeAt(startLoc); + node.expressions = [expr]; + while (this.eat(12)) { + node.expressions.push(this.parseMaybeAssign(refExpressionErrors)); + } + this.toReferencedList(node.expressions); + return this.finishNode(node, "SequenceExpression"); + } + return expr; + } + parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) { + return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) { + return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + setOptionalParametersError(refExpressionErrors) { + refExpressionErrors.optionalParametersLoc = this.state.startLoc; + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + const startLoc = this.state.startLoc; + const isYield = this.isContextual(108); + if (isYield) { + if (this.prodParam.hasYield) { + this.next(); + let left = this.parseYield(startLoc); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startLoc); + } + return left; + } + } + let ownExpressionErrors; + if (refExpressionErrors) { + ownExpressionErrors = false; + } else { + refExpressionErrors = new ExpressionErrors(); + ownExpressionErrors = true; + } + const { + type + } = this.state; + if (type === 10 || tokenIsIdentifier(type)) { + this.state.potentialArrowAt = this.state.start; + } + let left = this.parseMaybeConditional(refExpressionErrors); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startLoc); + } + if (tokenIsAssignment(this.state.type)) { + const node = this.startNodeAt(startLoc); + const operator = this.state.value; + node.operator = operator; + if (this.match(29)) { + this.toAssignable(left, true); + node.left = left; + const startIndex = startLoc.index; + if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) { + refExpressionErrors.doubleProtoLoc = null; + } + if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) { + refExpressionErrors.shorthandAssignLoc = null; + } + if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) { + this.checkDestructuringPrivate(refExpressionErrors); + refExpressionErrors.privateKeyLoc = null; + } + if (refExpressionErrors.voidPatternLoc != null && refExpressionErrors.voidPatternLoc.index >= startIndex) { + refExpressionErrors.voidPatternLoc = null; + } + } else { + node.left = left; + } + this.next(); + node.right = this.parseMaybeAssign(); + this.checkLVal(left, this.finishNode(node, "AssignmentExpression"), undefined, undefined, undefined, undefined, operator === "||=" || operator === "&&=" || operator === "??="); + return node; + } else if (ownExpressionErrors) { + this.checkExpressionErrors(refExpressionErrors, true); + } + if (isYield) { + const { + type + } = this.state; + const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54); + if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) { + this.raiseOverwrite(Errors.YieldNotInGeneratorFunction, startLoc); + return this.parseYield(startLoc); + } + } + return left; + } + parseMaybeConditional(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprOps(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseConditional(expr, startLoc, refExpressionErrors); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (this.eat(17)) { + const node = this.startNodeAt(startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssignAllowIn(); + this.expect(14); + node.alternate = this.parseMaybeAssign(); + return this.finishNode(node, "ConditionalExpression"); + } + return expr; + } + parseMaybeUnaryOrPrivate(refExpressionErrors) { + return this.match(139) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors); + } + parseExprOps(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseExprOp(expr, startLoc, -1); + } + parseExprOp(left, leftStartLoc, minPrec) { + if (this.isPrivateName(left)) { + const value = this.getPrivateNameSV(left); + if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) { + this.raise(Errors.PrivateInExpectedIn, left, { + identifierName: value + }); + } + this.classScope.usePrivateName(value, left.loc.start); + } + const op = this.state.type; + if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) { + let prec = tokenOperatorPrecedence(op); + if (prec > minPrec) { + if (op === 39) { + this.expectPlugin("pipelineOperator"); + if (this.state.inFSharpPipelineDirectBody) { + return left; + } + this.checkPipelineAtInfixOperator(left, leftStartLoc); + } + const node = this.startNodeAt(leftStartLoc); + node.left = left; + node.operator = this.state.value; + const logical = op === 41 || op === 42; + const coalesce = op === 40; + if (coalesce) { + prec = tokenOperatorPrecedence(42); + } + this.next(); + if (op === 39 && this.hasPlugin(["pipelineOperator", { + proposal: "minimal" + }])) { + if (this.state.type === 96 && this.prodParam.hasAwait) { + throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc); + } + } + node.right = this.parseExprOpRightExpr(op, prec); + const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression"); + const nextOp = this.state.type; + if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) { + throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc); + } + return this.parseExprOp(finishedNode, leftStartLoc, minPrec); + } + } + return left; + } + parseExprOpRightExpr(op, prec) { + const startLoc = this.state.startLoc; + switch (op) { + case 39: + switch (this.getPluginOption("pipelineOperator", "proposal")) { + case "hack": + return this.withTopicBindingContext(() => { + return this.parseHackPipeBody(); + }); + case "fsharp": + return this.withSoloAwaitPermittingContext(() => { + return this.parseFSharpPipelineBody(prec); + }); + } + if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { + return this.withTopicBindingContext(() => { + if (this.prodParam.hasYield && this.isContextual(108)) { + throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc); + } + return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc); + }); + } + default: + return this.parseExprOpBaseRightExpr(op, prec); + } + } + parseExprOpBaseRightExpr(op, prec) { + const startLoc = this.state.startLoc; + return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec); + } + parseHackPipeBody() { + var _body$extra; + const { + startLoc + } = this.state; + const body = this.parseMaybeAssign(); + const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type); + if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) { + this.raise(Errors.PipeUnparenthesizedBody, startLoc, { + type: body.type + }); + } + if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(Errors.PipeTopicUnused, startLoc); + } + return body; + } + checkExponentialAfterUnary(node) { + if (this.match(57)) { + this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument); + } + } + parseMaybeUnary(refExpressionErrors, sawUnary) { + const startLoc = this.state.startLoc; + const isAwait = this.isContextual(96); + if (isAwait && this.recordAwaitIfAllowed()) { + this.next(); + const expr = this.parseAwait(startLoc); + if (!sawUnary) this.checkExponentialAfterUnary(expr); + return expr; + } + const update = this.match(34); + const node = this.startNode(); + if (tokenIsPrefix(this.state.type)) { + node.operator = this.state.value; + node.prefix = true; + if (this.match(72)) { + this.expectPlugin("throwExpressions"); + } + const isDelete = this.match(89); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + this.checkExpressionErrors(refExpressionErrors, true); + if (this.state.strict && isDelete) { + const arg = node.argument; + if (arg.type === "Identifier") { + this.raise(Errors.StrictDelete, node); + } else if (this.hasPropertyAsPrivateName(arg)) { + this.raise(Errors.DeletePrivateField, node); + } + } + if (!update) { + if (!sawUnary) { + this.checkExponentialAfterUnary(node); + } + return this.finishNode(node, "UnaryExpression"); + } + } + const expr = this.parseUpdate(node, update, refExpressionErrors); + if (isAwait) { + const { + type + } = this.state; + const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54); + if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) { + this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc); + return this.parseAwait(startLoc); + } + } + return expr; + } + parseUpdate(node, update, refExpressionErrors) { + if (update) { + const updateExpressionNode = node; + this.checkLVal(updateExpressionNode.argument, this.finishNode(updateExpressionNode, "UpdateExpression")); + return node; + } + const startLoc = this.state.startLoc; + let expr = this.parseExprSubscripts(refExpressionErrors); + if (this.checkExpressionErrors(refExpressionErrors, false)) return expr; + while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startLoc); + node.operator = this.state.value; + node.prefix = false; + node.argument = expr; + this.next(); + this.checkLVal(expr, expr = this.finishNode(node, "UpdateExpression")); + } + return expr; + } + parseExprSubscripts(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprAtom(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseSubscripts(expr, startLoc); + } + parseSubscripts(base, startLoc, noCalls) { + const state = { + optionalChainMember: false, + maybeAsyncArrow: this.atPossibleAsyncArrow(base), + stop: false + }; + do { + base = this.parseSubscript(base, startLoc, noCalls, state); + state.maybeAsyncArrow = false; + } while (!state.stop); + return base; + } + parseSubscript(base, startLoc, noCalls, state) { + const { + type + } = this.state; + if (!noCalls && type === 15) { + return this.parseBind(base, startLoc, noCalls, state); + } else if (tokenIsTemplate(type)) { + return this.parseTaggedTemplateExpression(base, startLoc, state); + } + let optional = false; + if (type === 18) { + if (noCalls) { + this.raise(Errors.OptionalChainingNoNew, this.state.startLoc); + if (this.lookaheadCharCode() === 40) { + return this.stopParseSubscript(base, state); + } + } + state.optionalChainMember = optional = true; + this.next(); + } + if (!noCalls && this.match(10)) { + return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional); + } else { + const computed = this.eat(0); + if (computed || optional || this.eat(16)) { + return this.parseMember(base, startLoc, state, computed, optional); + } else { + return this.stopParseSubscript(base, state); + } + } + } + stopParseSubscript(base, state) { + state.stop = true; + return base; + } + parseMember(base, startLoc, state, computed, optional) { + const node = this.startNodeAt(startLoc); + node.object = base; + node.computed = computed; + if (computed) { + node.property = this.parseExpression(); + this.expect(3); + } else if (this.match(139)) { + if (base.type === "Super") { + this.raise(Errors.SuperPrivateField, startLoc); + } + this.classScope.usePrivateName(this.state.value, this.state.startLoc); + node.property = this.parsePrivateName(); + } else { + node.property = this.parseIdentifier(true); + } + if (state.optionalChainMember) { + node.optional = optional; + return this.finishNode(node, "OptionalMemberExpression"); + } else { + return this.finishNode(node, "MemberExpression"); + } + } + parseBind(base, startLoc, noCalls, state) { + const node = this.startNodeAt(startLoc); + node.object = base; + this.next(); + node.callee = this.parseNoCallExpr(); + state.stop = true; + return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls); + } + parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) { + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + let refExpressionErrors = null; + this.state.maybeInArrowParameters = true; + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + const { + maybeAsyncArrow, + optionalChainMember + } = state; + if (maybeAsyncArrow) { + this.expressionScope.enter(newAsyncArrowScope()); + refExpressionErrors = new ExpressionErrors(); + } + if (optionalChainMember) { + node.optional = optional; + } + if (optional) { + node.arguments = this.parseCallExpressionArguments(); + } else { + node.arguments = this.parseCallExpressionArguments(base.type !== "Super", node, refExpressionErrors); + } + let finishedNode = this.finishCallExpression(node, optionalChainMember); + if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) { + state.stop = true; + this.checkDestructuringPrivate(refExpressionErrors); + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode); + } else { + if (maybeAsyncArrow) { + this.checkExpressionErrors(refExpressionErrors, true); + this.expressionScope.exit(); + } + this.toReferencedArguments(finishedNode); + } + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return finishedNode; + } + toReferencedArguments(node, isParenthesizedExpr) { + this.toReferencedListDeep(node.arguments, isParenthesizedExpr); + } + parseTaggedTemplateExpression(base, startLoc, state) { + const node = this.startNodeAt(startLoc); + node.tag = base; + node.quasi = this.parseTemplate(true); + if (state.optionalChainMember) { + this.raise(Errors.OptionalChainingNoTemplate, startLoc); + } + return this.finishNode(node, "TaggedTemplateExpression"); + } + atPossibleAsyncArrow(base) { + return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.offsetToSourcePos(base.start) === this.state.potentialArrowAt; + } + finishCallExpression(node, optional) { + if (node.callee.type === "Import") { + if (node.arguments.length === 0 || node.arguments.length > 2) { + this.raise(Errors.ImportCallArity, node); + } else { + for (const arg of node.arguments) { + if (arg.type === "SpreadElement") { + this.raise(Errors.ImportCallSpreadArgument, arg); + } + } + } + } + return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression"); + } + parseCallExpressionArguments(allowPlaceholder, nodeForExtra, refExpressionErrors) { + const elts = []; + let first = true; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + while (!this.eat(11)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(11)) { + if (nodeForExtra) { + this.addTrailingCommaExtraToNode(nodeForExtra); + } + this.next(); + break; + } + } + elts.push(this.parseExprListItem(11, false, refExpressionErrors, allowPlaceholder)); + } + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return elts; + } + shouldParseAsyncArrow() { + return this.match(19) && !this.canInsertSemicolon(); + } + parseAsyncArrowFromCallExpression(node, call) { + var _call$extra; + this.resetPreviousNodeTrailingComments(call); + this.expect(19); + this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc); + if (call.innerComments) { + setInnerComments(node, call.innerComments); + } + if (call.callee.trailingComments) { + setInnerComments(node, call.callee.trailingComments); + } + return node; + } + parseNoCallExpr() { + const startLoc = this.state.startLoc; + return this.parseSubscripts(this.parseExprAtom(), startLoc, true); + } + parseExprAtom(refExpressionErrors) { + let node; + let decorators = null; + const { + type + } = this.state; + switch (type) { + case 79: + return this.parseSuper(); + case 83: + node = this.startNode(); + this.next(); + if (this.match(16)) { + return this.parseImportMetaPropertyOrPhaseCall(node); + } + if (this.match(10)) { + if (this.optionFlags & 512) { + return this.parseImportCall(node); + } else { + return this.finishNode(node, "Import"); + } + } else { + this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc); + return this.finishNode(node, "Import"); + } + case 78: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + case 90: + { + return this.parseDo(this.startNode(), false); + } + case 56: + case 31: + { + this.readRegexp(); + return this.parseRegExpLiteral(this.state.value); + } + case 135: + return this.parseNumericLiteral(this.state.value); + case 136: + return this.parseBigIntLiteral(this.state.value); + case 134: + return this.parseStringLiteral(this.state.value); + case 84: + return this.parseNullLiteral(); + case 85: + return this.parseBooleanLiteral(true); + case 86: + return this.parseBooleanLiteral(false); + case 10: + { + const canBeArrow = this.state.potentialArrowAt === this.state.start; + return this.parseParenAndDistinguishExpression(canBeArrow); + } + case 0: + { + return this.parseArrayLike(3, false, refExpressionErrors); + } + case 5: + { + return this.parseObjectLike(8, false, false, refExpressionErrors); + } + case 68: + return this.parseFunctionOrFunctionSent(); + case 26: + decorators = this.parseDecorators(); + case 80: + return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false); + case 77: + return this.parseNewOrNewTarget(); + case 25: + case 24: + return this.parseTemplate(false); + case 15: + { + node = this.startNode(); + this.next(); + node.object = null; + const callee = node.callee = this.parseNoCallExpr(); + if (callee.type === "MemberExpression") { + return this.finishNode(node, "BindExpression"); + } else { + throw this.raise(Errors.UnsupportedBind, callee); + } + } + case 139: + { + this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, { + identifierName: this.state.value + }); + return this.parsePrivateName(); + } + case 33: + { + return this.parseTopicReferenceThenEqualsSign(54, "%"); + } + case 32: + { + return this.parseTopicReferenceThenEqualsSign(44, "^"); + } + case 37: + case 38: + { + return this.parseTopicReference("hack"); + } + case 44: + case 54: + case 27: + { + const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); + if (pipeProposal) { + return this.parseTopicReference(pipeProposal); + } + throw this.unexpected(); + } + case 47: + { + const lookaheadCh = this.input.codePointAt(this.nextTokenStart()); + if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) { + throw this.expectOnePlugin(["jsx", "flow", "typescript"]); + } + throw this.unexpected(); + } + default: + if (type === 137) { + return this.parseDecimalLiteral(this.state.value); + } else if (type === 2 || type === 1) { + return this.parseArrayLike(this.state.type === 2 ? 4 : 3, true); + } else if (type === 6 || type === 7) { + return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true); + } + if (tokenIsIdentifier(type)) { + if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) { + return this.parseModuleExpression(); + } + const canBeArrow = this.state.potentialArrowAt === this.state.start; + const containsEsc = this.state.containsEsc; + const id = this.parseIdentifier(); + if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) { + const { + type + } = this.state; + if (type === 68) { + this.resetPreviousNodeTrailingComments(id); + this.next(); + return this.parseAsyncFunctionExpression(this.startNodeAtNode(id)); + } else if (tokenIsIdentifier(type)) { + if (this.lookaheadCharCode() === 61) { + return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id)); + } else { + return id; + } + } else if (type === 90) { + this.resetPreviousNodeTrailingComments(id); + return this.parseDo(this.startNodeAtNode(id), true); + } + } + if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) { + this.next(); + return this.parseArrowExpression(this.startNodeAtNode(id), [id], false); + } + return id; + } else { + throw this.unexpected(); + } + } + } + parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) { + const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); + if (pipeProposal) { + this.state.type = topicTokenType; + this.state.value = topicTokenValue; + this.state.pos--; + this.state.end--; + this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1); + return this.parseTopicReference(pipeProposal); + } + throw this.unexpected(); + } + parseTopicReference(pipeProposal) { + const node = this.startNode(); + const startLoc = this.state.startLoc; + const tokenType = this.state.type; + this.next(); + return this.finishTopicReference(node, startLoc, pipeProposal, tokenType); + } + finishTopicReference(node, startLoc, pipeProposal, tokenType) { + if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) { + if (pipeProposal === "hack") { + if (!this.topicReferenceIsAllowedInCurrentContext()) { + this.raise(Errors.PipeTopicUnbound, startLoc); + } + this.registerTopicReference(); + return this.finishNode(node, "TopicReference"); + } else { + if (!this.topicReferenceIsAllowedInCurrentContext()) { + this.raise(Errors.PrimaryTopicNotAllowed, startLoc); + } + this.registerTopicReference(); + return this.finishNode(node, "PipelinePrimaryTopicReference"); + } + } else { + throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, { + token: tokenLabelName(tokenType) + }); + } + } + testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) { + switch (pipeProposal) { + case "hack": + { + return this.hasPlugin(["pipelineOperator", { + topicToken: tokenLabelName(tokenType) + }]); + } + case "smart": + return tokenType === 27; + default: + throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc); + } + } + parseAsyncArrowUnaryFunction(node) { + this.prodParam.enter(functionFlags(true, this.prodParam.hasYield)); + const params = [this.parseIdentifier()]; + this.prodParam.exit(); + if (this.hasPrecedingLineBreak()) { + this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition()); + } + this.expect(19); + return this.parseArrowExpression(node, params, true); + } + parseDo(node, isAsync) { + this.expectPlugin("doExpressions"); + if (isAsync) { + this.expectPlugin("asyncDoExpressions"); + } + node.async = isAsync; + this.next(); + const oldLabels = this.state.labels; + this.state.labels = []; + if (isAsync) { + this.prodParam.enter(2); + node.body = this.parseBlock(); + this.prodParam.exit(); + } else { + node.body = this.parseBlock(); + } + this.state.labels = oldLabels; + return this.finishNode(node, "DoExpression"); + } + parseSuper() { + const node = this.startNode(); + this.next(); + if (this.match(10) && !this.scope.allowDirectSuper) { + if (!(this.optionFlags & 16)) { + this.raise(Errors.SuperNotAllowed, node); + } + } else if (!this.scope.allowSuper) { + if (!(this.optionFlags & 16)) { + this.raise(Errors.UnexpectedSuper, node); + } + } + if (!this.match(10) && !this.match(0) && !this.match(16)) { + this.raise(Errors.UnsupportedSuper, node); + } + return this.finishNode(node, "Super"); + } + parsePrivateName() { + const node = this.startNode(); + const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1)); + const name = this.state.value; + this.next(); + node.id = this.createIdentifier(id, name); + return this.finishNode(node, "PrivateName"); + } + parseFunctionOrFunctionSent() { + const node = this.startNode(); + this.next(); + if (this.prodParam.hasYield && this.match(16)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "function"); + this.next(); + if (this.match(103)) { + this.expectPlugin("functionSent"); + } else if (!this.hasPlugin("functionSent")) { + this.unexpected(); + } + return this.parseMetaProperty(node, meta, "sent"); + } + return this.parseFunction(node); + } + parseMetaProperty(node, meta, propertyName) { + node.meta = meta; + const containsEsc = this.state.containsEsc; + node.property = this.parseIdentifier(true); + if (node.property.name !== propertyName || containsEsc) { + this.raise(Errors.UnsupportedMetaProperty, node.property, { + target: meta.name, + onlyValidPropertyName: propertyName + }); + } + return this.finishNode(node, "MetaProperty"); + } + parseImportMetaPropertyOrPhaseCall(node) { + this.next(); + if (this.isContextual(105) || this.isContextual(97)) { + const isSource = this.isContextual(105); + this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation"); + this.next(); + node.phase = isSource ? "source" : "defer"; + return this.parseImportCall(node); + } else { + const id = this.createIdentifierAt(this.startNodeAtNode(node), "import", this.state.lastTokStartLoc); + if (this.isContextual(101)) { + if (!this.inModule) { + this.raise(Errors.ImportMetaOutsideModule, id); + } + this.sawUnambiguousESM = true; + } + return this.parseMetaProperty(node, id, "meta"); + } + } + parseLiteralAtNode(value, type, node) { + this.addExtra(node, "rawValue", value); + this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end)); + node.value = value; + this.next(); + return this.finishNode(node, type); + } + parseLiteral(value, type) { + const node = this.startNode(); + return this.parseLiteralAtNode(value, type, node); + } + parseStringLiteral(value) { + return this.parseLiteral(value, "StringLiteral"); + } + parseNumericLiteral(value) { + return this.parseLiteral(value, "NumericLiteral"); + } + parseBigIntLiteral(value) { + return this.parseLiteral(value, "BigIntLiteral"); + } + parseDecimalLiteral(value) { + return this.parseLiteral(value, "DecimalLiteral"); + } + parseRegExpLiteral(value) { + const node = this.startNode(); + this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end)); + node.pattern = value.pattern; + node.flags = value.flags; + this.next(); + return this.finishNode(node, "RegExpLiteral"); + } + parseBooleanLiteral(value) { + const node = this.startNode(); + node.value = value; + this.next(); + return this.finishNode(node, "BooleanLiteral"); + } + parseNullLiteral() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "NullLiteral"); + } + parseParenAndDistinguishExpression(canBeArrow) { + const startLoc = this.state.startLoc; + let val; + this.next(); + this.expressionScope.enter(newArrowHeadScope()); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.maybeInArrowParameters = true; + this.state.inFSharpPipelineDirectBody = false; + const innerStartLoc = this.state.startLoc; + const exprList = []; + const refExpressionErrors = new ExpressionErrors(); + let first = true; + let spreadStartLoc; + let optionalCommaStartLoc; + while (!this.match(11)) { + if (first) { + first = false; + } else { + this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc); + if (this.match(11)) { + optionalCommaStartLoc = this.state.startLoc; + break; + } + } + if (this.match(21)) { + const spreadNodeStartLoc = this.state.startLoc; + spreadStartLoc = this.state.startLoc; + exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc)); + if (!this.checkCommaAfterRest(41)) { + break; + } + } else { + exprList.push(this.parseMaybeAssignAllowInOrVoidPattern(11, refExpressionErrors, this.parseParenItem)); + } + } + const innerEndLoc = this.state.lastTokEndLoc; + this.expect(11); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let arrowNode = this.startNodeAt(startLoc); + if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) { + this.checkDestructuringPrivate(refExpressionErrors); + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + this.parseArrowExpression(arrowNode, exprList, false); + return arrowNode; + } + this.expressionScope.exit(); + if (!exprList.length) { + this.unexpected(this.state.lastTokStartLoc); + } + if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc); + if (spreadStartLoc) this.unexpected(spreadStartLoc); + this.checkExpressionErrors(refExpressionErrors, true); + this.toReferencedListDeep(exprList, true); + if (exprList.length > 1) { + val = this.startNodeAt(innerStartLoc); + val.expressions = exprList; + this.finishNode(val, "SequenceExpression"); + this.resetEndLocation(val, innerEndLoc); + } else { + val = exprList[0]; + } + return this.wrapParenthesis(startLoc, val); + } + wrapParenthesis(startLoc, expression) { + if (!(this.optionFlags & 1024)) { + this.addExtra(expression, "parenthesized", true); + this.addExtra(expression, "parenStart", startLoc.index); + this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index); + return expression; + } + const parenExpression = this.startNodeAt(startLoc); + parenExpression.expression = expression; + return this.finishNode(parenExpression, "ParenthesizedExpression"); + } + shouldParseArrow(params) { + return !this.canInsertSemicolon(); + } + parseArrow(node) { + if (this.eat(19)) { + return node; + } + } + parseParenItem(node, startLoc) { + return node; + } + parseNewOrNewTarget() { + const node = this.startNode(); + this.next(); + if (this.match(16)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "new"); + this.next(); + const metaProp = this.parseMetaProperty(node, meta, "target"); + if (!this.scope.allowNewTarget) { + this.raise(Errors.UnexpectedNewTarget, metaProp); + } + return metaProp; + } + return this.parseNew(node); + } + parseNew(node) { + this.parseNewCallee(node); + if (this.eat(10)) { + const args = this.parseExprList(11); + this.toReferencedList(args); + node.arguments = args; + } else { + node.arguments = []; + } + return this.finishNode(node, "NewExpression"); + } + parseNewCallee(node) { + const isImport = this.match(83); + const callee = this.parseNoCallExpr(); + node.callee = callee; + if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) { + this.raise(Errors.ImportCallNotNewExpression, callee); + } + } + parseTemplateElement(isTagged) { + const { + start, + startLoc, + end, + value + } = this.state; + const elemStart = start + 1; + const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1)); + if (value === null) { + if (!isTagged) { + this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1)); + } + } + const isTail = this.match(24); + const endOffset = isTail ? -1 : -2; + const elemEnd = end + endOffset; + elem.value = { + raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"), + cooked: value === null ? null : value.slice(1, endOffset) + }; + elem.tail = isTail; + this.next(); + const finishedNode = this.finishNode(elem, "TemplateElement"); + this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset)); + return finishedNode; + } + parseTemplate(isTagged) { + const node = this.startNode(); + let curElt = this.parseTemplateElement(isTagged); + const quasis = [curElt]; + const substitutions = []; + while (!curElt.tail) { + substitutions.push(this.parseTemplateSubstitution()); + this.readTemplateContinuation(); + quasis.push(curElt = this.parseTemplateElement(isTagged)); + } + node.expressions = substitutions; + node.quasis = quasis; + return this.finishNode(node, "TemplateLiteral"); + } + parseTemplateSubstitution() { + return this.parseExpression(); + } + parseObjectLike(close, isPattern, isRecord, refExpressionErrors) { + if (isRecord) { + this.expectPlugin("recordAndTuple"); + } + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + let sawProto = false; + let first = true; + const node = this.startNode(); + node.properties = []; + this.next(); + while (!this.match(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + this.addTrailingCommaExtraToNode(node); + break; + } + } + let prop; + if (isPattern) { + prop = this.parseBindingProperty(); + } else { + prop = this.parsePropertyDefinition(refExpressionErrors); + sawProto = this.checkProto(prop, isRecord, sawProto, refExpressionErrors); + } + if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") { + this.raise(Errors.InvalidRecordProperty, prop); + } + if (prop.shorthand) { + this.addExtra(prop, "shorthand", true); + } + node.properties.push(prop); + } + this.next(); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let type = "ObjectExpression"; + if (isPattern) { + type = "ObjectPattern"; + } else if (isRecord) { + type = "RecordExpression"; + } + return this.finishNode(node, type); + } + addTrailingCommaExtraToNode(node) { + this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index); + this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false); + } + maybeAsyncOrAccessorProp(prop) { + return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55)); + } + parsePropertyDefinition(refExpressionErrors) { + let decorators = []; + if (this.match(26)) { + if (this.hasPlugin("decorators")) { + this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc); + } + while (this.match(26)) { + decorators.push(this.parseDecorator()); + } + } + const prop = this.startNode(); + let isAsync = false; + let isAccessor = false; + let startLoc; + if (this.match(21)) { + if (decorators.length) this.unexpected(); + return this.parseSpread(); + } + if (decorators.length) { + prop.decorators = decorators; + decorators = []; + } + prop.method = false; + if (refExpressionErrors) { + startLoc = this.state.startLoc; + } + let isGenerator = this.eat(55); + this.parsePropertyNamePrefixOperator(prop); + const containsEsc = this.state.containsEsc; + this.parsePropertyName(prop, refExpressionErrors); + if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) { + const { + key + } = prop; + const keyName = key.name; + if (keyName === "async" && !this.hasPrecedingLineBreak()) { + isAsync = true; + this.resetPreviousNodeTrailingComments(key); + isGenerator = this.eat(55); + this.parsePropertyName(prop); + } + if (keyName === "get" || keyName === "set") { + isAccessor = true; + this.resetPreviousNodeTrailingComments(key); + prop.kind = keyName; + if (this.match(55)) { + isGenerator = true; + this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), { + kind: keyName + }); + this.next(); + } + this.parsePropertyName(prop); + } + } + return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors); + } + getGetterSetterExpectedParamCount(method) { + return method.kind === "get" ? 0 : 1; + } + getObjectOrClassMethodParams(method) { + return method.params; + } + checkGetterSetterParams(method) { + var _params; + const paramCount = this.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + if (params.length !== paramCount) { + this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method); + } + if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") { + this.raise(Errors.BadSetterRestParameter, method); + } + } + parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { + if (isAccessor) { + const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod"); + this.checkGetterSetterParams(finishedProp); + return finishedProp; + } + if (isAsync || isGenerator || this.match(10)) { + if (isPattern) this.unexpected(); + prop.kind = "method"; + prop.method = true; + return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod"); + } + } + parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { + prop.shorthand = false; + if (this.eat(14)) { + prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowInOrVoidPattern(8, refExpressionErrors); + return this.finishObjectProperty(prop); + } + if (!prop.computed && prop.key.type === "Identifier") { + this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false); + if (isPattern) { + prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key)); + } else if (this.match(29)) { + const shorthandAssignLoc = this.state.startLoc; + if (refExpressionErrors != null) { + if (refExpressionErrors.shorthandAssignLoc === null) { + refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc; + } + } else { + this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); + } + prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key)); + } else { + prop.value = this.cloneIdentifier(prop.key); + } + prop.shorthand = true; + return this.finishObjectProperty(prop); + } + } + finishObjectProperty(node) { + return this.finishNode(node, "ObjectProperty"); + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); + if (!node) this.unexpected(); + return node; + } + parsePropertyName(prop, refExpressionErrors) { + if (this.eat(0)) { + prop.computed = true; + prop.key = this.parseMaybeAssignAllowIn(); + this.expect(3); + } else { + const { + type, + value + } = this.state; + let key; + if (tokenIsKeywordOrIdentifier(type)) { + key = this.parseIdentifier(true); + } else { + switch (type) { + case 135: + key = this.parseNumericLiteral(value); + break; + case 134: + key = this.parseStringLiteral(value); + break; + case 136: + key = this.parseBigIntLiteral(value); + break; + case 139: + { + const privateKeyLoc = this.state.startLoc; + if (refExpressionErrors != null) { + if (refExpressionErrors.privateKeyLoc === null) { + refExpressionErrors.privateKeyLoc = privateKeyLoc; + } + } else { + this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); + } + key = this.parsePrivateName(); + break; + } + default: + if (type === 137) { + key = this.parseDecimalLiteral(value); + break; + } + this.unexpected(); + } + } + prop.key = key; + if (type !== 139) { + prop.computed = false; + } + } + } + initFunction(node, isAsync) { + node.id = null; + node.generator = false; + node.async = isAsync; + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + this.initFunction(node, isAsync); + node.generator = isGenerator; + this.scope.enter(514 | 16 | (inClassScope ? 576 : 0) | (allowDirectSuper ? 32 : 0)); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + this.parseFunctionParams(node, isConstructor); + const finishedNode = this.parseFunctionBodyAndFinish(node, type, true); + this.prodParam.exit(); + this.scope.exit(); + return finishedNode; + } + parseArrayLike(close, isTuple, refExpressionErrors) { + if (isTuple) { + this.expectPlugin("recordAndTuple"); + } + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + const node = this.startNode(); + this.next(); + node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression"); + } + parseArrowExpression(node, params, isAsync, trailingCommaLoc) { + this.scope.enter(514 | 4); + let flags = functionFlags(isAsync, false); + if (!this.match(5) && this.prodParam.hasIn) { + flags |= 8; + } + this.prodParam.enter(flags); + this.initFunction(node, isAsync); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + if (params) { + this.state.maybeInArrowParameters = true; + this.setArrowFunctionParameters(node, params, trailingCommaLoc); + } + this.state.maybeInArrowParameters = false; + this.parseFunctionBody(node, true); + this.prodParam.exit(); + this.scope.exit(); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return this.finishNode(node, "ArrowFunctionExpression"); + } + setArrowFunctionParameters(node, params, trailingCommaLoc) { + this.toAssignableList(params, trailingCommaLoc, false); + node.params = params; + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + this.parseFunctionBody(node, false, isMethod); + return this.finishNode(node, type); + } + parseFunctionBody(node, allowExpression, isMethod = false) { + const isExpression = allowExpression && !this.match(5); + this.expressionScope.enter(newExpressionScope()); + if (isExpression) { + node.body = this.parseMaybeAssign(); + this.checkParams(node, false, allowExpression, false); + } else { + const oldStrict = this.state.strict; + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(this.prodParam.currentFlags() | 4); + node.body = this.parseBlock(true, false, hasStrictModeDirective => { + const nonSimple = !this.isSimpleParamList(node.params); + if (hasStrictModeDirective && nonSimple) { + this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node); + } + const strictModeChanged = !oldStrict && this.state.strict; + this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged); + if (this.state.strict && node.id) { + this.checkIdentifier(node.id, 65, strictModeChanged); + } + }); + this.prodParam.exit(); + this.state.labels = oldLabels; + } + this.expressionScope.exit(); + } + isSimpleParameter(node) { + return node.type === "Identifier"; + } + isSimpleParamList(params) { + for (let i = 0, len = params.length; i < len; i++) { + if (!this.isSimpleParameter(params[i])) return false; + } + return true; + } + checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { + const checkClashes = !allowDuplicates && new Set(); + const formalParameters = { + type: "FormalParameters" + }; + for (const param of node.params) { + this.checkLVal(param, formalParameters, 5, checkClashes, strictModeChanged); + } + } + parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) { + const elts = []; + let first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + if (nodeForExtra) { + this.addTrailingCommaExtraToNode(nodeForExtra); + } + this.next(); + break; + } + } + elts.push(this.parseExprListItem(close, allowEmpty, refExpressionErrors)); + } + return elts; + } + parseExprListItem(close, allowEmpty, refExpressionErrors, allowPlaceholder) { + let elt; + if (this.match(12)) { + if (!allowEmpty) { + this.raise(Errors.UnexpectedToken, this.state.curPosition(), { + unexpected: "," + }); + } + elt = null; + } else if (this.match(21)) { + const spreadNodeStartLoc = this.state.startLoc; + elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc); + } else if (this.match(17)) { + this.expectPlugin("partialApplication"); + if (!allowPlaceholder) { + this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc); + } + const node = this.startNode(); + this.next(); + elt = this.finishNode(node, "ArgumentPlaceholder"); + } else { + elt = this.parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, this.parseParenItem); + } + return elt; + } + parseIdentifier(liberal) { + const node = this.startNode(); + const name = this.parseIdentifierName(liberal); + return this.createIdentifier(node, name); + } + createIdentifier(node, name) { + node.name = name; + node.loc.identifierName = name; + return this.finishNode(node, "Identifier"); + } + createIdentifierAt(node, name, endLoc) { + node.name = name; + node.loc.identifierName = name; + return this.finishNodeAt(node, "Identifier", endLoc); + } + parseIdentifierName(liberal) { + let name; + const { + startLoc, + type + } = this.state; + if (tokenIsKeywordOrIdentifier(type)) { + name = this.state.value; + } else { + this.unexpected(); + } + const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type); + if (liberal) { + if (tokenIsKeyword) { + this.replaceToken(132); + } + } else { + this.checkReservedWord(name, startLoc, tokenIsKeyword, false); + } + this.next(); + return name; + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (word.length > 10) { + return; + } + if (!canBeReservedWord(word)) { + return; + } + if (checkKeywords && isKeyword(word)) { + this.raise(Errors.UnexpectedKeyword, startLoc, { + keyword: word + }); + return; + } + const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; + if (reservedTest(word, this.inModule)) { + this.raise(Errors.UnexpectedReservedWord, startLoc, { + reservedWord: word + }); + return; + } else if (word === "yield") { + if (this.prodParam.hasYield) { + this.raise(Errors.YieldBindingIdentifier, startLoc); + return; + } + } else if (word === "await") { + if (this.prodParam.hasAwait) { + this.raise(Errors.AwaitBindingIdentifier, startLoc); + return; + } + if (this.scope.inStaticBlock) { + this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc); + return; + } + this.expressionScope.recordAsyncArrowParametersError(startLoc); + } else if (word === "arguments") { + if (this.scope.inClassAndNotInNonArrowFunction) { + this.raise(Errors.ArgumentsInClass, startLoc); + return; + } + } + } + recordAwaitIfAllowed() { + const isAwaitAllowed = this.prodParam.hasAwait; + if (isAwaitAllowed && !this.scope.inFunction) { + this.state.hasTopLevelAwait = true; + } + return isAwaitAllowed; + } + parseAwait(startLoc) { + const node = this.startNodeAt(startLoc); + this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node); + if (this.eat(55)) { + this.raise(Errors.ObsoleteAwaitStar, node); + } + if (!this.scope.inFunction && !(this.optionFlags & 1)) { + if (this.isAmbiguousPrefixOrIdentifier()) { + this.ambiguousScriptDifferentAst = true; + } else { + this.sawUnambiguousESM = true; + } + } + if (!this.state.soloAwait) { + node.argument = this.parseMaybeUnary(null, true); + } + return this.finishNode(node, "AwaitExpression"); + } + isAmbiguousPrefixOrIdentifier() { + if (this.hasPrecedingLineBreak()) return true; + const { + type + } = this.state; + return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 138 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54; + } + parseYield(startLoc) { + const node = this.startNodeAt(startLoc); + this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node); + let delegating = false; + let argument = null; + if (!this.hasPrecedingLineBreak()) { + delegating = this.eat(55); + switch (this.state.type) { + case 13: + case 140: + case 8: + case 11: + case 3: + case 9: + case 14: + case 12: + if (!delegating) break; + default: + argument = this.parseMaybeAssign(); + } + } + node.delegate = delegating; + node.argument = argument; + return this.finishNode(node, "YieldExpression"); + } + parseImportCall(node) { + this.next(); + node.source = this.parseMaybeAssignAllowIn(); + node.options = null; + if (this.eat(12)) { + if (!this.match(11)) { + node.options = this.parseMaybeAssignAllowIn(); + if (this.eat(12)) { + this.addTrailingCommaExtraToNode(node.options); + if (!this.match(11)) { + do { + this.parseMaybeAssignAllowIn(); + } while (this.eat(12) && !this.match(11)); + this.raise(Errors.ImportCallArity, node); + } + } + } else { + this.addTrailingCommaExtraToNode(node.source); + } + } + this.expect(11); + return this.finishNode(node, "ImportExpression"); + } + checkPipelineAtInfixOperator(left, leftStartLoc) { + if (this.hasPlugin(["pipelineOperator", { + proposal: "smart" + }])) { + if (left.type === "SequenceExpression") { + this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc); + } + } + } + parseSmartPipelineBodyInStyle(childExpr, startLoc) { + if (this.isSimpleReference(childExpr)) { + const bodyNode = this.startNodeAt(startLoc); + bodyNode.callee = childExpr; + return this.finishNode(bodyNode, "PipelineBareFunction"); + } else { + const bodyNode = this.startNodeAt(startLoc); + this.checkSmartPipeTopicBodyEarlyErrors(startLoc); + bodyNode.expression = childExpr; + return this.finishNode(bodyNode, "PipelineTopicExpression"); + } + } + isSimpleReference(expression) { + switch (expression.type) { + case "MemberExpression": + return !expression.computed && this.isSimpleReference(expression.object); + case "Identifier": + return true; + default: + return false; + } + } + checkSmartPipeTopicBodyEarlyErrors(startLoc) { + if (this.match(19)) { + throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc); + } + if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(Errors.PipelineTopicUnused, startLoc); + } + } + withTopicBindingContext(callback) { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 1, + maxTopicIndex: null + }; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } + withSmartMixTopicForbiddingContext(callback) { + if (this.hasPlugin(["pipelineOperator", { + proposal: "smart" + }])) { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } else { + return callback(); + } + } + withSoloAwaitPermittingContext(callback) { + const outerContextSoloAwaitState = this.state.soloAwait; + this.state.soloAwait = true; + try { + return callback(); + } finally { + this.state.soloAwait = outerContextSoloAwaitState; + } + } + allowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToSet = 8 & ~flags; + if (prodParamToSet) { + this.prodParam.enter(flags | 8); + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + return callback(); + } + disallowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToClear = 8 & flags; + if (prodParamToClear) { + this.prodParam.enter(flags & ~8); + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + return callback(); + } + registerTopicReference() { + this.state.topicContext.maxTopicIndex = 0; + } + topicReferenceIsAllowedInCurrentContext() { + return this.state.topicContext.maxNumOfResolvableTopics >= 1; + } + topicReferenceWasUsedInCurrentContext() { + return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0; + } + parseFSharpPipelineBody(prec) { + const startLoc = this.state.startLoc; + this.state.potentialArrowAt = this.state.start; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = true; + const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return ret; + } + parseModuleExpression() { + this.expectPlugin("moduleBlocks"); + const node = this.startNode(); + this.next(); + if (!this.match(5)) { + this.unexpected(null, 5); + } + const program = this.startNodeAt(this.state.endLoc); + this.next(); + const revertScopes = this.initializeScopes(true); + this.enterInitialScopes(); + try { + node.body = this.parseProgram(program, 8, "module"); + } finally { + revertScopes(); + } + return this.finishNode(node, "ModuleExpression"); + } + parseVoidPattern(refExpressionErrors) { + this.expectPlugin("discardBinding"); + const node = this.startNode(); + if (refExpressionErrors != null) { + refExpressionErrors.voidPatternLoc = this.state.startLoc; + } + this.next(); + return this.finishNode(node, "VoidPattern"); + } + parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, afterLeftParse) { + if (refExpressionErrors != null && this.match(88)) { + const nextCode = this.lookaheadCharCode(); + if (nextCode === 44 || nextCode === (close === 3 ? 93 : close === 8 ? 125 : 41) || nextCode === 61) { + return this.parseMaybeDefault(this.state.startLoc, this.parseVoidPattern(refExpressionErrors)); + } + } + return this.parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse); + } + parsePropertyNamePrefixOperator(prop) {} +} +const loopLabel = { + kind: 1 + }, + switchLabel = { + kind: 2 + }; +const loneSurrogate = /[\uD800-\uDFFF]/u; +const keywordRelationalOperator = /in(?:stanceof)?/y; +function babel7CompatTokens(tokens, input, startIndex) { + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + const { + type + } = token; + if (typeof type === "number") { + if (type === 139) { + const { + loc, + start, + value, + end + } = token; + const hashEndPos = start + 1; + const hashEndLoc = createPositionWithColumnOffset(loc.start, 1); + tokens.splice(i, 1, new Token({ + type: getExportedToken(27), + value: "#", + start: start, + end: hashEndPos, + startLoc: loc.start, + endLoc: hashEndLoc + }), new Token({ + type: getExportedToken(132), + value: value, + start: hashEndPos, + end: end, + startLoc: hashEndLoc, + endLoc: loc.end + })); + i++; + continue; + } + if (tokenIsTemplate(type)) { + const { + loc, + start, + value, + end + } = token; + const backquoteEnd = start + 1; + const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1); + let startToken; + if (input.charCodeAt(start - startIndex) === 96) { + startToken = new Token({ + type: getExportedToken(22), + value: "`", + start: start, + end: backquoteEnd, + startLoc: loc.start, + endLoc: backquoteEndLoc + }); + } else { + startToken = new Token({ + type: getExportedToken(8), + value: "}", + start: start, + end: backquoteEnd, + startLoc: loc.start, + endLoc: backquoteEndLoc + }); + } + let templateValue, templateElementEnd, templateElementEndLoc, endToken; + if (type === 24) { + templateElementEnd = end - 1; + templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1); + templateValue = value === null ? null : value.slice(1, -1); + endToken = new Token({ + type: getExportedToken(22), + value: "`", + start: templateElementEnd, + end: end, + startLoc: templateElementEndLoc, + endLoc: loc.end + }); + } else { + templateElementEnd = end - 2; + templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2); + templateValue = value === null ? null : value.slice(1, -2); + endToken = new Token({ + type: getExportedToken(23), + value: "${", + start: templateElementEnd, + end: end, + startLoc: templateElementEndLoc, + endLoc: loc.end + }); + } + tokens.splice(i, 1, startToken, new Token({ + type: getExportedToken(20), + value: templateValue, + start: backquoteEnd, + end: templateElementEnd, + startLoc: backquoteEndLoc, + endLoc: templateElementEndLoc + }), endToken); + i += 2; + continue; + } + token.type = getExportedToken(type); + } + } + return tokens; +} +class StatementParser extends ExpressionParser { + parseTopLevel(file, program) { + file.program = this.parseProgram(program, 140, this.options.sourceType === "module" ? "module" : "script"); + file.comments = this.comments; + if (this.optionFlags & 256) { + file.tokens = babel7CompatTokens(this.tokens, this.input, this.startIndex); + } + return this.finishNode(file, "File"); + } + parseProgram(program, end, sourceType) { + program.sourceType = sourceType; + program.interpreter = this.parseInterpreterDirective(); + this.parseBlockBody(program, true, true, end); + if (this.inModule) { + if (!(this.optionFlags & 64) && this.scope.undefinedExports.size > 0) { + for (const [localName, at] of Array.from(this.scope.undefinedExports)) { + this.raise(Errors.ModuleExportUndefined, at, { + localName + }); + } + } + this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait); + } + let finishedProgram; + if (end === 140) { + finishedProgram = this.finishNode(program, "Program"); + } else { + finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1)); + } + return finishedProgram; + } + stmtToDirective(stmt) { + const directive = this.castNodeTo(stmt, "Directive"); + const directiveLiteral = this.castNodeTo(stmt.expression, "DirectiveLiteral"); + const expressionValue = directiveLiteral.value; + const raw = this.input.slice(this.offsetToSourcePos(directiveLiteral.start), this.offsetToSourcePos(directiveLiteral.end)); + const val = directiveLiteral.value = raw.slice(1, -1); + this.addExtra(directiveLiteral, "raw", raw); + this.addExtra(directiveLiteral, "rawValue", val); + this.addExtra(directiveLiteral, "expressionValue", expressionValue); + directive.value = directiveLiteral; + delete stmt.expression; + return directive; + } + parseInterpreterDirective() { + if (!this.match(28)) { + return null; + } + const node = this.startNode(); + node.value = this.state.value; + this.next(); + return this.finishNode(node, "InterpreterDirective"); + } + isLet() { + if (!this.isContextual(100)) { + return false; + } + return this.hasFollowingBindingAtom(); + } + isUsing() { + if (!this.isContextual(107)) { + return false; + } + return this.nextTokenIsIdentifierOnSameLine(); + } + isForUsing() { + if (!this.isContextual(107)) { + return false; + } + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + if (this.isUnparsedContextual(next, "of")) { + const nextCharAfterOf = this.lookaheadCharCodeSince(next + 2); + if (nextCharAfterOf !== 61 && nextCharAfterOf !== 58 && nextCharAfterOf !== 59) { + return false; + } + } + if (this.chStartsBindingIdentifier(nextCh, next) || this.isUnparsedContextual(next, "void")) { + return true; + } + return false; + } + nextTokenIsIdentifierOnSameLine() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingIdentifier(nextCh, next); + } + isAwaitUsing() { + if (!this.isContextual(96)) { + return false; + } + let next = this.nextTokenInLineStart(); + if (this.isUnparsedContextual(next, "using")) { + next = this.nextTokenInLineStartSince(next + 5); + const nextCh = this.codePointAtPos(next); + if (this.chStartsBindingIdentifier(nextCh, next)) { + return true; + } + } + return false; + } + chStartsBindingIdentifier(ch, pos) { + if (isIdentifierStart(ch)) { + keywordRelationalOperator.lastIndex = pos; + if (keywordRelationalOperator.test(this.input)) { + const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex); + if (!isIdentifierChar(endCh) && endCh !== 92) { + return false; + } + } + return true; + } else if (ch === 92) { + return true; + } else { + return false; + } + } + chStartsBindingPattern(ch) { + return ch === 91 || ch === 123; + } + hasFollowingBindingAtom() { + const next = this.nextTokenStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next); + } + hasInLineFollowingBindingIdentifierOrBrace() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next); + } + allowsUsing() { + return (this.scope.inModule || !this.scope.inTopLevel) && !this.scope.inBareCaseStatement; + } + parseModuleItem() { + return this.parseStatementLike(1 | 2 | 4 | 8); + } + parseStatementListItem() { + return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8)); + } + parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) { + let flags = 0; + if (this.options.annexB && !this.state.strict) { + flags |= 4; + if (allowLabeledFunction) { + flags |= 8; + } + } + return this.parseStatementLike(flags); + } + parseStatement() { + return this.parseStatementLike(0); + } + parseStatementLike(flags) { + let decorators = null; + if (this.match(26)) { + decorators = this.parseDecorators(true); + } + return this.parseStatementContent(flags, decorators); + } + parseStatementContent(flags, decorators) { + const startType = this.state.type; + const node = this.startNode(); + const allowDeclaration = !!(flags & 2); + const allowFunctionDeclaration = !!(flags & 4); + const topLevel = flags & 1; + switch (startType) { + case 60: + return this.parseBreakContinueStatement(node, true); + case 63: + return this.parseBreakContinueStatement(node, false); + case 64: + return this.parseDebuggerStatement(node); + case 90: + return this.parseDoWhileStatement(node); + case 91: + return this.parseForStatement(node); + case 68: + if (this.lookaheadCharCode() === 46) break; + if (!allowFunctionDeclaration) { + this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc); + } + return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration); + case 80: + if (!allowDeclaration) this.unexpected(); + return this.parseClass(this.maybeTakeDecorators(decorators, node), true); + case 69: + return this.parseIfStatement(node); + case 70: + return this.parseReturnStatement(node); + case 71: + return this.parseSwitchStatement(node); + case 72: + return this.parseThrowStatement(node); + case 73: + return this.parseTryStatement(node); + case 96: + if (this.isAwaitUsing()) { + if (!this.allowsUsing()) { + this.raise(Errors.UnexpectedUsingDeclaration, node); + } else if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, node); + } else if (!this.recordAwaitIfAllowed()) { + this.raise(Errors.AwaitUsingNotInAsyncContext, node); + } + this.next(); + return this.parseVarStatement(node, "await using"); + } + break; + case 107: + if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) { + break; + } + if (!this.allowsUsing()) { + this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc); + } else if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); + } + return this.parseVarStatement(node, "using"); + case 100: + { + if (this.state.containsEsc) { + break; + } + const next = this.nextTokenStart(); + const nextCh = this.codePointAtPos(next); + if (nextCh !== 91) { + if (!allowDeclaration && this.hasFollowingLineBreak()) break; + if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) { + break; + } + } + } + case 75: + { + if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); + } + } + case 74: + { + const kind = this.state.value; + return this.parseVarStatement(node, kind); + } + case 92: + return this.parseWhileStatement(node); + case 76: + return this.parseWithStatement(node); + case 5: + return this.parseBlock(); + case 13: + return this.parseEmptyStatement(node); + case 83: + { + const nextTokenCharCode = this.lookaheadCharCode(); + if (nextTokenCharCode === 40 || nextTokenCharCode === 46) { + break; + } + } + case 82: + { + if (!(this.optionFlags & 8) && !topLevel) { + this.raise(Errors.UnexpectedImportExport, this.state.startLoc); + } + this.next(); + let result; + if (startType === 83) { + result = this.parseImport(node); + } else { + result = this.parseExport(node, decorators); + } + this.assertModuleNodeAllowed(result); + return result; + } + default: + { + if (this.isAsyncFunction()) { + if (!allowDeclaration) { + this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc); + } + this.next(); + return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration); + } + } + } + const maybeName = this.state.value; + const expr = this.parseExpression(); + if (tokenIsIdentifier(startType) && expr.type === "Identifier" && this.eat(14)) { + return this.parseLabeledStatement(node, maybeName, expr, flags); + } else { + return this.parseExpressionStatement(node, expr, decorators); + } + } + assertModuleNodeAllowed(node) { + if (!(this.optionFlags & 8) && !this.inModule) { + this.raise(Errors.ImportOutsideModule, node); + } + } + decoratorsEnabledBeforeExport() { + if (this.hasPlugin("decorators-legacy")) return true; + return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false; + } + maybeTakeDecorators(maybeDecorators, classNode, exportNode) { + if (maybeDecorators) { + var _classNode$decorators; + if ((_classNode$decorators = classNode.decorators) != null && _classNode$decorators.length) { + if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") { + this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]); + } + classNode.decorators.unshift(...maybeDecorators); + } else { + classNode.decorators = maybeDecorators; + } + this.resetStartLocationFromNode(classNode, maybeDecorators[0]); + if (exportNode) this.resetStartLocationFromNode(exportNode, classNode); + } + return classNode; + } + canHaveLeadingDecorator() { + return this.match(80); + } + parseDecorators(allowExport) { + const decorators = []; + do { + decorators.push(this.parseDecorator()); + } while (this.match(26)); + if (this.match(82)) { + if (!allowExport) { + this.unexpected(); + } + if (!this.decoratorsEnabledBeforeExport()) { + this.raise(Errors.DecoratorExportClass, this.state.startLoc); + } + } else if (!this.canHaveLeadingDecorator()) { + throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc); + } + return decorators; + } + parseDecorator() { + this.expectOnePlugin(["decorators", "decorators-legacy"]); + const node = this.startNode(); + this.next(); + if (this.hasPlugin("decorators")) { + const startLoc = this.state.startLoc; + let expr; + if (this.match(10)) { + const startLoc = this.state.startLoc; + this.next(); + expr = this.parseExpression(); + this.expect(11); + expr = this.wrapParenthesis(startLoc, expr); + const paramsStartLoc = this.state.startLoc; + node.expression = this.parseMaybeDecoratorArguments(expr, startLoc); + if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) { + this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc); + } + } else { + expr = this.parseIdentifier(false); + while (this.eat(16)) { + const node = this.startNodeAt(startLoc); + node.object = expr; + if (this.match(139)) { + this.classScope.usePrivateName(this.state.value, this.state.startLoc); + node.property = this.parsePrivateName(); + } else { + node.property = this.parseIdentifier(true); + } + node.computed = false; + expr = this.finishNode(node, "MemberExpression"); + } + node.expression = this.parseMaybeDecoratorArguments(expr, startLoc); + } + } else { + node.expression = this.parseExprSubscripts(); + } + return this.finishNode(node, "Decorator"); + } + parseMaybeDecoratorArguments(expr, startLoc) { + if (this.eat(10)) { + const node = this.startNodeAt(startLoc); + node.callee = expr; + node.arguments = this.parseCallExpressionArguments(); + this.toReferencedList(node.arguments); + return this.finishNode(node, "CallExpression"); + } + return expr; + } + parseBreakContinueStatement(node, isBreak) { + this.next(); + if (this.isLineTerminator()) { + node.label = null; + } else { + node.label = this.parseIdentifier(); + this.semicolon(); + } + this.verifyBreakContinue(node, isBreak); + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); + } + verifyBreakContinue(node, isBreak) { + let i; + for (i = 0; i < this.state.labels.length; ++i) { + const lab = this.state.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === 1)) { + break; + } + if (node.label && isBreak) break; + } + } + if (i === this.state.labels.length) { + const type = isBreak ? "BreakStatement" : "ContinueStatement"; + this.raise(Errors.IllegalBreakContinue, node, { + type + }); + } + } + parseDebuggerStatement(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement"); + } + parseHeaderExpression() { + this.expect(10); + const val = this.parseExpression(); + this.expect(11); + return val; + } + parseDoWhileStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.state.labels.pop(); + this.expect(92); + node.test = this.parseHeaderExpression(); + this.eat(13); + return this.finishNode(node, "DoWhileStatement"); + } + parseForStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + let awaitAt = null; + if (this.isContextual(96) && this.recordAwaitIfAllowed()) { + awaitAt = this.state.startLoc; + this.next(); + } + this.scope.enter(0); + this.expect(10); + if (this.match(13)) { + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, null); + } + const startsWithLet = this.isContextual(100); + { + const startsWithAwaitUsing = this.isAwaitUsing(); + const starsWithUsingDeclaration = startsWithAwaitUsing || this.isForUsing(); + const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration; + if (this.match(74) || this.match(75) || isLetOrUsing) { + const initNode = this.startNode(); + let kind; + if (startsWithAwaitUsing) { + kind = "await using"; + if (!this.recordAwaitIfAllowed()) { + this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc); + } + this.next(); + } else { + kind = this.state.value; + } + this.next(); + this.parseVar(initNode, true, kind); + const init = this.finishNode(initNode, "VariableDeclaration"); + const isForIn = this.match(58); + if (isForIn && starsWithUsingDeclaration) { + this.raise(Errors.ForInUsing, init); + } + if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) { + return this.parseForIn(node, init, awaitAt); + } + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init); + } + } + const startsWithAsync = this.isContextual(95); + const refExpressionErrors = new ExpressionErrors(); + const init = this.parseExpression(true, refExpressionErrors); + const isForOf = this.isContextual(102); + if (isForOf) { + if (startsWithLet) { + this.raise(Errors.ForOfLet, init); + } + if (awaitAt === null && startsWithAsync && init.type === "Identifier") { + this.raise(Errors.ForOfAsync, init); + } + } + if (isForOf || this.match(58)) { + this.checkDestructuringPrivate(refExpressionErrors); + this.toAssignable(init, true); + const type = isForOf ? "ForOfStatement" : "ForInStatement"; + this.checkLVal(init, { + type + }); + return this.parseForIn(node, init, awaitAt); + } else { + this.checkExpressionErrors(refExpressionErrors, true); + } + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init); + } + parseFunctionStatement(node, isAsync, isHangingDeclaration) { + this.next(); + return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0)); + } + parseIfStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration(); + node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null; + return this.finishNode(node, "IfStatement"); + } + parseReturnStatement(node) { + if (!this.prodParam.hasReturn) { + this.raise(Errors.IllegalReturn, this.state.startLoc); + } + this.next(); + if (this.isLineTerminator()) { + node.argument = null; + } else { + node.argument = this.parseExpression(); + this.semicolon(); + } + return this.finishNode(node, "ReturnStatement"); + } + parseSwitchStatement(node) { + this.next(); + node.discriminant = this.parseHeaderExpression(); + const cases = node.cases = []; + this.expect(5); + this.state.labels.push(switchLabel); + this.scope.enter(256); + let cur; + for (let sawDefault; !this.match(8);) { + if (this.match(61) || this.match(65)) { + const isCase = this.match(61); + if (cur) this.finishNode(cur, "SwitchCase"); + cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { + this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc); + } + sawDefault = true; + cur.test = null; + } + this.expect(14); + } else { + if (cur) { + cur.consequent.push(this.parseStatementListItem()); + } else { + this.unexpected(); + } + } + } + this.scope.exit(); + if (cur) this.finishNode(cur, "SwitchCase"); + this.next(); + this.state.labels.pop(); + return this.finishNode(node, "SwitchStatement"); + } + parseThrowStatement(node) { + this.next(); + if (this.hasPrecedingLineBreak()) { + this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc); + } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement"); + } + parseCatchClauseParam() { + const param = this.parseBindingAtom(); + this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0); + this.checkLVal(param, { + type: "CatchClause" + }, 9); + return param; + } + parseTryStatement(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.match(62)) { + const clause = this.startNode(); + this.next(); + if (this.match(10)) { + this.expect(10); + clause.param = this.parseCatchClauseParam(); + this.expect(11); + } else { + clause.param = null; + this.scope.enter(0); + } + clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false)); + this.scope.exit(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(67) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) { + this.raise(Errors.NoCatchOrFinally, node); + } + return this.finishNode(node, "TryStatement"); + } + parseVarStatement(node, kind, allowMissingInitializer = false) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); + } + parseWhileStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.state.labels.pop(); + return this.finishNode(node, "WhileStatement"); + } + parseWithStatement(node) { + if (this.state.strict) { + this.raise(Errors.StrictWith, this.state.startLoc); + } + this.next(); + node.object = this.parseHeaderExpression(); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + return this.finishNode(node, "WithStatement"); + } + parseEmptyStatement(node) { + this.next(); + return this.finishNode(node, "EmptyStatement"); + } + parseLabeledStatement(node, maybeName, expr, flags) { + for (const label of this.state.labels) { + if (label.name === maybeName) { + this.raise(Errors.LabelRedeclaration, expr, { + labelName: maybeName + }); + } + } + const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null; + for (let i = this.state.labels.length - 1; i >= 0; i--) { + const label = this.state.labels[i]; + if (label.statementStart === node.start) { + label.statementStart = this.sourceToOffsetPos(this.state.start); + label.kind = kind; + } else { + break; + } + } + this.state.labels.push({ + name: maybeName, + kind: kind, + statementStart: this.sourceToOffsetPos(this.state.start) + }); + node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement(); + this.state.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement"); + } + parseExpressionStatement(node, expr, decorators) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement"); + } + parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) { + const node = this.startNode(); + if (allowDirectives) { + this.state.strictErrors.clear(); + } + this.expect(5); + if (createNewLexicalScope) { + this.scope.enter(0); + } + this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse); + if (createNewLexicalScope) { + this.scope.exit(); + } + return this.finishNode(node, "BlockStatement"); + } + isValidDirective(stmt) { + return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized; + } + parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { + const body = node.body = []; + const directives = node.directives = []; + this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse); + } + parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) { + const oldStrict = this.state.strict; + let hasStrictModeDirective = false; + let parsedNonDirective = false; + while (!this.match(end)) { + const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem(); + if (directives && !parsedNonDirective) { + if (this.isValidDirective(stmt)) { + const directive = this.stmtToDirective(stmt); + directives.push(directive); + if (!hasStrictModeDirective && directive.value.value === "use strict") { + hasStrictModeDirective = true; + this.setStrict(true); + } + continue; + } + parsedNonDirective = true; + this.state.strictErrors.clear(); + } + body.push(stmt); + } + afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective); + if (!oldStrict) { + this.setStrict(false); + } + this.next(); + } + parseFor(node, init) { + node.init = init; + this.semicolon(false); + node.test = this.match(13) ? null : this.parseExpression(); + this.semicolon(false); + node.update = this.match(11) ? null : this.parseExpression(); + this.expect(11); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, "ForStatement"); + } + parseForIn(node, init, awaitAt) { + const isForIn = this.match(58); + this.next(); + if (isForIn) { + if (awaitAt !== null) this.unexpected(awaitAt); + } else { + node.await = awaitAt !== null; + } + if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { + this.raise(Errors.ForInOfLoopInitializer, init, { + type: isForIn ? "ForInStatement" : "ForOfStatement" + }); + } + if (init.type === "AssignmentPattern") { + this.raise(Errors.InvalidLhs, init, { + ancestor: { + type: "ForStatement" + } + }); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn(); + this.expect(11); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); + } + parseVar(node, isFor, kind, allowMissingInitializer = false) { + const declarations = node.declarations = []; + node.kind = kind; + for (;;) { + const decl = this.startNode(); + this.parseVarId(decl, kind); + decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn(); + if (decl.init === null && !allowMissingInitializer) { + if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) { + this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { + kind: "destructuring" + }); + } else if ((kind === "const" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) { + this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { + kind + }); + } + } + declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(12)) break; + } + return node; + } + parseVarId(decl, kind) { + const id = this.parseBindingAtom(); + if (kind === "using" || kind === "await using") { + if (id.type === "ArrayPattern" || id.type === "ObjectPattern") { + this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start); + } + } else { + if (id.type === "VoidPattern") { + this.raise(Errors.UnexpectedVoidPattern, id.loc.start); + } + } + this.checkLVal(id, { + type: "VariableDeclarator" + }, kind === "var" ? 5 : 8201); + decl.id = id; + } + parseAsyncFunctionExpression(node) { + return this.parseFunction(node, 8); + } + parseFunction(node, flags = 0) { + const hangingDeclaration = flags & 2; + const isDeclaration = !!(flags & 1); + const requireId = isDeclaration && !(flags & 4); + const isAsync = !!(flags & 8); + this.initFunction(node, isAsync); + if (this.match(55)) { + if (hangingDeclaration) { + this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc); + } + this.next(); + node.generator = true; + } + if (isDeclaration) { + node.id = this.parseFunctionId(requireId); + } + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = false; + this.scope.enter(514); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + if (!isDeclaration) { + node.id = this.parseFunctionId(); + } + this.parseFunctionParams(node, false); + this.withSmartMixTopicForbiddingContext(() => { + this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression"); + }); + this.prodParam.exit(); + this.scope.exit(); + if (isDeclaration && !hangingDeclaration) { + this.registerFunctionStatementId(node); + } + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return node; + } + parseFunctionId(requireId) { + return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null; + } + parseFunctionParams(node, isConstructor) { + this.expect(10); + this.expressionScope.enter(newParameterDeclarationScope()); + node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0)); + this.expressionScope.exit(); + } + registerFunctionStatementId(node) { + if (!node.id) return; + this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start); + } + parseClass(node, isStatement, optionalId) { + this.next(); + const oldStrict = this.state.strict; + this.state.strict = true; + this.parseClassId(node, isStatement, optionalId); + this.parseClassSuper(node); + node.body = this.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); + } + isClassProperty() { + return this.match(29) || this.match(13) || this.match(8); + } + isClassMethod() { + return this.match(10); + } + nameIsConstructor(key) { + return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor"; + } + isNonstaticConstructor(method) { + return !method.computed && !method.static && this.nameIsConstructor(method.key); + } + parseClassBody(hadSuperClass, oldStrict) { + this.classScope.enter(); + const state = { + hadConstructor: false, + hadSuperClass + }; + let decorators = []; + const classBody = this.startNode(); + classBody.body = []; + this.expect(5); + this.withSmartMixTopicForbiddingContext(() => { + while (!this.match(8)) { + if (this.eat(13)) { + if (decorators.length > 0) { + throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc); + } + continue; + } + if (this.match(26)) { + decorators.push(this.parseDecorator()); + continue; + } + const member = this.startNode(); + if (decorators.length) { + member.decorators = decorators; + this.resetStartLocationFromNode(member, decorators[0]); + decorators = []; + } + this.parseClassMember(classBody, member, state); + if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { + this.raise(Errors.DecoratorConstructor, member); + } + } + }); + this.state.strict = oldStrict; + this.next(); + if (decorators.length) { + throw this.raise(Errors.TrailingDecorator, this.state.startLoc); + } + this.classScope.exit(); + return this.finishNode(classBody, "ClassBody"); + } + parseClassMemberFromModifier(classBody, member) { + const key = this.parseIdentifier(true); + if (this.isClassMethod()) { + const method = member; + method.kind = "method"; + method.computed = false; + method.key = key; + method.static = false; + this.pushClassMethod(classBody, method, false, false, false, false); + return true; + } else if (this.isClassProperty()) { + const prop = member; + prop.computed = false; + prop.key = key; + prop.static = false; + classBody.body.push(this.parseClassProperty(prop)); + return true; + } + this.resetPreviousNodeTrailingComments(key); + return false; + } + parseClassMember(classBody, member, state) { + const isStatic = this.isContextual(106); + if (isStatic) { + if (this.parseClassMemberFromModifier(classBody, member)) { + return; + } + if (this.eat(5)) { + this.parseClassStaticBlock(classBody, member); + return; + } + } + this.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const publicMethod = member; + const privateMethod = member; + const publicProp = member; + const privateProp = member; + const accessorProp = member; + const method = publicMethod; + const publicMember = publicMethod; + member.static = isStatic; + this.parsePropertyNamePrefixOperator(member); + if (this.eat(55)) { + method.kind = "method"; + const isPrivateName = this.match(139); + this.parseClassElementName(method); + this.parsePostMemberNameModifiers(method); + if (isPrivateName) { + this.pushClassPrivateMethod(classBody, privateMethod, true, false); + return; + } + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsGenerator, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, true, false, false, false); + return; + } + const isContextual = !this.state.containsEsc && tokenIsIdentifier(this.state.type); + const key = this.parseClassElementName(member); + const maybeContextualKw = isContextual ? key.name : null; + const isPrivate = this.isPrivateName(key); + const maybeQuestionTokenStartLoc = this.state.startLoc; + this.parsePostMemberNameModifiers(publicMember); + if (this.isClassMethod()) { + method.kind = "method"; + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + return; + } + const isConstructor = this.isNonstaticConstructor(publicMethod); + let allowsDirectSuper = false; + if (isConstructor) { + publicMethod.kind = "constructor"; + if (state.hadConstructor && !this.hasPlugin("typescript")) { + this.raise(Errors.DuplicateConstructor, key); + } + if (isConstructor && this.hasPlugin("typescript") && member.override) { + this.raise(Errors.OverrideOnConstructor, key); + } + state.hadConstructor = true; + allowsDirectSuper = state.hadSuperClass; + } + this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper); + } else if (this.isClassProperty()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else if (maybeContextualKw === "async" && !this.isLineTerminator()) { + this.resetPreviousNodeTrailingComments(key); + const isGenerator = this.eat(55); + if (publicMember.optional) { + this.unexpected(maybeQuestionTokenStartLoc); + } + method.kind = "method"; + const isPrivate = this.match(139); + this.parseClassElementName(method); + this.parsePostMemberNameModifiers(publicMember); + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsAsync, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); + } + } else if ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) { + this.resetPreviousNodeTrailingComments(key); + method.kind = maybeContextualKw; + const isPrivate = this.match(139); + this.parseClassElementName(publicMethod); + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsAccessor, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, false, false, false, false); + } + this.checkGetterSetterParams(publicMethod); + } else if (maybeContextualKw === "accessor" && !this.isLineTerminator()) { + this.expectPlugin("decoratorAutoAccessors"); + this.resetPreviousNodeTrailingComments(key); + const isPrivate = this.match(139); + this.parseClassElementName(publicProp); + this.pushClassAccessorProperty(classBody, accessorProp, isPrivate); + } else if (this.isLineTerminator()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else { + this.unexpected(); + } + } + parseClassElementName(member) { + const { + type, + value + } = this.state; + if ((type === 132 || type === 134) && member.static && value === "prototype") { + this.raise(Errors.StaticPrototype, this.state.startLoc); + } + if (type === 139) { + if (value === "constructor") { + this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc); + } + const key = this.parsePrivateName(); + member.key = key; + return key; + } + this.parsePropertyName(member); + return member.key; + } + parseClassStaticBlock(classBody, member) { + var _member$decorators; + this.scope.enter(576 | 128 | 16); + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(0); + const body = member.body = []; + this.parseBlockOrModuleBlockBody(body, undefined, false, 8); + this.prodParam.exit(); + this.scope.exit(); + this.state.labels = oldLabels; + classBody.body.push(this.finishNode(member, "StaticBlock")); + if ((_member$decorators = member.decorators) != null && _member$decorators.length) { + this.raise(Errors.DecoratorStaticBlock, member); + } + } + pushClassProperty(classBody, prop) { + if (!prop.computed && this.nameIsConstructor(prop.key)) { + this.raise(Errors.ConstructorClassField, prop.key); + } + classBody.body.push(this.parseClassProperty(prop)); + } + pushClassPrivateProperty(classBody, prop) { + const node = this.parseClassPrivateProperty(prop); + classBody.body.push(node); + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); + } + pushClassAccessorProperty(classBody, prop, isPrivate) { + if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) { + this.raise(Errors.ConstructorClassField, prop.key); + } + const node = this.parseClassAccessorProperty(prop); + classBody.body.push(node); + if (isPrivate) { + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); + } + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true)); + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true); + classBody.body.push(node); + const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0; + this.declareClassPrivateMethodInScope(node, kind); + } + declareClassPrivateMethodInScope(node, kind) { + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start); + } + parsePostMemberNameModifiers(methodOrProp) {} + parseClassPrivateProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassPrivateProperty"); + } + parseClassProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassProperty"); + } + parseClassAccessorProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassAccessorProperty"); + } + parseInitializer(node) { + this.scope.enter(576 | 16); + this.expressionScope.enter(newExpressionScope()); + this.prodParam.enter(0); + node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null; + this.expressionScope.exit(); + this.prodParam.exit(); + this.scope.exit(); + } + parseClassId(node, isStatement, optionalId, bindingType = 8331) { + if (tokenIsIdentifier(this.state.type)) { + node.id = this.parseIdentifier(); + if (isStatement) { + this.declareNameFromIdentifier(node.id, bindingType); + } + } else { + if (optionalId || !isStatement) { + node.id = null; + } else { + throw this.raise(Errors.MissingClassName, this.state.startLoc); + } + } + } + parseClassSuper(node) { + node.superClass = this.eat(81) ? this.parseExprSubscripts() : null; + } + parseExport(node, decorators) { + const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true); + const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); + const parseAfterDefault = !hasDefault || this.eat(12); + const hasStar = parseAfterDefault && this.eatExportStar(node); + const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node); + const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12)); + const isFromRequired = hasDefault || hasStar; + if (hasStar && !hasNamespace) { + if (hasDefault) this.unexpected(); + if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.parseExportFrom(node, true); + this.sawUnambiguousESM = true; + return this.finishNode(node, "ExportAllDeclaration"); + } + const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node); + if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) { + this.unexpected(null, 5); + } + if (hasNamespace && parseAfterNamespace) { + this.unexpected(null, 98); + } + let hasDeclaration; + if (isFromRequired || hasSpecifiers) { + hasDeclaration = false; + if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.parseExportFrom(node, isFromRequired); + } else { + hasDeclaration = this.maybeParseExportDeclaration(node); + } + if (isFromRequired || hasSpecifiers || hasDeclaration) { + var _node2$declaration; + const node2 = node; + this.checkExport(node2, true, false, !!node2.source); + if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") { + this.maybeTakeDecorators(decorators, node2.declaration, node2); + } else if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.sawUnambiguousESM = true; + return this.finishNode(node2, "ExportNamedDeclaration"); + } + if (this.eat(65)) { + const node2 = node; + const decl = this.parseExportDefaultExpression(); + node2.declaration = decl; + if (decl.type === "ClassDeclaration") { + this.maybeTakeDecorators(decorators, decl, node2); + } else if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.checkExport(node2, true, true); + this.sawUnambiguousESM = true; + return this.finishNode(node2, "ExportDefaultDeclaration"); + } + throw this.unexpected(null, 5); + } + eatExportStar(node) { + return this.eat(55); + } + maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { + if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) { + this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start); + const id = maybeDefaultIdentifier || this.parseIdentifier(true); + const specifier = this.startNodeAtNode(id); + specifier.exported = id; + node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return true; + } + return false; + } + maybeParseExportNamespaceSpecifier(node) { + if (this.isContextual(93)) { + var _ref, _ref$specifiers; + (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.specifiers = []; + const specifier = this.startNodeAt(this.state.lastTokStartLoc); + this.next(); + specifier.exported = this.parseModuleExportName(); + node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); + return true; + } + return false; + } + maybeParseExportNamedSpecifiers(node) { + if (this.match(5)) { + const node2 = node; + if (!node2.specifiers) node2.specifiers = []; + const isTypeExport = node2.exportKind === "type"; + node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport)); + node2.source = null; + if (this.hasPlugin("importAssertions")) { + node2.assertions = []; + } else { + node2.attributes = []; + } + node2.declaration = null; + return true; + } + return false; + } + maybeParseExportDeclaration(node) { + if (this.shouldParseExportDeclaration()) { + node.specifiers = []; + node.source = null; + if (this.hasPlugin("importAssertions")) { + node.assertions = []; + } else { + node.attributes = []; + } + node.declaration = this.parseExportDeclaration(node); + return true; + } + return false; + } + isAsyncFunction() { + if (!this.isContextual(95)) return false; + const next = this.nextTokenInLineStart(); + return this.isUnparsedContextual(next, "function"); + } + parseExportDefaultExpression() { + const expr = this.startNode(); + if (this.match(68)) { + this.next(); + return this.parseFunction(expr, 1 | 4); + } else if (this.isAsyncFunction()) { + this.next(); + this.next(); + return this.parseFunction(expr, 1 | 4 | 8); + } + if (this.match(80)) { + return this.parseClass(expr, true, true); + } + if (this.match(26)) { + if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { + this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); + } + return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true); + } + if (this.match(75) || this.match(74) || this.isLet() || this.isUsing() || this.isAwaitUsing()) { + throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc); + } + const res = this.parseMaybeAssignAllowIn(); + this.semicolon(); + return res; + } + parseExportDeclaration(node) { + if (this.match(80)) { + const node = this.parseClass(this.startNode(), true, false); + return node; + } + return this.parseStatementListItem(); + } + isExportDefaultSpecifier() { + const { + type + } = this.state; + if (tokenIsIdentifier(type)) { + if (type === 95 && !this.state.containsEsc || type === 100) { + return false; + } + if ((type === 130 || type === 129) && !this.state.containsEsc) { + const next = this.nextTokenStart(); + const nextChar = this.input.charCodeAt(next); + if (nextChar === 123 || this.chStartsBindingIdentifier(nextChar, next) && !this.input.startsWith("from", next)) { + this.expectOnePlugin(["flow", "typescript"]); + return false; + } + } + } else if (!this.match(65)) { + return false; + } + const next = this.nextTokenStart(); + const hasFrom = this.isUnparsedContextual(next, "from"); + if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) { + return true; + } + if (this.match(65) && hasFrom) { + const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4)); + return nextAfterFrom === 34 || nextAfterFrom === 39; + } + return false; + } + parseExportFrom(node, expect) { + if (this.eatContextual(98)) { + node.source = this.parseImportSource(); + this.checkExport(node); + this.maybeParseImportAttributes(node); + this.checkJSONModuleImport(node); + } else if (expect) { + this.unexpected(); + } + this.semicolon(); + } + shouldParseExportDeclaration() { + const { + type + } = this.state; + if (type === 26) { + this.expectOnePlugin(["decorators", "decorators-legacy"]); + if (this.hasPlugin("decorators")) { + if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { + this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); + } + return true; + } + } + if (this.isUsing()) { + this.raise(Errors.UsingDeclarationExport, this.state.startLoc); + return true; + } + if (this.isAwaitUsing()) { + this.raise(Errors.UsingDeclarationExport, this.state.startLoc); + return true; + } + return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction(); + } + checkExport(node, checkNames, isDefault, isFrom) { + if (checkNames) { + var _node$specifiers; + if (isDefault) { + this.checkDuplicateExports(node, "default"); + if (this.hasPlugin("exportDefaultFrom")) { + var _declaration$extra; + const declaration = node.declaration; + if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) { + this.raise(Errors.ExportDefaultFromAsIdentifier, declaration); + } + } + } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) { + for (const specifier of node.specifiers) { + const { + exported + } = specifier; + const exportName = exported.type === "Identifier" ? exported.name : exported.value; + this.checkDuplicateExports(specifier, exportName); + if (!isFrom && specifier.local) { + const { + local + } = specifier; + if (local.type !== "Identifier") { + this.raise(Errors.ExportBindingIsString, specifier, { + localName: local.value, + exportName + }); + } else { + this.checkReservedWord(local.name, local.loc.start, true, false); + this.scope.checkLocalExport(local); + } + } + } + } else if (node.declaration) { + const decl = node.declaration; + if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") { + const { + id + } = decl; + if (!id) throw new Error("Assertion failure"); + this.checkDuplicateExports(node, id.name); + } else if (decl.type === "VariableDeclaration") { + for (const declaration of decl.declarations) { + this.checkDeclaration(declaration.id); + } + } + } + } + } + checkDeclaration(node) { + if (node.type === "Identifier") { + this.checkDuplicateExports(node, node.name); + } else if (node.type === "ObjectPattern") { + for (const prop of node.properties) { + this.checkDeclaration(prop); + } + } else if (node.type === "ArrayPattern") { + for (const elem of node.elements) { + if (elem) { + this.checkDeclaration(elem); + } + } + } else if (node.type === "ObjectProperty") { + this.checkDeclaration(node.value); + } else if (node.type === "RestElement") { + this.checkDeclaration(node.argument); + } else if (node.type === "AssignmentPattern") { + this.checkDeclaration(node.left); + } + } + checkDuplicateExports(node, exportName) { + if (this.exportedIdentifiers.has(exportName)) { + if (exportName === "default") { + this.raise(Errors.DuplicateDefaultExport, node); + } else { + this.raise(Errors.DuplicateExport, node, { + exportName + }); + } + } + this.exportedIdentifiers.add(exportName); + } + parseExportSpecifiers(isInTypeExport) { + const nodes = []; + let first = true; + this.expect(5); + while (!this.eat(8)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.eat(8)) break; + } + const isMaybeTypeOnly = this.isContextual(130); + const isString = this.match(134); + const node = this.startNode(); + node.local = this.parseModuleExportName(); + nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly)); + } + return nodes; + } + parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { + if (this.eatContextual(93)) { + node.exported = this.parseModuleExportName(); + } else if (isString) { + node.exported = this.cloneStringLiteral(node.local); + } else if (!node.exported) { + node.exported = this.cloneIdentifier(node.local); + } + return this.finishNode(node, "ExportSpecifier"); + } + parseModuleExportName() { + if (this.match(134)) { + const result = this.parseStringLiteral(this.state.value); + const surrogate = loneSurrogate.exec(result.value); + if (surrogate) { + this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, { + surrogateCharCode: surrogate[0].charCodeAt(0) + }); + } + return result; + } + return this.parseIdentifier(true); + } + isJSONModuleImport(node) { + if (node.assertions != null) { + return node.assertions.some(({ + key, + value + }) => { + return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type"); + }); + } + return false; + } + checkImportReflection(node) { + const { + specifiers + } = node; + const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null; + if (node.phase === "source") { + if (singleBindingType !== "ImportDefaultSpecifier") { + this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start); + } + } else if (node.phase === "defer") { + if (singleBindingType !== "ImportNamespaceSpecifier") { + this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start); + } + } else if (node.module) { + var _node$assertions; + if (singleBindingType !== "ImportDefaultSpecifier") { + this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start); + } + if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) { + this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start); + } + } + } + checkJSONModuleImport(node) { + if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") { + const { + specifiers + } = node; + if (specifiers != null) { + const nonDefaultNamedSpecifier = specifiers.find(specifier => { + let imported; + if (specifier.type === "ExportSpecifier") { + imported = specifier.local; + } else if (specifier.type === "ImportSpecifier") { + imported = specifier.imported; + } + if (imported !== undefined) { + return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default"; + } + }); + if (nonDefaultNamedSpecifier !== undefined) { + this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start); + } + } + } + } + isPotentialImportPhase(isExport) { + if (isExport) return false; + return this.isContextual(105) || this.isContextual(97) || this.isContextual(127); + } + applyImportPhase(node, isExport, phase, loc) { + if (isExport) { + return; + } + if (phase === "module") { + this.expectPlugin("importReflection", loc); + node.module = true; + } else if (this.hasPlugin("importReflection")) { + node.module = false; + } + if (phase === "source") { + this.expectPlugin("sourcePhaseImports", loc); + node.phase = "source"; + } else if (phase === "defer") { + this.expectPlugin("deferredImportEvaluation", loc); + node.phase = "defer"; + } else if (this.hasPlugin("sourcePhaseImports")) { + node.phase = null; + } + } + parseMaybeImportPhase(node, isExport) { + if (!this.isPotentialImportPhase(isExport)) { + this.applyImportPhase(node, isExport, null); + return null; + } + const phaseIdentifier = this.startNode(); + const phaseIdentifierName = this.parseIdentifierName(true); + const { + type + } = this.state; + const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; + if (isImportPhase) { + this.applyImportPhase(node, isExport, phaseIdentifierName, phaseIdentifier.loc.start); + return null; + } else { + this.applyImportPhase(node, isExport, null); + return this.createIdentifier(phaseIdentifier, phaseIdentifierName); + } + } + isPrecedingIdImportPhase(phase) { + const { + type + } = this.state; + return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; + } + parseImport(node) { + if (this.match(134)) { + return this.parseImportSourceAndAttributes(node); + } + return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false)); + } + parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) { + node.specifiers = []; + const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier); + const parseNext = !hasDefault || this.eat(12); + const hasStar = parseNext && this.maybeParseStarImportSpecifier(node); + if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node); + this.expectContextual(98); + return this.parseImportSourceAndAttributes(node); + } + parseImportSourceAndAttributes(node) { + var _node$specifiers2; + (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = []; + node.source = this.parseImportSource(); + this.maybeParseImportAttributes(node); + this.checkImportReflection(node); + this.checkJSONModuleImport(node); + this.semicolon(); + this.sawUnambiguousESM = true; + return this.finishNode(node, "ImportDeclaration"); + } + parseImportSource() { + if (!this.match(134)) this.unexpected(); + return this.parseExprAtom(); + } + parseImportSpecifierLocal(node, specifier, type) { + specifier.local = this.parseIdentifier(); + node.specifiers.push(this.finishImportSpecifier(specifier, type)); + } + finishImportSpecifier(specifier, type, bindingType = 8201) { + this.checkLVal(specifier.local, { + type + }, bindingType); + return this.finishNode(specifier, type); + } + parseImportAttributes() { + this.expect(5); + const attrs = []; + const attrNames = new Set(); + do { + if (this.match(8)) { + break; + } + const node = this.startNode(); + const keyName = this.state.value; + if (attrNames.has(keyName)) { + this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, { + key: keyName + }); + } + attrNames.add(keyName); + if (this.match(134)) { + node.key = this.parseStringLiteral(keyName); + } else { + node.key = this.parseIdentifier(true); + } + this.expect(14); + if (!this.match(134)) { + throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); + } + node.value = this.parseStringLiteral(this.state.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(12)); + this.expect(8); + return attrs; + } + parseModuleAttributes() { + const attrs = []; + const attributes = new Set(); + do { + const node = this.startNode(); + node.key = this.parseIdentifier(true); + if (node.key.name !== "type") { + this.raise(Errors.ModuleAttributeDifferentFromType, node.key); + } + if (attributes.has(node.key.name)) { + this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, { + key: node.key.name + }); + } + attributes.add(node.key.name); + this.expect(14); + if (!this.match(134)) { + throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); + } + node.value = this.parseStringLiteral(this.state.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(12)); + return attrs; + } + maybeParseImportAttributes(node) { + let attributes; + var useWith = false; + if (this.match(76)) { + if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) { + return; + } + this.next(); + if (this.hasPlugin("moduleAttributes")) { + attributes = this.parseModuleAttributes(); + this.addExtra(node, "deprecatedWithLegacySyntax", true); + } else { + attributes = this.parseImportAttributes(); + } + useWith = true; + } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) { + if (!this.hasPlugin("deprecatedImportAssert") && !this.hasPlugin("importAssertions")) { + this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc); + } + if (!this.hasPlugin("importAssertions")) { + this.addExtra(node, "deprecatedAssertSyntax", true); + } + this.next(); + attributes = this.parseImportAttributes(); + } else { + attributes = []; + } + if (!useWith && this.hasPlugin("importAssertions")) { + node.assertions = attributes; + } else { + node.attributes = attributes; + } + } + maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) { + if (maybeDefaultIdentifier) { + const specifier = this.startNodeAtNode(maybeDefaultIdentifier); + specifier.local = maybeDefaultIdentifier; + node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier")); + return true; + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier"); + return true; + } + return false; + } + maybeParseStarImportSpecifier(node) { + if (this.match(55)) { + const specifier = this.startNode(); + this.next(); + this.expectContextual(93); + this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier"); + return true; + } + return false; + } + parseNamedImportSpecifiers(node) { + let first = true; + this.expect(5); + while (!this.eat(8)) { + if (first) { + first = false; + } else { + if (this.eat(14)) { + throw this.raise(Errors.DestructureNamedImport, this.state.startLoc); + } + this.expect(12); + if (this.eat(8)) break; + } + const specifier = this.startNode(); + const importedIsString = this.match(134); + const isMaybeTypeOnly = this.isContextual(130); + specifier.imported = this.parseModuleExportName(); + const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined); + node.specifiers.push(importSpecifier); + } + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + if (this.eatContextual(93)) { + specifier.local = this.parseIdentifier(); + } else { + const { + imported + } = specifier; + if (importedIsString) { + throw this.raise(Errors.ImportBindingIsString, specifier, { + importName: imported.value + }); + } + this.checkReservedWord(imported.name, specifier.loc.start, true, true); + if (!specifier.local) { + specifier.local = this.cloneIdentifier(imported); + } + } + return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType); + } + isThisParam(param) { + return param.type === "Identifier" && param.name === "this"; + } +} +class Parser extends StatementParser { + constructor(options, input, pluginsMap) { + const normalizedOptions = getOptions(options); + super(normalizedOptions, input); + this.options = normalizedOptions; + this.initializeScopes(); + this.plugins = pluginsMap; + this.filename = normalizedOptions.sourceFilename; + this.startIndex = normalizedOptions.startIndex; + let optionFlags = 0; + if (normalizedOptions.allowAwaitOutsideFunction) { + optionFlags |= 1; + } + if (normalizedOptions.allowReturnOutsideFunction) { + optionFlags |= 2; + } + if (normalizedOptions.allowImportExportEverywhere) { + optionFlags |= 8; + } + if (normalizedOptions.allowSuperOutsideMethod) { + optionFlags |= 16; + } + if (normalizedOptions.allowUndeclaredExports) { + optionFlags |= 64; + } + if (normalizedOptions.allowNewTargetOutsideFunction) { + optionFlags |= 4; + } + if (normalizedOptions.allowYieldOutsideFunction) { + optionFlags |= 32; + } + if (normalizedOptions.ranges) { + optionFlags |= 128; + } + if (normalizedOptions.tokens) { + optionFlags |= 256; + } + if (normalizedOptions.createImportExpressions) { + optionFlags |= 512; + } + if (normalizedOptions.createParenthesizedExpressions) { + optionFlags |= 1024; + } + if (normalizedOptions.errorRecovery) { + optionFlags |= 2048; + } + if (normalizedOptions.attachComment) { + optionFlags |= 4096; + } + if (normalizedOptions.annexB) { + optionFlags |= 8192; + } + this.optionFlags = optionFlags; + } + getScopeHandler() { + return ScopeHandler; + } + parse() { + this.enterInitialScopes(); + const file = this.startNode(); + const program = this.startNode(); + this.nextToken(); + file.errors = null; + const result = this.parseTopLevel(file, program); + result.errors = this.state.errors; + result.comments.length = this.state.commentsLen; + return result; + } +} +function parse(input, options) { + var _options; + if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") { + options = Object.assign({}, options); + try { + options.sourceType = "module"; + const parser = getParser(options, input); + const ast = parser.parse(); + if (parser.sawUnambiguousESM) { + return ast; + } + if (parser.ambiguousScriptDifferentAst) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused) {} + } else { + ast.program.sourceType = "script"; + } + return ast; + } catch (moduleError) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused2) {} + throw moduleError; + } + } else { + return getParser(options, input).parse(); + } +} +function parseExpression(input, options) { + const parser = getParser(options, input); + if (parser.options.strictMode) { + parser.state.strict = true; + } + return parser.getExpression(); +} +function generateExportedTokenTypes(internalTokenTypes) { + const tokenTypes = {}; + for (const typeName of Object.keys(internalTokenTypes)) { + tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]); + } + return tokenTypes; +} +const tokTypes = generateExportedTokenTypes(tt); +function getParser(options, input) { + let cls = Parser; + const pluginsMap = new Map(); + if (options != null && options.plugins) { + for (const plugin of options.plugins) { + let name, opts; + if (typeof plugin === "string") { + name = plugin; + } else { + [name, opts] = plugin; + } + if (!pluginsMap.has(name)) { + pluginsMap.set(name, opts || {}); + } + } + validatePlugins(pluginsMap); + cls = getParserClass(pluginsMap); + } + return new cls(options, input, pluginsMap); +} +const parserClassCache = new Map(); +function getParserClass(pluginsMap) { + const pluginList = []; + for (const name of mixinPluginNames) { + if (pluginsMap.has(name)) { + pluginList.push(name); + } + } + const key = pluginList.join("|"); + let cls = parserClassCache.get(key); + if (!cls) { + cls = Parser; + for (const plugin of pluginList) { + cls = mixinPlugins[plugin](cls); + } + parserClassCache.set(key, cls); + } + return cls; +} +exports.parse = parse; +exports.parseExpression = parseExpression; +exports.tokTypes = tokTypes; +//# sourceMappingURL=index.js.map diff --git a/vanilla/node_modules/@babel/parser/lib/index.js.map b/vanilla/node_modules/@babel/parser/lib/index.js.map new file mode 100644 index 0000000..0f73da4 --- /dev/null +++ b/vanilla/node_modules/@babel/parser/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/util/location.ts","../src/parse-error/module-errors.ts","../src/parse-error/to-node-description.ts","../src/parse-error/standard-errors.ts","../src/parse-error/strict-mode-errors.ts","../src/parse-error/parse-expression-errors.ts","../src/parse-error/pipeline-operator-errors.ts","../src/parse-error.ts","../src/options.ts","../src/plugins/estree.ts","../src/tokenizer/context.ts","../src/tokenizer/types.ts","../../babel-helper-validator-identifier/src/identifier.ts","../../babel-helper-validator-identifier/src/keyword.ts","../src/util/identifier.ts","../src/util/scope.ts","../src/plugins/flow/scope.ts","../src/plugins/flow/index.ts","../src/plugins/jsx/xhtml.ts","../src/util/whitespace.ts","../src/plugins/jsx/index.ts","../src/plugins/typescript/scope.ts","../src/util/production-parameter.ts","../src/parser/base.ts","../src/parser/comments.ts","../src/tokenizer/state.ts","../../babel-helper-string-parser/src/index.ts","../src/tokenizer/index.ts","../src/util/class-scope.ts","../src/util/expression-scope.ts","../src/parser/util.ts","../src/parser/node.ts","../src/parser/lval.ts","../src/plugins/typescript/index.ts","../src/plugins/placeholders.ts","../src/plugins/v8intrinsic.ts","../src/plugin-utils.ts","../src/parser/expression.ts","../src/parser/statement.ts","../src/parser/index.ts","../src/index.ts"],"sourcesContent":["export type Pos = {\n start: number;\n};\n\n// These are used when `options.locations` is on, for the\n// `startLoc` and `endLoc` properties.\n\nexport class Position {\n line: number;\n column: number;\n index: number;\n\n constructor(line: number, col: number, index: number) {\n this.line = line;\n this.column = col;\n this.index = index;\n }\n}\n\nexport class SourceLocation {\n start: Position;\n end: Position;\n filename: string | undefined;\n identifierName: string | undefined | null;\n\n constructor(start: Position, end?: Position) {\n this.start = start;\n // (may start as null, but initialized later)\n this.end = end!;\n }\n}\n\n/**\n * creates a new position with a non-zero column offset from the given position.\n * This function should be only be used when we create AST node out of the token\n * boundaries, such as TemplateElement ends before tt.templateNonTail. This\n * function does not skip whitespaces.\n */\nexport function createPositionWithColumnOffset(\n position: Position,\n columnOffset: number,\n) {\n const { line, column, index } = position;\n return new Position(line, column + columnOffset, index + columnOffset);\n}\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\n\nconst code = \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\";\n\nexport default {\n ImportMetaOutsideModule: {\n message: `import.meta may appear only with 'sourceType: \"module\"'`,\n code,\n },\n ImportOutsideModule: {\n message: `'import' and 'export' may appear only with 'sourceType: \"module\"'`,\n code,\n },\n} satisfies ParseErrorTemplates;\n","const NodeDescriptions = {\n ArrayPattern: \"array destructuring pattern\",\n AssignmentExpression: \"assignment expression\",\n AssignmentPattern: \"assignment expression\",\n ArrowFunctionExpression: \"arrow function expression\",\n ConditionalExpression: \"conditional expression\",\n CatchClause: \"catch clause\",\n ForOfStatement: \"for-of statement\",\n ForInStatement: \"for-in statement\",\n ForStatement: \"for-loop\",\n FormalParameters: \"function parameter list\",\n Identifier: \"identifier\",\n ImportSpecifier: \"import specifier\",\n ImportDefaultSpecifier: \"import default specifier\",\n ImportNamespaceSpecifier: \"import namespace specifier\",\n ObjectPattern: \"object destructuring pattern\",\n ParenthesizedExpression: \"parenthesized expression\",\n RestElement: \"rest element\",\n UpdateExpression: {\n true: \"prefix operation\",\n false: \"postfix operation\",\n },\n VariableDeclarator: \"variable declaration\",\n YieldExpression: \"yield expression\",\n};\n\ntype NodeTypesWithDescriptions = keyof Omit<\n typeof NodeDescriptions,\n \"UpdateExpression\"\n>;\n\ntype NodeWithDescription =\n | {\n type: \"UpdateExpression\";\n prefix: boolean;\n }\n | {\n type: NodeTypesWithDescriptions;\n };\n\nconst toNodeDescription = (node: NodeWithDescription) =>\n node.type === \"UpdateExpression\"\n ? NodeDescriptions.UpdateExpression[`${node.prefix}`]\n : NodeDescriptions[node.type];\n\nexport default toNodeDescription;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\nimport toNodeDescription from \"./to-node-description.ts\";\n\nexport type LValAncestor =\n | { type: \"UpdateExpression\"; prefix: boolean }\n | {\n type:\n | \"ArrayPattern\"\n | \"AssignmentExpression\"\n | \"CatchClause\"\n | \"ForOfStatement\"\n | \"FormalParameters\"\n | \"ForInStatement\"\n | \"ForStatement\"\n | \"ImportSpecifier\"\n | \"ImportNamespaceSpecifier\"\n | \"ImportDefaultSpecifier\"\n | \"ParenthesizedExpression\"\n | \"ObjectPattern\"\n | \"RestElement\"\n | \"VariableDeclarator\";\n };\n\nexport default {\n AccessorIsGenerator: ({ kind }: { kind: \"get\" | \"set\" }) =>\n `A ${kind}ter cannot be a generator.`,\n ArgumentsInClass:\n \"'arguments' is only allowed in functions and class methods.\",\n AsyncFunctionInSingleStatementContext:\n \"Async functions can only be declared at the top level or inside a block.\",\n AwaitBindingIdentifier:\n \"Can not use 'await' as identifier inside an async function.\",\n AwaitBindingIdentifierInStaticBlock:\n \"Can not use 'await' as identifier inside a static block.\",\n AwaitExpressionFormalParameter:\n \"'await' is not allowed in async function parameters.\",\n AwaitUsingNotInAsyncContext:\n \"'await using' is only allowed within async functions and at the top levels of modules.\",\n AwaitNotInAsyncContext:\n \"'await' is only allowed within async functions and at the top levels of modules.\",\n BadGetterArity: \"A 'get' accessor must not have any formal parameters.\",\n BadSetterArity: \"A 'set' accessor must have exactly one formal parameter.\",\n BadSetterRestParameter:\n \"A 'set' accessor function argument must not be a rest parameter.\",\n ConstructorClassField: \"Classes may not have a field named 'constructor'.\",\n ConstructorClassPrivateField:\n \"Classes may not have a private field named '#constructor'.\",\n ConstructorIsAccessor: \"Class constructor may not be an accessor.\",\n ConstructorIsAsync: \"Constructor can't be an async function.\",\n ConstructorIsGenerator: \"Constructor can't be a generator.\",\n DeclarationMissingInitializer: ({\n kind,\n }: {\n kind: \"await using\" | \"const\" | \"destructuring\" | \"using\";\n }) => `Missing initializer in ${kind} declaration.`,\n DecoratorArgumentsOutsideParentheses:\n \"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.\",\n DecoratorBeforeExport:\n \"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.\",\n DecoratorsBeforeAfterExport:\n \"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.\",\n DecoratorConstructor:\n \"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?\",\n DecoratorExportClass:\n \"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.\",\n DecoratorSemicolon: \"Decorators must not be followed by a semicolon.\",\n DecoratorStaticBlock: \"Decorators can't be used with a static block.\",\n DeferImportRequiresNamespace:\n 'Only `import defer * as x from \"./module\"` is valid.',\n DeletePrivateField: \"Deleting a private field is not allowed.\",\n DestructureNamedImport:\n \"ES2015 named imports do not destructure. Use another statement for destructuring after the import.\",\n DuplicateConstructor: \"Duplicate constructor in the same class.\",\n DuplicateDefaultExport: \"Only one default export allowed per module.\",\n DuplicateExport: ({ exportName }: { exportName: string }) =>\n `\\`${exportName}\\` has already been exported. Exported identifiers must be unique.`,\n DuplicateProto: \"Redefinition of __proto__ property.\",\n DuplicateRegExpFlags: \"Duplicate regular expression flag.\",\n ElementAfterRest: \"Rest element must be last element.\",\n EscapedCharNotAnIdentifier: \"Invalid Unicode escape.\",\n ExportBindingIsString: ({\n localName,\n exportName,\n }: {\n localName: string;\n exportName: string;\n }) =>\n `A string literal cannot be used as an exported binding without \\`from\\`.\\n- Did you mean \\`export { '${localName}' as '${exportName}' } from 'some-module'\\`?`,\n ExportDefaultFromAsIdentifier:\n \"'from' is not allowed as an identifier after 'export default'.\",\n\n ForInOfLoopInitializer: ({\n type,\n }: {\n type: \"ForInStatement\" | \"ForOfStatement\";\n }) =>\n `'${\n type === \"ForInStatement\" ? \"for-in\" : \"for-of\"\n }' loop variable declaration may not have an initializer.`,\n ForInUsing: \"For-in loop may not start with 'using' declaration.\",\n\n ForOfAsync: \"The left-hand side of a for-of loop may not be 'async'.\",\n ForOfLet: \"The left-hand side of a for-of loop may not start with 'let'.\",\n GeneratorInSingleStatementContext:\n \"Generators can only be declared at the top level or inside a block.\",\n\n IllegalBreakContinue: ({\n type,\n }: {\n type: \"BreakStatement\" | \"ContinueStatement\";\n }) => `Unsyntactic ${type === \"BreakStatement\" ? \"break\" : \"continue\"}.`,\n\n IllegalLanguageModeDirective:\n \"Illegal 'use strict' directive in function with non-simple parameter list.\",\n IllegalReturn: \"'return' outside of function.\",\n ImportAttributesUseAssert:\n \"The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.\",\n ImportBindingIsString: ({ importName }: { importName: string }) =>\n `A string literal cannot be used as an imported binding.\\n- Did you mean \\`import { \"${importName}\" as foo }\\`?`,\n ImportCallArity: `\\`import()\\` requires exactly one or two arguments.`,\n ImportCallNotNewExpression: \"Cannot use new with import(...).\",\n ImportCallSpreadArgument: \"`...` is not allowed in `import()`.\",\n ImportJSONBindingNotDefault:\n \"A JSON module can only be imported with `default`.\",\n ImportReflectionHasAssertion: \"`import module x` cannot have assertions.\",\n ImportReflectionNotBinding:\n 'Only `import module x from \"./module\"` is valid.',\n IncompatibleRegExpUVFlags:\n \"The 'u' and 'v' regular expression flags cannot be enabled at the same time.\",\n InvalidBigIntLiteral: \"Invalid BigIntLiteral.\",\n InvalidCodePoint: \"Code point out of bounds.\",\n InvalidCoverDiscardElement:\n \"'void' must be followed by an expression when not used in a binding position.\",\n InvalidCoverInitializedName: \"Invalid shorthand property initializer.\",\n InvalidDecimal: \"Invalid decimal.\",\n InvalidDigit: ({ radix }: { radix: number }) =>\n `Expected number in radix ${radix}.`,\n InvalidEscapeSequence: \"Bad character escape sequence.\",\n InvalidEscapeSequenceTemplate: \"Invalid escape sequence in template.\",\n InvalidEscapedReservedWord: ({ reservedWord }: { reservedWord: string }) =>\n `Escape sequence in keyword ${reservedWord}.`,\n InvalidIdentifier: ({ identifierName }: { identifierName: string }) =>\n `Invalid identifier ${identifierName}.`,\n InvalidLhs: ({ ancestor }: { ancestor: LValAncestor }) =>\n `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,\n InvalidLhsBinding: ({ ancestor }: { ancestor: LValAncestor }) =>\n `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,\n InvalidLhsOptionalChaining: ({ ancestor }: { ancestor: LValAncestor }) =>\n `Invalid optional chaining in the left-hand side of ${toNodeDescription(\n ancestor,\n )}.`,\n InvalidNumber: \"Invalid number.\",\n InvalidOrMissingExponent:\n \"Floating-point numbers require a valid exponent after the 'e'.\",\n InvalidOrUnexpectedToken: ({ unexpected }: { unexpected: string }) =>\n `Unexpected character '${unexpected}'.`,\n InvalidParenthesizedAssignment: \"Invalid parenthesized assignment pattern.\",\n InvalidPrivateFieldResolution: ({\n identifierName,\n }: {\n identifierName: string;\n }) => `Private name #${identifierName} is not defined.`,\n InvalidPropertyBindingPattern: \"Binding member expression.\",\n InvalidRecordProperty:\n \"Only properties and spread elements are allowed in record definitions.\",\n InvalidRestAssignmentPattern: \"Invalid rest operator's argument.\",\n LabelRedeclaration: ({ labelName }: { labelName: string }) =>\n `Label '${labelName}' is already declared.`,\n LetInLexicalBinding: \"'let' is disallowed as a lexically bound name.\",\n LineTerminatorBeforeArrow: \"No line break is allowed before '=>'.\",\n MalformedRegExpFlags: \"Invalid regular expression flag.\",\n MissingClassName: \"A class name is required.\",\n MissingEqInAssignment:\n \"Only '=' operator can be used for specifying default value.\",\n MissingSemicolon: \"Missing semicolon.\",\n MissingPlugin: ({ missingPlugin }: { missingPlugin: [string] }) =>\n `This experimental syntax requires enabling the parser plugin: ${missingPlugin\n .map(name => JSON.stringify(name))\n .join(\", \")}.`,\n // FIXME: Would be nice to make this \"missingPlugins\" instead.\n // Also, seems like we can drop the \"(s)\" from the message and just make it \"s\".\n MissingOneOfPlugins: ({ missingPlugin }: { missingPlugin: string[] }) =>\n `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin\n .map(name => JSON.stringify(name))\n .join(\", \")}.`,\n MissingUnicodeEscape: \"Expecting Unicode escape sequence \\\\uXXXX.\",\n MixingCoalesceWithLogical:\n \"Nullish coalescing operator(??) requires parens when mixing with logical operators.\",\n ModuleAttributeDifferentFromType:\n \"The only accepted module attribute is `type`.\",\n ModuleAttributeInvalidValue:\n \"Only string literals are allowed as module attribute values.\",\n ModuleAttributesWithDuplicateKeys: ({ key }: { key: string }) =>\n `Duplicate key \"${key}\" is not allowed in module attributes.`,\n ModuleExportNameHasLoneSurrogate: ({\n surrogateCharCode,\n }: {\n surrogateCharCode: number;\n }) =>\n `An export name cannot include a lone surrogate, found '\\\\u${surrogateCharCode.toString(\n 16,\n )}'.`,\n ModuleExportUndefined: ({ localName }: { localName: string }) =>\n `Export '${localName}' is not defined.`,\n MultipleDefaultsInSwitch: \"Multiple default clauses.\",\n NewlineAfterThrow: \"Illegal newline after throw.\",\n NoCatchOrFinally: \"Missing catch or finally clause.\",\n NumberIdentifier: \"Identifier directly after number.\",\n NumericSeparatorInEscapeSequence:\n \"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.\",\n ObsoleteAwaitStar:\n \"'await*' has been removed from the async functions proposal. Use Promise.all() instead.\",\n OptionalChainingNoNew:\n \"Constructors in/after an Optional Chain are not allowed.\",\n OptionalChainingNoTemplate:\n \"Tagged Template Literals are not allowed in optionalChain.\",\n OverrideOnConstructor:\n \"'override' modifier cannot appear on a constructor declaration.\",\n ParamDupe: \"Argument name clash.\",\n PatternHasAccessor: \"Object pattern can't contain getter or setter.\",\n PatternHasMethod: \"Object pattern can't contain methods.\",\n PrivateInExpectedIn: ({ identifierName }: { identifierName: string }) =>\n `Private names are only allowed in property accesses (\\`obj.#${identifierName}\\`) or in \\`in\\` expressions (\\`#${identifierName} in obj\\`).`,\n PrivateNameRedeclaration: ({ identifierName }: { identifierName: string }) =>\n `Duplicate private name #${identifierName}.`,\n RecordExpressionBarIncorrectEndSyntaxType:\n \"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionBarIncorrectStartSyntaxType:\n \"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n RecordExpressionHashIncorrectStartSyntaxType:\n \"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n RecordNoProto: \"'__proto__' is not allowed in Record expressions.\",\n RestTrailingComma: \"Unexpected trailing comma after rest element.\",\n SloppyFunction:\n \"In non-strict mode code, functions can only be declared at top level or inside a block.\",\n SloppyFunctionAnnexB:\n \"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.\",\n SourcePhaseImportRequiresDefault:\n 'Only `import source x from \"./module\"` is valid.',\n StaticPrototype: \"Classes may not have static property named prototype.\",\n SuperNotAllowed:\n \"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?\",\n SuperPrivateField: \"Private fields can't be accessed on super.\",\n TrailingDecorator: \"Decorators must be attached to a class element.\",\n TupleExpressionBarIncorrectEndSyntaxType:\n \"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionBarIncorrectStartSyntaxType:\n \"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n TupleExpressionHashIncorrectStartSyntaxType:\n \"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n UnexpectedArgumentPlaceholder: \"Unexpected argument placeholder.\",\n UnexpectedAwaitAfterPipelineBody:\n 'Unexpected \"await\" after pipeline body; await must have parentheses in minimal proposal.',\n UnexpectedDigitAfterHash: \"Unexpected digit after hash token.\",\n UnexpectedImportExport:\n \"'import' and 'export' may only appear at the top level.\",\n UnexpectedKeyword: ({ keyword }: { keyword: string }) =>\n `Unexpected keyword '${keyword}'.`,\n UnexpectedLeadingDecorator:\n \"Leading decorators must be attached to a class declaration.\",\n UnexpectedLexicalDeclaration:\n \"Lexical declaration cannot appear in a single-statement context.\",\n UnexpectedNewTarget:\n \"`new.target` can only be used in functions or class properties.\",\n UnexpectedNumericSeparator:\n \"A numeric separator is only allowed between two digits.\",\n UnexpectedPrivateField: \"Unexpected private name.\",\n UnexpectedReservedWord: ({ reservedWord }: { reservedWord: string }) =>\n `Unexpected reserved word '${reservedWord}'.`,\n UnexpectedSuper: \"'super' is only allowed in object methods and classes.\",\n UnexpectedToken: ({\n expected,\n unexpected,\n }: {\n expected?: string | null;\n unexpected?: string | null;\n }) =>\n `Unexpected token${unexpected ? ` '${unexpected}'.` : \"\"}${\n expected ? `, expected \"${expected}\"` : \"\"\n }`,\n UnexpectedTokenUnaryExponentiation:\n \"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.\",\n UnexpectedUsingDeclaration:\n \"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.\",\n UnexpectedVoidPattern: \"Unexpected void binding.\",\n UnsupportedBind: \"Binding should be performed on object property.\",\n UnsupportedDecoratorExport:\n \"A decorated export must export a class declaration.\",\n UnsupportedDefaultExport:\n \"Only expressions, functions or classes are allowed as the `default` export.\",\n UnsupportedImport:\n \"`import` can only be used in `import()` or `import.meta`.\",\n UnsupportedMetaProperty: ({\n target,\n onlyValidPropertyName,\n }: {\n target: string;\n onlyValidPropertyName: string;\n }) =>\n `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,\n UnsupportedParameterDecorator:\n \"Decorators cannot be used to decorate parameters.\",\n UnsupportedPropertyDecorator:\n \"Decorators cannot be used to decorate object literal properties.\",\n UnsupportedSuper:\n \"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).\",\n UnterminatedComment: \"Unterminated comment.\",\n UnterminatedRegExp: \"Unterminated regular expression.\",\n UnterminatedString: \"Unterminated string constant.\",\n UnterminatedTemplate: \"Unterminated template.\",\n UsingDeclarationExport: \"Using declaration cannot be exported.\",\n UsingDeclarationHasBindingPattern:\n \"Using declaration cannot have destructuring patterns.\",\n VarRedeclaration: ({ identifierName }: { identifierName: string }) =>\n `Identifier '${identifierName}' has already been declared.`,\n VoidPatternCatchClauseParam:\n \"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.\",\n VoidPatternInitializer: \"A void binding may not have an initializer.\",\n YieldBindingIdentifier:\n \"Can not use 'yield' as identifier inside a generator.\",\n YieldInParameter: \"Yield expression is not allowed in formal parameters.\",\n YieldNotInGeneratorFunction:\n \"'yield' is only allowed within generator functions.\",\n ZeroDigitNumericSeparator:\n \"Numeric separator can not be used after leading 0.\",\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error\";\n\nexport default {\n StrictDelete: \"Deleting local variable in strict mode.\",\n\n // `referenceName` is the StringValue[1] of an IdentifierReference[2], which\n // is represented as just an `Identifier`[3] in the Babel AST.\n // 1. https://tc39.es/ecma262/#sec-static-semantics-stringvalue\n // 2. https://tc39.es/ecma262/#prod-IdentifierReference\n // 3. https://github.com/babel/babel/blob/main/packages/babel-parser/ast/spec.md#identifier\n StrictEvalArguments: ({ referenceName }: { referenceName: string }) =>\n `Assigning to '${referenceName}' in strict mode.`,\n\n // `bindingName` is the StringValue[1] of a BindingIdentifier[2], which is\n // represented as just an `Identifier`[3] in the Babel AST.\n // 1. https://tc39.es/ecma262/#sec-static-semantics-stringvalue\n // 2. https://tc39.es/ecma262/#prod-BindingIdentifier\n // 3. https://github.com/babel/babel/blob/main/packages/babel-parser/ast/spec.md#identifier\n StrictEvalArgumentsBinding: ({ bindingName }: { bindingName: string }) =>\n `Binding '${bindingName}' in strict mode.`,\n\n StrictFunction:\n \"In strict mode code, functions can only be declared at top level or inside a block.\",\n\n StrictNumericEscape: \"The only valid numeric escape in strict mode is '\\\\0'.\",\n\n StrictOctalLiteral: \"Legacy octal literals are not allowed in strict mode.\",\n\n StrictWith: \"'with' in strict mode.\",\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\n\nexport default {\n ParseExpressionEmptyInput:\n \"Unexpected parseExpression() input: The input is empty or contains only comments.\",\n ParseExpressionExpectsEOF: ({ unexpected }: { unexpected: number }) =>\n `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \\`${String.fromCodePoint(unexpected)}\\`.`,\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\nimport toNodeDescription from \"./to-node-description.ts\";\n\nexport const UnparenthesizedPipeBodyDescriptions = new Set([\n \"ArrowFunctionExpression\",\n \"AssignmentExpression\",\n \"ConditionalExpression\",\n \"YieldExpression\",\n] as const);\n\ntype GetSetMemberType> =\n T extends Set ? M : unknown;\n\nexport type UnparenthesizedPipeBodyTypes = GetSetMemberType<\n typeof UnparenthesizedPipeBodyDescriptions\n>;\n\nexport default {\n // This error is only used by the smart-mix proposal\n PipeBodyIsTighter:\n \"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.\",\n PipeTopicRequiresHackPipes: process.env.BABEL_8_BREAKING\n ? 'Topic references are only supported when using the `\"proposal\": \"hack\"` version of the pipeline proposal.'\n : 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n PipeTopicUnbound:\n \"Topic reference is unbound; it must be inside a pipe body.\",\n PipeTopicUnconfiguredToken: ({ token }: { token: string }) =>\n `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { \"proposal\": \"hack\", \"topicToken\": \"${token}\" }.`,\n PipeTopicUnused:\n \"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.\",\n PipeUnparenthesizedBody: ({ type }: { type: UnparenthesizedPipeBodyTypes }) =>\n `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({\n type,\n })}; please wrap it in parentheses.`,\n\n ...(process.env.BABEL_8_BREAKING\n ? {}\n : {\n // Messages whose codes start with “Pipeline” or “PrimaryTopic”\n // are retained for backwards compatibility\n // with the deprecated smart-mix pipe operator proposal plugin.\n // They are subject to removal in a future major version.\n PipelineBodyNoArrow:\n 'Unexpected arrow \"=>\" after pipeline body; arrow function in pipeline body must be parenthesized.',\n PipelineBodySequenceExpression:\n \"Pipeline body may not be a comma-separated sequence expression.\",\n PipelineHeadSequenceExpression:\n \"Pipeline head should not be a comma-separated sequence expression.\",\n PipelineTopicUnused:\n \"Pipeline is in topic style but does not use topic reference.\",\n PrimaryTopicNotAllowed:\n \"Topic reference was used in a lexical context without topic binding.\",\n PrimaryTopicRequiresSmartPipeline:\n 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n }),\n} satisfies ParseErrorTemplates;\n","import { Position } from \"./util/location.ts\";\n\ntype SyntaxPlugin =\n | \"flow\"\n | \"typescript\"\n | \"jsx\"\n | \"pipelineOperator\"\n | \"placeholders\";\n\ntype ParseErrorCode =\n | \"BABEL_PARSER_SYNTAX_ERROR\"\n | \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\";\n\n// Babel uses \"normal\" SyntaxErrors for it's errors, but adds some extra\n// functionality. This functionality is defined in the\n// `ParseErrorSpecification` interface below. We may choose to change to someday\n// give our errors their own full-blown class, but until then this allow us to\n// keep all the desirable properties of SyntaxErrors (like their name in stack\n// traces, etc.), and also allows us to punt on any publicly facing\n// class-hierarchy decisions until Babel 8.\ninterface ParseErrorSpecification {\n // Look, these *could* be readonly, but then Flow complains when we initially\n // set them. We could do a whole dance and make a special interface that's not\n // readonly for when we create the error, then cast it to the readonly\n // interface for public use, but the previous implementation didn't have them\n // as readonly, so let's just not worry about it for now.\n code: ParseErrorCode;\n reasonCode: string;\n syntaxPlugin?: SyntaxPlugin;\n missingPlugin?: string | string[];\n loc: Position;\n details: ErrorDetails;\n\n // We should consider removing this as it now just contains the same\n // information as `loc.index`.\n pos: number;\n}\n\nexport type ParseError = SyntaxError &\n ParseErrorSpecification;\n\n// By `ParseErrorConstructor`, we mean something like the new-less style\n// `ErrorConstructor`[1], since `ParseError`'s are not themselves actually\n// separate classes from `SyntaxError`'s.\n//\n// 1. https://github.com/microsoft/TypeScript/blob/v4.5.5/lib/lib.es5.d.ts#L1027\nexport type ParseErrorConstructor = (\n loc: Position,\n details: ErrorDetails,\n) => ParseError;\n\ntype ToMessage = (self: ErrorDetails) => string;\n\ntype ParseErrorCredentials = {\n code: string;\n reasonCode: string;\n syntaxPlugin?: SyntaxPlugin;\n toMessage: ToMessage;\n};\n\nfunction defineHidden(obj: object, key: string, value: unknown) {\n Object.defineProperty(obj, key, {\n enumerable: false,\n configurable: true,\n value,\n });\n}\n\nfunction toParseErrorConstructor({\n toMessage,\n code,\n reasonCode,\n syntaxPlugin,\n}: ParseErrorCredentials): ParseErrorConstructor {\n const hasMissingPlugin =\n reasonCode === \"MissingPlugin\" || reasonCode === \"MissingOneOfPlugins\";\n\n if (!process.env.BABEL_8_BREAKING) {\n const oldReasonCodes: Record = {\n AccessorCannotDeclareThisParameter: \"AccesorCannotDeclareThisParameter\",\n AccessorCannotHaveTypeParameters: \"AccesorCannotHaveTypeParameters\",\n ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:\n \"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference\",\n SetAccessorCannotHaveOptionalParameter:\n \"SetAccesorCannotHaveOptionalParameter\",\n SetAccessorCannotHaveRestParameter: \"SetAccesorCannotHaveRestParameter\",\n SetAccessorCannotHaveReturnType: \"SetAccesorCannotHaveReturnType\",\n };\n if (oldReasonCodes[reasonCode]) {\n reasonCode = oldReasonCodes[reasonCode];\n }\n }\n\n return function constructor(loc: Position, details: ErrorDetails) {\n const error: ParseError = new SyntaxError() as any;\n\n error.code = code as ParseErrorCode;\n error.reasonCode = reasonCode;\n error.loc = loc;\n error.pos = loc.index;\n\n error.syntaxPlugin = syntaxPlugin;\n if (hasMissingPlugin) {\n error.missingPlugin = (details as any).missingPlugin;\n }\n\n type Overrides = {\n loc?: Position;\n details?: ErrorDetails;\n };\n defineHidden(error, \"clone\", function clone(overrides: Overrides = {}) {\n const { line, column, index } = overrides.loc ?? loc;\n return constructor(new Position(line, column, index), {\n ...details,\n ...overrides.details,\n });\n });\n\n defineHidden(error, \"details\", details);\n\n Object.defineProperty(error, \"message\", {\n configurable: true,\n get(this: ParseError): string {\n const message = `${toMessage(details)} (${loc.line}:${loc.column})`;\n this.message = message;\n return message;\n },\n set(value: string) {\n Object.defineProperty(this, \"message\", { value, writable: true });\n },\n });\n\n return error;\n };\n}\n\ntype ParseErrorTemplate =\n | string\n | ToMessage\n | { message: string | ToMessage; code?: ParseErrorCode };\n\nexport type ParseErrorTemplates = Record;\n\n// This is the templated form of `ParseErrorEnum`.\n//\n// Note: We could factor out the return type calculation into something like\n// `ParseErrorConstructor`, and then we could\n// reuse it in the non-templated form of `ParseErrorEnum`, but TypeScript\n// doesn't seem to drill down that far when showing you the computed type of\n// an object in an editor, so we'll leave it inlined for now.\nexport function ParseErrorEnum(a: TemplateStringsArray): <\n T extends ParseErrorTemplates,\n>(\n parseErrorTemplates: T,\n) => {\n [K in keyof T]: ParseErrorConstructor<\n T[K] extends { message: string | ToMessage }\n ? T[K][\"message\"] extends ToMessage\n ? Parameters[0]\n : object\n : T[K] extends ToMessage\n ? Parameters[0]\n : object\n >;\n};\n\nexport function ParseErrorEnum(\n parseErrorTemplates: T,\n syntaxPlugin?: SyntaxPlugin,\n): {\n [K in keyof T]: ParseErrorConstructor<\n T[K] extends { message: string | ToMessage }\n ? T[K][\"message\"] extends ToMessage\n ? Parameters[0]\n : object\n : T[K] extends ToMessage\n ? Parameters[0]\n : object\n >;\n};\n\n// You call `ParseErrorEnum` with a mapping from `ReasonCode`'s to either:\n//\n// 1. a static error message,\n// 2. `toMessage` functions that define additional necessary `details` needed by\n// the `ParseError`, or\n// 3. Objects that contain a `message` of one of the above and overridden `code`\n// and/or `reasonCode`:\n//\n// ParseErrorEnum `optionalSyntaxPlugin` ({\n// ErrorWithStaticMessage: \"message\",\n// ErrorWithDynamicMessage: ({ type } : { type: string }) => `${type}`),\n// ErrorWithOverriddenCodeAndOrReasonCode: {\n// message: ({ type }: { type: string }) => `${type}`),\n// code: \"AN_ERROR_CODE\",\n// ...(BABEL_8_BREAKING ? { } : { reasonCode: \"CustomErrorReasonCode\" })\n// }\n// });\n//\nexport function ParseErrorEnum(\n argument: TemplateStringsArray | ParseErrorTemplates,\n syntaxPlugin?: SyntaxPlugin,\n) {\n // If the first parameter is an array, that means we were called with a tagged\n // template literal. Extract the syntaxPlugin from this, and call again in\n // the \"normalized\" form.\n if (Array.isArray(argument)) {\n return (parseErrorTemplates: ParseErrorTemplates) =>\n ParseErrorEnum(parseErrorTemplates, argument[0]);\n }\n\n const ParseErrorConstructors = {} as Record<\n string,\n ParseErrorConstructor\n >;\n\n for (const reasonCode of Object.keys(argument)) {\n const template = (argument as ParseErrorTemplates)[reasonCode];\n const { message, ...rest } =\n typeof template === \"string\"\n ? { message: () => template }\n : typeof template === \"function\"\n ? { message: template }\n : template;\n const toMessage = typeof message === \"string\" ? () => message : message;\n\n ParseErrorConstructors[reasonCode] = toParseErrorConstructor({\n code: \"BABEL_PARSER_SYNTAX_ERROR\",\n reasonCode,\n toMessage,\n ...(syntaxPlugin ? { syntaxPlugin } : {}),\n ...rest,\n });\n }\n\n return ParseErrorConstructors;\n}\n\nimport ModuleErrors from \"./parse-error/module-errors.ts\";\nimport StandardErrors from \"./parse-error/standard-errors.ts\";\nimport StrictModeErrors from \"./parse-error/strict-mode-errors.ts\";\nimport ParseExpressionErrors from \"./parse-error/parse-expression-errors.ts\";\nimport PipelineOperatorErrors from \"./parse-error/pipeline-operator-errors.ts\";\n\nexport const Errors = {\n ...ParseErrorEnum(ModuleErrors),\n ...ParseErrorEnum(StandardErrors),\n ...ParseErrorEnum(StrictModeErrors),\n ...ParseErrorEnum(ParseExpressionErrors),\n ...ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors),\n};\n\nexport type { LValAncestor } from \"./parse-error/standard-errors.ts\";\n","import type { Plugin } from \"./plugin-utils.ts\";\n\n// A second optional argument can be given to further configure\n// the parser process. These options are recognized:\n\nexport type SourceType = \"script\" | \"commonjs\" | \"module\" | \"unambiguous\";\n\nexport interface Options {\n /**\n * By default, import and export declarations can only appear at a program's top level.\n * Setting this option to true allows them anywhere where a statement is allowed.\n */\n allowImportExportEverywhere?: boolean;\n\n /**\n * By default, await use is not allowed outside of an async function.\n * Set this to true to accept such code.\n */\n allowAwaitOutsideFunction?: boolean;\n\n /**\n * By default, a return statement at the top level raises an error.\n * Set this to true to accept such code.\n */\n allowReturnOutsideFunction?: boolean;\n\n /**\n * By default, new.target use is not allowed outside of a function or class.\n * Set this to true to accept such code.\n */\n allowNewTargetOutsideFunction?: boolean;\n\n /**\n * By default, super calls are not allowed outside of a method.\n * Set this to true to accept such code.\n */\n allowSuperOutsideMethod?: boolean;\n\n /**\n * By default, exported identifiers must refer to a declared variable.\n * Set this to true to allow export statements to reference undeclared variables.\n */\n allowUndeclaredExports?: boolean;\n\n /**\n * By default, yield use is not allowed outside of a generator function.\n * Set this to true to accept such code.\n */\n\n allowYieldOutsideFunction?: boolean;\n\n /**\n * By default, Babel parser JavaScript code according to Annex B syntax.\n * Set this to `false` to disable such behavior.\n */\n annexB?: boolean;\n\n /**\n * By default, Babel attaches comments to adjacent AST nodes.\n * When this option is set to false, comments are not attached.\n * It can provide up to 30% performance improvement when the input code has many comments.\n * @babel/eslint-parser will set it for you.\n * It is not recommended to use attachComment: false with Babel transform,\n * as doing so removes all the comments in output code, and renders annotations such as\n * /* istanbul ignore next *\\/ nonfunctional.\n */\n attachComment?: boolean;\n\n /**\n * By default, Babel always throws an error when it finds some invalid code.\n * When this option is set to true, it will store the parsing error and\n * try to continue parsing the invalid input file.\n */\n errorRecovery?: boolean;\n\n /**\n * Indicate the mode the code should be parsed in.\n * Can be one of \"script\", \"commonjs\", \"module\", or \"unambiguous\". Defaults to \"script\".\n * \"unambiguous\" will make @babel/parser attempt to guess, based on the presence\n * of ES6 import or export statements.\n * Files with ES6 imports and exports are considered \"module\" and are otherwise \"script\".\n *\n * Use \"commonjs\" to parse code that is intended to be run in a CommonJS environment such as Node.js.\n */\n sourceType?: SourceType;\n\n /**\n * Correlate output AST nodes with their source filename.\n * Useful when generating code and source maps from the ASTs of multiple input files.\n */\n sourceFilename?: string;\n\n /**\n * By default, all source indexes start from 0.\n * You can provide a start index to alternatively start with.\n * Useful for integration with other source tools.\n */\n startIndex?: number;\n\n /**\n * By default, the first line of code parsed is treated as line 1.\n * You can provide a line number to alternatively start with.\n * Useful for integration with other source tools.\n */\n startLine?: number;\n\n /**\n * By default, the parsed code is treated as if it starts from line 1, column 0.\n * You can provide a column number to alternatively start with.\n * Useful for integration with other source tools.\n */\n startColumn?: number;\n\n /**\n * Array containing the plugins that you want to enable.\n */\n plugins?: Plugin[];\n\n /**\n * Should the parser work in strict mode.\n * Defaults to true if sourceType === 'module'. Otherwise, false.\n */\n strictMode?: boolean;\n\n /**\n * Adds a ranges property to each node: [node.start, node.end]\n */\n ranges?: boolean;\n\n /**\n * Adds all parsed tokens to a tokens property on the File node.\n */\n tokens?: boolean;\n\n /**\n * By default, the parser adds information about parentheses by setting\n * `extra.parenthesized` to `true` as needed.\n * When this option is `true` the parser creates `ParenthesizedExpression`\n * AST nodes instead of using the `extra` property.\n */\n createParenthesizedExpressions?: boolean;\n\n /**\n * The default is false in Babel 7 and true in Babel 8\n * Set this to true to parse it as an `ImportExpression` node.\n * Otherwise `import(foo)` is parsed as `CallExpression(Import, [Identifier(foo)])`.\n */\n createImportExpressions?: boolean;\n}\n\nexport const enum OptionFlags {\n AllowAwaitOutsideFunction = 1 << 0,\n AllowReturnOutsideFunction = 1 << 1,\n AllowNewTargetOutsideFunction = 1 << 2,\n AllowImportExportEverywhere = 1 << 3,\n AllowSuperOutsideMethod = 1 << 4,\n AllowYieldOutsideFunction = 1 << 5,\n AllowUndeclaredExports = 1 << 6,\n Ranges = 1 << 7,\n Tokens = 1 << 8,\n CreateImportExpressions = 1 << 9,\n CreateParenthesizedExpressions = 1 << 10,\n ErrorRecovery = 1 << 11,\n AttachComment = 1 << 12,\n AnnexB = 1 << 13,\n}\n\ntype KeepOptionalKeys = \"sourceFilename\" | \"strictMode\";\nexport type OptionsWithDefaults = Omit, KeepOptionalKeys> &\n Pick;\n\nfunction createDefaultOptions(): OptionsWithDefaults {\n return {\n // Source type (\"script\" or \"module\") for different semantics\n sourceType: \"script\",\n // Source filename.\n sourceFilename: undefined,\n // Index (0-based) from which to start counting source. Useful for\n // integration with other tools.\n startIndex: 0,\n // Column (0-based) from which to start counting source. Useful for\n // integration with other tools.\n startColumn: 0,\n // Line (1-based) from which to start counting source. Useful for\n // integration with other tools.\n startLine: 1,\n // When enabled, await at the top level is not considered an\n // error.\n allowAwaitOutsideFunction: false,\n // When enabled, a return at the top level is not considered an\n // error.\n allowReturnOutsideFunction: false,\n // When enabled, new.target outside a function or class is not\n // considered an error.\n allowNewTargetOutsideFunction: false,\n // When enabled, import/export statements are not constrained to\n // appearing at the top of the program.\n allowImportExportEverywhere: false,\n // When enabled, super outside a method is not considered an error.\n allowSuperOutsideMethod: false,\n // When enabled, export statements can reference undeclared variables.\n allowUndeclaredExports: false,\n allowYieldOutsideFunction: false,\n // An array of plugins to enable\n plugins: [],\n // TODO\n strictMode: undefined,\n // Nodes have their start and end characters offsets recorded in\n // `start` and `end` properties (directly on the node, rather than\n // the `loc` object, which holds line/column data. To also add a\n // [semi-standardized][range] `range` property holding a `[start,\n // end]` array with the same numbers, set the `ranges` option to\n // `true`.\n //\n // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678\n ranges: false,\n // Adds all parsed tokens to a `tokens` property on the `File` node\n tokens: false,\n // Whether to create ImportExpression AST nodes (if false\n // `import(foo)` will be parsed as CallExpression(Import, [Identifier(foo)])\n createImportExpressions: process.env.BABEL_8_BREAKING ? true : false,\n // Whether to create ParenthesizedExpression AST nodes (if false\n // the parser sets extra.parenthesized on the expression nodes instead).\n createParenthesizedExpressions: false,\n // When enabled, errors are attached to the AST instead of being directly thrown.\n // Some errors will still throw, because @babel/parser can't always recover.\n errorRecovery: false,\n // When enabled, comments will be attached to adjacent AST nodes as one of\n // `leadingComments`, `trailingComments` and `innerComments`. The comment attachment\n // is vital to preserve comments after transform. If you don't print AST back,\n // consider set this option to `false` for performance\n attachComment: true,\n // When enabled, the parser will support Annex B syntax.\n // https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers\n annexB: true,\n };\n}\n\n// Interpret and default an options object\n\nexport function getOptions(opts?: Options | null): OptionsWithDefaults {\n // https://github.com/babel/babel/pull/16918\n // `options` is accessed frequently, please make sure it is a fast object.\n // `%ToFastProperties` can make it a fast object, but the performance is the same as the slow object.\n const options: any = createDefaultOptions();\n\n if (opts == null) {\n return options;\n }\n if (opts.annexB != null && opts.annexB !== false) {\n throw new Error(\"The `annexB` option can only be set to `false`.\");\n }\n\n for (const key of Object.keys(options) as (keyof Options)[]) {\n if (opts[key] != null) options[key] = opts[key];\n }\n\n if (options.startLine === 1) {\n if (opts.startIndex == null && options.startColumn > 0) {\n options.startIndex = options.startColumn;\n } else if (opts.startColumn == null && options.startIndex > 0) {\n options.startColumn = options.startIndex;\n }\n } else if (opts.startColumn == null || opts.startIndex == null) {\n if (opts.startIndex != null || process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"With a `startLine > 1` you must also specify `startIndex` and `startColumn`.\",\n );\n }\n }\n\n if (options.sourceType === \"commonjs\") {\n if (opts.allowAwaitOutsideFunction != null) {\n throw new Error(\n \"The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.\",\n );\n }\n if (opts.allowReturnOutsideFunction != null) {\n throw new Error(\n \"`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.\",\n );\n }\n if (opts.allowNewTargetOutsideFunction != null) {\n throw new Error(\n \"`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.\",\n );\n }\n }\n\n return options;\n}\n","import type { TokenType } from \"../tokenizer/types.ts\";\nimport type Parser from \"../parser/index.ts\";\nimport type * as N from \"../types.ts\";\nimport type { Node as NodeType, NodeBase } from \"../types.ts\";\nimport type { Position } from \"../util/location.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport type { Undone } from \"../parser/node.ts\";\nimport type { BindingFlag } from \"../util/scopeflags.ts\";\nimport { OptionFlags } from \"../options.ts\";\nimport type { ExpressionErrors } from \"../parser/util.ts\";\nimport type { ParseResult, File } from \"../index.ts\";\n\nconst { defineProperty } = Object;\nconst toUnenumerable = (object: any, key: string) => {\n if (object) {\n defineProperty(object, key, { enumerable: false, value: object[key] });\n }\n};\n\nfunction toESTreeLocation(node: any) {\n toUnenumerable(node.loc.start, \"index\");\n toUnenumerable(node.loc.end, \"index\");\n\n return node;\n}\n\nexport default (superClass: typeof Parser) =>\n class ESTreeParserMixin extends superClass implements Parser {\n parse(): ParseResult {\n const file = toESTreeLocation(super.parse());\n\n if (this.optionFlags & OptionFlags.Tokens) {\n file.tokens = file.tokens.map(toESTreeLocation);\n }\n\n return file;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseRegExpLiteral({ pattern, flags }): N.EstreeRegExpLiteral {\n let regex: RegExp | null = null;\n try {\n regex = new RegExp(pattern, flags);\n } catch (_) {\n // In environments that don't support these flags value will\n // be null as the regex can't be represented natively.\n }\n const node = this.estreeParseLiteral(regex);\n node.regex = { pattern, flags };\n\n return node;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseBigIntLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/es2020.md#bigintliteral\n let bigInt: bigint | null;\n try {\n bigInt = BigInt(value);\n } catch {\n bigInt = null;\n }\n const node = this.estreeParseLiteral(bigInt);\n node.bigint = String(node.value || value);\n\n return node;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseDecimalLiteral(value: any): N.Node {\n // https://github.com/estree/estree/blob/master/experimental/decimal.md\n // todo: use BigDecimal when node supports it.\n const decimal: null = null;\n const node = this.estreeParseLiteral(decimal);\n node.decimal = String(node.value || value);\n\n return node;\n }\n\n estreeParseLiteral(value: any) {\n // @ts-expect-error ESTree plugin changes node types\n return this.parseLiteral(value, \"Literal\");\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseStringLiteral(value: any): N.Node {\n return this.estreeParseLiteral(value);\n }\n\n parseNumericLiteral(value: any): any {\n return this.estreeParseLiteral(value);\n }\n\n // @ts-expect-error ESTree plugin changes node types\n parseNullLiteral(): N.Node {\n return this.estreeParseLiteral(null);\n }\n\n parseBooleanLiteral(value: boolean): N.BooleanLiteral {\n // @ts-expect-error ESTree plugin changes node types\n return this.estreeParseLiteral(value);\n }\n\n // https://github.com/estree/estree/blob/master/es2020.md#chainexpression\n estreeParseChainExpression(\n node: N.Expression,\n endLoc: Position,\n ): N.EstreeChainExpression {\n const chain = this.startNodeAtNode(node);\n chain.expression = node;\n return this.finishNodeAt(chain, \"ChainExpression\", endLoc);\n }\n\n // Cast a Directive to an ExpressionStatement. Mutates the input Directive.\n directiveToStmt(directive: N.Directive): N.ExpressionStatement {\n const expression = directive.value as any as N.EstreeLiteral;\n // @ts-expect-error delete non-optional properties\n delete directive.value;\n\n this.castNodeTo(expression, \"Literal\");\n expression.raw = expression.extra!.raw;\n expression.value = expression.extra!.expressionValue;\n\n const stmt = this.castNodeTo(directive, \"ExpressionStatement\");\n stmt.expression = expression;\n stmt.directive = expression.extra!.rawValue;\n\n delete expression.extra;\n\n return stmt;\n }\n\n /**\n * The TS-ESLint always define optional AST properties, here we provide the\n * default value for such properties immediately after `finishNode` was invoked.\n * This hook will be implemented by the typescript plugin.\n *\n * Note: This hook should be manually invoked when we change the `type` of a given AST\n * node, to ensure that the optional properties are correctly filled.\n * @param node The AST node finished by finishNode\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n fillOptionalPropertiesForTSESLint(node: NodeType) {}\n\n cloneEstreeStringLiteral(node: N.EstreeLiteral): N.EstreeLiteral {\n const { start, end, loc, range, raw, value } = node;\n const cloned = Object.create(node.constructor.prototype);\n cloned.type = \"Literal\";\n cloned.start = start;\n cloned.end = end;\n cloned.loc = loc;\n cloned.range = range;\n cloned.raw = raw;\n cloned.value = value;\n return cloned;\n }\n\n // ==================================\n // Overrides\n // ==================================\n\n initFunction(node: N.BodilessFunctionOrMethodBase, isAsync: boolean): void {\n super.initFunction(node, isAsync);\n node.expression = false;\n }\n\n checkDeclaration(node: N.Pattern | N.ObjectProperty): void {\n if (node != null && this.isObjectProperty(node)) {\n // @ts-expect-error plugin typings\n this.checkDeclaration((node as unknown as N.EstreeProperty).value);\n } else {\n super.checkDeclaration(node);\n }\n }\n\n getObjectOrClassMethodParams(method: N.ObjectMethod | N.ClassMethod) {\n return (method as unknown as N.EstreeMethodDefinition).value.params;\n }\n\n isValidDirective(stmt: N.Statement): stmt is N.ExpressionStatement {\n return (\n stmt.type === \"ExpressionStatement\" &&\n stmt.expression.type === \"Literal\" &&\n typeof stmt.expression.value === \"string\" &&\n !stmt.expression.extra?.parenthesized\n );\n }\n\n parseBlockBody(\n node: N.BlockStatementLike,\n allowDirectives: boolean | undefined | null,\n topLevel: boolean,\n end: TokenType,\n afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n ): void {\n super.parseBlockBody(\n node,\n allowDirectives,\n topLevel,\n end,\n afterBlockParse,\n );\n\n const directiveStatements = node.directives.map(d =>\n this.directiveToStmt(d),\n );\n // @ts-expect-error estree plugin typings\n node.body = directiveStatements.concat(node.body);\n // @ts-expect-error delete non-optional properties\n delete node.directives;\n }\n\n parsePrivateName(): any {\n const node = super.parsePrivateName();\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return node;\n }\n }\n return this.convertPrivateNameToPrivateIdentifier(node);\n }\n\n convertPrivateNameToPrivateIdentifier(\n node: N.PrivateName,\n ): N.EstreePrivateIdentifier {\n const name = super.getPrivateNameSV(node);\n // @ts-expect-error delete non-optional properties\n delete node.id;\n // @ts-expect-error mutate AST types\n node.name = name;\n return this.castNodeTo(node, \"PrivateIdentifier\");\n }\n\n // @ts-expect-error ESTree plugin changes node types\n isPrivateName(node: N.Node): node is N.EstreePrivateIdentifier {\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.isPrivateName(node);\n }\n }\n return node.type === \"PrivateIdentifier\";\n }\n\n // @ts-expect-error ESTree plugin changes node types\n getPrivateNameSV(node: N.EstreePrivateIdentifier): string {\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return super.getPrivateNameSV(node as unknown as N.PrivateName);\n }\n }\n return node.name;\n }\n\n // @ts-expect-error plugin may override interfaces\n parseLiteral(value: any, type: T[\"type\"]): T {\n const node = super.parseLiteral(value, type);\n // @ts-expect-error mutating AST types\n node.raw = node.extra.raw;\n delete node.extra;\n\n return node;\n }\n\n parseFunctionBody(\n node: N.Function,\n allowExpression?: boolean | null,\n isMethod: boolean = false,\n ): void {\n super.parseFunctionBody(node, allowExpression, isMethod);\n node.expression = node.body.type !== \"BlockStatement\";\n }\n\n // @ts-expect-error plugin may override interfaces\n parseMethod<\n T extends N.ClassPrivateMethod | N.ObjectMethod | N.ClassMethod,\n >(\n node: Undone,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowDirectSuper: boolean,\n type: T[\"type\"],\n inClassScope: boolean = false,\n ):\n | N.EstreeProperty\n | N.EstreeMethodDefinition\n | N.EstreeTSAbstractMethodDefinition {\n let funcNode = this.startNode();\n funcNode.kind = node.kind; // provide kind, so super method correctly sets state\n funcNode = super.parseMethod(\n funcNode,\n isGenerator,\n isAsync,\n isConstructor,\n allowDirectSuper,\n type,\n inClassScope,\n );\n // @ts-expect-error delete non-optional properties\n delete funcNode.kind;\n const { typeParameters } = node;\n if (typeParameters) {\n delete node.typeParameters;\n funcNode.typeParameters = typeParameters;\n this.resetStartLocationFromNode(funcNode, typeParameters);\n }\n const valueNode = this.castNodeTo(\n funcNode as N.MethodLike,\n process.env.BABEL_8_BREAKING &&\n this.hasPlugin(\"typescript\") &&\n !funcNode.body\n ? \"TSEmptyBodyFunctionExpression\"\n : \"FunctionExpression\",\n );\n (\n node as unknown as Undone<\n | N.EstreeProperty\n | N.EstreeMethodDefinition\n | N.EstreeTSAbstractMethodDefinition\n >\n ).value = valueNode;\n if (type === \"ClassPrivateMethod\") {\n node.computed = false;\n }\n if (process.env.BABEL_8_BREAKING && this.hasPlugin(\"typescript\")) {\n // @ts-expect-error todo(flow->ts) property not defined for all types in union\n if (node.abstract) {\n // @ts-expect-error remove abstract from TSAbstractMethodDefinition\n delete node.abstract;\n return this.finishNode(\n // @ts-expect-error cast methods to estree types\n node as Undone,\n \"TSAbstractMethodDefinition\",\n );\n }\n }\n if (type === \"ObjectMethod\") {\n if ((node as any as N.ObjectMethod).kind === \"method\") {\n (node as any as N.EstreeProperty).kind = \"init\";\n }\n (node as any as N.EstreeProperty).shorthand = false;\n return this.finishNode(\n // @ts-expect-error cast methods to estree types\n node as Undone,\n \"Property\",\n );\n } else {\n return this.finishNode(\n // @ts-expect-error cast methods to estree types\n node as Undone,\n \"MethodDefinition\",\n );\n }\n }\n\n nameIsConstructor(key: N.Expression | N.PrivateName): boolean {\n if (key.type === \"Literal\") return key.value === \"constructor\";\n return super.nameIsConstructor(key);\n }\n\n parseClassProperty(...args: [N.ClassProperty]): any {\n const propertyNode = super.parseClassProperty(...args);\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return propertyNode as unknown as N.EstreePropertyDefinition;\n }\n }\n if (\n process.env.BABEL_8_BREAKING &&\n propertyNode.abstract &&\n this.hasPlugin(\"typescript\")\n ) {\n delete propertyNode.abstract;\n this.castNodeTo(propertyNode, \"TSAbstractPropertyDefinition\");\n } else {\n this.castNodeTo(propertyNode, \"PropertyDefinition\");\n }\n return propertyNode;\n }\n\n parseClassPrivateProperty(...args: [N.ClassPrivateProperty]): any {\n const propertyNode = super.parseClassPrivateProperty(...args);\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return propertyNode as unknown as N.EstreePropertyDefinition;\n }\n }\n if (\n process.env.BABEL_8_BREAKING &&\n propertyNode.abstract &&\n this.hasPlugin(\"typescript\")\n ) {\n this.castNodeTo(propertyNode, \"TSAbstractPropertyDefinition\");\n } else {\n this.castNodeTo(propertyNode, \"PropertyDefinition\");\n }\n propertyNode.computed = false;\n return propertyNode;\n }\n\n parseClassAccessorProperty(\n this: Parser,\n node: N.ClassAccessorProperty,\n ): any {\n const accessorPropertyNode = super.parseClassAccessorProperty(node);\n if (!process.env.BABEL_8_BREAKING) {\n if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n return accessorPropertyNode;\n }\n }\n if (accessorPropertyNode.abstract && this.hasPlugin(\"typescript\")) {\n delete accessorPropertyNode.abstract;\n this.castNodeTo(accessorPropertyNode, \"TSAbstractAccessorProperty\");\n } else {\n this.castNodeTo(accessorPropertyNode, \"AccessorProperty\");\n }\n return accessorPropertyNode;\n }\n\n parseObjectProperty(\n prop: N.ObjectProperty,\n startLoc: Position | undefined | null,\n isPattern: boolean,\n refExpressionErrors?: ExpressionErrors | null,\n ): N.ObjectProperty | undefined | null {\n const node: N.EstreeProperty = super.parseObjectProperty(\n prop,\n startLoc,\n isPattern,\n refExpressionErrors,\n ) as any;\n\n if (node) {\n node.kind = \"init\";\n this.castNodeTo(node, \"Property\");\n }\n\n return node as any;\n }\n\n finishObjectProperty(node: Undone): N.ObjectProperty {\n (node as unknown as Undone).kind = \"init\";\n return this.finishNode(\n node as unknown as Undone,\n \"Property\",\n ) as any;\n }\n\n isValidLVal(\n type: string,\n disallowCallExpression: boolean,\n isUnparenthesizedInAssign: boolean,\n binding: BindingFlag,\n ) {\n return type === \"Property\"\n ? \"value\"\n : super.isValidLVal(\n type,\n disallowCallExpression,\n isUnparenthesizedInAssign,\n binding,\n );\n }\n\n isAssignable(node: N.Node, isBinding?: boolean): boolean {\n if (node != null && this.isObjectProperty(node)) {\n return this.isAssignable(node.value, isBinding);\n }\n return super.isAssignable(node, isBinding);\n }\n\n toAssignable(node: N.Node, isLHS: boolean = false): void {\n if (node != null && this.isObjectProperty(node)) {\n const { key, value } = node;\n if (this.isPrivateName(key)) {\n this.classScope.usePrivateName(\n this.getPrivateNameSV(key),\n key.loc.start,\n );\n }\n this.toAssignable(value, isLHS);\n } else {\n super.toAssignable(node, isLHS);\n }\n }\n\n toAssignableObjectExpressionProp(\n prop: N.Node,\n isLast: boolean,\n isLHS: boolean,\n ) {\n if (\n prop.type === \"Property\" &&\n (prop.kind === \"get\" || prop.kind === \"set\")\n ) {\n this.raise(Errors.PatternHasAccessor, prop.key);\n } else if (prop.type === \"Property\" && prop.method) {\n this.raise(Errors.PatternHasMethod, prop.key);\n } else {\n super.toAssignableObjectExpressionProp(prop, isLast, isLHS);\n }\n }\n\n finishCallExpression(\n unfinished: Undone,\n optional: boolean,\n ): T {\n const node = super.finishCallExpression(unfinished, optional);\n\n if (node.callee.type === \"Import\") {\n this.castNodeTo(node, \"ImportExpression\");\n (node as N.Node as N.EstreeImportExpression).source = node\n .arguments[0] as N.Expression;\n (node as N.Node as N.EstreeImportExpression).options =\n (node.arguments[1] as N.Expression) ?? null;\n if (!process.env.BABEL_8_BREAKING) {\n // compatibility with previous ESTree AST\n (node as N.Node as N.EstreeImportExpression).attributes =\n (node.arguments[1] as N.Expression) ?? null;\n }\n // arguments isn't optional in the type definition\n // @ts-expect-error delete non-optional properties\n delete node.arguments;\n // callee isn't optional in the type definition\n // @ts-expect-error delete non-optional properties\n delete node.callee;\n } else if (node.type === \"OptionalCallExpression\") {\n this.castNodeTo(node, \"CallExpression\");\n } else {\n node.optional = false;\n }\n\n return node;\n }\n\n toReferencedArguments(\n node:\n | N.CallExpression\n | N.OptionalCallExpression\n | N.EstreeImportExpression,\n /* isParenthesizedExpr?: boolean, */\n ) {\n // ImportExpressions do not have an arguments array.\n if (node.type === \"ImportExpression\") {\n return;\n }\n\n super.toReferencedArguments(node);\n }\n\n parseExport(\n unfinished: Undone,\n decorators: N.Decorator[] | null,\n ) {\n const exportStartLoc = this.state.lastTokStartLoc!;\n const node = super.parseExport(unfinished, decorators);\n\n switch (node.type) {\n case \"ExportAllDeclaration\":\n // @ts-expect-error mutating AST types\n node.exported = null;\n break;\n\n case \"ExportNamedDeclaration\":\n if (\n node.specifiers.length === 1 &&\n node.specifiers[0].type === \"ExportNamespaceSpecifier\"\n ) {\n this.castNodeTo(node, \"ExportAllDeclaration\");\n // @ts-expect-error mutating AST types\n node.exported = node.specifiers[0].exported;\n // @ts-expect-error The ESTree AST shape differs from the Babel AST\n delete node.specifiers;\n }\n\n // fallthrough\n case \"ExportDefaultDeclaration\":\n {\n const { declaration } = node;\n if (\n declaration?.type === \"ClassDeclaration\" &&\n // @ts-expect-error comparing undefined and number\n declaration.decorators?.length > 0 &&\n // decorator comes before export\n declaration.start === node.start\n ) {\n this.resetStartLocation(\n node,\n // For compatibility with ESLint's keyword-spacing rule, which assumes that an\n // export declaration must start with export.\n // https://github.com/babel/babel/issues/15085\n // Here we reset export declaration's start to be the start of the export token\n exportStartLoc,\n );\n }\n }\n\n break;\n }\n\n return node;\n }\n\n stopParseSubscript(base: N.Expression, state: N.ParseSubscriptState) {\n const node = super.stopParseSubscript(base, state);\n if (state.optionalChainMember) {\n return this.estreeParseChainExpression(node, base.loc.end);\n }\n return node;\n }\n\n parseMember(\n base: N.Expression,\n startLoc: Position,\n state: N.ParseSubscriptState,\n computed: boolean,\n optional: boolean,\n ) {\n const node = super.parseMember(base, startLoc, state, computed, optional);\n if (node.type === \"OptionalMemberExpression\") {\n this.castNodeTo(node, \"MemberExpression\");\n } else {\n node.optional = false;\n }\n return node;\n }\n\n isOptionalMemberExpression(node: N.Node) {\n if (node.type === \"ChainExpression\") {\n return node.expression.type === \"MemberExpression\";\n }\n return super.isOptionalMemberExpression(node);\n }\n\n hasPropertyAsPrivateName(node: N.Node): boolean {\n if (node.type === \"ChainExpression\") {\n node = node.expression;\n }\n return super.hasPropertyAsPrivateName(node);\n }\n\n // @ts-expect-error ESTree plugin changes node types\n isObjectProperty(node: N.Node): node is N.EstreeProperty {\n return node.type === \"Property\" && node.kind === \"init\" && !node.method;\n }\n\n // @ts-expect-error ESTree plugin changes node types\n isObjectMethod(node: N.Node): node is N.EstreeProperty {\n return (\n node.type === \"Property\" &&\n (node.method || node.kind === \"get\" || node.kind === \"set\")\n );\n }\n\n /* ============================================================ *\n * parser/node.ts *\n * ============================================================ */\n\n castNodeTo(\n node: N.Node,\n type: T,\n ): Extract {\n const result = super.castNodeTo(node, type);\n this.fillOptionalPropertiesForTSESLint(result);\n return result;\n }\n\n cloneIdentifier(node: T): T {\n const cloned = super.cloneIdentifier(node);\n this.fillOptionalPropertiesForTSESLint(cloned);\n return cloned;\n }\n\n cloneStringLiteral<\n T extends N.EstreeLiteral | N.StringLiteral | N.Placeholder,\n >(node: T): T {\n if (node.type === \"Literal\") {\n return this.cloneEstreeStringLiteral(node) as T;\n }\n return super.cloneStringLiteral(node);\n }\n\n finishNodeAt(\n node: Undone,\n type: T[\"type\"],\n endLoc: Position,\n ): T {\n return toESTreeLocation(super.finishNodeAt(node, type, endLoc));\n }\n\n // Override for TS-ESLint that does not allow optional AST properties\n finishNode(node: Undone, type: T[\"type\"]): T {\n const result = super.finishNode(node, type);\n this.fillOptionalPropertiesForTSESLint(result);\n return result;\n }\n\n resetStartLocation(node: N.Node, startLoc: Position) {\n super.resetStartLocation(node, startLoc);\n toESTreeLocation(node);\n }\n\n resetEndLocation(\n node: NodeBase,\n endLoc: Position = this.state.lastTokEndLoc!,\n ): void {\n super.resetEndLocation(node, endLoc);\n toESTreeLocation(node);\n }\n };\n","// The token context is used in JSX plugin to track\n// jsx tag / jsx text / normal JavaScript expression\n\nexport class TokContext {\n constructor(token: string, preserveSpace?: boolean) {\n this.token = token;\n this.preserveSpace = !!preserveSpace;\n }\n\n token: string;\n preserveSpace: boolean;\n}\n\nconst types: Record = {\n brace: new TokContext(\"{\"), // normal JavaScript expression\n j_oTag: new TokContext(\"...\", true), // JSX expressions\n};\n\nif (!process.env.BABEL_8_BREAKING) {\n types.template = new TokContext(\"`\", true);\n}\n\nexport { types };\n","import { types as tc, type TokContext } from \"./context.ts\";\n// ## Token types\n\n// The assignment of fine-grained, information-carrying type objects\n// allows the tokenizer to store the information it has about a\n// token in a way that is very cheap for the parser to look up.\n\n// All token type variables start with an underscore, to make them\n// easy to recognize.\n\n// The `beforeExpr` property is used to disambiguate between 1) binary\n// expression (<) and JSX Tag start (); 2) object literal and JSX\n// texts. It is set on the `updateContext` function in the JSX plugin.\n\n// The `startsExpr` property is used to determine whether an expression\n// may be the “argument” subexpression of a `yield` expression or\n// `yield` statement. It is set on all token types that may be at the\n// start of a subexpression.\n\n// `isLoop` marks a keyword as starting a loop, which is important\n// to know when parsing a label, in order to allow or disallow\n// continue jumps to that label.\n\nconst beforeExpr = true;\nconst startsExpr = true;\nconst isLoop = true;\nconst isAssign = true;\nconst prefix = true;\nconst postfix = true;\n\ntype TokenOptions = {\n keyword?: string;\n beforeExpr?: boolean;\n startsExpr?: boolean;\n rightAssociative?: boolean;\n isLoop?: boolean;\n isAssign?: boolean;\n prefix?: boolean;\n postfix?: boolean;\n binop?: number | null;\n};\n\n// Internally the tokenizer stores token as a number\nexport type TokenType = number;\n\n// The `ExportedTokenType` is exported via `tokTypes` and accessible\n// when `tokens: true` is enabled. Unlike internal token type, it provides\n// metadata of the tokens.\nexport class ExportedTokenType {\n label: string;\n keyword: string | undefined | null;\n beforeExpr: boolean;\n startsExpr: boolean;\n rightAssociative: boolean;\n isLoop: boolean;\n isAssign: boolean;\n prefix: boolean;\n postfix: boolean;\n binop: number | undefined | null;\n // todo(Babel 8): remove updateContext from exposed token layout\n declare updateContext: ((context: TokContext[]) => void) | undefined | null;\n\n constructor(label: string, conf: TokenOptions = {}) {\n this.label = label;\n this.keyword = conf.keyword;\n this.beforeExpr = !!conf.beforeExpr;\n this.startsExpr = !!conf.startsExpr;\n this.rightAssociative = !!conf.rightAssociative;\n this.isLoop = !!conf.isLoop;\n this.isAssign = !!conf.isAssign;\n this.prefix = !!conf.prefix;\n this.postfix = !!conf.postfix;\n this.binop = conf.binop != null ? conf.binop : null;\n if (!process.env.BABEL_8_BREAKING) {\n this.updateContext = null;\n }\n }\n}\n\n// A map from keyword/keyword-like string value to the token type\nexport const keywords = new Map();\n\nfunction createKeyword(name: string, options: TokenOptions = {}): TokenType {\n options.keyword = name;\n const token = createToken(name, options);\n keywords.set(name, token);\n return token;\n}\n\nfunction createBinop(name: string, binop: number) {\n return createToken(name, { beforeExpr, binop });\n}\n\nlet tokenTypeCounter = -1;\nexport const tokenTypes: ExportedTokenType[] = [];\nconst tokenLabels: string[] = [];\nconst tokenBinops: number[] = [];\nconst tokenBeforeExprs: boolean[] = [];\nconst tokenStartsExprs: boolean[] = [];\nconst tokenPrefixes: boolean[] = [];\n\nfunction createToken(name: string, options: TokenOptions = {}): TokenType {\n ++tokenTypeCounter;\n tokenLabels.push(name);\n tokenBinops.push(options.binop ?? -1);\n tokenBeforeExprs.push(options.beforeExpr ?? false);\n tokenStartsExprs.push(options.startsExpr ?? false);\n tokenPrefixes.push(options.prefix ?? false);\n tokenTypes.push(new ExportedTokenType(name, options));\n\n return tokenTypeCounter;\n}\n\nfunction createKeywordLike(\n name: string,\n options: TokenOptions = {},\n): TokenType {\n ++tokenTypeCounter;\n keywords.set(name, tokenTypeCounter);\n tokenLabels.push(name);\n tokenBinops.push(options.binop ?? -1);\n tokenBeforeExprs.push(options.beforeExpr ?? false);\n tokenStartsExprs.push(options.startsExpr ?? false);\n tokenPrefixes.push(options.prefix ?? false);\n // In the exported token type, we set the label as \"name\" for backward compatibility with Babel 7\n tokenTypes.push(new ExportedTokenType(\"name\", options));\n\n return tokenTypeCounter;\n}\n\n// For performance the token type helpers depend on the following declarations order.\n// When adding new token types, please also check if the token helpers need update.\n\nexport type InternalTokenTypes = typeof tt;\n\nexport const tt = {\n // Punctuation token types.\n bracketL: createToken(\"[\", { beforeExpr, startsExpr }),\n // TODO: Remove this in Babel 8\n bracketHashL: createToken(\"#[\", { beforeExpr, startsExpr }),\n // TODO: Remove this in Babel 8\n bracketBarL: createToken(\"[|\", { beforeExpr, startsExpr }),\n bracketR: createToken(\"]\"),\n // TODO: Remove this in Babel 8\n bracketBarR: createToken(\"|]\"),\n braceL: createToken(\"{\", { beforeExpr, startsExpr }),\n // TODO: Remove this in Babel 8\n braceBarL: createToken(\"{|\", { beforeExpr, startsExpr }),\n // TODO: Remove this in Babel 8\n braceHashL: createToken(\"#{\", { beforeExpr, startsExpr }),\n braceR: createToken(\"}\"),\n braceBarR: createToken(\"|}\"),\n parenL: createToken(\"(\", { beforeExpr, startsExpr }),\n parenR: createToken(\")\"),\n comma: createToken(\",\", { beforeExpr }),\n semi: createToken(\";\", { beforeExpr }),\n colon: createToken(\":\", { beforeExpr }),\n doubleColon: createToken(\"::\", { beforeExpr }),\n dot: createToken(\".\"),\n question: createToken(\"?\", { beforeExpr }),\n questionDot: createToken(\"?.\"),\n arrow: createToken(\"=>\", { beforeExpr }),\n template: createToken(\"template\"),\n ellipsis: createToken(\"...\", { beforeExpr }),\n backQuote: createToken(\"`\", { startsExpr }),\n dollarBraceL: createToken(\"${\", { beforeExpr, startsExpr }),\n // start: isTemplate\n templateTail: createToken(\"...`\", { startsExpr }),\n templateNonTail: createToken(\"...${\", { beforeExpr, startsExpr }),\n // end: isTemplate\n at: createToken(\"@\"),\n hash: createToken(\"#\", { startsExpr }),\n\n // Special hashbang token.\n interpreterDirective: createToken(\"#!...\"),\n\n // Operators. These carry several kinds of properties to help the\n // parser use them properly (the presence of these properties is\n // what categorizes them as operators).\n //\n // `binop`, when present, specifies that this operator is a binary\n // operator, and will refer to its precedence.\n //\n // `prefix` and `postfix` mark the operator as a prefix or postfix\n // unary operator.\n //\n // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as\n // binary operators with a very low precedence, that should result\n // in AssignmentExpression nodes.\n\n // start: isAssign\n eq: createToken(\"=\", { beforeExpr, isAssign }),\n assign: createToken(\"_=\", { beforeExpr, isAssign }),\n slashAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n // These are only needed to support % and ^ as a Hack-pipe topic token.\n // When the proposal settles on a token, the others can be merged with\n // tt.assign.\n xorAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n moduloAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n // end: isAssign\n\n incDec: createToken(\"++/--\", { prefix, postfix, startsExpr }),\n bang: createToken(\"!\", { beforeExpr, prefix, startsExpr }),\n tilde: createToken(\"~\", { beforeExpr, prefix, startsExpr }),\n\n // More possible topic tokens.\n // When the proposal settles on a token, at least one of these may be removed.\n doubleCaret: createToken(\"^^\", { startsExpr }),\n doubleAt: createToken(\"@@\", { startsExpr }),\n\n // start: isBinop\n pipeline: createBinop(\"|>\", 0),\n nullishCoalescing: createBinop(\"??\", 1),\n logicalOR: createBinop(\"||\", 1),\n logicalAND: createBinop(\"&&\", 2),\n bitwiseOR: createBinop(\"|\", 3),\n bitwiseXOR: createBinop(\"^\", 4),\n bitwiseAND: createBinop(\"&\", 5),\n equality: createBinop(\"==/!=/===/!==\", 6),\n lt: createBinop(\"/<=/>=\", 7),\n gt: createBinop(\"/<=/>=\", 7),\n relational: createBinop(\"/<=/>=\", 7),\n bitShift: createBinop(\"<>/>>>\", 8),\n bitShiftL: createBinop(\"<>/>>>\", 8),\n bitShiftR: createBinop(\"<>/>>>\", 8),\n plusMin: createToken(\"+/-\", { beforeExpr, binop: 9, prefix, startsExpr }),\n // startsExpr: required by v8intrinsic plugin\n modulo: createToken(\"%\", { binop: 10, startsExpr }),\n // unset `beforeExpr` as it can be `function *`\n star: createToken(\"*\", { binop: 10 }),\n slash: createBinop(\"/\", 10),\n exponent: createToken(\"**\", {\n beforeExpr,\n binop: 11,\n rightAssociative: true,\n }),\n\n // Keywords\n // Don't forget to update packages/babel-helper-validator-identifier/src/keyword.js\n // when new keywords are added\n // start: isLiteralPropertyName\n // start: isKeyword\n _in: createKeyword(\"in\", { beforeExpr, binop: 7 }),\n _instanceof: createKeyword(\"instanceof\", { beforeExpr, binop: 7 }),\n // end: isBinop\n _break: createKeyword(\"break\"),\n _case: createKeyword(\"case\", { beforeExpr }),\n _catch: createKeyword(\"catch\"),\n _continue: createKeyword(\"continue\"),\n _debugger: createKeyword(\"debugger\"),\n _default: createKeyword(\"default\", { beforeExpr }),\n _else: createKeyword(\"else\", { beforeExpr }),\n _finally: createKeyword(\"finally\"),\n _function: createKeyword(\"function\", { startsExpr }),\n _if: createKeyword(\"if\"),\n _return: createKeyword(\"return\", { beforeExpr }),\n _switch: createKeyword(\"switch\"),\n _throw: createKeyword(\"throw\", { beforeExpr, prefix, startsExpr }),\n _try: createKeyword(\"try\"),\n _var: createKeyword(\"var\"),\n _const: createKeyword(\"const\"),\n _with: createKeyword(\"with\"),\n _new: createKeyword(\"new\", { beforeExpr, startsExpr }),\n _this: createKeyword(\"this\", { startsExpr }),\n _super: createKeyword(\"super\", { startsExpr }),\n _class: createKeyword(\"class\", { startsExpr }),\n _extends: createKeyword(\"extends\", { beforeExpr }),\n _export: createKeyword(\"export\"),\n _import: createKeyword(\"import\", { startsExpr }),\n _null: createKeyword(\"null\", { startsExpr }),\n _true: createKeyword(\"true\", { startsExpr }),\n _false: createKeyword(\"false\", { startsExpr }),\n _typeof: createKeyword(\"typeof\", { beforeExpr, prefix, startsExpr }),\n _void: createKeyword(\"void\", { beforeExpr, prefix, startsExpr }),\n _delete: createKeyword(\"delete\", { beforeExpr, prefix, startsExpr }),\n // start: isLoop\n _do: createKeyword(\"do\", { isLoop, beforeExpr }),\n _for: createKeyword(\"for\", { isLoop }),\n _while: createKeyword(\"while\", { isLoop }),\n // end: isLoop\n // end: isKeyword\n\n // Primary literals\n // start: isIdentifier\n _as: createKeywordLike(\"as\", { startsExpr }),\n _assert: createKeywordLike(\"assert\", { startsExpr }),\n _async: createKeywordLike(\"async\", { startsExpr }),\n _await: createKeywordLike(\"await\", { startsExpr }),\n _defer: createKeywordLike(\"defer\", { startsExpr }),\n _from: createKeywordLike(\"from\", { startsExpr }),\n _get: createKeywordLike(\"get\", { startsExpr }),\n _let: createKeywordLike(\"let\", { startsExpr }),\n _meta: createKeywordLike(\"meta\", { startsExpr }),\n _of: createKeywordLike(\"of\", { startsExpr }),\n _sent: createKeywordLike(\"sent\", { startsExpr }),\n _set: createKeywordLike(\"set\", { startsExpr }),\n _source: createKeywordLike(\"source\", { startsExpr }),\n _static: createKeywordLike(\"static\", { startsExpr }),\n _using: createKeywordLike(\"using\", { startsExpr }),\n _yield: createKeywordLike(\"yield\", { startsExpr }),\n\n // Flow and TypeScript Keywordlike\n _asserts: createKeywordLike(\"asserts\", { startsExpr }),\n _checks: createKeywordLike(\"checks\", { startsExpr }),\n _exports: createKeywordLike(\"exports\", { startsExpr }),\n _global: createKeywordLike(\"global\", { startsExpr }),\n _implements: createKeywordLike(\"implements\", { startsExpr }),\n _intrinsic: createKeywordLike(\"intrinsic\", { startsExpr }),\n _infer: createKeywordLike(\"infer\", { startsExpr }),\n _is: createKeywordLike(\"is\", { startsExpr }),\n _mixins: createKeywordLike(\"mixins\", { startsExpr }),\n _proto: createKeywordLike(\"proto\", { startsExpr }),\n _require: createKeywordLike(\"require\", { startsExpr }),\n _satisfies: createKeywordLike(\"satisfies\", { startsExpr }),\n // start: isTSTypeOperator\n _keyof: createKeywordLike(\"keyof\", { startsExpr }),\n _readonly: createKeywordLike(\"readonly\", { startsExpr }),\n _unique: createKeywordLike(\"unique\", { startsExpr }),\n // end: isTSTypeOperator\n // start: isTSDeclarationStart\n _abstract: createKeywordLike(\"abstract\", { startsExpr }),\n _declare: createKeywordLike(\"declare\", { startsExpr }),\n _enum: createKeywordLike(\"enum\", { startsExpr }),\n _module: createKeywordLike(\"module\", { startsExpr }),\n _namespace: createKeywordLike(\"namespace\", { startsExpr }),\n // start: isFlowInterfaceOrTypeOrOpaque\n _interface: createKeywordLike(\"interface\", { startsExpr }),\n _type: createKeywordLike(\"type\", { startsExpr }),\n // end: isTSDeclarationStart\n _opaque: createKeywordLike(\"opaque\", { startsExpr }),\n // end: isFlowInterfaceOrTypeOrOpaque\n name: createToken(\"name\", { startsExpr }),\n\n // placeholder plugin\n placeholder: createToken(\"%%\", { startsExpr }),\n // end: isIdentifier\n\n string: createToken(\"string\", { startsExpr }),\n num: createToken(\"num\", { startsExpr }),\n bigint: createToken(\"bigint\", { startsExpr }),\n // TODO: Remove this in Babel 8\n decimal: createToken(\"decimal\", { startsExpr }),\n // end: isLiteralPropertyName\n regexp: createToken(\"regexp\", { startsExpr }),\n privateName: createToken(\"#name\", { startsExpr }),\n eof: createToken(\"eof\"),\n\n // jsx plugin\n jsxName: createToken(\"jsxName\"),\n jsxText: createToken(\"jsxText\", { beforeExpr }),\n jsxTagStart: createToken(\"jsxTagStart\", { startsExpr }),\n jsxTagEnd: createToken(\"jsxTagEnd\"),\n} as const;\n\nexport function tokenIsIdentifier(token: TokenType): boolean {\n return token >= tt._as && token <= tt.placeholder;\n}\n\nexport function tokenKeywordOrIdentifierIsKeyword(token: TokenType): boolean {\n // we can remove the token >= tt._in check when we\n // know a token is either keyword or identifier\n return token <= tt._while;\n}\n\nexport function tokenIsKeywordOrIdentifier(token: TokenType): boolean {\n return token >= tt._in && token <= tt.placeholder;\n}\n\nexport function tokenIsLiteralPropertyName(token: TokenType): boolean {\n return token >= tt._in && token <= tt.decimal;\n}\n\nexport function tokenComesBeforeExpression(token: TokenType): boolean {\n return tokenBeforeExprs[token];\n}\n\nexport function tokenCanStartExpression(token: TokenType): boolean {\n return tokenStartsExprs[token];\n}\n\nexport function tokenIsAssignment(token: TokenType): boolean {\n return token >= tt.eq && token <= tt.moduloAssign;\n}\n\nexport function tokenIsFlowInterfaceOrTypeOrOpaque(token: TokenType): boolean {\n return token >= tt._interface && token <= tt._opaque;\n}\n\nexport function tokenIsLoop(token: TokenType): boolean {\n return token >= tt._do && token <= tt._while;\n}\n\nexport function tokenIsKeyword(token: TokenType): boolean {\n return token >= tt._in && token <= tt._while;\n}\n\nexport function tokenIsOperator(token: TokenType): boolean {\n return token >= tt.pipeline && token <= tt._instanceof;\n}\n\nexport function tokenIsPostfix(token: TokenType): boolean {\n return token === tt.incDec;\n}\n\nexport function tokenIsPrefix(token: TokenType): boolean {\n return tokenPrefixes[token];\n}\n\nexport function tokenIsTSTypeOperator(token: TokenType): boolean {\n return token >= tt._keyof && token <= tt._unique;\n}\n\nexport function tokenIsTSDeclarationStart(token: TokenType): boolean {\n return token >= tt._abstract && token <= tt._type;\n}\n\nexport function tokenLabelName(token: TokenType): string {\n return tokenLabels[token];\n}\n\nexport function tokenOperatorPrecedence(token: TokenType): number {\n return tokenBinops[token];\n}\n\nexport function tokenIsBinaryOperator(token: TokenType): boolean {\n return tokenBinops[token] !== -1;\n}\n\nexport function tokenIsRightAssociative(token: TokenType): boolean {\n return token === tt.exponent;\n}\n\nexport function tokenIsTemplate(token: TokenType): boolean {\n return token >= tt.templateTail && token <= tt.templateNonTail;\n}\n\nexport function getExportedToken(token: TokenType): ExportedTokenType {\n return tokenTypes[token];\n}\n\nexport function isTokenType(obj: any): boolean {\n return typeof obj === \"number\";\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n tokenTypes[tt.braceR].updateContext = context => {\n context.pop();\n };\n\n tokenTypes[tt.braceL].updateContext =\n tokenTypes[tt.braceHashL].updateContext =\n tokenTypes[tt.dollarBraceL].updateContext =\n context => {\n context.push(tc.brace);\n };\n\n tokenTypes[tt.backQuote].updateContext = context => {\n if (context[context.length - 1] === tc.template) {\n context.pop();\n } else {\n context.push(tc.template);\n }\n };\n\n tokenTypes[tt.jsxTagStart].updateContext = context => {\n context.push(tc.j_expr, tc.j_oTag);\n };\n}\n","// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.cjs`.\n\n/* prettier-ignore */\nlet nonASCIIidentifierStartChars = \"\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u0870-\\u0887\\u0889-\\u088f\\u08a0-\\u08c9\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c5c\\u0c5d\\u0c60\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cdc-\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d04-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e86-\\u0e8a\\u0e8c-\\u0ea3\\u0ea5\\u0ea7-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u1711\\u171f-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4c\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c8a\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7dc\\ua7f1-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\";\n/* prettier-ignore */\nlet nonASCIIidentifierChars = \"\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u0897-\\u089f\\u08ca-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3c\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0cf3\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ece\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u180f-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf-\\u1add\\u1ae0-\\u1aeb\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1dff\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\u30fb\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\\uff65\";\n\nconst nonASCIIidentifierStart = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.cjs`.\n/* prettier-ignore */\nconst astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489];\n/* prettier-ignore */\nconst astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n let pos = 0x10000;\n for (let i = 0, length = set.length; i < length; i += 2) {\n pos += set[i];\n if (pos > code) return false;\n\n pos += set[i + 1];\n if (pos >= code) return true;\n }\n return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return (\n code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n );\n }\n return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n if (code < charCodes.digit0) return code === charCodes.dollarSign;\n if (code < charCodes.colon) return true;\n if (code < charCodes.uppercaseA) return false;\n if (code <= charCodes.uppercaseZ) return true;\n if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n if (code <= charCodes.lowercaseZ) return true;\n if (code <= 0xffff) {\n return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n }\n return (\n isInAstralSet(code, astralIdentifierStartCodes) ||\n isInAstralSet(code, astralIdentifierCodes)\n );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n let isFirst = true;\n for (let i = 0; i < name.length; i++) {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = name.charCodeAt(i);\n if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n const trail = name.charCodeAt(++i);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n if (isFirst) {\n isFirst = false;\n if (!isIdentifierStart(cp)) {\n return false;\n }\n } else if (!isIdentifierChar(cp)) {\n return false;\n }\n }\n return !isFirst;\n}\n","const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n","import * as charCodes from \"charcodes\";\nimport { isIdentifierStart } from \"@babel/helper-validator-identifier\";\n\nexport {\n isIdentifierStart,\n isIdentifierChar,\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"@babel/helper-validator-identifier\";\n\nexport const keywordRelationalOperator = /^in(stanceof)?$/;\n\n// Test whether a current state character code and next character code is @\n\nexport function isIteratorStart(\n current: number,\n next: number,\n next2: number,\n): boolean {\n return (\n current === charCodes.atSign &&\n next === charCodes.atSign &&\n isIdentifierStart(next2)\n );\n}\n\n// This is the comprehensive set of JavaScript reserved words\n// If a word is in this set, it could be a reserved word,\n// depending on sourceType/strictMode/binding info. In other words\n// if a word is not in this set, it is not a reserved word under\n// any circumstance.\nconst reservedWordLikeSet = new Set([\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n // strict\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n // strictBind\n \"eval\",\n \"arguments\",\n // reservedWorkLike\n \"enum\",\n \"await\",\n]);\n\nexport function canBeReservedWord(word: string): boolean {\n return reservedWordLikeSet.has(word);\n}\n","import { ScopeFlag, BindingFlag } from \"./scopeflags.ts\";\nimport type { Position } from \"./location.ts\";\nimport type * as N from \"../types.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport type Tokenizer from \"../tokenizer/index.ts\";\n\nexport const enum NameType {\n // var-declared names in the current lexical scope\n Var = 1 << 0,\n // lexically-declared names in the current lexical scope\n Lexical = 1 << 1,\n // lexically-declared FunctionDeclaration names in the current lexical scope\n Function = 1 << 2,\n}\n\n// Start an AST node, attaching a start offset.\nexport class Scope {\n flags: ScopeFlag = 0;\n names = new Map();\n firstLexicalName = \"\";\n\n constructor(flags: ScopeFlag) {\n this.flags = flags;\n }\n}\n\n// The functions in this module keep track of declared variables in the\n// current scope in order to detect duplicate variable names.\nexport default class ScopeHandler {\n parser: Tokenizer;\n scopeStack: IScope[] = [];\n inModule: boolean;\n undefinedExports = new Map();\n\n constructor(parser: Tokenizer, inModule: boolean) {\n this.parser = parser;\n this.inModule = inModule;\n }\n\n get inTopLevel() {\n return (this.currentScope().flags & ScopeFlag.PROGRAM) > 0;\n }\n get inFunction() {\n return (this.currentVarScopeFlags() & ScopeFlag.FUNCTION_BASE) > 0;\n }\n get allowSuper() {\n return (this.currentThisScopeFlags() & ScopeFlag.SUPER) > 0;\n }\n get allowDirectSuper() {\n return (this.currentThisScopeFlags() & ScopeFlag.DIRECT_SUPER) > 0;\n }\n get allowNewTarget() {\n return (this.currentThisScopeFlags() & ScopeFlag.NEW_TARGET) > 0;\n }\n get inClass() {\n return (this.currentThisScopeFlags() & ScopeFlag.CLASS_BASE) > 0;\n }\n get inClassAndNotInNonArrowFunction() {\n const flags = this.currentThisScopeFlags();\n return (\n (flags & ScopeFlag.CLASS_BASE) > 0 &&\n (flags & ScopeFlag.FUNCTION_BASE) === 0\n );\n }\n get inStaticBlock() {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & ScopeFlag.STATIC_BLOCK) {\n return true;\n }\n if (flags & (ScopeFlag.VAR | ScopeFlag.CLASS_BASE)) {\n // function body, module body, class property initializers\n return false;\n }\n }\n }\n get inNonArrowFunction() {\n return (this.currentThisScopeFlags() & ScopeFlag.FUNCTION_BASE) > 0;\n }\n get inBareCaseStatement() {\n return (this.currentScope().flags & ScopeFlag.SWITCH) > 0;\n }\n get treatFunctionsAsVar() {\n return this.treatFunctionsAsVarInScope(this.currentScope());\n }\n\n createScope(flags: ScopeFlag): Scope {\n return new Scope(flags);\n }\n\n enter(flags: ScopeFlag) {\n /*:: +createScope: (flags:ScopeFlag) => IScope; */\n // @ts-expect-error This method will be overwritten by subclasses\n this.scopeStack.push(this.createScope(flags));\n }\n\n exit(): ScopeFlag {\n const scope = this.scopeStack.pop()!;\n return scope.flags;\n }\n\n // The spec says:\n // > At the top level of a function, or script, function declarations are\n // > treated like var declarations rather than like lexical declarations.\n treatFunctionsAsVarInScope(scope: IScope): boolean {\n return !!(\n scope.flags & (ScopeFlag.FUNCTION_BASE | ScopeFlag.STATIC_BLOCK) ||\n (!this.parser.inModule && scope.flags & ScopeFlag.PROGRAM)\n );\n }\n\n declareName(name: string, bindingType: BindingFlag, loc: Position) {\n let scope = this.currentScope();\n if (\n bindingType & BindingFlag.SCOPE_LEXICAL ||\n bindingType & BindingFlag.SCOPE_FUNCTION\n ) {\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n\n let type = scope.names.get(name) || 0;\n\n if (bindingType & BindingFlag.SCOPE_FUNCTION) {\n type = type | NameType.Function;\n } else {\n if (!scope.firstLexicalName) {\n scope.firstLexicalName = name;\n }\n type = type | NameType.Lexical;\n }\n\n scope.names.set(name, type);\n\n if (bindingType & BindingFlag.SCOPE_LEXICAL) {\n this.maybeExportDefined(scope, name);\n }\n } else if (bindingType & BindingFlag.SCOPE_VAR) {\n for (let i = this.scopeStack.length - 1; i >= 0; --i) {\n scope = this.scopeStack[i];\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n scope.names.set(name, (scope.names.get(name) || 0) | NameType.Var);\n this.maybeExportDefined(scope, name);\n\n if (scope.flags & ScopeFlag.VAR) break;\n }\n }\n if (this.parser.inModule && scope.flags & ScopeFlag.PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n maybeExportDefined(scope: IScope, name: string) {\n if (this.parser.inModule && scope.flags & ScopeFlag.PROGRAM) {\n this.undefinedExports.delete(name);\n }\n }\n\n checkRedeclarationInScope(\n scope: IScope,\n name: string,\n bindingType: BindingFlag,\n loc: Position,\n ) {\n if (this.isRedeclaredInScope(scope, name, bindingType)) {\n this.parser.raise(Errors.VarRedeclaration, loc, {\n identifierName: name,\n });\n }\n }\n\n isRedeclaredInScope(\n scope: IScope,\n name: string,\n bindingType: BindingFlag,\n ): boolean {\n if (!(bindingType & BindingFlag.KIND_VALUE)) return false;\n\n if (bindingType & BindingFlag.SCOPE_LEXICAL) {\n return scope.names.has(name);\n }\n\n const type = scope.names.get(name) || 0;\n\n if (bindingType & BindingFlag.SCOPE_FUNCTION) {\n return (\n (type & NameType.Lexical) > 0 ||\n (!this.treatFunctionsAsVarInScope(scope) && (type & NameType.Var) > 0)\n );\n }\n\n return (\n ((type & NameType.Lexical) > 0 &&\n // Annex B.3.4\n // https://tc39.es/ecma262/#sec-variablestatements-in-catch-blocks\n !(\n scope.flags & ScopeFlag.SIMPLE_CATCH &&\n scope.firstLexicalName === name\n )) ||\n (!this.treatFunctionsAsVarInScope(scope) &&\n (type & NameType.Function) > 0)\n );\n }\n\n checkLocalExport(id: N.Identifier) {\n const { name } = id;\n const topLevelScope = this.scopeStack[0];\n if (!topLevelScope.names.has(name)) {\n this.undefinedExports.set(name, id.loc.start);\n }\n }\n\n currentScope(): IScope {\n return this.scopeStack[this.scopeStack.length - 1];\n }\n\n currentVarScopeFlags(): ScopeFlag {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (flags & ScopeFlag.VAR) {\n return flags;\n }\n }\n }\n\n // Could be useful for `arguments`, `this`, `new.target`, `super()`, `super.property`, and `super[property]`.\n currentThisScopeFlags(): ScopeFlag {\n for (let i = this.scopeStack.length - 1; ; i--) {\n const { flags } = this.scopeStack[i];\n if (\n flags & (ScopeFlag.VAR | ScopeFlag.CLASS_BASE) &&\n !(flags & ScopeFlag.ARROW)\n ) {\n return flags;\n }\n }\n }\n}\n","import type { Position } from \"../../util/location.ts\";\nimport ScopeHandler, { NameType, Scope } from \"../../util/scope.ts\";\nimport { BindingFlag, type ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type * as N from \"../../types.ts\";\n\n// Reference implementation: https://github.com/facebook/flow/blob/23aeb2a2ef6eb4241ce178fde5d8f17c5f747fb5/src/typing/env.ml#L536-L584\nclass FlowScope extends Scope {\n // declare function foo(): type;\n declareFunctions = new Set();\n}\n\nexport default class FlowScopeHandler extends ScopeHandler {\n createScope(flags: ScopeFlag): FlowScope {\n return new FlowScope(flags);\n }\n\n declareName(name: string, bindingType: BindingFlag, loc: Position) {\n const scope = this.currentScope();\n if (bindingType & BindingFlag.FLAG_FLOW_DECLARE_FN) {\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n this.maybeExportDefined(scope, name);\n scope.declareFunctions.add(name);\n return;\n }\n\n super.declareName(name, bindingType, loc);\n }\n\n isRedeclaredInScope(\n scope: FlowScope,\n name: string,\n bindingType: BindingFlag,\n ): boolean {\n if (super.isRedeclaredInScope(scope, name, bindingType)) return true;\n\n if (\n bindingType & BindingFlag.FLAG_FLOW_DECLARE_FN &&\n !scope.declareFunctions.has(name)\n ) {\n const type = scope.names.get(name)!;\n return (type & NameType.Function) > 0 || (type & NameType.Lexical) > 0;\n }\n\n return false;\n }\n\n checkLocalExport(id: N.Identifier) {\n if (!this.scopeStack[0].declareFunctions.has(id.name)) {\n super.checkLocalExport(id);\n }\n }\n}\n","/*:: declare var invariant; */\n\nimport type Parser from \"../../parser/index.ts\";\nimport {\n tokenIsIdentifier,\n tokenIsKeyword,\n tokenIsKeywordOrIdentifier,\n tokenIsLiteralPropertyName,\n tokenLabelName,\n tt,\n type TokenType,\n tokenIsFlowInterfaceOrTypeOrOpaque,\n} from \"../../tokenizer/types.ts\";\nimport type * as N from \"../../types.ts\";\nimport type { Position } from \"../../util/location.ts\";\nimport { types as tc } from \"../../tokenizer/context.ts\";\nimport * as charCodes from \"charcodes\";\nimport { isIteratorStart } from \"../../util/identifier.ts\";\nimport FlowScopeHandler from \"./scope.ts\";\nimport { BindingFlag, ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type { ExpressionErrors } from \"../../parser/util.ts\";\nimport type { ParseStatementFlag } from \"../../parser/statement.ts\";\nimport { Errors, ParseErrorEnum } from \"../../parse-error.ts\";\nimport type { Undone } from \"../../parser/node.ts\";\nimport type { ClassWithMixin, IJSXParserMixin } from \"../jsx/index.ts\";\n\nconst reservedTypes = new Set([\n \"_\",\n \"any\",\n \"bool\",\n \"boolean\",\n \"empty\",\n \"extends\",\n \"false\",\n \"interface\",\n \"mixed\",\n \"null\",\n \"number\",\n \"static\",\n \"string\",\n \"true\",\n \"typeof\",\n \"void\",\n]);\n\n/* eslint sort-keys: \"error\" */\n// The Errors key follows https://github.com/facebook/flow/blob/master/src/parser/parse_error.ml unless it does not exist\nconst FlowErrors = ParseErrorEnum`flow`({\n AmbiguousConditionalArrow:\n \"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.\",\n AmbiguousDeclareModuleKind:\n \"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.\",\n // TODO: When we get proper string enums in typescript make this ReservedType.\n // Not really worth it to do the whole $Values dance with reservedTypes set.\n AssignReservedType: ({ reservedType }: { reservedType: string }) =>\n `Cannot overwrite reserved type ${reservedType}.`,\n DeclareClassElement:\n \"The `declare` modifier can only appear on class fields.\",\n DeclareClassFieldInitializer:\n \"Initializers are not allowed in fields with the `declare` modifier.\",\n DuplicateDeclareModuleExports:\n \"Duplicate `declare module.exports` statement.\",\n EnumBooleanMemberNotInitialized: ({\n memberName,\n enumName,\n }: {\n memberName: string;\n enumName: string;\n }) =>\n `Boolean enum members need to be initialized. Use either \\`${memberName} = true,\\` or \\`${memberName} = false,\\` in enum \\`${enumName}\\`.`,\n EnumDuplicateMemberName: ({\n memberName,\n enumName,\n }: {\n memberName: string;\n enumName: string;\n }) =>\n `Enum member names need to be unique, but the name \\`${memberName}\\` has already been used before in enum \\`${enumName}\\`.`,\n EnumInconsistentMemberValues: ({ enumName }: { enumName: string }) =>\n `Enum \\`${enumName}\\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,\n EnumInvalidExplicitType: ({\n invalidEnumType,\n enumName,\n }: {\n invalidEnumType: string;\n enumName: string;\n }) =>\n `Enum type \\`${invalidEnumType}\\` is not valid. Use one of \\`boolean\\`, \\`number\\`, \\`string\\`, or \\`symbol\\` in enum \\`${enumName}\\`.`,\n EnumInvalidExplicitTypeUnknownSupplied: ({\n enumName,\n }: {\n enumName: string;\n }) =>\n `Supplied enum type is not valid. Use one of \\`boolean\\`, \\`number\\`, \\`string\\`, or \\`symbol\\` in enum \\`${enumName}\\`.`,\n\n // TODO: When moving to typescript, we should either have each of the\n // following errors only accept the specific strings they want:\n //\n // ...PrimaryType: explicitType: \"string\" | \"number\" | \"boolean\"\n // ...SymbolType: explicitType: \"symbol\"\n // ...UnknownType: explicitType: null\n //\n // Or, alternatively, merge these three errors together into one\n // `EnumInvalidMemberInitializer` error that can accept `EnumExplicitType`\n // without alteration, and then just have its message change based on the\n // explicitType.\n EnumInvalidMemberInitializerPrimaryType: ({\n enumName,\n memberName,\n explicitType,\n }: {\n enumName: string;\n memberName: string;\n explicitType: EnumExplicitType;\n }) =>\n `Enum \\`${enumName}\\` has type \\`${explicitType}\\`, so the initializer of \\`${memberName}\\` needs to be a ${explicitType} literal.`,\n EnumInvalidMemberInitializerSymbolType: ({\n enumName,\n memberName,\n }: {\n enumName: string;\n memberName: string;\n explicitType: EnumExplicitType;\n }) =>\n `Symbol enum members cannot be initialized. Use \\`${memberName},\\` in enum \\`${enumName}\\`.`,\n EnumInvalidMemberInitializerUnknownType: ({\n enumName,\n memberName,\n }: {\n enumName: string;\n memberName: string;\n explicitType: EnumExplicitType;\n }) =>\n `The enum member initializer for \\`${memberName}\\` needs to be a literal (either a boolean, number, or string) in enum \\`${enumName}\\`.`,\n EnumInvalidMemberName: ({\n enumName,\n memberName,\n suggestion,\n }: {\n enumName: string;\n memberName: string;\n suggestion: string;\n }) =>\n `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \\`${memberName}\\`, consider using \\`${suggestion}\\`, in enum \\`${enumName}\\`.`,\n EnumNumberMemberNotInitialized: ({\n enumName,\n memberName,\n }: {\n enumName: string;\n memberName: string;\n }) =>\n `Number enum members need to be initialized, e.g. \\`${memberName} = 1\\` in enum \\`${enumName}\\`.`,\n EnumStringMemberInconsistentlyInitialized: ({\n enumName,\n }: {\n enumName: string;\n }) =>\n `String enum members need to consistently either all use initializers, or use no initializers, in enum \\`${enumName}\\`.`,\n GetterMayNotHaveThisParam: \"A getter cannot have a `this` parameter.\",\n ImportReflectionHasImportType:\n \"An `import module` declaration can not use `type` or `typeof` keyword.\",\n ImportTypeShorthandOnlyInPureImport:\n \"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.\",\n InexactInsideExact:\n \"Explicit inexact syntax cannot appear inside an explicit exact object type.\",\n InexactInsideNonObject:\n \"Explicit inexact syntax cannot appear in class or interface definitions.\",\n InexactVariance: \"Explicit inexact syntax cannot have variance.\",\n InvalidNonTypeImportInDeclareModule:\n \"Imports within a `declare module` body must always be `import type` or `import typeof`.\",\n MissingTypeParamDefault:\n \"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.\",\n NestedDeclareModule:\n \"`declare module` cannot be used inside another `declare module`.\",\n NestedFlowComment: \"Cannot have a flow comment inside another flow comment.\",\n PatternIsOptional: {\n message:\n \"A binding pattern parameter cannot be optional in an implementation signature.\",\n // For consistency in TypeScript and Flow error codes\n ...(!process.env.BABEL_8_BREAKING\n ? { reasonCode: \"OptionalBindingPattern\" }\n : {}),\n },\n SetterMayNotHaveThisParam: \"A setter cannot have a `this` parameter.\",\n SpreadVariance: \"Spread properties cannot have variance.\",\n ThisParamAnnotationRequired:\n \"A type annotation is required for the `this` parameter.\",\n ThisParamBannedInConstructor:\n \"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.\",\n ThisParamMayNotBeOptional: \"The `this` parameter cannot be optional.\",\n ThisParamMustBeFirst:\n \"The `this` parameter must be the first function parameter.\",\n ThisParamNoDefault: \"The `this` parameter may not have a default value.\",\n TypeBeforeInitializer:\n \"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.\",\n TypeCastInPattern:\n \"The type cast expression is expected to be wrapped with parenthesis.\",\n UnexpectedExplicitInexactInObject:\n \"Explicit inexact syntax must appear at the end of an inexact object.\",\n UnexpectedReservedType: ({ reservedType }: { reservedType: string }) =>\n `Unexpected reserved type ${reservedType}.`,\n UnexpectedReservedUnderscore:\n \"`_` is only allowed as a type argument to call or new.\",\n UnexpectedSpaceBetweenModuloChecks:\n \"Spaces between `%` and `checks` are not allowed here.\",\n UnexpectedSpreadType:\n \"Spread operator cannot appear in class or interface definitions.\",\n UnexpectedSubtractionOperand:\n 'Unexpected token, expected \"number\" or \"bigint\".',\n UnexpectedTokenAfterTypeParameter:\n \"Expected an arrow function after this type parameter declaration.\",\n UnexpectedTypeParameterBeforeAsyncArrowFunction:\n \"Type parameters must come after the async keyword, e.g. instead of ` async () => {}`, use `async () => {}`.\",\n UnsupportedDeclareExportKind: ({\n unsupportedExportKind,\n suggestion,\n }: {\n unsupportedExportKind: string;\n suggestion: string;\n }) =>\n `\\`declare export ${unsupportedExportKind}\\` is not supported. Use \\`${suggestion}\\` instead.`,\n UnsupportedStatementInDeclareModule:\n \"Only declares and type imports are allowed inside declare module.\",\n UnterminatedFlowComment: \"Unterminated flow-comment.\",\n});\n/* eslint-disable sort-keys */\n\nfunction isEsModuleType(bodyElement: N.Node): boolean {\n return (\n bodyElement.type === \"DeclareExportAllDeclaration\" ||\n (bodyElement.type === \"DeclareExportDeclaration\" &&\n (!bodyElement.declaration ||\n (bodyElement.declaration.type !== \"TypeAlias\" &&\n bodyElement.declaration.type !== \"InterfaceDeclaration\")))\n );\n}\n\nfunction hasTypeImportKind(\n node: Undone,\n): boolean {\n return node.importKind === \"type\" || node.importKind === \"typeof\";\n}\n\nconst exportSuggestions = {\n const: \"declare export var\",\n let: \"declare export var\",\n type: \"export type\",\n interface: \"export interface\",\n};\n\n// Like Array#filter, but returns a tuple [ acceptedElements, discardedElements ]\nfunction partition(\n list: T[],\n test: (c: T, b: number, a: T[]) => boolean | undefined | null,\n): [T[], T[]] {\n const list1: T[] = [];\n const list2: T[] = [];\n for (let i = 0; i < list.length; i++) {\n (test(list[i], i, list) ? list1 : list2).push(list[i]);\n }\n return [list1, list2];\n}\n\nconst FLOW_PRAGMA_REGEX = /\\*?\\s*@((?:no)?flow)\\b/;\n\n// Flow enums types\ntype EnumExplicitType = null | \"boolean\" | \"number\" | \"string\" | \"symbol\";\n\ntype EnumContext = {\n enumName: string;\n explicitType: EnumExplicitType;\n memberName: string;\n};\n\ntype EnumMemberInit =\n | {\n type: \"number\";\n loc: Position;\n value: N.Node;\n }\n | {\n type: \"string\";\n loc: Position;\n value: N.Node;\n }\n | {\n type: \"boolean\";\n loc: Position;\n value: N.Node;\n }\n | {\n type: \"invalid\";\n loc: Position;\n }\n | {\n type: \"none\";\n loc: Position;\n };\n\nexport default (superClass: ClassWithMixin) =>\n class FlowParserMixin extends superClass implements Parser {\n // The value of the @flow/@noflow pragma. Initially undefined, transitions\n // to \"@flow\" or \"@noflow\" if we see a pragma. Transitions to null if we are\n // past the initial comment.\n flowPragma: void | null | \"flow\" | \"noflow\" = undefined;\n\n getScopeHandler(): new (...args: any) => FlowScopeHandler {\n return FlowScopeHandler;\n }\n\n shouldParseTypes(): boolean {\n return this.getPluginOption(\"flow\", \"all\") || this.flowPragma === \"flow\";\n }\n\n finishToken(type: TokenType, val: any): void {\n if (\n type !== tt.string &&\n type !== tt.semi &&\n type !== tt.interpreterDirective\n ) {\n if (this.flowPragma === undefined) {\n this.flowPragma = null;\n }\n }\n super.finishToken(type, val);\n }\n\n addComment(comment: N.Comment): void {\n if (this.flowPragma === undefined) {\n // Try to parse a flow pragma.\n const matches = FLOW_PRAGMA_REGEX.exec(comment.value);\n if (!matches) {\n // do nothing\n } else if (matches[1] === \"flow\") {\n this.flowPragma = \"flow\";\n } else if (matches[1] === \"noflow\") {\n this.flowPragma = \"noflow\";\n } else {\n throw new Error(\"Unexpected flow pragma\");\n }\n }\n super.addComment(comment);\n }\n\n flowParseTypeInitialiser(tok?: TokenType): N.FlowType {\n const oldInType = this.state.inType;\n this.state.inType = true;\n this.expect(tok || tt.colon);\n\n const type = this.flowParseType();\n this.state.inType = oldInType;\n return type;\n }\n\n flowParsePredicate(): N.FlowPredicate {\n const node = this.startNode();\n const moduloLoc = this.state.startLoc;\n this.next(); // eat `%`\n this.expectContextual(tt._checks);\n // Force '%' and 'checks' to be adjacent\n if (this.state.lastTokStartLoc!.index > moduloLoc.index + 1) {\n this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc);\n }\n if (this.eat(tt.parenL)) {\n node.value = super.parseExpression();\n this.expect(tt.parenR);\n return this.finishNode(node, \"DeclaredPredicate\");\n } else {\n return this.finishNode(node, \"InferredPredicate\");\n }\n }\n\n flowParseTypeAndPredicateInitialiser(): [\n N.FlowType | null,\n N.FlowPredicate | null,\n ] {\n const oldInType = this.state.inType;\n this.state.inType = true;\n this.expect(tt.colon);\n let type = null;\n let predicate = null;\n if (this.match(tt.modulo)) {\n this.state.inType = oldInType;\n predicate = this.flowParsePredicate();\n } else {\n type = this.flowParseType();\n this.state.inType = oldInType;\n if (this.match(tt.modulo)) {\n predicate = this.flowParsePredicate();\n }\n }\n return [type, predicate];\n }\n\n flowParseDeclareClass(\n node: Undone,\n ): N.FlowDeclareClass {\n this.next();\n this.flowParseInterfaceish(node, /*isClass*/ true);\n return this.finishNode(node, \"DeclareClass\");\n }\n\n flowParseDeclareFunction(\n node: Undone,\n ): N.FlowDeclareFunction {\n this.next();\n\n const id = (node.id = this.parseIdentifier());\n\n const typeNode = this.startNode();\n const typeContainer = this.startNode();\n\n if (this.match(tt.lt)) {\n typeNode.typeParameters = this.flowParseTypeParameterDeclaration();\n } else {\n typeNode.typeParameters = null;\n }\n\n this.expect(tt.parenL);\n const tmp = this.flowParseFunctionTypeParams();\n typeNode.params = tmp.params;\n typeNode.rest = tmp.rest;\n typeNode.this = tmp._this;\n this.expect(tt.parenR);\n\n [typeNode.returnType, node.predicate] =\n this.flowParseTypeAndPredicateInitialiser();\n\n typeContainer.typeAnnotation = this.finishNode(\n typeNode,\n \"FunctionTypeAnnotation\",\n );\n\n id.typeAnnotation = this.finishNode(typeContainer, \"TypeAnnotation\");\n\n this.resetEndLocation(id);\n this.semicolon();\n\n this.scope.declareName(\n node.id.name,\n BindingFlag.TYPE_FLOW_DECLARE_FN,\n node.id.loc.start,\n );\n\n return this.finishNode(node, \"DeclareFunction\");\n }\n\n flowParseDeclare(\n node: Undone,\n insideModule?: boolean,\n ): N.FlowDeclare {\n if (this.match(tt._class)) {\n return this.flowParseDeclareClass(node);\n } else if (this.match(tt._function)) {\n return this.flowParseDeclareFunction(node);\n } else if (this.match(tt._var)) {\n return this.flowParseDeclareVariable(node);\n } else if (this.eatContextual(tt._module)) {\n if (this.match(tt.dot)) {\n return this.flowParseDeclareModuleExports(node);\n } else {\n if (insideModule) {\n this.raise(\n FlowErrors.NestedDeclareModule,\n this.state.lastTokStartLoc!,\n );\n }\n return this.flowParseDeclareModule(node);\n }\n } else if (this.isContextual(tt._type)) {\n return this.flowParseDeclareTypeAlias(node);\n } else if (this.isContextual(tt._opaque)) {\n return this.flowParseDeclareOpaqueType(node);\n } else if (this.isContextual(tt._interface)) {\n return this.flowParseDeclareInterface(node);\n } else if (this.match(tt._export)) {\n return this.flowParseDeclareExportDeclaration(node, insideModule);\n }\n throw this.unexpected();\n }\n\n flowParseDeclareVariable(\n node: Undone,\n ): N.FlowDeclareVariable {\n this.next();\n node.id = this.flowParseTypeAnnotatableIdentifier(\n /*allowPrimitiveOverride*/ true,\n );\n this.scope.declareName(\n node.id.name,\n BindingFlag.TYPE_VAR,\n node.id.loc.start,\n );\n this.semicolon();\n return this.finishNode(node, \"DeclareVariable\");\n }\n\n flowParseDeclareModule(\n node: Undone,\n ): N.FlowDeclareModule {\n this.scope.enter(ScopeFlag.OTHER);\n\n if (this.match(tt.string)) {\n node.id = super.parseExprAtom();\n } else {\n node.id = this.parseIdentifier();\n }\n\n const bodyNode = (node.body = this.startNode());\n const body: N.Statement[] = (bodyNode.body = []);\n this.expect(tt.braceL);\n while (!this.match(tt.braceR)) {\n const bodyNode = this.startNode();\n\n if (this.match(tt._import)) {\n this.next();\n if (!this.isContextual(tt._type) && !this.match(tt._typeof)) {\n this.raise(\n FlowErrors.InvalidNonTypeImportInDeclareModule,\n this.state.lastTokStartLoc!,\n );\n }\n body.push(super.parseImport(bodyNode));\n } else {\n this.expectContextual(\n tt._declare,\n FlowErrors.UnsupportedStatementInDeclareModule,\n );\n body.push(this.flowParseDeclare(bodyNode, true));\n }\n }\n\n this.scope.exit();\n\n this.expect(tt.braceR);\n\n this.finishNode(bodyNode, \"BlockStatement\");\n\n let kind: \"CommonJS\" | \"ES\" | null = null;\n let hasModuleExport = false;\n body.forEach(bodyElement => {\n if (isEsModuleType(bodyElement)) {\n if (kind === \"CommonJS\") {\n this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);\n }\n kind = \"ES\";\n } else if (bodyElement.type === \"DeclareModuleExports\") {\n if (hasModuleExport) {\n this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement);\n }\n if (kind === \"ES\") {\n this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);\n }\n kind = \"CommonJS\";\n hasModuleExport = true;\n }\n });\n\n node.kind = kind || \"CommonJS\";\n return this.finishNode(node, \"DeclareModule\");\n }\n\n flowParseDeclareExportDeclaration(\n node: Undone,\n insideModule?: boolean | null,\n ): N.FlowDeclareExportDeclaration {\n this.expect(tt._export);\n\n if (this.eat(tt._default)) {\n if (this.match(tt._function) || this.match(tt._class)) {\n // declare export default class ...\n // declare export default function ...\n node.declaration = this.flowParseDeclare(this.startNode());\n } else {\n // declare export default [type];\n node.declaration = this.flowParseType();\n this.semicolon();\n }\n node.default = true;\n\n return this.finishNode(node, \"DeclareExportDeclaration\");\n } else {\n if (\n this.match(tt._const) ||\n this.isLet() ||\n ((this.isContextual(tt._type) || this.isContextual(tt._interface)) &&\n !insideModule)\n ) {\n const label = this.state.value as\n | \"const\"\n | \"let\"\n | \"type\"\n | \"interface\";\n throw this.raise(\n FlowErrors.UnsupportedDeclareExportKind,\n this.state.startLoc,\n {\n unsupportedExportKind: label,\n suggestion: exportSuggestions[label],\n },\n );\n }\n\n if (\n this.match(tt._var) || // declare export var ...\n this.match(tt._function) || // declare export function ...\n this.match(tt._class) || // declare export class ...\n this.isContextual(tt._opaque) // declare export opaque ..\n ) {\n node.declaration = this.flowParseDeclare(this.startNode());\n node.default = false;\n\n return this.finishNode(node, \"DeclareExportDeclaration\");\n } else if (\n this.match(tt.star) || // declare export * from ''\n this.match(tt.braceL) || // declare export {} ...\n this.isContextual(tt._interface) || // declare export interface ...\n this.isContextual(tt._type) || // declare export type ...\n this.isContextual(tt._opaque) // declare export opaque type ...\n ) {\n node = this.parseExport(\n node as Undone,\n /* decorators */ null,\n );\n if (node.type === \"ExportNamedDeclaration\") {\n node.default = false;\n delete node.exportKind;\n return this.castNodeTo(\n node as N.ExportNamedDeclaration,\n \"DeclareExportDeclaration\",\n );\n } else {\n return this.castNodeTo(\n node as N.ExportAllDeclaration,\n \"DeclareExportAllDeclaration\",\n );\n }\n }\n }\n\n throw this.unexpected();\n }\n\n flowParseDeclareModuleExports(\n node: Undone,\n ): N.FlowDeclareModuleExports {\n this.next();\n this.expectContextual(tt._exports);\n node.typeAnnotation = this.flowParseTypeAnnotation();\n this.semicolon();\n\n return this.finishNode(node, \"DeclareModuleExports\");\n }\n\n flowParseDeclareTypeAlias(\n node: Undone,\n ): N.FlowDeclareTypeAlias {\n this.next();\n const finished = this.flowParseTypeAlias(\n node,\n ) as unknown as N.FlowDeclareTypeAlias;\n // Don't do finishNode as we don't want to process comments twice\n this.castNodeTo(finished, \"DeclareTypeAlias\");\n return finished;\n }\n\n flowParseDeclareOpaqueType(\n node: Undone,\n ): N.FlowDeclareOpaqueType {\n this.next();\n const finished = this.flowParseOpaqueType(\n node,\n true,\n ) as unknown as N.FlowDeclareOpaqueType;\n // Don't do finishNode as we don't want to process comments twice\n this.castNodeTo(finished, \"DeclareOpaqueType\");\n return finished;\n }\n\n flowParseDeclareInterface(\n node: Undone,\n ): N.FlowDeclareInterface {\n this.next();\n this.flowParseInterfaceish(node, /* isClass */ false);\n return this.finishNode(node, \"DeclareInterface\");\n }\n\n // Interfaces\n\n flowParseInterfaceish(node: Undone, isClass: boolean): void {\n node.id = this.flowParseRestrictedIdentifier(\n /* liberal */ !isClass,\n /* declaration */ true,\n );\n\n this.scope.declareName(\n node.id.name,\n isClass ? BindingFlag.TYPE_FUNCTION : BindingFlag.TYPE_LEXICAL,\n node.id.loc.start,\n );\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n } else {\n node.typeParameters = null;\n }\n\n node.extends = [];\n\n if (this.eat(tt._extends)) {\n do {\n node.extends.push(this.flowParseInterfaceExtends());\n } while (!isClass && this.eat(tt.comma));\n }\n\n if (isClass) {\n node.implements = [];\n node.mixins = [];\n\n if (this.eatContextual(tt._mixins)) {\n do {\n node.mixins.push(this.flowParseInterfaceExtends());\n } while (this.eat(tt.comma));\n }\n\n if (this.eatContextual(tt._implements)) {\n do {\n node.implements.push(this.flowParseInterfaceExtends());\n } while (this.eat(tt.comma));\n }\n }\n\n node.body = this.flowParseObjectType({\n allowStatic: isClass,\n allowExact: false,\n allowSpread: false,\n allowProto: isClass,\n allowInexact: false,\n });\n }\n\n flowParseInterfaceExtends(): N.FlowInterfaceExtends {\n const node = this.startNode();\n\n node.id = this.flowParseQualifiedTypeIdentifier();\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterInstantiation();\n } else {\n node.typeParameters = null;\n }\n\n return this.finishNode(node, \"InterfaceExtends\");\n }\n\n flowParseInterface(node: Undone): N.FlowInterface {\n this.flowParseInterfaceish(node, /* isClass */ false);\n return this.finishNode(node, \"InterfaceDeclaration\");\n }\n\n checkNotUnderscore(word: string) {\n if (word === \"_\") {\n this.raise(\n FlowErrors.UnexpectedReservedUnderscore,\n this.state.startLoc,\n );\n }\n }\n\n checkReservedType(word: string, startLoc: Position, declaration?: boolean) {\n if (!reservedTypes.has(word)) return;\n\n this.raise(\n declaration\n ? FlowErrors.AssignReservedType\n : FlowErrors.UnexpectedReservedType,\n startLoc,\n {\n reservedType: word,\n },\n );\n }\n\n flowParseRestrictedIdentifier(\n liberal?: boolean,\n declaration?: boolean,\n ): N.Identifier {\n this.checkReservedType(\n this.state.value,\n this.state.startLoc,\n declaration,\n );\n return this.parseIdentifier(liberal);\n }\n\n // Type aliases\n\n flowParseTypeAlias(node: Undone): N.FlowTypeAlias {\n node.id = this.flowParseRestrictedIdentifier(\n /* liberal */ false,\n /* declaration */ true,\n );\n this.scope.declareName(\n node.id.name,\n BindingFlag.TYPE_LEXICAL,\n node.id.loc.start,\n );\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n } else {\n node.typeParameters = null;\n }\n\n node.right = this.flowParseTypeInitialiser(tt.eq);\n this.semicolon();\n\n return this.finishNode(node, \"TypeAlias\");\n }\n\n flowParseOpaqueType(\n node: Undone,\n declare: boolean,\n ): N.FlowOpaqueType {\n this.expectContextual(tt._type);\n node.id = this.flowParseRestrictedIdentifier(\n /* liberal */ true,\n /* declaration */ true,\n );\n this.scope.declareName(\n node.id.name,\n BindingFlag.TYPE_LEXICAL,\n node.id.loc.start,\n );\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n } else {\n node.typeParameters = null;\n }\n\n // Parse the supertype\n node.supertype = null;\n if (this.match(tt.colon)) {\n node.supertype = this.flowParseTypeInitialiser(tt.colon);\n }\n\n node.impltype = null;\n if (!declare) {\n node.impltype = this.flowParseTypeInitialiser(tt.eq);\n }\n this.semicolon();\n\n return this.finishNode(node, \"OpaqueType\");\n }\n\n // Type annotations\n\n flowParseTypeParameter(requireDefault: boolean = false): N.TypeParameter {\n const nodeStartLoc = this.state.startLoc;\n\n const node = this.startNode();\n\n const variance = this.flowParseVariance();\n\n const ident = this.flowParseTypeAnnotatableIdentifier();\n node.name = ident.name;\n // @ts-expect-error migrate to Babel types\n node.variance = variance;\n // @ts-expect-error migrate to Babel types\n node.bound = ident.typeAnnotation;\n\n if (this.match(tt.eq)) {\n this.eat(tt.eq);\n // @ts-expect-error migrate to Babel types\n node.default = this.flowParseType();\n } else {\n if (requireDefault) {\n this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc);\n }\n }\n\n return this.finishNode(node, \"TypeParameter\");\n }\n\n flowParseTypeParameterDeclaration(): N.TypeParameterDeclaration {\n const oldInType = this.state.inType;\n const node = this.startNode();\n node.params = [];\n\n this.state.inType = true;\n\n // istanbul ignore else: this condition is already checked at all call sites\n if (this.match(tt.lt) || this.match(tt.jsxTagStart)) {\n this.next();\n } else {\n this.unexpected();\n }\n\n let defaultRequired = false;\n\n do {\n const typeParameter = this.flowParseTypeParameter(defaultRequired);\n\n node.params.push(typeParameter);\n\n if (typeParameter.default) {\n defaultRequired = true;\n }\n\n if (!this.match(tt.gt)) {\n this.expect(tt.comma);\n }\n } while (!this.match(tt.gt));\n this.expect(tt.gt);\n\n this.state.inType = oldInType;\n\n return this.finishNode(node, \"TypeParameterDeclaration\");\n }\n\n // Parse in top level normal context if we are in a JSX context\n flowInTopLevelContext(cb: () => T): T {\n if (this.curContext() !== tc.brace) {\n const oldContext = this.state.context;\n this.state.context = [oldContext[0]];\n try {\n return cb();\n } finally {\n this.state.context = oldContext;\n }\n } else {\n return cb();\n }\n }\n\n // Used when parsing type arguments from ES or JSX productions, where the first token\n // has been created without state.inType. Thus we need to re-scan the lt token.\n flowParseTypeParameterInstantiationInExpression():\n | N.TypeParameterInstantiation\n | undefined {\n if (this.reScan_lt() !== tt.lt) return;\n return this.flowParseTypeParameterInstantiation();\n }\n\n flowParseTypeParameterInstantiation(): N.TypeParameterInstantiation {\n const node = this.startNode();\n const oldInType = this.state.inType;\n\n this.state.inType = true;\n node.params = [];\n this.flowInTopLevelContext(() => {\n this.expect(tt.lt);\n const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n this.state.noAnonFunctionType = false;\n while (!this.match(tt.gt)) {\n node.params.push(this.flowParseType());\n if (!this.match(tt.gt)) {\n this.expect(tt.comma);\n }\n }\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n });\n\n this.state.inType = oldInType;\n if (!this.state.inType && this.curContext() === tc.brace) {\n // rescan `>` when we are no longer in type context and JSX parsing context\n // since it was tokenized when `inType` is `true`.\n this.reScan_lt_gt();\n }\n this.expect(tt.gt);\n\n return this.finishNode(node, \"TypeParameterInstantiation\");\n }\n\n flowParseTypeParameterInstantiationCallOrNew(): N.TypeParameterInstantiation | null {\n if (this.reScan_lt() !== tt.lt) return null;\n const node = this.startNode();\n const oldInType = this.state.inType;\n node.params = [];\n\n this.state.inType = true;\n\n this.expect(tt.lt);\n while (!this.match(tt.gt)) {\n node.params.push(this.flowParseTypeOrImplicitInstantiation());\n if (!this.match(tt.gt)) {\n this.expect(tt.comma);\n }\n }\n this.expect(tt.gt);\n\n this.state.inType = oldInType;\n\n return this.finishNode(node, \"TypeParameterInstantiation\");\n }\n\n flowParseInterfaceType(): N.FlowInterfaceType {\n const node = this.startNode();\n this.expectContextual(tt._interface);\n\n node.extends = [];\n if (this.eat(tt._extends)) {\n do {\n node.extends.push(this.flowParseInterfaceExtends());\n } while (this.eat(tt.comma));\n }\n\n node.body = this.flowParseObjectType({\n allowStatic: false,\n allowExact: false,\n allowSpread: false,\n allowProto: false,\n allowInexact: false,\n });\n\n return this.finishNode(node, \"InterfaceTypeAnnotation\");\n }\n\n flowParseObjectPropertyKey(): N.Expression {\n return this.match(tt.num) || this.match(tt.string)\n ? super.parseExprAtom()\n : this.parseIdentifier(true);\n }\n\n flowParseObjectTypeIndexer(\n node: Undone,\n isStatic: boolean,\n variance?: N.FlowVariance | null,\n ): N.FlowObjectTypeIndexer {\n node.static = isStatic;\n\n // Note: bracketL has already been consumed\n if (this.lookahead().type === tt.colon) {\n node.id = this.flowParseObjectPropertyKey();\n node.key = this.flowParseTypeInitialiser();\n } else {\n node.id = null;\n node.key = this.flowParseType();\n }\n this.expect(tt.bracketR);\n node.value = this.flowParseTypeInitialiser();\n node.variance = variance;\n\n return this.finishNode(node, \"ObjectTypeIndexer\");\n }\n\n flowParseObjectTypeInternalSlot(\n node: Undone,\n isStatic: boolean,\n ): N.FlowObjectTypeInternalSlot {\n node.static = isStatic;\n // Note: both bracketL have already been consumed\n node.id = this.flowParseObjectPropertyKey();\n this.expect(tt.bracketR);\n this.expect(tt.bracketR);\n if (this.match(tt.lt) || this.match(tt.parenL)) {\n node.method = true;\n node.optional = false;\n node.value = this.flowParseObjectTypeMethodish(\n this.startNodeAt(node.loc.start),\n );\n } else {\n node.method = false;\n if (this.eat(tt.question)) {\n node.optional = true;\n }\n node.value = this.flowParseTypeInitialiser();\n }\n return this.finishNode(node, \"ObjectTypeInternalSlot\");\n }\n\n flowParseObjectTypeMethodish(\n node: Undone,\n ): N.FlowFunctionTypeAnnotation {\n node.params = [];\n node.rest = null;\n node.typeParameters = null;\n node.this = null;\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n\n this.expect(tt.parenL);\n if (this.match(tt._this)) {\n node.this = this.flowParseFunctionTypeParam(/* first */ true);\n // match Flow parser behavior\n node.this.name = null;\n if (!this.match(tt.parenR)) {\n this.expect(tt.comma);\n }\n }\n while (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {\n node.params.push(this.flowParseFunctionTypeParam(false));\n if (!this.match(tt.parenR)) {\n this.expect(tt.comma);\n }\n }\n\n if (this.eat(tt.ellipsis)) {\n node.rest = this.flowParseFunctionTypeParam(false);\n }\n this.expect(tt.parenR);\n node.returnType = this.flowParseTypeInitialiser();\n\n return this.finishNode(node, \"FunctionTypeAnnotation\");\n }\n\n flowParseObjectTypeCallProperty(\n node: Undone,\n isStatic: boolean,\n ): N.FlowObjectTypeCallProperty {\n const valueNode = this.startNode();\n node.static = isStatic;\n node.value = this.flowParseObjectTypeMethodish(valueNode);\n return this.finishNode(node, \"ObjectTypeCallProperty\");\n }\n\n flowParseObjectType({\n allowStatic,\n allowExact,\n allowSpread,\n allowProto,\n allowInexact,\n }: {\n allowStatic: boolean;\n allowExact: boolean;\n allowSpread: boolean;\n allowProto: boolean;\n allowInexact: boolean;\n }): N.FlowObjectTypeAnnotation {\n const oldInType = this.state.inType;\n this.state.inType = true;\n\n const nodeStart = this.startNode();\n\n nodeStart.callProperties = [];\n nodeStart.properties = [];\n nodeStart.indexers = [];\n nodeStart.internalSlots = [];\n\n let endDelim;\n let exact;\n let inexact = false;\n if (allowExact && this.match(tt.braceBarL)) {\n this.expect(tt.braceBarL);\n endDelim = tt.braceBarR;\n exact = true;\n } else {\n this.expect(tt.braceL);\n endDelim = tt.braceR;\n exact = false;\n }\n\n nodeStart.exact = exact;\n\n while (!this.match(endDelim)) {\n let isStatic = false;\n let protoStartLoc: Position | undefined | null = null;\n let inexactStartLoc: Position | undefined | null = null;\n const node = this.startNode();\n\n if (allowProto && this.isContextual(tt._proto)) {\n const lookahead = this.lookahead();\n\n if (lookahead.type !== tt.colon && lookahead.type !== tt.question) {\n this.next();\n protoStartLoc = this.state.startLoc;\n allowStatic = false;\n }\n }\n\n if (allowStatic && this.isContextual(tt._static)) {\n const lookahead = this.lookahead();\n\n // static is a valid identifier name\n if (lookahead.type !== tt.colon && lookahead.type !== tt.question) {\n this.next();\n isStatic = true;\n }\n }\n\n const variance = this.flowParseVariance();\n\n if (this.eat(tt.bracketL)) {\n if (protoStartLoc != null) {\n this.unexpected(protoStartLoc);\n }\n if (this.eat(tt.bracketL)) {\n if (variance) {\n this.unexpected(variance.loc.start);\n }\n nodeStart.internalSlots.push(\n this.flowParseObjectTypeInternalSlot(node, isStatic),\n );\n } else {\n nodeStart.indexers.push(\n this.flowParseObjectTypeIndexer(node, isStatic, variance),\n );\n }\n } else if (this.match(tt.parenL) || this.match(tt.lt)) {\n if (protoStartLoc != null) {\n this.unexpected(protoStartLoc);\n }\n if (variance) {\n this.unexpected(variance.loc.start);\n }\n nodeStart.callProperties.push(\n this.flowParseObjectTypeCallProperty(node, isStatic),\n );\n } else {\n let kind = \"init\";\n\n if (this.isContextual(tt._get) || this.isContextual(tt._set)) {\n const lookahead = this.lookahead();\n if (tokenIsLiteralPropertyName(lookahead.type)) {\n kind = this.state.value;\n this.next();\n }\n }\n\n const propOrInexact = this.flowParseObjectTypeProperty(\n node,\n isStatic,\n protoStartLoc,\n variance,\n kind,\n allowSpread,\n allowInexact ?? !exact,\n );\n\n if (propOrInexact === null) {\n inexact = true;\n inexactStartLoc = this.state.lastTokStartLoc;\n } else {\n nodeStart.properties.push(propOrInexact);\n }\n }\n\n this.flowObjectTypeSemicolon();\n\n if (\n inexactStartLoc &&\n !this.match(tt.braceR) &&\n !this.match(tt.braceBarR)\n ) {\n this.raise(\n FlowErrors.UnexpectedExplicitInexactInObject,\n inexactStartLoc,\n );\n }\n }\n\n this.expect(endDelim);\n\n /* The inexact flag should only be added on ObjectTypeAnnotations that\n * are not the body of an interface, declare interface, or declare class.\n * Since spreads are only allowed in object types, checking that is\n * sufficient here.\n */\n if (allowSpread) {\n nodeStart.inexact = inexact;\n }\n\n const out = this.finishNode(nodeStart, \"ObjectTypeAnnotation\");\n\n this.state.inType = oldInType;\n\n return out;\n }\n\n flowParseObjectTypeProperty(\n node: Undone,\n isStatic: boolean,\n protoStartLoc: Position | undefined | null,\n variance: N.FlowVariance | undefined | null,\n kind: string,\n allowSpread: boolean,\n allowInexact: boolean,\n ): N.FlowObjectTypeProperty | N.FlowObjectTypeSpreadProperty | null {\n if (this.eat(tt.ellipsis)) {\n const isInexactToken =\n this.match(tt.comma) ||\n this.match(tt.semi) ||\n this.match(tt.braceR) ||\n this.match(tt.braceBarR);\n\n if (isInexactToken) {\n if (!allowSpread) {\n this.raise(\n FlowErrors.InexactInsideNonObject,\n this.state.lastTokStartLoc!,\n );\n } else if (!allowInexact) {\n this.raise(\n FlowErrors.InexactInsideExact,\n this.state.lastTokStartLoc!,\n );\n }\n if (variance) {\n this.raise(FlowErrors.InexactVariance, variance);\n }\n\n return null;\n }\n\n if (!allowSpread) {\n this.raise(\n FlowErrors.UnexpectedSpreadType,\n this.state.lastTokStartLoc!,\n );\n }\n if (protoStartLoc != null) {\n this.unexpected(protoStartLoc);\n }\n if (variance) {\n this.raise(FlowErrors.SpreadVariance, variance);\n }\n\n node.argument = this.flowParseType();\n return this.finishNode(node, \"ObjectTypeSpreadProperty\");\n } else {\n node.key = this.flowParseObjectPropertyKey();\n node.static = isStatic;\n node.proto = protoStartLoc != null;\n node.kind = kind;\n\n let optional = false;\n if (this.match(tt.lt) || this.match(tt.parenL)) {\n // This is a method property\n node.method = true;\n\n if (protoStartLoc != null) {\n this.unexpected(protoStartLoc);\n }\n if (variance) {\n this.unexpected(variance.loc.start);\n }\n\n node.value = this.flowParseObjectTypeMethodish(\n this.startNodeAt(node.loc.start),\n );\n if (kind === \"get\" || kind === \"set\") {\n this.flowCheckGetterSetterParams(node);\n }\n /** Declared classes/interfaces do not allow spread */\n if (\n !allowSpread &&\n node.key.name === \"constructor\" &&\n node.value.this\n ) {\n this.raise(\n FlowErrors.ThisParamBannedInConstructor,\n node.value.this,\n );\n }\n } else {\n if (kind !== \"init\") this.unexpected();\n\n node.method = false;\n\n if (this.eat(tt.question)) {\n optional = true;\n }\n node.value = this.flowParseTypeInitialiser();\n node.variance = variance;\n }\n\n node.optional = optional;\n\n return this.finishNode(node, \"ObjectTypeProperty\");\n }\n }\n\n // This is similar to checkGetterSetterParams, but as\n // @babel/parser uses non estree properties we cannot reuse it here\n flowCheckGetterSetterParams(\n property: Undone<\n N.FlowObjectTypeProperty | N.FlowObjectTypeSpreadProperty\n >,\n ): void {\n const paramCount = property.kind === \"get\" ? 0 : 1;\n const length =\n property.value.params.length + (property.value.rest ? 1 : 0);\n\n if (property.value.this) {\n this.raise(\n property.kind === \"get\"\n ? FlowErrors.GetterMayNotHaveThisParam\n : FlowErrors.SetterMayNotHaveThisParam,\n property.value.this,\n );\n }\n\n if (length !== paramCount) {\n this.raise(\n property.kind === \"get\"\n ? Errors.BadGetterArity\n : Errors.BadSetterArity,\n property,\n );\n }\n\n if (property.kind === \"set\" && property.value.rest) {\n this.raise(Errors.BadSetterRestParameter, property);\n }\n }\n\n flowObjectTypeSemicolon(): void {\n if (\n !this.eat(tt.semi) &&\n !this.eat(tt.comma) &&\n !this.match(tt.braceR) &&\n !this.match(tt.braceBarR)\n ) {\n this.unexpected();\n }\n }\n\n flowParseQualifiedTypeIdentifier(\n startLoc?: Position,\n id?: N.Identifier,\n ): N.FlowQualifiedTypeIdentifier | N.Identifier {\n startLoc ??= this.state.startLoc;\n let node: N.Identifier | N.FlowQualifiedTypeIdentifier =\n id || this.flowParseRestrictedIdentifier(true);\n\n while (this.eat(tt.dot)) {\n const node2 = this.startNodeAt(startLoc);\n node2.qualification = node;\n node2.id = this.flowParseRestrictedIdentifier(true);\n node = this.finishNode(node2, \"QualifiedTypeIdentifier\");\n }\n\n return node;\n }\n\n flowParseGenericType(\n startLoc: Position,\n id: N.Identifier,\n ): N.FlowGenericTypeAnnotation {\n const node = this.startNodeAt(startLoc);\n\n node.typeParameters = null;\n node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);\n\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterInstantiation();\n }\n\n return this.finishNode(node, \"GenericTypeAnnotation\");\n }\n\n flowParseTypeofType(): N.FlowTypeofTypeAnnotation {\n const node = this.startNode();\n this.expect(tt._typeof);\n node.argument = this.flowParsePrimaryType();\n return this.finishNode(node, \"TypeofTypeAnnotation\");\n }\n\n flowParseTupleType(): N.FlowTupleTypeAnnotation {\n const node = this.startNode();\n node.types = [];\n this.expect(tt.bracketL);\n // We allow trailing commas\n while (this.state.pos < this.length && !this.match(tt.bracketR)) {\n node.types.push(this.flowParseType());\n if (this.match(tt.bracketR)) break;\n this.expect(tt.comma);\n }\n this.expect(tt.bracketR);\n return this.finishNode(node, \"TupleTypeAnnotation\");\n }\n\n flowParseFunctionTypeParam(first: boolean): N.FlowFunctionTypeParam {\n let name = null;\n let optional = false;\n let typeAnnotation = null;\n const node = this.startNode();\n const lh = this.lookahead();\n const isThis = this.state.type === tt._this;\n\n if (lh.type === tt.colon || lh.type === tt.question) {\n if (isThis && !first) {\n this.raise(FlowErrors.ThisParamMustBeFirst, node);\n }\n name = this.parseIdentifier(isThis);\n if (this.eat(tt.question)) {\n optional = true;\n if (isThis) {\n this.raise(FlowErrors.ThisParamMayNotBeOptional, node);\n }\n }\n typeAnnotation = this.flowParseTypeInitialiser();\n } else {\n typeAnnotation = this.flowParseType();\n }\n node.name = name;\n node.optional = optional;\n node.typeAnnotation = typeAnnotation;\n return this.finishNode(node, \"FunctionTypeParam\");\n }\n\n reinterpretTypeAsFunctionTypeParam(\n type: N.FlowType,\n ): N.FlowFunctionTypeParam {\n const node = this.startNodeAt(type.loc.start);\n node.name = null;\n node.optional = false;\n node.typeAnnotation = type;\n return this.finishNode(node, \"FunctionTypeParam\");\n }\n\n flowParseFunctionTypeParams(params: N.FlowFunctionTypeParam[] = []): {\n params: N.FlowFunctionTypeParam[];\n rest: N.FlowFunctionTypeParam | undefined | null;\n _this: N.FlowFunctionTypeParam | undefined | null;\n } {\n let rest: N.FlowFunctionTypeParam | undefined | null = null;\n let _this: N.FlowFunctionTypeParam | undefined | null = null;\n if (this.match(tt._this)) {\n _this = this.flowParseFunctionTypeParam(/* first */ true);\n // match Flow parser behavior\n _this.name = null;\n if (!this.match(tt.parenR)) {\n this.expect(tt.comma);\n }\n }\n while (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {\n params.push(this.flowParseFunctionTypeParam(false));\n if (!this.match(tt.parenR)) {\n this.expect(tt.comma);\n }\n }\n if (this.eat(tt.ellipsis)) {\n rest = this.flowParseFunctionTypeParam(false);\n }\n return { params, rest, _this };\n }\n\n flowIdentToTypeAnnotation(\n startLoc: Position,\n node: Undone,\n id: N.Identifier,\n ): N.FlowType {\n switch (id.name) {\n case \"any\":\n return this.finishNode(node, \"AnyTypeAnnotation\");\n\n case \"bool\":\n case \"boolean\":\n return this.finishNode(node, \"BooleanTypeAnnotation\");\n\n case \"mixed\":\n return this.finishNode(node, \"MixedTypeAnnotation\");\n\n case \"empty\":\n return this.finishNode(node, \"EmptyTypeAnnotation\");\n\n case \"number\":\n return this.finishNode(node, \"NumberTypeAnnotation\");\n\n case \"string\":\n return this.finishNode(node, \"StringTypeAnnotation\");\n\n case \"symbol\":\n return this.finishNode(node, \"SymbolTypeAnnotation\");\n\n default:\n this.checkNotUnderscore(id.name);\n return this.flowParseGenericType(startLoc, id);\n }\n }\n\n // The parsing of types roughly parallels the parsing of expressions, and\n // primary types are kind of like primary expressions...they're the\n // primitives with which other types are constructed.\n flowParsePrimaryType(): N.FlowType {\n const startLoc = this.state.startLoc;\n const node = this.startNode();\n let tmp;\n let type;\n let isGroupedType = false;\n const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n\n switch (this.state.type) {\n case tt.braceL:\n return this.flowParseObjectType({\n allowStatic: false,\n allowExact: false,\n allowSpread: true,\n allowProto: false,\n allowInexact: true,\n });\n\n case tt.braceBarL:\n return this.flowParseObjectType({\n allowStatic: false,\n allowExact: true,\n allowSpread: true,\n allowProto: false,\n allowInexact: false,\n });\n\n case tt.bracketL:\n this.state.noAnonFunctionType = false;\n type = this.flowParseTupleType();\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n return type;\n\n case tt.lt: {\n const node = this.startNode();\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n this.expect(tt.parenL);\n tmp = this.flowParseFunctionTypeParams();\n node.params = tmp.params;\n node.rest = tmp.rest;\n node.this = tmp._this;\n this.expect(tt.parenR);\n\n this.expect(tt.arrow);\n\n node.returnType = this.flowParseType();\n\n return this.finishNode(node, \"FunctionTypeAnnotation\");\n }\n\n case tt.parenL: {\n const node = this.startNode();\n this.next();\n\n // Check to see if this is actually a grouped type\n if (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {\n if (tokenIsIdentifier(this.state.type) || this.match(tt._this)) {\n const token = this.lookahead().type;\n isGroupedType = token !== tt.question && token !== tt.colon;\n } else {\n isGroupedType = true;\n }\n }\n\n if (isGroupedType) {\n this.state.noAnonFunctionType = false;\n type = this.flowParseType();\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n\n // A `,` or a `) =>` means this is an anonymous function type\n if (\n this.state.noAnonFunctionType ||\n !(\n this.match(tt.comma) ||\n (this.match(tt.parenR) && this.lookahead().type === tt.arrow)\n )\n ) {\n this.expect(tt.parenR);\n return type;\n } else {\n // Eat a comma if there is one\n this.eat(tt.comma);\n }\n }\n\n if (type) {\n tmp = this.flowParseFunctionTypeParams([\n this.reinterpretTypeAsFunctionTypeParam(type),\n ]);\n } else {\n tmp = this.flowParseFunctionTypeParams();\n }\n\n node.params = tmp.params;\n node.rest = tmp.rest;\n node.this = tmp._this;\n\n this.expect(tt.parenR);\n\n this.expect(tt.arrow);\n\n node.returnType = this.flowParseType();\n\n node.typeParameters = null;\n\n return this.finishNode(node, \"FunctionTypeAnnotation\");\n }\n\n case tt.string:\n return this.parseLiteral(\n this.state.value,\n \"StringLiteralTypeAnnotation\",\n );\n\n case tt._true:\n case tt._false:\n node.value = this.match(tt._true);\n this.next();\n return this.finishNode(\n node as Undone,\n \"BooleanLiteralTypeAnnotation\",\n );\n\n case tt.plusMin:\n if (this.state.value === \"-\") {\n this.next();\n if (this.match(tt.num)) {\n return this.parseLiteralAtNode(\n -this.state.value,\n \"NumberLiteralTypeAnnotation\",\n node,\n );\n }\n\n if (this.match(tt.bigint)) {\n return this.parseLiteralAtNode(\n -this.state.value,\n \"BigIntLiteralTypeAnnotation\",\n node,\n );\n }\n\n throw this.raise(\n FlowErrors.UnexpectedSubtractionOperand,\n this.state.startLoc,\n );\n }\n throw this.unexpected();\n case tt.num:\n return this.parseLiteral(\n this.state.value,\n \"NumberLiteralTypeAnnotation\",\n );\n\n case tt.bigint:\n return this.parseLiteral(\n this.state.value,\n \"BigIntLiteralTypeAnnotation\",\n );\n\n case tt._void:\n this.next();\n return this.finishNode(node, \"VoidTypeAnnotation\");\n\n case tt._null:\n this.next();\n return this.finishNode(node, \"NullLiteralTypeAnnotation\");\n\n case tt._this:\n this.next();\n return this.finishNode(node, \"ThisTypeAnnotation\");\n\n case tt.star:\n this.next();\n return this.finishNode(node, \"ExistsTypeAnnotation\");\n\n case tt._typeof:\n return this.flowParseTypeofType();\n\n default:\n if (tokenIsKeyword(this.state.type)) {\n const label = tokenLabelName(this.state.type);\n this.next();\n return super.createIdentifier(node as Undone, label);\n } else if (tokenIsIdentifier(this.state.type)) {\n if (this.isContextual(tt._interface)) {\n return this.flowParseInterfaceType();\n }\n\n return this.flowIdentToTypeAnnotation(\n startLoc,\n node,\n this.parseIdentifier(),\n );\n }\n }\n\n throw this.unexpected();\n }\n\n flowParsePostfixType(): N.FlowType {\n const startLoc = this.state.startLoc;\n let type = this.flowParsePrimaryType();\n let seenOptionalIndexedAccess = false;\n while (\n (this.match(tt.bracketL) || this.match(tt.questionDot)) &&\n !this.canInsertSemicolon()\n ) {\n const node = this.startNodeAt(startLoc);\n const optional = this.eat(tt.questionDot);\n seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;\n this.expect(tt.bracketL);\n if (!optional && this.match(tt.bracketR)) {\n node.elementType = type;\n this.next(); // eat `]`\n type = this.finishNode(node, \"ArrayTypeAnnotation\");\n } else {\n node.objectType = type;\n node.indexType = this.flowParseType();\n this.expect(tt.bracketR);\n if (seenOptionalIndexedAccess) {\n node.optional = optional;\n type = this.finishNode(\n // @ts-expect-error todo(flow->ts)\n node,\n \"OptionalIndexedAccessType\",\n );\n } else {\n type = this.finishNode(\n // @ts-expect-error todo(flow->ts)\n node,\n \"IndexedAccessType\",\n );\n }\n }\n }\n return type;\n }\n\n flowParsePrefixType(): N.FlowType {\n const node = this.startNode();\n if (this.eat(tt.question)) {\n node.typeAnnotation = this.flowParsePrefixType();\n return this.finishNode(node, \"NullableTypeAnnotation\");\n } else {\n return this.flowParsePostfixType();\n }\n }\n\n flowParseAnonFunctionWithoutParens(): N.FlowType {\n const param = this.flowParsePrefixType();\n if (!this.state.noAnonFunctionType && this.eat(tt.arrow)) {\n // TODO: This should be a type error. Passing in a SourceLocation, and it expects a Position.\n const node = this.startNodeAt(\n param.loc.start,\n );\n node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];\n node.rest = null;\n node.this = null;\n node.returnType = this.flowParseType();\n node.typeParameters = null;\n return this.finishNode(node, \"FunctionTypeAnnotation\");\n }\n return param;\n }\n\n flowParseIntersectionType(): N.FlowType {\n const node = this.startNode();\n this.eat(tt.bitwiseAND);\n const type = this.flowParseAnonFunctionWithoutParens();\n node.types = [type];\n while (this.eat(tt.bitwiseAND)) {\n node.types.push(this.flowParseAnonFunctionWithoutParens());\n }\n return node.types.length === 1\n ? type\n : this.finishNode(node, \"IntersectionTypeAnnotation\");\n }\n\n flowParseUnionType(): N.FlowType {\n const node = this.startNode();\n this.eat(tt.bitwiseOR);\n const type = this.flowParseIntersectionType();\n node.types = [type];\n while (this.eat(tt.bitwiseOR)) {\n node.types.push(this.flowParseIntersectionType());\n }\n return node.types.length === 1\n ? type\n : this.finishNode(node, \"UnionTypeAnnotation\");\n }\n\n flowParseType(): N.FlowType {\n const oldInType = this.state.inType;\n this.state.inType = true;\n const type = this.flowParseUnionType();\n this.state.inType = oldInType;\n return type;\n }\n\n flowParseTypeOrImplicitInstantiation(): N.FlowType {\n if (this.state.type === tt.name && this.state.value === \"_\") {\n const startLoc = this.state.startLoc;\n const node = this.parseIdentifier();\n return this.flowParseGenericType(startLoc, node);\n } else {\n return this.flowParseType();\n }\n }\n\n flowParseTypeAnnotation(): N.TypeAnnotation {\n const node = this.startNode();\n node.typeAnnotation = this.flowParseTypeInitialiser();\n return this.finishNode(node, \"TypeAnnotation\");\n }\n\n flowParseTypeAnnotatableIdentifier(\n allowPrimitiveOverride?: boolean,\n ): N.Identifier {\n const ident = allowPrimitiveOverride\n ? this.parseIdentifier()\n : this.flowParseRestrictedIdentifier();\n if (this.match(tt.colon)) {\n ident.typeAnnotation = this.flowParseTypeAnnotation();\n this.resetEndLocation(ident);\n }\n return ident;\n }\n\n typeCastToParameter(node: N.TypeCastExpression): N.Expression {\n (node.expression as N.Identifier).typeAnnotation = node.typeAnnotation;\n\n this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);\n\n return node.expression;\n }\n\n flowParseVariance(): N.FlowVariance | undefined | null {\n let variance = null;\n if (this.match(tt.plusMin)) {\n variance = this.startNode();\n if (this.state.value === \"+\") {\n variance.kind = \"plus\";\n } else {\n variance.kind = \"minus\";\n }\n this.next();\n return this.finishNode(variance, \"Variance\");\n }\n return variance;\n }\n\n // ==================================\n // Overrides\n // ==================================\n\n parseFunctionBody(\n node: N.Function,\n allowExpressionBody?: boolean | null,\n isMethod: boolean = false,\n ): void {\n if (allowExpressionBody) {\n this.forwardNoArrowParamsConversionAt(node, () =>\n super.parseFunctionBody(node, true, isMethod),\n );\n return;\n }\n\n super.parseFunctionBody(node, false, isMethod);\n }\n\n parseFunctionBodyAndFinish<\n T extends\n | N.Function\n | N.TSDeclareMethod\n | N.TSDeclareFunction\n | N.ClassPrivateMethod,\n >(node: Undone, type: T[\"type\"], isMethod: boolean = false): T {\n if (this.match(tt.colon)) {\n const typeNode = this.startNode();\n\n [\n typeNode.typeAnnotation,\n // @ts-expect-error predicate may not exist\n node.predicate,\n ] = this.flowParseTypeAndPredicateInitialiser() as [\n N.FlowType,\n N.FlowPredicate,\n ];\n\n node.returnType = typeNode.typeAnnotation\n ? this.finishNode(typeNode, \"TypeAnnotation\")\n : null;\n }\n\n return super.parseFunctionBodyAndFinish(node, type, isMethod);\n }\n\n // interfaces and enums\n parseStatementLike(flags: ParseStatementFlag): N.Statement {\n // strict mode handling of `interface` since it's a reserved word\n if (this.state.strict && this.isContextual(tt._interface)) {\n const lookahead = this.lookahead();\n if (tokenIsKeywordOrIdentifier(lookahead.type)) {\n const node = this.startNode();\n this.next();\n return this.flowParseInterface(node);\n }\n } else if (this.isContextual(tt._enum)) {\n const node = this.startNode();\n this.next();\n return this.flowParseEnumDeclaration(node);\n }\n const stmt = super.parseStatementLike(flags);\n // We will parse a flow pragma in any comment before the first statement.\n if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {\n this.flowPragma = null;\n }\n return stmt;\n }\n\n // declares, interfaces and type aliases\n parseExpressionStatement(\n node: N.ExpressionStatement,\n expr: N.Expression,\n decorators: N.Decorator[] | null,\n ): N.ExpressionStatement {\n if (expr.type === \"Identifier\") {\n if (expr.name === \"declare\") {\n if (\n this.match(tt._class) ||\n tokenIsIdentifier(this.state.type) ||\n this.match(tt._function) ||\n this.match(tt._var) ||\n this.match(tt._export)\n ) {\n // @ts-expect-error: refine typings\n return this.flowParseDeclare(node);\n }\n } else if (tokenIsIdentifier(this.state.type)) {\n if (expr.name === \"interface\") {\n // @ts-expect-error: refine typings\n return this.flowParseInterface(node);\n } else if (expr.name === \"type\") {\n // @ts-expect-error: refine typings\n return this.flowParseTypeAlias(node);\n } else if (expr.name === \"opaque\") {\n // @ts-expect-error: refine typings\n return this.flowParseOpaqueType(node, false);\n }\n }\n }\n\n return super.parseExpressionStatement(node, expr, decorators);\n }\n\n // export type\n shouldParseExportDeclaration(): boolean {\n const { type } = this.state;\n if (type === tt._enum || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {\n return !this.state.containsEsc;\n }\n return super.shouldParseExportDeclaration();\n }\n\n isExportDefaultSpecifier(): boolean {\n const { type } = this.state;\n if (type === tt._enum || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {\n return this.state.containsEsc;\n }\n\n return super.isExportDefaultSpecifier();\n }\n\n parseExportDefaultExpression() {\n if (this.isContextual(tt._enum)) {\n const node = this.startNode();\n this.next();\n return this.flowParseEnumDeclaration(node);\n }\n return super.parseExportDefaultExpression();\n }\n\n parseConditional(\n expr: N.Expression,\n\n startLoc: Position,\n refExpressionErrors?: ExpressionErrors | null,\n ): N.Expression {\n if (!this.match(tt.question)) return expr;\n\n if (this.state.maybeInArrowParameters) {\n const nextCh = this.lookaheadCharCode();\n // These tokens cannot start an expression, so if one of them follows\n // ? then we are probably in an arrow function parameters list and we\n // don't parse the conditional expression.\n if (\n nextCh === charCodes.comma || // (a?, b) => c\n nextCh === charCodes.equalsTo || // (a? = b) => c\n nextCh === charCodes.colon || // (a?: b) => c\n nextCh === charCodes.rightParenthesis // (a?) => c\n ) {\n /*:: invariant(refExpressionErrors != null) */\n this.setOptionalParametersError(refExpressionErrors!);\n return expr;\n }\n }\n\n this.expect(tt.question);\n const state = this.state.clone();\n const originalNoArrowAt = this.state.noArrowAt;\n const node = this.startNodeAt(startLoc);\n let { consequent, failed } = this.tryParseConditionalConsequent();\n let [valid, invalid] = this.getArrowLikeExpressions(consequent);\n\n if (failed || invalid.length > 0) {\n const noArrowAt = [...originalNoArrowAt];\n\n if (invalid.length > 0) {\n this.state = state;\n this.state.noArrowAt = noArrowAt;\n\n for (let i = 0; i < invalid.length; i++) {\n noArrowAt.push(invalid[i].start);\n }\n\n ({ consequent, failed } = this.tryParseConditionalConsequent());\n [valid, invalid] = this.getArrowLikeExpressions(consequent);\n }\n\n if (failed && valid.length > 1) {\n // if there are two or more possible correct ways of parsing, throw an\n // error.\n // e.g. Source: a ? (b): c => (d): e => f\n // Result 1: a ? b : (c => ((d): e => f))\n // Result 2: a ? ((b): c => d) : (e => f)\n this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc);\n }\n\n if (failed && valid.length === 1) {\n this.state = state;\n noArrowAt.push(valid[0].start);\n this.state.noArrowAt = noArrowAt;\n ({ consequent, failed } = this.tryParseConditionalConsequent());\n }\n }\n\n this.getArrowLikeExpressions(consequent, true);\n\n this.state.noArrowAt = originalNoArrowAt;\n this.expect(tt.colon);\n\n node.test = expr;\n node.consequent = consequent;\n node.alternate = this.forwardNoArrowParamsConversionAt(node, () =>\n this.parseMaybeAssign(undefined, undefined),\n );\n\n return this.finishNode(node, \"ConditionalExpression\");\n }\n\n tryParseConditionalConsequent(): {\n consequent: N.Expression;\n failed: boolean;\n } {\n this.state.noArrowParamsConversionAt.push(this.state.start);\n\n const consequent = this.parseMaybeAssignAllowIn();\n const failed = !this.match(tt.colon);\n\n this.state.noArrowParamsConversionAt.pop();\n\n return { consequent, failed };\n }\n\n // Given an expression, walks through out its arrow functions whose body is\n // an expression and through out conditional expressions. It returns every\n // function which has been parsed with a return type but could have been\n // parenthesized expressions.\n // These functions are separated into two arrays: one containing the ones\n // whose parameters can be converted to assignable lists, one containing the\n // others.\n getArrowLikeExpressions(\n node: N.Expression,\n disallowInvalid?: boolean,\n ): [N.ArrowFunctionExpression[], N.ArrowFunctionExpression[]] {\n const stack = [node];\n const arrows: N.ArrowFunctionExpression[] = [];\n\n while (stack.length !== 0) {\n const node = stack.pop()!;\n if (\n node.type === \"ArrowFunctionExpression\" &&\n node.body.type !== \"BlockStatement\"\n ) {\n if (node.typeParameters || !node.returnType) {\n // This is an arrow expression without ambiguity, so check its parameters\n this.finishArrowValidation(node);\n } else {\n arrows.push(node);\n }\n stack.push(node.body);\n } else if (node.type === \"ConditionalExpression\") {\n stack.push(node.consequent);\n stack.push(node.alternate);\n }\n }\n\n if (disallowInvalid) {\n arrows.forEach(node => this.finishArrowValidation(node));\n return [arrows, []];\n }\n\n return partition(arrows, node =>\n node.params.every(param => this.isAssignable(param, true)),\n );\n }\n\n finishArrowValidation(node: N.ArrowFunctionExpression) {\n this.toAssignableList(\n // node.params is Expression[] instead of $ReadOnlyArray because it\n // has not been converted yet.\n node.params as any as N.Expression[],\n node.extra?.trailingCommaLoc,\n /* isLHS */ false,\n );\n // Enter scope, as checkParams defines bindings\n this.scope.enter(ScopeFlag.FUNCTION | ScopeFlag.ARROW);\n // Use super's method to force the parameters to be checked\n super.checkParams(node, false, true);\n this.scope.exit();\n }\n\n forwardNoArrowParamsConversionAt(\n node: Undone,\n parse: () => T,\n ): T {\n let result: T;\n if (\n this.state.noArrowParamsConversionAt.includes(\n this.offsetToSourcePos(node.start),\n )\n ) {\n this.state.noArrowParamsConversionAt.push(this.state.start);\n result = parse();\n this.state.noArrowParamsConversionAt.pop();\n } else {\n result = parse();\n }\n\n return result;\n }\n\n parseParenItem(\n node: T,\n startLoc: Position,\n ): T | N.TypeCastExpression | N.TsTypeCastExpression {\n const newNode = super.parseParenItem(node, startLoc);\n if (this.eat(tt.question)) {\n (newNode as N.Identifier).optional = true;\n // Include questionmark in location of node\n // Don't use this.finishNode() as otherwise we might process comments twice and\n // include already consumed parens\n this.resetEndLocation(node);\n }\n\n if (this.match(tt.colon)) {\n const typeCastNode = this.startNodeAt(startLoc);\n typeCastNode.expression = newNode as N.Expression;\n typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();\n\n return this.finishNode(typeCastNode, \"TypeCastExpression\");\n }\n\n return newNode;\n }\n\n assertModuleNodeAllowed(node: N.Node) {\n if (\n (node.type === \"ImportDeclaration\" &&\n (node.importKind === \"type\" || node.importKind === \"typeof\")) ||\n (node.type === \"ExportNamedDeclaration\" &&\n node.exportKind === \"type\") ||\n (node.type === \"ExportAllDeclaration\" && node.exportKind === \"type\")\n ) {\n // Allow Flowtype imports and exports in all conditions because\n // Flow itself does not care about 'sourceType'.\n return;\n }\n\n super.assertModuleNodeAllowed(node);\n }\n\n parseExportDeclaration(\n node: N.ExportNamedDeclaration,\n ): N.Declaration | undefined | null {\n if (this.isContextual(tt._type)) {\n node.exportKind = \"type\";\n\n const declarationNode = this.startNode();\n this.next();\n\n if (this.match(tt.braceL)) {\n // export type { foo, bar };\n node.specifiers = this.parseExportSpecifiers(\n /* isInTypeExport */ true,\n );\n super.parseExportFrom(node);\n return null;\n } else {\n // export type Foo = Bar;\n // @ts-expect-error: refine typings\n return this.flowParseTypeAlias(declarationNode);\n }\n } else if (this.isContextual(tt._opaque)) {\n node.exportKind = \"type\";\n\n const declarationNode = this.startNode();\n this.next();\n // export opaque type Foo = Bar;\n // @ts-expect-error: refine typings\n return this.flowParseOpaqueType(declarationNode, false);\n } else if (this.isContextual(tt._interface)) {\n node.exportKind = \"type\";\n const declarationNode = this.startNode();\n this.next();\n // @ts-expect-error: refine typings\n return this.flowParseInterface(declarationNode);\n } else if (this.isContextual(tt._enum)) {\n node.exportKind = \"value\";\n const declarationNode = this.startNode();\n this.next();\n // @ts-expect-error: refine typings\n return this.flowParseEnumDeclaration(declarationNode);\n } else {\n return super.parseExportDeclaration(node);\n }\n }\n\n eatExportStar(\n node: Undone,\n ): node is Undone {\n if (super.eatExportStar(node)) return true;\n\n if (this.isContextual(tt._type) && this.lookahead().type === tt.star) {\n (\n node as Undone\n ).exportKind = \"type\";\n this.next();\n this.next();\n return true;\n }\n\n return false;\n }\n\n maybeParseExportNamespaceSpecifier(\n node: Undone,\n ): node is Undone {\n const { startLoc } = this.state;\n const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);\n if (hasNamespace && node.exportKind === \"type\") {\n this.unexpected(startLoc);\n }\n return hasNamespace;\n }\n\n parseClassId(\n node: N.Class,\n isStatement: boolean,\n optionalId?: boolean | null,\n ) {\n super.parseClassId(node, isStatement, optionalId);\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n }\n\n parseClassMember(\n classBody: N.ClassBody,\n member: any,\n state: N.ParseClassMemberState,\n ): void {\n const { startLoc } = this.state;\n if (this.isContextual(tt._declare)) {\n if (super.parseClassMemberFromModifier(classBody, member)) {\n // 'declare' is a class element name\n return;\n }\n\n member.declare = true;\n }\n\n super.parseClassMember(classBody, member, state);\n\n if (member.declare) {\n if (\n member.type !== \"ClassProperty\" &&\n member.type !== \"ClassPrivateProperty\" &&\n member.type !== \"PropertyDefinition\" // Used by estree plugin\n ) {\n this.raise(FlowErrors.DeclareClassElement, startLoc);\n } else if (member.value) {\n this.raise(FlowErrors.DeclareClassFieldInitializer, member.value);\n }\n }\n }\n\n isIterator(word: string): boolean {\n return word === \"iterator\" || word === \"asyncIterator\";\n }\n\n readIterator(): void {\n const word = super.readWord1();\n const fullWord = \"@@\" + word;\n\n // Allow @@iterator and @@asyncIterator as a identifier only inside type\n if (!this.isIterator(word) || !this.state.inType) {\n this.raise(Errors.InvalidIdentifier, this.state.curPosition(), {\n identifierName: fullWord,\n });\n }\n\n this.finishToken(tt.name, fullWord);\n }\n\n // ensure that inside flow types, we bypass the jsx parser plugin\n getTokenFromCode(code: number): void {\n const next = this.input.charCodeAt(this.state.pos + 1);\n if (code === charCodes.leftCurlyBrace && next === charCodes.verticalBar) {\n this.finishOp(tt.braceBarL, 2);\n } else if (\n this.state.inType &&\n (code === charCodes.greaterThan || code === charCodes.lessThan)\n ) {\n this.finishOp(code === charCodes.greaterThan ? tt.gt : tt.lt, 1);\n } else if (this.state.inType && code === charCodes.questionMark) {\n if (next === charCodes.dot) {\n this.finishOp(tt.questionDot, 2);\n } else {\n // allow double nullable types in Flow: ??string\n this.finishOp(tt.question, 1);\n }\n } else if (\n isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))\n ) {\n this.state.pos += 2; // eat \"@@\"\n this.readIterator();\n } else {\n super.getTokenFromCode(code);\n }\n }\n\n isAssignable(node: N.Node, isBinding?: boolean): boolean {\n if (node.type === \"TypeCastExpression\") {\n return this.isAssignable(node.expression, isBinding);\n } else {\n return super.isAssignable(node, isBinding);\n }\n }\n\n toAssignable(node: N.Node, isLHS: boolean = false): void {\n if (\n !isLHS &&\n node.type === \"AssignmentExpression\" &&\n node.left.type === \"TypeCastExpression\"\n ) {\n node.left = this.typeCastToParameter(node.left) as N.Assignable;\n }\n super.toAssignable(node, isLHS);\n }\n\n // turn type casts that we found in function parameter head into type annotated params\n toAssignableList(\n exprList: N.Expression[],\n trailingCommaLoc: Position | undefined | null,\n isLHS: boolean,\n ): void {\n for (let i = 0; i < exprList.length; i++) {\n const expr = exprList[i];\n if (expr?.type === \"TypeCastExpression\") {\n exprList[i] = this.typeCastToParameter(expr);\n }\n }\n super.toAssignableList(exprList, trailingCommaLoc, isLHS);\n }\n\n // this is a list of nodes, from something like a call expression, we need to filter the\n // type casts that we've found that are illegal in this context\n toReferencedList(\n exprList:\n | readonly (N.Expression | N.SpreadElement | null)[]\n | readonly (N.Expression | N.RestElement)[],\n isParenthesizedExpr?: boolean,\n ):\n | readonly (N.Expression | N.SpreadElement | null)[]\n | readonly (N.Expression | N.RestElement)[] {\n for (let i = 0; i < exprList.length; i++) {\n const expr = exprList[i];\n if (\n expr &&\n expr.type === \"TypeCastExpression\" &&\n !expr.extra?.parenthesized &&\n (exprList.length > 1 || !isParenthesizedExpr)\n ) {\n this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation);\n }\n }\n\n return exprList;\n }\n\n parseArrayLike(\n close: TokenType,\n isTuple: boolean,\n refExpressionErrors?: ExpressionErrors | null,\n ): N.ArrayExpression | N.TupleExpression {\n const node = super.parseArrayLike(close, isTuple, refExpressionErrors);\n\n // This could be an array pattern:\n // ([a: string, b: string]) => {}\n // In this case, we don't have to call toReferencedList. We will\n // call it, if needed, when we are sure that it is a parenthesized\n // expression by calling toReferencedListDeep.\n if (refExpressionErrors != null && !this.state.maybeInArrowParameters) {\n this.toReferencedList(node.elements);\n }\n\n return node;\n }\n\n isValidLVal(\n type: string,\n disallowCallExpression: boolean,\n isParenthesized: boolean,\n binding: BindingFlag,\n ) {\n return (\n type === \"TypeCastExpression\" ||\n super.isValidLVal(\n type,\n disallowCallExpression,\n isParenthesized,\n binding,\n )\n );\n }\n\n // parse class property type annotations\n parseClassProperty(node: N.ClassProperty): N.ClassProperty {\n if (this.match(tt.colon)) {\n node.typeAnnotation = this.flowParseTypeAnnotation();\n }\n return super.parseClassProperty(node);\n }\n\n parseClassPrivateProperty(\n node: N.ClassPrivateProperty,\n ): N.ClassPrivateProperty {\n if (this.match(tt.colon)) {\n node.typeAnnotation = this.flowParseTypeAnnotation();\n }\n return super.parseClassPrivateProperty(node);\n }\n\n // determine whether or not we're currently in the position where a class method would appear\n isClassMethod(): boolean {\n return this.match(tt.lt) || super.isClassMethod();\n }\n\n // determine whether or not we're currently in the position where a class property would appear\n isClassProperty(): boolean {\n return this.match(tt.colon) || super.isClassProperty();\n }\n\n isNonstaticConstructor(method: N.ClassMethod | N.ClassProperty): boolean {\n return !this.match(tt.colon) && super.isNonstaticConstructor(method);\n }\n\n // parse type parameters for class methods\n pushClassMethod(\n classBody: N.ClassBody,\n method: N.ClassMethod,\n isGenerator: boolean,\n isAsync: boolean,\n isConstructor: boolean,\n allowsDirectSuper: boolean,\n ): void {\n if ((method as any).variance) {\n this.unexpected((method as any).variance.loc.start);\n }\n delete (method as any).variance;\n if (this.match(tt.lt)) {\n method.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n\n super.pushClassMethod(\n classBody,\n method,\n isGenerator,\n isAsync,\n isConstructor,\n allowsDirectSuper,\n );\n\n if (method.params && isConstructor) {\n const params = method.params;\n if (params.length > 0 && this.isThisParam(params[0])) {\n this.raise(FlowErrors.ThisParamBannedInConstructor, method);\n }\n // estree support\n } else if (\n // @ts-expect-error TS does not know about the fact that estree can replace ClassMethod with MethodDefinition\n method.type === \"MethodDefinition\" &&\n isConstructor &&\n // @ts-expect-error estree\n method.value.params\n ) {\n // @ts-expect-error estree\n const params = method.value.params;\n if (params.length > 0 && this.isThisParam(params[0])) {\n this.raise(FlowErrors.ThisParamBannedInConstructor, method);\n }\n }\n }\n\n pushClassPrivateMethod(\n classBody: N.ClassBody,\n method: N.ClassPrivateMethod,\n isGenerator: boolean,\n isAsync: boolean,\n ): void {\n if ((method as any).variance) {\n this.unexpected((method as any).variance.loc.start);\n }\n delete (method as any).variance;\n if (this.match(tt.lt)) {\n method.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n\n super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);\n }\n\n // parse a the super class type parameters and implements\n parseClassSuper(node: N.Class): void {\n super.parseClassSuper(node);\n if (\n node.superClass &&\n (this.match(tt.lt) ||\n // handles `class extends C<`\n this.match(tt.bitShiftL))\n ) {\n if (process.env.BABEL_8_BREAKING) {\n node.superTypeArguments =\n this.flowParseTypeParameterInstantiationInExpression();\n } else {\n node.superTypeParameters =\n this.flowParseTypeParameterInstantiationInExpression();\n }\n }\n if (this.isContextual(tt._implements)) {\n this.next();\n const implemented: N.FlowClassImplements[] = (node.implements = []);\n do {\n const node = this.startNode();\n node.id = this.flowParseRestrictedIdentifier(/*liberal*/ true);\n if (this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterInstantiation();\n } else {\n node.typeParameters = null;\n }\n implemented.push(this.finishNode(node, \"ClassImplements\"));\n } while (this.eat(tt.comma));\n }\n }\n\n checkGetterSetterParams(method: N.ObjectMethod | N.ClassMethod): void {\n super.checkGetterSetterParams(method);\n const params = this.getObjectOrClassMethodParams(method);\n if (params.length > 0) {\n const param = params[0];\n if (this.isThisParam(param) && method.kind === \"get\") {\n this.raise(FlowErrors.GetterMayNotHaveThisParam, param);\n } else if (this.isThisParam(param)) {\n this.raise(FlowErrors.SetterMayNotHaveThisParam, param);\n }\n }\n }\n\n parsePropertyNamePrefixOperator(\n node: N.ObjectOrClassMember | N.ClassMember,\n ): void {\n node.variance = this.flowParseVariance();\n }\n\n // parse type parameters for object method shorthand\n parseObjPropValue(\n prop: Undone,\n startLoc: Position | undefined | null,\n isGenerator: boolean,\n isAsync: boolean,\n isPattern: boolean,\n isAccessor: boolean,\n refExpressionErrors?: ExpressionErrors | null,\n ): T {\n if ((prop as any).variance) {\n this.unexpected((prop as any).variance.loc.start);\n }\n delete (prop as any).variance;\n\n let typeParameters;\n\n // method shorthand\n if (this.match(tt.lt) && !isAccessor) {\n typeParameters = this.flowParseTypeParameterDeclaration();\n if (!this.match(tt.parenL)) this.unexpected();\n }\n\n const result = super.parseObjPropValue(\n prop,\n startLoc,\n isGenerator,\n isAsync,\n isPattern,\n isAccessor,\n refExpressionErrors,\n );\n\n // add typeParameters if we found them\n if (typeParameters) {\n // @ts-expect-error: refine typings\n (result.value || result).typeParameters = typeParameters;\n }\n return result;\n }\n\n parseFunctionParamType(param: N.Pattern): N.Pattern {\n if (this.eat(tt.question)) {\n if (param.type !== \"Identifier\") {\n this.raise(FlowErrors.PatternIsOptional, param);\n }\n if (this.isThisParam(param)) {\n this.raise(FlowErrors.ThisParamMayNotBeOptional, param);\n }\n\n (param as any as N.Identifier).optional = true;\n }\n if (this.match(tt.colon)) {\n param.typeAnnotation = this.flowParseTypeAnnotation();\n } else if (this.isThisParam(param)) {\n this.raise(FlowErrors.ThisParamAnnotationRequired, param);\n }\n\n if (this.match(tt.eq) && this.isThisParam(param)) {\n this.raise(FlowErrors.ThisParamNoDefault, param);\n }\n\n this.resetEndLocation(param);\n return param;\n }\n\n parseMaybeDefault

(\n startLoc?: Position | null,\n left?: P | null,\n ): P | N.AssignmentPattern {\n const node = super.parseMaybeDefault(startLoc, left);\n\n if (\n node.type === \"AssignmentPattern\" &&\n node.typeAnnotation &&\n node.right.start < node.typeAnnotation.start\n ) {\n this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation);\n }\n\n return node;\n }\n\n checkImportReflection(node: Undone) {\n super.checkImportReflection(node);\n if (node.module && node.importKind !== \"value\") {\n this.raise(\n FlowErrors.ImportReflectionHasImportType,\n node.specifiers[0].loc.start,\n );\n }\n }\n\n parseImportSpecifierLocal<\n T extends\n | N.ImportSpecifier\n | N.ImportDefaultSpecifier\n | N.ImportNamespaceSpecifier,\n >(node: N.ImportDeclaration, specifier: Undone, type: T[\"type\"]): void {\n specifier.local = hasTypeImportKind(node)\n ? this.flowParseRestrictedIdentifier(\n /* liberal */ true,\n /* declaration */ true,\n )\n : this.parseIdentifier();\n\n node.specifiers.push(this.finishImportSpecifier(specifier, type));\n }\n\n isPotentialImportPhase(isExport: boolean): boolean {\n if (super.isPotentialImportPhase(isExport)) return true;\n if (this.isContextual(tt._type)) {\n if (!isExport) return true;\n const ch = this.lookaheadCharCode();\n return ch === charCodes.leftCurlyBrace || ch === charCodes.asterisk;\n }\n return !isExport && this.isContextual(tt._typeof);\n }\n\n applyImportPhase(\n node: Undone,\n isExport: boolean,\n phase: string | null,\n loc?: Position,\n ): void {\n super.applyImportPhase(node, isExport, phase, loc);\n if (isExport) {\n if (!phase && this.match(tt._default)) {\n // TODO: Align with our TS AST and always add .exportKind\n return;\n }\n (node as N.ExportNamedDeclaration).exportKind =\n phase === \"type\" ? phase : \"value\";\n } else {\n if (phase === \"type\" && this.match(tt.star)) this.unexpected();\n (node as N.ImportDeclaration).importKind =\n phase === \"type\" || phase === \"typeof\" ? phase : \"value\";\n }\n }\n\n // parse import-type/typeof shorthand\n parseImportSpecifier(\n specifier: any,\n importedIsString: boolean,\n isInTypeOnlyImport: boolean,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isMaybeTypeOnly: boolean,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bindingType: BindingFlag | undefined,\n ): N.ImportSpecifier {\n const firstIdent = specifier.imported;\n\n let specifierTypeKind = null;\n if (firstIdent.type === \"Identifier\") {\n if (firstIdent.name === \"type\") {\n specifierTypeKind = \"type\";\n } else if (firstIdent.name === \"typeof\") {\n specifierTypeKind = \"typeof\";\n }\n }\n\n let isBinding = false;\n if (this.isContextual(tt._as) && !this.isLookaheadContextual(\"as\")) {\n const as_ident = this.parseIdentifier(true);\n if (\n specifierTypeKind !== null &&\n !tokenIsKeywordOrIdentifier(this.state.type)\n ) {\n // `import {type as ,` or `import {type as }`\n specifier.imported = as_ident;\n specifier.importKind = specifierTypeKind;\n specifier.local = this.cloneIdentifier(as_ident);\n } else {\n // `import {type as foo`\n specifier.imported = firstIdent;\n specifier.importKind = null;\n specifier.local = this.parseIdentifier();\n }\n } else {\n if (\n specifierTypeKind !== null &&\n tokenIsKeywordOrIdentifier(this.state.type)\n ) {\n // `import {type foo`\n specifier.imported = this.parseIdentifier(true);\n specifier.importKind = specifierTypeKind;\n } else {\n if (importedIsString) {\n /*:: invariant(firstIdent instanceof N.StringLiteral) */\n throw this.raise(Errors.ImportBindingIsString, specifier, {\n importName: firstIdent.value,\n });\n }\n /*:: invariant(firstIdent instanceof N.Node) */\n specifier.imported = firstIdent;\n specifier.importKind = null;\n }\n\n if (this.eatContextual(tt._as)) {\n specifier.local = this.parseIdentifier();\n } else {\n isBinding = true;\n specifier.local = this.cloneIdentifier(specifier.imported);\n }\n }\n\n const specifierIsTypeImport = hasTypeImportKind(specifier);\n\n if (isInTypeOnlyImport && specifierIsTypeImport) {\n this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier);\n }\n\n if (isInTypeOnlyImport || specifierIsTypeImport) {\n this.checkReservedType(\n specifier.local.name,\n specifier.local.loc.start,\n /* declaration */ true,\n );\n }\n\n if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {\n this.checkReservedWord(\n specifier.local.name,\n specifier.loc.start,\n true,\n true,\n );\n }\n\n return this.finishImportSpecifier(specifier, \"ImportSpecifier\");\n }\n\n parseBindingAtom(): N.Pattern {\n switch (this.state.type) {\n case tt._this:\n // \"this\" may be the name of a parameter, so allow it.\n return this.parseIdentifier(/* liberal */ true);\n default:\n return super.parseBindingAtom();\n }\n }\n\n // parse function type parameters - function foo() {}\n parseFunctionParams(\n node: Undone,\n isConstructor: boolean,\n ): void {\n // @ts-expect-error kind may not index node\n const kind = node.kind;\n if (kind !== \"get\" && kind !== \"set\" && this.match(tt.lt)) {\n node.typeParameters = this.flowParseTypeParameterDeclaration();\n }\n super.parseFunctionParams(node, isConstructor);\n }\n\n // parse flow type annotations on variable declarator heads - let foo: string = bar\n parseVarId(\n decl: N.VariableDeclarator,\n kind: \"var\" | \"let\" | \"const\" | \"using\" | \"await using\",\n ): void {\n super.parseVarId(decl, kind);\n if (this.match(tt.colon)) {\n decl.id.typeAnnotation = this.flowParseTypeAnnotation();\n this.resetEndLocation(decl.id); // set end position to end of type\n }\n }\n\n // parse the return type of an async arrow function - let foo = (async (): number => {});\n parseAsyncArrowFromCallExpression(\n node: N.ArrowFunctionExpression,\n call: N.CallExpression,\n ): N.ArrowFunctionExpression {\n if (this.match(tt.colon)) {\n const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n this.state.noAnonFunctionType = true;\n node.returnType = this.flowParseTypeAnnotation();\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n }\n\n return super.parseAsyncArrowFromCallExpression(node, call);\n }\n\n // todo description\n shouldParseAsyncArrow(): boolean {\n return this.match(tt.colon) || super.shouldParseAsyncArrow();\n }\n\n // We need to support type parameter declarations for arrow functions. This\n // is tricky. There are three situations we need to handle\n //\n // 1. This is either JSX or an arrow function. We'll try JSX first. If that\n // fails, we'll try an arrow function. If that fails, we'll throw the JSX\n // error.\n // 2. This is an arrow function. We'll parse the type parameter declaration,\n // parse the rest, make sure the rest is an arrow function, and go from\n // there\n // 3. This is neither. Just call the super method\n parseMaybeAssign(\n refExpressionErrors?: ExpressionErrors | null,\n afterLeftParse?: Function,\n ): N.Expression {\n let state = null;\n\n let jsx;\n\n if (\n this.hasPlugin(\"jsx\") &&\n (this.match(tt.jsxTagStart) || this.match(tt.lt))\n ) {\n state = this.state.clone();\n\n jsx = this.tryParse(\n () => super.parseMaybeAssign(refExpressionErrors, afterLeftParse),\n state,\n );\n\n /*:: invariant(!jsx.aborted) */\n /*:: invariant(jsx.node != null) */\n if (!jsx.error) return jsx.node!;\n\n // Remove `tc.j_expr` and `tc.j_oTag` from context added\n // by parsing `jsxTagStart` to stop the JSX plugin from\n // messing with the tokens\n const { context } = this.state;\n const currentContext = context[context.length - 1];\n if (currentContext === tc.j_oTag || currentContext === tc.j_expr) {\n context.pop();\n }\n }\n\n if (jsx?.error || this.match(tt.lt)) {\n state = state || this.state.clone();\n\n let typeParameters: N.TypeParameterDeclaration;\n\n const arrow = this.tryParse((abort: () => never) => {\n typeParameters = this.flowParseTypeParameterDeclaration();\n\n const arrowExpression = this.forwardNoArrowParamsConversionAt(\n typeParameters,\n () => {\n const result = super.parseMaybeAssign(\n refExpressionErrors,\n afterLeftParse,\n );\n\n this.resetStartLocationFromNode(result, typeParameters);\n\n return result;\n },\n );\n\n // (() => {});\n // (() => {}: any);\n if (arrowExpression.extra?.parenthesized) abort();\n\n // The above can return a TypeCastExpression when the arrow\n // expression is not wrapped in parens. See also `this.parseParenItem`.\n // (() => {}: any);\n const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);\n\n if (expr.type !== \"ArrowFunctionExpression\") abort();\n\n expr.typeParameters = typeParameters;\n this.resetStartLocationFromNode(expr, typeParameters);\n\n return arrowExpression;\n }, state);\n\n let arrowExpression:\n | N.ArrowFunctionExpression\n | N.TypeCastExpression\n | undefined\n | null = null;\n\n if (\n arrow.node &&\n this.maybeUnwrapTypeCastExpression(arrow.node).type ===\n \"ArrowFunctionExpression\"\n ) {\n if (!arrow.error && !arrow.aborted) {\n // async () => {}\n // @ts-expect-error: refine tryParse typings\n if (arrow.node.async) {\n /*:: invariant(typeParameters) */\n this.raise(\n FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction,\n typeParameters!,\n );\n }\n return arrow.node;\n }\n\n // @ts-expect-error: refine typings\n arrowExpression = arrow.node;\n }\n\n // If we are here, both JSX and Flow parsing attempts failed.\n // Give the precedence to the JSX error, except if JSX had an\n // unrecoverable error while Flow didn't.\n // If the error is recoverable, we can only re-report it if there is\n // a node we can return.\n\n if (jsx?.node) {\n /*:: invariant(jsx.failState) */\n this.state = jsx.failState;\n return jsx.node;\n }\n\n if (arrowExpression) {\n /*:: invariant(arrow.failState) */\n this.state = arrow.failState!;\n return arrowExpression;\n }\n\n if (jsx?.thrown) throw jsx.error;\n if (arrow.thrown) throw arrow.error;\n\n /*:: invariant(typeParameters) */\n throw this.raise(\n FlowErrors.UnexpectedTokenAfterTypeParameter,\n typeParameters!,\n );\n }\n\n return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);\n }\n\n // handle return types for arrow functions\n parseArrow(\n node: Undone,\n ): Undone | undefined | null {\n if (this.match(tt.colon)) {\n // @ts-expect-error todo(flow->ts)\n const result = this.tryParse(() => {\n const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n this.state.noAnonFunctionType = true;\n\n const typeNode = this.startNode();\n\n [\n typeNode.typeAnnotation,\n // @ts-expect-error (destructuring not supported yet)\n node.predicate,\n ] = this.flowParseTypeAndPredicateInitialiser() as [\n N.FlowType,\n N.FlowPredicate,\n ];\n\n this.state.noAnonFunctionType = oldNoAnonFunctionType;\n\n if (this.canInsertSemicolon()) this.unexpected();\n if (!this.match(tt.arrow)) this.unexpected();\n\n return typeNode;\n });\n\n if (result.thrown) return null;\n /*:: invariant(result.node) */\n\n if (result.error) this.state = result.failState;\n\n // assign after it is clear it is an arrow\n // @ts-expect-error todo(flow->ts)\n node.returnType = result.node.typeAnnotation\n ? this.finishNode(result.node!, \"TypeAnnotation\")\n : null;\n }\n\n return super.parseArrow(node);\n }\n\n shouldParseArrow(params: N.Node[]): boolean {\n return this.match(tt.colon) || super.shouldParseArrow(params);\n }\n\n setArrowFunctionParameters(\n node: Undone,\n params:\n | (N.Expression | N.SpreadElement)[]\n | (N.Expression | N.RestElement)[],\n ): void {\n if (\n this.state.noArrowParamsConversionAt.includes(\n this.offsetToSourcePos(node.start),\n )\n ) {\n node.params = params as N.ArrowFunctionExpression[\"params\"];\n } else {\n super.setArrowFunctionParameters(node, params);\n }\n }\n\n checkParams(\n node: N.Function,\n allowDuplicates: boolean,\n isArrowFunction?: boolean | null,\n strictModeChanged: boolean = true,\n ): void {\n if (\n isArrowFunction &&\n this.state.noArrowParamsConversionAt.includes(\n this.offsetToSourcePos(node.start),\n )\n ) {\n return;\n }\n\n // ensure the `this` param is first, if it exists\n for (let i = 0; i < node.params.length; i++) {\n if (this.isThisParam(node.params[i]) && i > 0) {\n this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]);\n }\n }\n\n super.checkParams(\n node,\n allowDuplicates,\n isArrowFunction,\n strictModeChanged,\n );\n }\n\n parseParenAndDistinguishExpression(canBeArrow: boolean): N.Expression {\n return super.parseParenAndDistinguishExpression(\n canBeArrow &&\n !this.state.noArrowAt.includes(\n this.sourceToOffsetPos(this.state.start),\n ),\n );\n }\n\n parseSubscripts(\n base: N.Expression,\n startLoc: Position,\n noCalls?: boolean | null,\n ): N.Expression {\n if (\n base.type === \"Identifier\" &&\n base.name === \"async\" &&\n this.state.noArrowAt.includes(startLoc.index)\n ) {\n this.next();\n\n const node = this.startNodeAt(startLoc);\n node.callee = base;\n node.arguments = super.parseCallExpressionArguments();\n base = this.finishNode(node, \"CallExpression\");\n } else if (\n base.type === \"Identifier\" &&\n base.name === \"async\" &&\n this.match(tt.lt)\n ) {\n const state = this.state.clone();\n const arrow = this.tryParse(\n abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(),\n state,\n );\n\n /*:: invariant(arrow.node != null) */\n // @ts-expect-error: refine tryParse typings\n if (!arrow.error && !arrow.aborted) return arrow.node;\n\n const result = this.tryParse(\n () => super.parseSubscripts(base, startLoc, noCalls),\n state,\n );\n\n if (result.node && !result.error) return result.node;\n\n if (arrow.node) {\n this.state = arrow.failState;\n // @ts-expect-error: refine tryParse typings\n return arrow.node;\n }\n\n if (result.node) {\n this.state = result.failState!;\n return result.node;\n }\n\n throw arrow.error || result.error!;\n }\n\n return super.parseSubscripts(base, startLoc, noCalls);\n }\n\n parseSubscript(\n base: N.Expression,\n startLoc: Position,\n noCalls: boolean | undefined | null,\n subscriptState: N.ParseSubscriptState,\n ): N.Expression {\n if (this.match(tt.questionDot) && this.isLookaheadToken_lt()) {\n subscriptState.optionalChainMember = true;\n if (noCalls) {\n subscriptState.stop = true;\n return base;\n }\n this.next();\n const node = this.startNodeAt(startLoc);\n node.callee = base;\n node.typeArguments =\n this.flowParseTypeParameterInstantiationInExpression();\n this.expect(tt.parenL);\n node.arguments = this.parseCallExpressionArguments();\n node.optional = true;\n return this.finishCallExpression(node, /* optional */ true);\n } else if (\n !noCalls &&\n this.shouldParseTypes() &&\n (this.match(tt.lt) ||\n // also handles `new C<`\n this.match(tt.bitShiftL))\n ) {\n const node = this.startNodeAt<\n N.OptionalCallExpression | N.CallExpression\n >(startLoc);\n node.callee = base;\n\n const result = this.tryParse(() => {\n node.typeArguments =\n this.flowParseTypeParameterInstantiationCallOrNew();\n this.expect(tt.parenL);\n node.arguments = super.parseCallExpressionArguments();\n if (subscriptState.optionalChainMember) {\n (node as Undone).optional = false;\n }\n return this.finishCallExpression(\n node,\n subscriptState.optionalChainMember,\n );\n });\n\n if (result.node) {\n if (result.error) this.state = result.failState;\n return result.node;\n }\n }\n\n return super.parseSubscript(base, startLoc, noCalls, subscriptState);\n }\n\n parseNewCallee(node: N.NewExpression): void {\n super.parseNewCallee(node);\n\n let targs = null;\n if (this.shouldParseTypes() && this.match(tt.lt)) {\n targs = this.tryParse(() =>\n this.flowParseTypeParameterInstantiationCallOrNew(),\n ).node;\n }\n node.typeArguments = targs;\n }\n\n parseAsyncArrowWithTypeParameters(\n startLoc: Position,\n ): N.ArrowFunctionExpression | undefined | null {\n const node = this.startNodeAt(startLoc);\n this.parseFunctionParams(node, false);\n if (!this.parseArrow(node)) return;\n return super.parseArrowExpression(\n node,\n /* params */ undefined,\n /* isAsync */ true,\n );\n }\n\n readToken_mult_modulo(code: number): void {\n const next = this.input.charCodeAt(this.state.pos + 1);\n if (\n code === charCodes.asterisk &&\n next === charCodes.slash &&\n this.state.hasFlowComment\n ) {\n this.state.hasFlowComment = false;\n this.state.pos += 2;\n this.nextToken();\n return;\n }\n\n super.readToken_mult_modulo(code);\n }\n\n readToken_pipe_amp(code: number): void {\n const next = this.input.charCodeAt(this.state.pos + 1);\n if (\n code === charCodes.verticalBar &&\n next === charCodes.rightCurlyBrace\n ) {\n // '|}'\n this.finishOp(tt.braceBarR, 2);\n return;\n }\n\n super.readToken_pipe_amp(code);\n }\n\n parseTopLevel(file: N.File, program: N.Program): N.File {\n const fileNode = super.parseTopLevel(file, program);\n if (this.state.hasFlowComment) {\n this.raise(\n FlowErrors.UnterminatedFlowComment,\n this.state.curPosition(),\n );\n }\n return fileNode;\n }\n\n skipBlockComment(): N.CommentBlock | undefined {\n if (this.hasPlugin(\"flowComments\") && this.skipFlowComment()) {\n if (this.state.hasFlowComment) {\n throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc);\n }\n this.hasFlowCommentCompletion();\n const commentSkip = this.skipFlowComment();\n if (commentSkip) {\n this.state.pos += commentSkip;\n this.state.hasFlowComment = true;\n }\n return;\n }\n\n return super.skipBlockComment(this.state.hasFlowComment ? \"*-/\" : \"*/\");\n }\n\n skipFlowComment(): number | false {\n const { pos } = this.state;\n let shiftToFirstNonWhiteSpace = 2;\n while (\n [charCodes.space, charCodes.tab].includes(\n // @ts-expect-error testing whether a number is included\n this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace),\n )\n ) {\n shiftToFirstNonWhiteSpace++;\n }\n\n const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);\n const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);\n\n if (ch2 === charCodes.colon && ch3 === charCodes.colon) {\n return shiftToFirstNonWhiteSpace + 2; // check for /*::\n }\n if (\n this.input.slice(\n shiftToFirstNonWhiteSpace + pos,\n shiftToFirstNonWhiteSpace + pos + 12,\n ) === \"flow-include\"\n ) {\n return shiftToFirstNonWhiteSpace + 12; // check for /*flow-include\n }\n if (ch2 === charCodes.colon && ch3 !== charCodes.colon) {\n return shiftToFirstNonWhiteSpace; // check for /*:, advance up to :\n }\n return false;\n }\n\n hasFlowCommentCompletion(): void {\n const end = this.input.indexOf(\"*/\", this.state.pos);\n if (end === -1) {\n throw this.raise(Errors.UnterminatedComment, this.state.curPosition());\n }\n }\n\n // Flow enum parsing\n\n flowEnumErrorBooleanMemberNotInitialized(\n loc: Position,\n {\n enumName,\n memberName,\n }: {\n enumName: string;\n memberName: string;\n },\n ): void {\n this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, {\n memberName,\n enumName,\n });\n }\n\n flowEnumErrorInvalidMemberInitializer(\n loc: Position,\n enumContext: EnumContext,\n ) {\n return this.raise(\n !enumContext.explicitType\n ? FlowErrors.EnumInvalidMemberInitializerUnknownType\n : enumContext.explicitType === \"symbol\"\n ? FlowErrors.EnumInvalidMemberInitializerSymbolType\n : FlowErrors.EnumInvalidMemberInitializerPrimaryType,\n loc,\n enumContext,\n );\n }\n\n flowEnumErrorNumberMemberNotInitialized(\n loc: Position,\n details: {\n enumName: string;\n memberName: string;\n },\n ): void {\n this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details);\n }\n\n flowEnumErrorStringMemberInconsistentlyInitialized(\n node: N.Node,\n details: {\n enumName: string;\n },\n ): void {\n this.raise(\n FlowErrors.EnumStringMemberInconsistentlyInitialized,\n node,\n details,\n );\n }\n\n flowEnumMemberInit(): EnumMemberInit {\n const startLoc = this.state.startLoc;\n const endOfInit = () => this.match(tt.comma) || this.match(tt.braceR);\n switch (this.state.type) {\n case tt.num: {\n const literal = this.parseNumericLiteral(this.state.value);\n if (endOfInit()) {\n return { type: \"number\", loc: literal.loc.start, value: literal };\n }\n return { type: \"invalid\", loc: startLoc };\n }\n case tt.string: {\n const literal = this.parseStringLiteral(this.state.value);\n if (endOfInit()) {\n return { type: \"string\", loc: literal.loc.start, value: literal };\n }\n return { type: \"invalid\", loc: startLoc };\n }\n case tt._true:\n case tt._false: {\n const literal = this.parseBooleanLiteral(this.match(tt._true));\n if (endOfInit()) {\n return {\n type: \"boolean\",\n loc: literal.loc.start,\n value: literal,\n };\n }\n return { type: \"invalid\", loc: startLoc };\n }\n default:\n return { type: \"invalid\", loc: startLoc };\n }\n }\n\n flowEnumMemberRaw(): {\n id: N.Identifier;\n init: EnumMemberInit;\n } {\n const loc = this.state.startLoc;\n const id = this.parseIdentifier(true);\n const init = this.eat(tt.eq)\n ? this.flowEnumMemberInit()\n : { type: \"none\" as const, loc };\n return { id, init };\n }\n\n flowEnumCheckExplicitTypeMismatch(\n loc: Position,\n context: EnumContext,\n expectedType: EnumExplicitType,\n ): void {\n const { explicitType } = context;\n if (explicitType === null) {\n return;\n }\n if (explicitType !== expectedType) {\n this.flowEnumErrorInvalidMemberInitializer(loc, context);\n }\n }\n\n flowEnumMembers({\n enumName,\n explicitType,\n }: {\n enumName: string;\n explicitType: EnumExplicitType;\n }): {\n members: {\n booleanMembers: Extract<\n N.FlowEnumMember,\n { type: \"EnumBooleanMember\" }\n >[];\n numberMembers: Extract<\n N.FlowEnumMember,\n { type: \"EnumNumberMember\" }\n >[];\n stringMembers: Extract<\n N.FlowEnumMember,\n { type: \"EnumStringMember\" }\n >[];\n defaultedMembers: Extract<\n N.FlowEnumMember,\n { type: \"EnumDefaultedMember\" }\n >[];\n };\n hasUnknownMembers: boolean;\n } {\n const seenNames = new Set();\n const members = {\n booleanMembers: [],\n numberMembers: [],\n stringMembers: [],\n defaultedMembers: [],\n };\n let hasUnknownMembers = false;\n while (!this.match(tt.braceR)) {\n if (this.eat(tt.ellipsis)) {\n hasUnknownMembers = true;\n break;\n }\n const memberNode = this.startNode();\n const { id, init } = this.flowEnumMemberRaw();\n const memberName = id.name;\n if (memberName === \"\") {\n continue;\n }\n if (/^[a-z]/.test(memberName)) {\n this.raise(FlowErrors.EnumInvalidMemberName, id, {\n memberName,\n suggestion: memberName[0].toUpperCase() + memberName.slice(1),\n enumName,\n });\n }\n if (seenNames.has(memberName)) {\n this.raise(FlowErrors.EnumDuplicateMemberName, id, {\n memberName,\n enumName,\n });\n }\n seenNames.add(memberName);\n const context = { enumName, explicitType, memberName };\n memberNode.id = id;\n switch (init.type) {\n case \"boolean\": {\n this.flowEnumCheckExplicitTypeMismatch(\n init.loc,\n context,\n \"boolean\",\n );\n memberNode.init = init.value;\n members.booleanMembers.push(\n // @ts-expect-error NodeAny not supported\n this.finishNode(memberNode, \"EnumBooleanMember\"),\n );\n break;\n }\n case \"number\": {\n this.flowEnumCheckExplicitTypeMismatch(init.loc, context, \"number\");\n memberNode.init = init.value;\n members.numberMembers.push(\n // @ts-expect-error NodeAny not supported\n this.finishNode(memberNode, \"EnumNumberMember\"),\n );\n break;\n }\n case \"string\": {\n this.flowEnumCheckExplicitTypeMismatch(init.loc, context, \"string\");\n memberNode.init = init.value;\n members.stringMembers.push(\n // @ts-expect-error NodeAny not supported\n this.finishNode(memberNode, \"EnumStringMember\"),\n );\n break;\n }\n case \"invalid\": {\n throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);\n }\n case \"none\": {\n switch (explicitType) {\n case \"boolean\":\n this.flowEnumErrorBooleanMemberNotInitialized(\n init.loc,\n context,\n );\n break;\n case \"number\":\n this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);\n break;\n default:\n members.defaultedMembers.push(\n // @ts-expect-error NodeAny not supported\n this.finishNode(memberNode, \"EnumDefaultedMember\"),\n );\n }\n }\n }\n\n if (!this.match(tt.braceR)) {\n this.expect(tt.comma);\n }\n }\n return { members, hasUnknownMembers };\n }\n\n flowEnumStringMembers(\n initializedMembers: N.Node[],\n defaultedMembers: N.Node[],\n {\n enumName,\n }: {\n enumName: string;\n },\n ): N.Node[] {\n if (initializedMembers.length === 0) {\n return defaultedMembers;\n } else if (defaultedMembers.length === 0) {\n return initializedMembers;\n } else if (defaultedMembers.length > initializedMembers.length) {\n for (const member of initializedMembers) {\n this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {\n enumName,\n });\n }\n return defaultedMembers;\n } else {\n for (const member of defaultedMembers) {\n this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {\n enumName,\n });\n }\n return initializedMembers;\n }\n }\n\n flowEnumParseExplicitType({\n enumName,\n }: {\n enumName: string;\n }): EnumExplicitType {\n if (!this.eatContextual(tt._of)) return null;\n\n if (!tokenIsIdentifier(this.state.type)) {\n throw this.raise(\n FlowErrors.EnumInvalidExplicitTypeUnknownSupplied,\n this.state.startLoc,\n {\n enumName,\n },\n );\n }\n\n const { value } = this.state;\n this.next();\n\n if (\n value !== \"boolean\" &&\n value !== \"number\" &&\n value !== \"string\" &&\n value !== \"symbol\"\n ) {\n this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, {\n enumName,\n invalidEnumType: value,\n });\n }\n\n return value;\n }\n\n flowEnumBody(node: Undone, id: N.Identifier): N.Node {\n const enumName = id.name;\n const nameLoc = id.loc.start;\n const explicitType = this.flowEnumParseExplicitType({ enumName });\n this.expect(tt.braceL);\n const { members, hasUnknownMembers } = this.flowEnumMembers({\n enumName,\n explicitType,\n });\n node.hasUnknownMembers = hasUnknownMembers;\n\n switch (explicitType) {\n case \"boolean\":\n node.explicitType = true;\n node.members = members.booleanMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumBooleanBody\");\n case \"number\":\n node.explicitType = true;\n node.members = members.numberMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumNumberBody\");\n case \"string\":\n node.explicitType = true;\n node.members = this.flowEnumStringMembers(\n members.stringMembers,\n members.defaultedMembers,\n { enumName },\n );\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumStringBody\");\n case \"symbol\":\n node.members = members.defaultedMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumSymbolBody\");\n default: {\n // `explicitType` is `null`\n const empty = () => {\n node.members = [];\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumStringBody\");\n };\n node.explicitType = false;\n\n const boolsLen = members.booleanMembers.length;\n const numsLen = members.numberMembers.length;\n const strsLen = members.stringMembers.length;\n const defaultedLen = members.defaultedMembers.length;\n\n if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {\n return empty();\n } else if (!boolsLen && !numsLen) {\n node.members = this.flowEnumStringMembers(\n members.stringMembers,\n members.defaultedMembers,\n { enumName },\n );\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumStringBody\");\n } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {\n for (const member of members.defaultedMembers) {\n this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {\n enumName,\n memberName: member.id.name,\n });\n }\n node.members = members.booleanMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumBooleanBody\");\n } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {\n for (const member of members.defaultedMembers) {\n this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {\n enumName,\n memberName: member.id.name,\n });\n }\n node.members = members.numberMembers;\n this.expect(tt.braceR);\n return this.finishNode(node, \"EnumNumberBody\");\n } else {\n this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, {\n enumName,\n });\n return empty();\n }\n }\n }\n }\n\n flowParseEnumDeclaration(\n node: Undone,\n ): N.FlowEnumDeclaration {\n const id = this.parseIdentifier();\n node.id = id;\n node.body = this.flowEnumBody(this.startNode(), id);\n return this.finishNode(node, \"EnumDeclaration\");\n }\n\n jsxParseOpeningElementAfterName(\n node: N.JSXOpeningElement,\n ): N.JSXOpeningElement {\n if (this.shouldParseTypes()) {\n if (this.match(tt.lt) || this.match(tt.bitShiftL)) {\n node.typeArguments =\n this.flowParseTypeParameterInstantiationInExpression();\n }\n }\n\n return super.jsxParseOpeningElementAfterName(node);\n }\n\n // check if the next token is a tt.lt\n isLookaheadToken_lt(): boolean {\n const next = this.nextTokenStart();\n if (this.input.charCodeAt(next) === charCodes.lessThan) {\n const afterNext = this.input.charCodeAt(next + 1);\n return (\n afterNext !== charCodes.lessThan && afterNext !== charCodes.equalsTo\n );\n }\n return false;\n }\n\n // used after we have finished parsing types\n reScan_lt_gt() {\n const { type } = this.state;\n if (type === tt.lt) {\n this.state.pos -= 1;\n this.readToken_lt();\n } else if (type === tt.gt) {\n this.state.pos -= 1;\n this.readToken_gt();\n }\n }\n\n reScan_lt() {\n const { type } = this.state;\n if (type === tt.bitShiftL) {\n this.state.pos -= 2;\n this.finishOp(tt.lt, 1);\n return tt.lt;\n }\n return type;\n }\n\n maybeUnwrapTypeCastExpression(node: N.Node) {\n return node.type === \"TypeCastExpression\" ? node.expression : node;\n }\n };\n","const entities: Record = {\n // @ts-expect-error __proto__ is not an actual property: https://github.com/microsoft/TypeScript/issues/38385\n __proto__: null,\n quot: \"\\u0022\",\n amp: \"&\",\n apos: \"\\u0027\",\n lt: \"<\",\n gt: \">\",\n nbsp: \"\\u00A0\",\n iexcl: \"\\u00A1\",\n cent: \"\\u00A2\",\n pound: \"\\u00A3\",\n curren: \"\\u00A4\",\n yen: \"\\u00A5\",\n brvbar: \"\\u00A6\",\n sect: \"\\u00A7\",\n uml: \"\\u00A8\",\n copy: \"\\u00A9\",\n ordf: \"\\u00AA\",\n laquo: \"\\u00AB\",\n not: \"\\u00AC\",\n shy: \"\\u00AD\",\n reg: \"\\u00AE\",\n macr: \"\\u00AF\",\n deg: \"\\u00B0\",\n plusmn: \"\\u00B1\",\n sup2: \"\\u00B2\",\n sup3: \"\\u00B3\",\n acute: \"\\u00B4\",\n micro: \"\\u00B5\",\n para: \"\\u00B6\",\n middot: \"\\u00B7\",\n cedil: \"\\u00B8\",\n sup1: \"\\u00B9\",\n ordm: \"\\u00BA\",\n raquo: \"\\u00BB\",\n frac14: \"\\u00BC\",\n frac12: \"\\u00BD\",\n frac34: \"\\u00BE\",\n iquest: \"\\u00BF\",\n Agrave: \"\\u00C0\",\n Aacute: \"\\u00C1\",\n Acirc: \"\\u00C2\",\n Atilde: \"\\u00C3\",\n Auml: \"\\u00C4\",\n Aring: \"\\u00C5\",\n AElig: \"\\u00C6\",\n Ccedil: \"\\u00C7\",\n Egrave: \"\\u00C8\",\n Eacute: \"\\u00C9\",\n Ecirc: \"\\u00CA\",\n Euml: \"\\u00CB\",\n Igrave: \"\\u00CC\",\n Iacute: \"\\u00CD\",\n Icirc: \"\\u00CE\",\n Iuml: \"\\u00CF\",\n ETH: \"\\u00D0\",\n Ntilde: \"\\u00D1\",\n Ograve: \"\\u00D2\",\n Oacute: \"\\u00D3\",\n Ocirc: \"\\u00D4\",\n Otilde: \"\\u00D5\",\n Ouml: \"\\u00D6\",\n times: \"\\u00D7\",\n Oslash: \"\\u00D8\",\n Ugrave: \"\\u00D9\",\n Uacute: \"\\u00DA\",\n Ucirc: \"\\u00DB\",\n Uuml: \"\\u00DC\",\n Yacute: \"\\u00DD\",\n THORN: \"\\u00DE\",\n szlig: \"\\u00DF\",\n agrave: \"\\u00E0\",\n aacute: \"\\u00E1\",\n acirc: \"\\u00E2\",\n atilde: \"\\u00E3\",\n auml: \"\\u00E4\",\n aring: \"\\u00E5\",\n aelig: \"\\u00E6\",\n ccedil: \"\\u00E7\",\n egrave: \"\\u00E8\",\n eacute: \"\\u00E9\",\n ecirc: \"\\u00EA\",\n euml: \"\\u00EB\",\n igrave: \"\\u00EC\",\n iacute: \"\\u00ED\",\n icirc: \"\\u00EE\",\n iuml: \"\\u00EF\",\n eth: \"\\u00F0\",\n ntilde: \"\\u00F1\",\n ograve: \"\\u00F2\",\n oacute: \"\\u00F3\",\n ocirc: \"\\u00F4\",\n otilde: \"\\u00F5\",\n ouml: \"\\u00F6\",\n divide: \"\\u00F7\",\n oslash: \"\\u00F8\",\n ugrave: \"\\u00F9\",\n uacute: \"\\u00FA\",\n ucirc: \"\\u00FB\",\n uuml: \"\\u00FC\",\n yacute: \"\\u00FD\",\n thorn: \"\\u00FE\",\n yuml: \"\\u00FF\",\n OElig: \"\\u0152\",\n oelig: \"\\u0153\",\n Scaron: \"\\u0160\",\n scaron: \"\\u0161\",\n Yuml: \"\\u0178\",\n fnof: \"\\u0192\",\n circ: \"\\u02C6\",\n tilde: \"\\u02DC\",\n Alpha: \"\\u0391\",\n Beta: \"\\u0392\",\n Gamma: \"\\u0393\",\n Delta: \"\\u0394\",\n Epsilon: \"\\u0395\",\n Zeta: \"\\u0396\",\n Eta: \"\\u0397\",\n Theta: \"\\u0398\",\n Iota: \"\\u0399\",\n Kappa: \"\\u039A\",\n Lambda: \"\\u039B\",\n Mu: \"\\u039C\",\n Nu: \"\\u039D\",\n Xi: \"\\u039E\",\n Omicron: \"\\u039F\",\n Pi: \"\\u03A0\",\n Rho: \"\\u03A1\",\n Sigma: \"\\u03A3\",\n Tau: \"\\u03A4\",\n Upsilon: \"\\u03A5\",\n Phi: \"\\u03A6\",\n Chi: \"\\u03A7\",\n Psi: \"\\u03A8\",\n Omega: \"\\u03A9\",\n alpha: \"\\u03B1\",\n beta: \"\\u03B2\",\n gamma: \"\\u03B3\",\n delta: \"\\u03B4\",\n epsilon: \"\\u03B5\",\n zeta: \"\\u03B6\",\n eta: \"\\u03B7\",\n theta: \"\\u03B8\",\n iota: \"\\u03B9\",\n kappa: \"\\u03BA\",\n lambda: \"\\u03BB\",\n mu: \"\\u03BC\",\n nu: \"\\u03BD\",\n xi: \"\\u03BE\",\n omicron: \"\\u03BF\",\n pi: \"\\u03C0\",\n rho: \"\\u03C1\",\n sigmaf: \"\\u03C2\",\n sigma: \"\\u03C3\",\n tau: \"\\u03C4\",\n upsilon: \"\\u03C5\",\n phi: \"\\u03C6\",\n chi: \"\\u03C7\",\n psi: \"\\u03C8\",\n omega: \"\\u03C9\",\n thetasym: \"\\u03D1\",\n upsih: \"\\u03D2\",\n piv: \"\\u03D6\",\n ensp: \"\\u2002\",\n emsp: \"\\u2003\",\n thinsp: \"\\u2009\",\n zwnj: \"\\u200C\",\n zwj: \"\\u200D\",\n lrm: \"\\u200E\",\n rlm: \"\\u200F\",\n ndash: \"\\u2013\",\n mdash: \"\\u2014\",\n lsquo: \"\\u2018\",\n rsquo: \"\\u2019\",\n sbquo: \"\\u201A\",\n ldquo: \"\\u201C\",\n rdquo: \"\\u201D\",\n bdquo: \"\\u201E\",\n dagger: \"\\u2020\",\n Dagger: \"\\u2021\",\n bull: \"\\u2022\",\n hellip: \"\\u2026\",\n permil: \"\\u2030\",\n prime: \"\\u2032\",\n Prime: \"\\u2033\",\n lsaquo: \"\\u2039\",\n rsaquo: \"\\u203A\",\n oline: \"\\u203E\",\n frasl: \"\\u2044\",\n euro: \"\\u20AC\",\n image: \"\\u2111\",\n weierp: \"\\u2118\",\n real: \"\\u211C\",\n trade: \"\\u2122\",\n alefsym: \"\\u2135\",\n larr: \"\\u2190\",\n uarr: \"\\u2191\",\n rarr: \"\\u2192\",\n darr: \"\\u2193\",\n harr: \"\\u2194\",\n crarr: \"\\u21B5\",\n lArr: \"\\u21D0\",\n uArr: \"\\u21D1\",\n rArr: \"\\u21D2\",\n dArr: \"\\u21D3\",\n hArr: \"\\u21D4\",\n forall: \"\\u2200\",\n part: \"\\u2202\",\n exist: \"\\u2203\",\n empty: \"\\u2205\",\n nabla: \"\\u2207\",\n isin: \"\\u2208\",\n notin: \"\\u2209\",\n ni: \"\\u220B\",\n prod: \"\\u220F\",\n sum: \"\\u2211\",\n minus: \"\\u2212\",\n lowast: \"\\u2217\",\n radic: \"\\u221A\",\n prop: \"\\u221D\",\n infin: \"\\u221E\",\n ang: \"\\u2220\",\n and: \"\\u2227\",\n or: \"\\u2228\",\n cap: \"\\u2229\",\n cup: \"\\u222A\",\n int: \"\\u222B\",\n there4: \"\\u2234\",\n sim: \"\\u223C\",\n cong: \"\\u2245\",\n asymp: \"\\u2248\",\n ne: \"\\u2260\",\n equiv: \"\\u2261\",\n le: \"\\u2264\",\n ge: \"\\u2265\",\n sub: \"\\u2282\",\n sup: \"\\u2283\",\n nsub: \"\\u2284\",\n sube: \"\\u2286\",\n supe: \"\\u2287\",\n oplus: \"\\u2295\",\n otimes: \"\\u2297\",\n perp: \"\\u22A5\",\n sdot: \"\\u22C5\",\n lceil: \"\\u2308\",\n rceil: \"\\u2309\",\n lfloor: \"\\u230A\",\n rfloor: \"\\u230B\",\n lang: \"\\u2329\",\n rang: \"\\u232A\",\n loz: \"\\u25CA\",\n spades: \"\\u2660\",\n clubs: \"\\u2663\",\n hearts: \"\\u2665\",\n diams: \"\\u2666\",\n} as const;\nexport default entities;\n","import * as charCodes from \"charcodes\";\n\n// Matches a whole line break (where CRLF is considered a single\n// line break). Used to count lines.\nexport const lineBreak = /\\r\\n|[\\r\\n\\u2028\\u2029]/;\nexport const lineBreakG = new RegExp(lineBreak.source, \"g\");\n\n// https://tc39.github.io/ecma262/#sec-line-terminators\nexport function isNewLine(code: number): boolean {\n switch (code) {\n case charCodes.lineFeed:\n case charCodes.carriageReturn:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return true;\n\n default:\n return false;\n }\n}\n\nexport function hasNewLine(input: string, start: number, end: number): boolean {\n for (let i = start; i < end; i++) {\n if (isNewLine(input.charCodeAt(i))) {\n return true;\n }\n }\n return false;\n}\n\nexport const skipWhiteSpace = /(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g;\n\nexport const skipWhiteSpaceInLine =\n /(?:[^\\S\\n\\r\\u2028\\u2029]|\\/\\/.*|\\/\\*.*?\\*\\/)*/g;\n\n// https://tc39.github.io/ecma262/#sec-white-space\nexport function isWhitespace(code: number): boolean {\n switch (code) {\n case 0x0009: // CHARACTER TABULATION\n case 0x000b: // LINE TABULATION\n case 0x000c: // FORM FEED\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.oghamSpaceMark:\n case 0x2000: // EN QUAD\n case 0x2001: // EM QUAD\n case 0x2002: // EN SPACE\n case 0x2003: // EM SPACE\n case 0x2004: // THREE-PER-EM SPACE\n case 0x2005: // FOUR-PER-EM SPACE\n case 0x2006: // SIX-PER-EM SPACE\n case 0x2007: // FIGURE SPACE\n case 0x2008: // PUNCTUATION SPACE\n case 0x2009: // THIN SPACE\n case 0x200a: // HAIR SPACE\n case 0x202f: // NARROW NO-BREAK SPACE\n case 0x205f: // MEDIUM MATHEMATICAL SPACE\n case 0x3000: // IDEOGRAPHIC SPACE\n case 0xfeff: // ZERO WIDTH NO-BREAK SPACE\n return true;\n\n default:\n return false;\n }\n}\n","import * as charCodes from \"charcodes\";\n\nimport XHTMLEntities from \"./xhtml.ts\";\nimport type Parser from \"../../parser/index.ts\";\nimport type { ExpressionErrors } from \"../../parser/util.ts\";\nimport {\n tokenComesBeforeExpression,\n tokenIsKeyword,\n tokenLabelName,\n type TokenType,\n tt,\n} from \"../../tokenizer/types.ts\";\nimport type { TokContext } from \"../../tokenizer/context.ts\";\nimport { types as tc } from \"../../tokenizer/context.ts\";\nimport type * as N from \"../../types.ts\";\nimport { isIdentifierChar, isIdentifierStart } from \"../../util/identifier.ts\";\nimport type { Position } from \"../../util/location.ts\";\nimport { isNewLine } from \"../../util/whitespace.ts\";\nimport { Errors, ParseErrorEnum } from \"../../parse-error.ts\";\nimport type { Undone } from \"../../parser/node.ts\";\n\n/* eslint sort-keys: \"error\" */\nconst JsxErrors = ParseErrorEnum`jsx`({\n AttributeIsEmpty:\n \"JSX attributes must only be assigned a non-empty expression.\",\n MissingClosingTagElement: ({ openingTagName }: { openingTagName: string }) =>\n `Expected corresponding JSX closing tag for <${openingTagName}>.`,\n MissingClosingTagFragment: \"Expected corresponding JSX closing tag for <>.\",\n UnexpectedSequenceExpression:\n \"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?\",\n // FIXME: Unify with Errors.UnexpectedToken\n UnexpectedToken: ({\n unexpected,\n HTMLEntity,\n }: {\n unexpected: string;\n HTMLEntity: string;\n }) =>\n `Unexpected token \\`${unexpected}\\`. Did you mean \\`${HTMLEntity}\\` or \\`{'${unexpected}'}\\`?`,\n UnsupportedJsxValue:\n \"JSX value should be either an expression or a quoted JSX text.\",\n UnterminatedJsxContent: \"Unterminated JSX contents.\",\n UnwrappedAdjacentJSXElements:\n \"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?\",\n});\n\n/* eslint-disable sort-keys */\n\nfunction isFragment(object?: N.JSXTag | null): object is N.JSXFragmentTag {\n return object\n ? object.type === \"JSXOpeningFragment\" ||\n object.type === \"JSXClosingFragment\"\n : false;\n}\n\n// Transforms JSX element name to string.\n\nfunction getQualifiedJSXName(\n object: N.JSXIdentifier | N.JSXNamespacedName | N.JSXMemberExpression,\n): string {\n if (object.type === \"JSXIdentifier\") {\n return object.name;\n }\n\n if (object.type === \"JSXNamespacedName\") {\n return object.namespace.name + \":\" + object.name.name;\n }\n\n if (object.type === \"JSXMemberExpression\") {\n return (\n getQualifiedJSXName(object.object) +\n \".\" +\n getQualifiedJSXName(object.property)\n );\n }\n\n // istanbul ignore next\n // @ts-expect-error - object is 'never'\n throw new Error(\"Node had unexpected type: \" + object.type);\n}\n\nexport interface IJSXParserMixin {\n jsxParseOpeningElementAfterName(\n node: N.JSXOpeningElement,\n ): N.JSXOpeningElement;\n}\n\nexport type ClassWithMixin<\n T extends new (...args: any) => any,\n M extends object,\n> = T extends new (...args: infer P) => infer I\n ? new (...args: P) => I & M\n : never;\n\nexport default (superClass: typeof Parser) =>\n class JSXParserMixin extends superClass implements Parser, IJSXParserMixin {\n // Reads inline JSX contents token.\n\n jsxReadToken(): void {\n let out = \"\";\n let chunkStart = this.state.pos;\n for (;;) {\n if (this.state.pos >= this.length) {\n throw this.raise(\n JsxErrors.UnterminatedJsxContent,\n this.state.startLoc,\n );\n }\n\n const ch = this.input.charCodeAt(this.state.pos);\n\n switch (ch) {\n case charCodes.lessThan:\n case charCodes.leftCurlyBrace:\n if (this.state.pos === this.state.start) {\n if (ch === charCodes.lessThan && this.state.canStartJSXElement) {\n ++this.state.pos;\n this.finishToken(tt.jsxTagStart);\n } else {\n super.getTokenFromCode(ch);\n }\n return;\n }\n out += this.input.slice(chunkStart, this.state.pos);\n this.finishToken(tt.jsxText, out);\n return;\n\n case charCodes.ampersand:\n out += this.input.slice(chunkStart, this.state.pos);\n out += this.jsxReadEntity();\n chunkStart = this.state.pos;\n break;\n\n case charCodes.greaterThan:\n case charCodes.rightCurlyBrace:\n if (process.env.BABEL_8_BREAKING) {\n this.raise(JsxErrors.UnexpectedToken, this.state.curPosition(), {\n unexpected: this.input[this.state.pos],\n HTMLEntity:\n ch === charCodes.rightCurlyBrace ? \"}\" : \">\",\n });\n }\n /* falls through */\n\n default:\n if (isNewLine(ch)) {\n out += this.input.slice(chunkStart, this.state.pos);\n out += this.jsxReadNewLine(true);\n chunkStart = this.state.pos;\n } else {\n ++this.state.pos;\n }\n }\n }\n }\n\n jsxReadNewLine(normalizeCRLF: boolean): string {\n const ch = this.input.charCodeAt(this.state.pos);\n let out;\n ++this.state.pos;\n if (\n ch === charCodes.carriageReturn &&\n this.input.charCodeAt(this.state.pos) === charCodes.lineFeed\n ) {\n ++this.state.pos;\n out = normalizeCRLF ? \"\\n\" : \"\\r\\n\";\n } else {\n out = String.fromCharCode(ch);\n }\n ++this.state.curLine;\n this.state.lineStart = this.state.pos;\n\n return out;\n }\n\n jsxReadString(quote: number): void {\n let out = \"\";\n let chunkStart = ++this.state.pos;\n for (;;) {\n if (this.state.pos >= this.length) {\n throw this.raise(Errors.UnterminatedString, this.state.startLoc);\n }\n\n const ch = this.input.charCodeAt(this.state.pos);\n if (ch === quote) break;\n if (ch === charCodes.ampersand) {\n out += this.input.slice(chunkStart, this.state.pos);\n out += this.jsxReadEntity();\n chunkStart = this.state.pos;\n } else if (isNewLine(ch)) {\n out += this.input.slice(chunkStart, this.state.pos);\n out += this.jsxReadNewLine(false);\n chunkStart = this.state.pos;\n } else {\n ++this.state.pos;\n }\n }\n out += this.input.slice(chunkStart, this.state.pos++);\n this.finishToken(tt.string, out);\n }\n\n jsxReadEntity(): string {\n const startPos = ++this.state.pos;\n if (this.codePointAtPos(this.state.pos) === charCodes.numberSign) {\n ++this.state.pos;\n\n let radix = 10;\n if (this.codePointAtPos(this.state.pos) === charCodes.lowercaseX) {\n radix = 16;\n ++this.state.pos;\n }\n\n const codePoint = this.readInt(\n radix,\n /* len */ undefined,\n /* forceLen */ false,\n /* allowNumSeparator */ \"bail\",\n );\n if (\n codePoint !== null &&\n this.codePointAtPos(this.state.pos) === charCodes.semicolon\n ) {\n ++this.state.pos;\n return String.fromCodePoint(codePoint);\n }\n } else {\n let count = 0;\n let semi = false;\n while (\n count++ < 10 &&\n this.state.pos < this.length &&\n !(semi = this.codePointAtPos(this.state.pos) === charCodes.semicolon)\n ) {\n ++this.state.pos;\n }\n\n if (semi) {\n const desc = this.input.slice(startPos, this.state.pos);\n const entity = XHTMLEntities[desc];\n ++this.state.pos;\n\n if (entity) {\n return entity;\n }\n }\n }\n\n // Not a valid entity\n this.state.pos = startPos;\n return \"&\";\n }\n\n // Read a JSX identifier (valid tag or attribute name).\n //\n // Optimized version since JSX identifiers can\"t contain\n // escape characters and so can be read as single slice.\n // Also assumes that first character was already checked\n // by isIdentifierStart in readToken.\n\n jsxReadWord(): void {\n let ch;\n const start = this.state.pos;\n do {\n ch = this.input.charCodeAt(++this.state.pos);\n } while (isIdentifierChar(ch) || ch === charCodes.dash);\n this.finishToken(tt.jsxName, this.input.slice(start, this.state.pos));\n }\n\n // Parse next token as JSX identifier\n\n jsxParseIdentifier(): N.JSXIdentifier {\n const node = this.startNode();\n if (this.match(tt.jsxName)) {\n node.name = this.state.value;\n } else if (tokenIsKeyword(this.state.type)) {\n node.name = tokenLabelName(this.state.type);\n } else {\n this.unexpected();\n }\n this.next();\n return this.finishNode(node, \"JSXIdentifier\");\n }\n\n // Parse namespaced identifier.\n\n jsxParseNamespacedName(): N.JSXNamespacedName | N.JSXIdentifier {\n const startLoc = this.state.startLoc;\n const name = this.jsxParseIdentifier();\n if (!this.eat(tt.colon)) return name;\n\n const node = this.startNodeAt(startLoc);\n node.namespace = name;\n node.name = this.jsxParseIdentifier();\n return this.finishNode(node, \"JSXNamespacedName\");\n }\n\n // Parses element name in any form - namespaced, member\n // or single identifier.\n\n jsxParseElementName():\n | N.JSXIdentifier\n | N.JSXNamespacedName\n | N.JSXMemberExpression {\n const startLoc = this.state.startLoc;\n let node: N.JSXIdentifier | N.JSXNamespacedName | N.JSXMemberExpression =\n this.jsxParseNamespacedName();\n if (node.type === \"JSXNamespacedName\") {\n return node;\n }\n while (this.eat(tt.dot)) {\n const newNode = this.startNodeAt(startLoc);\n newNode.object = node;\n newNode.property = this.jsxParseIdentifier();\n node = this.finishNode(newNode, \"JSXMemberExpression\");\n }\n return node;\n }\n\n // Parses any type of JSX attribute value.\n\n jsxParseAttributeValue():\n | N.JSXExpressionContainer\n | N.JSXElement\n | N.StringLiteral {\n let node;\n switch (this.state.type) {\n case tt.braceL:\n node = this.startNode();\n this.setContext(tc.brace);\n this.next();\n node = this.jsxParseExpressionContainer(node, tc.j_oTag);\n if (node.expression.type === \"JSXEmptyExpression\") {\n this.raise(JsxErrors.AttributeIsEmpty, node);\n }\n return node;\n\n case tt.jsxTagStart:\n case tt.string:\n return this.parseExprAtom() as N.JSXElement | N.StringLiteral;\n\n default:\n throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc);\n }\n }\n\n // JSXEmptyExpression is unique type since it doesn't actually parse anything,\n // and so it should start at the end of last read token (left brace) and finish\n // at the beginning of the next one (right brace).\n\n jsxParseEmptyExpression(): N.JSXEmptyExpression {\n const node = this.startNodeAt(this.state.lastTokEndLoc!);\n return this.finishNodeAt(node, \"JSXEmptyExpression\", this.state.startLoc);\n }\n\n // Parse JSX spread child\n\n jsxParseSpreadChild(node: Undone): N.JSXSpreadChild {\n this.next(); // ellipsis\n node.expression = this.parseExpression();\n this.setContext(tc.j_expr);\n this.state.canStartJSXElement = true;\n this.expect(tt.braceR);\n\n return this.finishNode(node, \"JSXSpreadChild\");\n }\n\n // Parses JSX expression enclosed into curly brackets.\n\n jsxParseExpressionContainer(\n node: Undone,\n previousContext: TokContext,\n ): N.JSXExpressionContainer {\n if (this.match(tt.braceR)) {\n node.expression = this.jsxParseEmptyExpression();\n } else {\n const expression = this.parseExpression();\n\n if (process.env.BABEL_8_BREAKING) {\n if (\n expression.type === \"SequenceExpression\" &&\n !expression.extra?.parenthesized\n ) {\n this.raise(\n JsxErrors.UnexpectedSequenceExpression,\n expression.expressions[1],\n );\n }\n }\n\n node.expression = expression;\n }\n this.setContext(previousContext);\n this.state.canStartJSXElement = true;\n this.expect(tt.braceR);\n\n return this.finishNode(node, \"JSXExpressionContainer\");\n }\n\n // Parses following JSX attribute name-value pair.\n\n jsxParseAttribute(): N.JSXAttribute | N.JSXSpreadAttribute {\n const node = this.startNode();\n if (this.match(tt.braceL)) {\n this.setContext(tc.brace);\n this.next();\n this.expect(tt.ellipsis);\n node.argument = this.parseMaybeAssignAllowIn();\n this.setContext(tc.j_oTag);\n this.state.canStartJSXElement = true;\n this.expect(tt.braceR);\n return this.finishNode(node, \"JSXSpreadAttribute\");\n }\n node.name = this.jsxParseNamespacedName();\n node.value = this.eat(tt.eq) ? this.jsxParseAttributeValue() : null;\n return this.finishNode(node, \"JSXAttribute\");\n }\n\n // Parses JSX opening tag starting after \"<\".\n\n jsxParseOpeningElementAt(\n startLoc: Position,\n ): N.JSXOpeningElement | N.JSXOpeningFragment {\n const node = this.startNodeAt(\n startLoc,\n );\n if (this.eat(tt.jsxTagEnd)) {\n return this.finishNode(node, \"JSXOpeningFragment\");\n }\n node.name = this.jsxParseElementName();\n return this.jsxParseOpeningElementAfterName(\n node as Undone,\n );\n }\n\n jsxParseOpeningElementAfterName(\n node: Undone,\n ): N.JSXOpeningElement {\n const attributes: (N.JSXAttribute | N.JSXSpreadAttribute)[] = [];\n while (!this.match(tt.slash) && !this.match(tt.jsxTagEnd)) {\n attributes.push(this.jsxParseAttribute());\n }\n node.attributes = attributes;\n node.selfClosing = this.eat(tt.slash);\n this.expect(tt.jsxTagEnd);\n return this.finishNode(node, \"JSXOpeningElement\");\n }\n\n // Parses JSX closing tag starting after \"(\n startLoc,\n );\n if (this.eat(tt.jsxTagEnd)) {\n return this.finishNode(node, \"JSXClosingFragment\");\n }\n node.name = this.jsxParseElementName();\n this.expect(tt.jsxTagEnd);\n return this.finishNode(node, \"JSXClosingElement\");\n }\n\n // Parses entire JSX element, including it\"s opening tag\n // (starting after \"<\"), attributes, contents and closing tag.\n\n jsxParseElementAt(startLoc: Position): N.JSXElement | N.JSXFragment {\n const node = this.startNodeAt(startLoc);\n const children = [];\n const openingElement = this.jsxParseOpeningElementAt(startLoc);\n let closingElement = null;\n\n if (!openingElement.selfClosing) {\n contents: for (;;) {\n switch (this.state.type) {\n case tt.jsxTagStart:\n startLoc = this.state.startLoc;\n this.next();\n if (this.eat(tt.slash)) {\n closingElement = this.jsxParseClosingElementAt(startLoc);\n break contents;\n }\n children.push(this.jsxParseElementAt(startLoc));\n break;\n\n case tt.jsxText:\n children.push(this.parseLiteral(this.state.value, \"JSXText\"));\n break;\n\n case tt.braceL: {\n const node = this.startNode<\n N.JSXSpreadChild | N.JSXExpressionContainer\n >();\n this.setContext(tc.brace);\n this.next();\n if (this.match(tt.ellipsis)) {\n children.push(this.jsxParseSpreadChild(node));\n } else {\n children.push(\n this.jsxParseExpressionContainer(node, tc.j_expr),\n );\n }\n\n break;\n }\n // istanbul ignore next - should never happen\n default:\n this.unexpected();\n }\n }\n\n if (\n isFragment(openingElement) &&\n !isFragment(closingElement) &&\n closingElement !== null\n ) {\n this.raise(JsxErrors.MissingClosingTagFragment, closingElement);\n } else if (!isFragment(openingElement) && isFragment(closingElement)) {\n this.raise(JsxErrors.MissingClosingTagElement, closingElement, {\n openingTagName: getQualifiedJSXName(openingElement.name),\n });\n } else if (!isFragment(openingElement) && !isFragment(closingElement)) {\n if (\n getQualifiedJSXName(closingElement.name) !==\n getQualifiedJSXName(openingElement.name)\n ) {\n this.raise(JsxErrors.MissingClosingTagElement, closingElement, {\n openingTagName: getQualifiedJSXName(openingElement.name),\n });\n }\n }\n }\n\n if (isFragment(openingElement)) {\n node.openingFragment = openingElement;\n node.closingFragment = closingElement;\n } else {\n node.openingElement = openingElement;\n node.closingElement = closingElement;\n }\n node.children = children;\n if (this.match(tt.lt)) {\n throw this.raise(\n JsxErrors.UnwrappedAdjacentJSXElements,\n this.state.startLoc,\n );\n }\n\n return isFragment(openingElement)\n ? this.finishNode(node, \"JSXFragment\")\n : this.finishNode(node, \"JSXElement\");\n }\n\n // Parses entire JSX element from current position.\n\n jsxParseElement(): N.JSXElement | N.JSXFragment {\n const startLoc = this.state.startLoc;\n this.next();\n return this.jsxParseElementAt(startLoc);\n }\n\n setContext(newContext: TokContext) {\n const { context } = this.state;\n context[context.length - 1] = newContext;\n }\n\n // ==================================\n // Overrides\n // ==================================\n\n parseExprAtom(refExpressionErrors?: ExpressionErrors | null): N.Expression {\n if (this.match(tt.jsxTagStart)) {\n return this.jsxParseElement();\n } else if (\n this.match(tt.lt) &&\n this.input.charCodeAt(this.state.pos) !== charCodes.exclamationMark\n ) {\n // In case we encounter an lt token here it will always be the start of\n // jsx as the lt sign is not allowed in places that expect an expression\n this.replaceToken(tt.jsxTagStart);\n return this.jsxParseElement();\n } else {\n return super.parseExprAtom(refExpressionErrors);\n }\n }\n\n skipSpace() {\n const curContext = this.curContext();\n if (!curContext.preserveSpace) super.skipSpace();\n }\n\n getTokenFromCode(code: number): void {\n const context = this.curContext();\n\n if (context === tc.j_expr) {\n this.jsxReadToken();\n return;\n }\n\n if (context === tc.j_oTag || context === tc.j_cTag) {\n if (isIdentifierStart(code)) {\n this.jsxReadWord();\n return;\n }\n\n if (code === charCodes.greaterThan) {\n ++this.state.pos;\n this.finishToken(tt.jsxTagEnd);\n return;\n }\n\n if (\n (code === charCodes.quotationMark || code === charCodes.apostrophe) &&\n context === tc.j_oTag\n ) {\n this.jsxReadString(code);\n return;\n }\n }\n\n if (\n code === charCodes.lessThan &&\n this.state.canStartJSXElement &&\n this.input.charCodeAt(this.state.pos + 1) !== charCodes.exclamationMark\n ) {\n ++this.state.pos;\n this.finishToken(tt.jsxTagStart);\n return;\n }\n\n super.getTokenFromCode(code);\n }\n\n updateContext(prevType: TokenType): void {\n const { context, type } = this.state;\n if (type === tt.slash && prevType === tt.jsxTagStart) {\n // do not consider JSX expr -> JSX open tag -> ... anymore\n // reconsider as closing tag context\n context.splice(-2, 2, tc.j_cTag);\n this.state.canStartJSXElement = false;\n } else if (type === tt.jsxTagStart) {\n // start opening tag context\n context.push(tc.j_oTag);\n } else if (type === tt.jsxTagEnd) {\n const out = context[context.length - 1];\n if ((out === tc.j_oTag && prevType === tt.slash) || out === tc.j_cTag) {\n context.pop();\n this.state.canStartJSXElement =\n context[context.length - 1] === tc.j_expr;\n } else {\n this.setContext(tc.j_expr);\n this.state.canStartJSXElement = true;\n }\n } else {\n this.state.canStartJSXElement = tokenComesBeforeExpression(type);\n }\n }\n };\n","import type { Position } from \"../../util/location.ts\";\nimport ScopeHandler, { NameType, Scope } from \"../../util/scope.ts\";\nimport { BindingFlag, ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type * as N from \"../../types.ts\";\nimport { Errors } from \"../../parse-error.ts\";\n\nconst enum TsNameType {\n Types = 1 << 0,\n // enums (which are also in .types)\n Enums = 1 << 1,\n // const enums (which are also in .enums and .types)\n ConstEnums = 1 << 2,\n // classes (which are also in .lexical) and interface (which are also in .types)\n Classes = 1 << 3,\n // namespaces and ambient functions (or classes) are too difficult to track,\n // especially without type analysis.\n // We need to track them anyway, to avoid \"X is not defined\" errors\n // when exporting them.\n ExportOnlyBindings = 1 << 4,\n}\n\nclass TypeScriptScope extends Scope {\n tsNames = new Map();\n}\n\n// See https://github.com/babel/babel/pull/9766#discussion_r268920730 for an\n// explanation of how typescript handles scope.\n\nexport default class TypeScriptScopeHandler extends ScopeHandler {\n importsStack: Set[] = [];\n\n createScope(flags: ScopeFlag): TypeScriptScope {\n this.importsStack.push(new Set()); // Always keep the top-level scope for export checks.\n\n return new TypeScriptScope(flags);\n }\n\n enter(flags: ScopeFlag): void {\n if (flags === ScopeFlag.TS_MODULE) {\n this.importsStack.push(new Set());\n }\n\n super.enter(flags);\n }\n\n exit() {\n const flags = super.exit();\n\n if (flags === ScopeFlag.TS_MODULE) {\n this.importsStack.pop();\n }\n\n return flags;\n }\n\n hasImport(name: string, allowShadow?: boolean) {\n const len = this.importsStack.length;\n if (this.importsStack[len - 1].has(name)) {\n return true;\n }\n if (!allowShadow && len > 1) {\n for (let i = 0; i < len - 1; i++) {\n if (this.importsStack[i].has(name)) return true;\n }\n }\n return false;\n }\n\n declareName(name: string, bindingType: BindingFlag, loc: Position) {\n if (bindingType & BindingFlag.FLAG_TS_IMPORT) {\n if (this.hasImport(name, true)) {\n this.parser.raise(Errors.VarRedeclaration, loc, {\n identifierName: name,\n });\n }\n this.importsStack[this.importsStack.length - 1].add(name);\n return;\n }\n\n const scope = this.currentScope();\n let type = scope.tsNames.get(name) || 0;\n\n if (bindingType & BindingFlag.FLAG_TS_EXPORT_ONLY) {\n this.maybeExportDefined(scope, name);\n scope.tsNames.set(name, type | TsNameType.ExportOnlyBindings);\n return;\n }\n\n super.declareName(name, bindingType, loc);\n\n if (bindingType & BindingFlag.KIND_TYPE) {\n if (!(bindingType & BindingFlag.KIND_VALUE)) {\n // \"Value\" bindings have already been registered by the superclass.\n this.checkRedeclarationInScope(scope, name, bindingType, loc);\n this.maybeExportDefined(scope, name);\n }\n type = type | TsNameType.Types;\n }\n if (bindingType & BindingFlag.FLAG_TS_ENUM) {\n type = type | TsNameType.Enums;\n }\n if (bindingType & BindingFlag.FLAG_TS_CONST_ENUM) {\n type = type | TsNameType.ConstEnums;\n }\n if (bindingType & BindingFlag.FLAG_CLASS) {\n type = type | TsNameType.Classes;\n }\n if (type) scope.tsNames.set(name, type);\n }\n\n isRedeclaredInScope(\n scope: TypeScriptScope,\n name: string,\n bindingType: BindingFlag,\n ): boolean {\n const type = scope.tsNames.get(name)!;\n if ((type & TsNameType.Enums) > 0) {\n if (bindingType & BindingFlag.FLAG_TS_ENUM) {\n // Enums can be merged with other enums if they are both\n // const or both non-const.\n const isConst = !!(bindingType & BindingFlag.FLAG_TS_CONST_ENUM);\n const wasConst = (type & TsNameType.ConstEnums) > 0;\n return isConst !== wasConst;\n }\n return true;\n }\n if (\n bindingType & BindingFlag.FLAG_CLASS &&\n (type & TsNameType.Classes) > 0\n ) {\n if (scope.names.get(name)! & NameType.Lexical) {\n // Classes can be merged with interfaces\n return !!(bindingType & BindingFlag.KIND_VALUE);\n } else {\n // Interface can be merged with other classes or interfaces\n return false;\n }\n }\n if (bindingType & BindingFlag.KIND_TYPE && (type & TsNameType.Types) > 0) {\n return true;\n }\n\n return super.isRedeclaredInScope(scope, name, bindingType);\n }\n\n checkLocalExport(id: N.Identifier) {\n const { name } = id;\n\n if (this.hasImport(name)) return;\n\n const len = this.scopeStack.length;\n for (let i = len - 1; i >= 0; i--) {\n const scope = this.scopeStack[i];\n const type = scope.tsNames.get(name)!;\n if (\n (type & TsNameType.Types) > 0 ||\n (type & TsNameType.ExportOnlyBindings) > 0\n ) {\n return;\n }\n }\n\n super.checkLocalExport(id);\n }\n}\n","// ProductionParameterHandler is a stack fashioned production parameter tracker\n// https://tc39.es/ecma262/#sec-grammar-notation\n// The tracked parameters are defined above.\n//\n// Whenever [+Await]/[+Yield] appears in the right-hand sides of a production,\n// we must enter a new tracking stack. For example when parsing\n//\n// AsyncFunctionDeclaration [Yield, Await]:\n// async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await]\n// ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody }\n//\n// we must follow such process:\n//\n// 1. parse async keyword\n// 2. parse function keyword\n// 3. parse bindingIdentifier <= inherit current parameters: [?Await]\n// 4. enter new stack with (PARAM_AWAIT)\n// 5. parse formal parameters <= must have [Await] parameter [+Await]\n// 6. parse function body\n// 7. exit current stack\n\nexport const enum ParamKind {\n // Initial Parameter flags\n PARAM = 0b0000,\n // track [Yield] production parameter\n PARAM_YIELD = 0b0001,\n // track [Await] production parameter\n PARAM_AWAIT = 0b0010,\n // track [Return] production parameter\n PARAM_RETURN = 0b0100,\n // track [In] production parameter\n PARAM_IN = 0b1000,\n}\n\n// todo(flow->ts) - check if more granular type can be used,\n// type below is not good because things like PARAM_AWAIT|PARAM_YIELD are not included\n// export type ParamKind =\n// | typeof PARAM\n// | typeof PARAM_AWAIT\n// | typeof PARAM_IN\n// | typeof PARAM_RETURN\n// | typeof PARAM_YIELD;\n\nexport default class ProductionParameterHandler {\n stacks: ParamKind[] = [];\n enter(flags: ParamKind) {\n this.stacks.push(flags);\n }\n\n exit() {\n this.stacks.pop();\n }\n\n currentFlags(): ParamKind {\n return this.stacks[this.stacks.length - 1];\n }\n\n get hasAwait(): boolean {\n return (this.currentFlags() & ParamKind.PARAM_AWAIT) > 0;\n }\n\n get hasYield(): boolean {\n return (this.currentFlags() & ParamKind.PARAM_YIELD) > 0;\n }\n\n get hasReturn(): boolean {\n return (this.currentFlags() & ParamKind.PARAM_RETURN) > 0;\n }\n\n get hasIn(): boolean {\n return (this.currentFlags() & ParamKind.PARAM_IN) > 0;\n }\n}\n\nexport function functionFlags(\n isAsync: boolean,\n isGenerator: boolean,\n): ParamKind {\n return (\n (isAsync ? ParamKind.PARAM_AWAIT : 0) |\n (isGenerator ? ParamKind.PARAM_YIELD : 0)\n );\n}\n","import type { OptionFlags, Options } from \"../options.ts\";\nimport type State from \"../tokenizer/state.ts\";\nimport type { PluginsMap } from \"./index.ts\";\nimport type ScopeHandler from \"../util/scope.ts\";\nimport type ExpressionScopeHandler from \"../util/expression-scope.ts\";\nimport type ClassScopeHandler from \"../util/class-scope.ts\";\nimport type ProductionParameterHandler from \"../util/production-parameter.ts\";\nimport type {\n ParserPluginWithOptions,\n PluginConfig,\n PluginOptions,\n} from \"../typings.ts\";\nimport type * as N from \"../types.ts\";\n\nexport default class BaseParser {\n // Properties set by constructor in index.js\n declare options: Options;\n declare optionFlags: OptionFlags;\n declare inModule: boolean;\n declare scope: ScopeHandler;\n declare classScope: ClassScopeHandler;\n declare prodParam: ProductionParameterHandler;\n declare expressionScope: ExpressionScopeHandler;\n declare plugins: PluginsMap;\n declare filename: string | undefined | null;\n declare startIndex: number;\n // Names of exports store. `default` is stored as a name for both\n // `export default foo;` and `export { foo as default };`.\n declare exportedIdentifiers: Set;\n sawUnambiguousESM: boolean = false;\n ambiguousScriptDifferentAst: boolean = false;\n\n // Initialized by Tokenizer\n declare state: State;\n // input and length are not in state as they are constant and we do\n // not want to ever copy them, which happens if state gets cloned\n declare input: string;\n declare length: number;\n // Comment store for Program.comments\n declare comments: N.Comment[];\n\n sourceToOffsetPos(sourcePos: number) {\n return sourcePos + this.startIndex;\n }\n\n offsetToSourcePos(offsetPos: number) {\n return offsetPos - this.startIndex;\n }\n\n // This method accepts either a string (plugin name) or an array pair\n // (plugin name and options object). If an options object is given,\n // then each value is non-recursively checked for identity with that\n // plugin’s actual option value.\n hasPlugin(pluginConfig: PluginConfig): boolean {\n if (typeof pluginConfig === \"string\") {\n return this.plugins.has(pluginConfig);\n } else {\n const [pluginName, pluginOptions] = pluginConfig;\n if (!this.hasPlugin(pluginName)) {\n return false;\n }\n const actualOptions = this.plugins.get(pluginName);\n for (const key of Object.keys(\n pluginOptions,\n ) as (keyof typeof pluginOptions)[]) {\n if (actualOptions?.[key] !== pluginOptions[key]) {\n return false;\n }\n }\n return true;\n }\n }\n\n getPluginOption<\n PluginName extends ParserPluginWithOptions[0],\n OptionName extends keyof PluginOptions,\n >(plugin: PluginName, name: OptionName) {\n return (this.plugins.get(plugin) as null | PluginOptions)?.[\n name\n ];\n }\n}\n","/*:: declare var invariant; */\n\nimport BaseParser from \"./base.ts\";\nimport type { Comment, Node } from \"../types.ts\";\nimport * as charCodes from \"charcodes\";\nimport type { Undone } from \"./node.ts\";\n\n/**\n * A whitespace token containing comments\n */\nexport type CommentWhitespace = {\n /**\n * the start of the whitespace token.\n */\n start: number;\n /**\n * the end of the whitespace token.\n */\n end: number;\n /**\n * the containing comments\n */\n comments: Comment[];\n /**\n * the immediately preceding AST node of the whitespace token\n */\n leadingNode: Node | null;\n /**\n * the immediately following AST node of the whitespace token\n */\n trailingNode: Node | null;\n /**\n * the innermost AST node containing the whitespace with minimal size (|end - start|)\n */\n containingNode: Node | null;\n};\n\n/**\n * Merge comments with node's trailingComments or assign comments to be\n * trailingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nfunction setTrailingComments(node: Undone, comments: Comment[]) {\n if (node.trailingComments === undefined) {\n node.trailingComments = comments;\n } else {\n node.trailingComments.unshift(...comments);\n }\n}\n\n/**\n * Merge comments with node's leadingComments or assign comments to be\n * leadingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nfunction setLeadingComments(node: Undone, comments: Comment[]) {\n if (node.leadingComments === undefined) {\n node.leadingComments = comments;\n } else {\n node.leadingComments.unshift(...comments);\n }\n}\n\n/**\n * Merge comments with node's innerComments or assign comments to be\n * innerComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nexport function setInnerComments(node: Undone, comments: Comment[]) {\n if (node.innerComments === undefined) {\n node.innerComments = comments;\n } else {\n node.innerComments.unshift(...comments);\n }\n}\n\n/**\n * Given node and elements array, if elements has non-null element,\n * merge comments to its trailingComments, otherwise merge comments\n * to node's innerComments\n */\nfunction adjustInnerComments(\n node: Undone,\n elements: (Node | null)[],\n commentWS: CommentWhitespace,\n) {\n let lastElement = null;\n let i = elements.length;\n while (lastElement === null && i > 0) {\n lastElement = elements[--i];\n }\n if (lastElement === null || lastElement.start > commentWS.start) {\n setInnerComments(node, commentWS.comments);\n } else {\n setTrailingComments(lastElement, commentWS.comments);\n }\n}\n\nexport default class CommentsParser extends BaseParser {\n addComment(comment: Comment): void {\n if (this.filename) comment.loc.filename = this.filename;\n const { commentsLen } = this.state;\n if (this.comments.length !== commentsLen) {\n this.comments.length = commentsLen;\n }\n this.comments.push(comment);\n this.state.commentsLen++;\n }\n\n /**\n * Given a newly created AST node _n_, attach _n_ to a comment whitespace _w_ if applicable\n * {@see {@link CommentWhitespace}}\n */\n processComment(node: Node): void {\n const { commentStack } = this.state;\n const commentStackLength = commentStack.length;\n if (commentStackLength === 0) return;\n let i = commentStackLength - 1;\n const lastCommentWS = commentStack[i];\n\n if (lastCommentWS.start === node.end) {\n lastCommentWS.leadingNode = node;\n i--;\n }\n\n const { start: nodeStart } = node;\n // invariant: for all 0 <= j <= i, let c = commentStack[j], c must satisfy c.end < node.end\n for (; i >= 0; i--) {\n const commentWS = commentStack[i];\n const commentEnd = commentWS.end;\n if (commentEnd > nodeStart) {\n // by definition of commentWhiteSpace, this implies commentWS.start > nodeStart\n // so node can be a containingNode candidate. At this time we can finalize the comment\n // whitespace, because\n // 1) its leadingNode or trailingNode, if exists, will not change\n // 2) its containingNode have been assigned and will not change because it is the\n // innermost minimal-sized AST node\n commentWS.containingNode = node;\n this.finalizeComment(commentWS);\n commentStack.splice(i, 1);\n } else {\n if (commentEnd === nodeStart) {\n commentWS.trailingNode = node;\n }\n // stop the loop when commentEnd <= nodeStart\n break;\n }\n }\n }\n\n /**\n * Assign the comments of comment whitespaces to related AST nodes.\n * Also adjust innerComments following trailing comma.\n */\n finalizeComment(commentWS: CommentWhitespace) {\n const { comments } = commentWS;\n if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {\n if (commentWS.leadingNode !== null) {\n setTrailingComments(commentWS.leadingNode, comments);\n }\n if (commentWS.trailingNode !== null) {\n setLeadingComments(commentWS.trailingNode, comments);\n }\n } else {\n /*:: invariant(commentWS.containingNode !== null) */\n const node = commentWS.containingNode!;\n const commentStart = commentWS.start;\n if (\n this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) ===\n charCodes.comma\n ) {\n // If a commentWhitespace follows a comma and the containingNode allows\n // list structures with trailing comma, merge it to the trailingComment\n // of the last non-null list element\n switch (node.type) {\n case \"ObjectExpression\":\n case \"ObjectPattern\":\n adjustInnerComments(node, node.properties, commentWS);\n break;\n case \"CallExpression\":\n case \"OptionalCallExpression\":\n adjustInnerComments(node, node.arguments, commentWS);\n break;\n case \"ImportExpression\":\n adjustInnerComments(\n node,\n [node.source, node.options ?? null],\n commentWS,\n );\n break;\n case \"FunctionDeclaration\":\n case \"FunctionExpression\":\n case \"ArrowFunctionExpression\":\n case \"ObjectMethod\":\n case \"ClassMethod\":\n case \"ClassPrivateMethod\":\n adjustInnerComments(node, node.params, commentWS);\n break;\n case \"ArrayExpression\":\n case \"ArrayPattern\":\n adjustInnerComments(node, node.elements, commentWS);\n break;\n case \"ExportNamedDeclaration\":\n case \"ImportDeclaration\":\n adjustInnerComments(node, node.specifiers, commentWS);\n break;\n case \"TSEnumDeclaration\":\n if (!process.env.BABEL_8_BREAKING) {\n adjustInnerComments(node, node.members!, commentWS);\n } else {\n setInnerComments(node, comments);\n }\n break;\n case \"TSEnumBody\":\n adjustInnerComments(node, node.members, commentWS);\n break;\n default: {\n if (!process.env.BABEL_8_BREAKING) {\n if (node.type === \"RecordExpression\") {\n adjustInnerComments(node, node.properties, commentWS);\n break;\n }\n if (node.type === \"TupleExpression\") {\n adjustInnerComments(node, node.elements, commentWS);\n break;\n }\n }\n setInnerComments(node, comments);\n }\n }\n } else {\n setInnerComments(node, comments);\n }\n }\n }\n\n /**\n * Drains remaining commentStack and applies finalizeComment\n * to each comment whitespace. Used only in parseExpression\n * where the top level AST node is _not_ Program\n * {@see {@link CommentsParser#finalizeComment}}\n */\n finalizeRemainingComments() {\n const { commentStack } = this.state;\n for (let i = commentStack.length - 1; i >= 0; i--) {\n this.finalizeComment(commentStack[i]);\n }\n this.state.commentStack = [];\n }\n\n /* eslint-disable no-irregular-whitespace */\n /**\n * Reset previous node trailing comments. Used in object / class\n * property parsing. We parse `async`, `static`, `set` and `get`\n * as an identifier but may reinterpret it into an async/static/accessor\n * method later. In this case the identifier is not part of the AST and we\n * should sync the knowledge to commentStacks\n *\n * For example, when parsing\n * ```\n * async /* 1 *​/ function f() {}\n * ```\n * the comment whitespace `/* 1 *​/` has leading node Identifier(async). When\n * we see the function token, we create a Function node and mark `/* 1 *​/` as\n * inner comments. So `/* 1 *​/` should be detached from the Identifier node.\n *\n * @param node the last finished AST node _before_ current token\n */\n /* eslint-enable no-irregular-whitespace */\n resetPreviousNodeTrailingComments(node: Node) {\n const { commentStack } = this.state;\n const { length } = commentStack;\n if (length === 0) return;\n const commentWS = commentStack[length - 1];\n if (commentWS.leadingNode === node) {\n commentWS.leadingNode = null;\n }\n }\n\n /**\n * Attach a node to the comment whitespaces right before/after\n * the given range.\n *\n * This is used to properly attach comments around parenthesized\n * expressions as leading/trailing comments of the inner expression.\n */\n takeSurroundingComments(node: Node, start: number, end: number) {\n const { commentStack } = this.state;\n const commentStackLength = commentStack.length;\n if (commentStackLength === 0) return;\n let i = commentStackLength - 1;\n\n for (; i >= 0; i--) {\n const commentWS = commentStack[i];\n const commentEnd = commentWS.end;\n const commentStart = commentWS.start;\n\n if (commentStart === end) {\n commentWS.leadingNode = node;\n } else if (commentEnd === start) {\n commentWS.trailingNode = node;\n } else if (commentEnd < start) {\n break;\n }\n }\n }\n}\n","import type { OptionsWithDefaults } from \"../options.ts\";\nimport type { CommentWhitespace } from \"../parser/comments\";\nimport { Position } from \"../util/location.ts\";\n\nimport { types as ct, type TokContext } from \"./context.ts\";\nimport { tt, type TokenType } from \"./types.ts\";\nimport type { Errors } from \"../parse-error.ts\";\nimport type { ParseError } from \"../parse-error.ts\";\n\nexport type DeferredStrictError =\n | typeof Errors.StrictNumericEscape\n | typeof Errors.StrictOctalLiteral;\n\ntype TopicContextState = {\n // When a topic binding has been currently established,\n // then this is 1. Otherwise, it is 0. This is forwards compatible\n // with a future plugin for multiple lexical topics.\n maxNumOfResolvableTopics: number;\n // When a topic binding has been currently established, and if that binding\n // has been used as a topic reference `#`, then this is 0. Otherwise, it is\n // `null`. This is forwards compatible with a future plugin for multiple\n // lexical topics.\n maxTopicIndex: null | 0;\n};\n\nexport const enum LoopLabelKind {\n Loop = 1,\n Switch = 2,\n}\n\ndeclare const bit: import(\"../../../../scripts/babel-plugin-bit-decorator/types.d.ts\").BitDecorator;\n\nexport default class State {\n @bit.storage flags: number = 0;\n\n @bit accessor strict = false;\n\n startIndex!: number;\n curLine!: number;\n lineStart!: number;\n\n // And, if locations are used, the {line, column} object\n // corresponding to those offsets\n startLoc!: Position;\n endLoc!: Position;\n\n init({\n strictMode,\n sourceType,\n startIndex,\n startLine,\n startColumn,\n }: OptionsWithDefaults): void {\n this.strict =\n strictMode === false\n ? false\n : strictMode === true\n ? true\n : sourceType === \"module\";\n\n this.startIndex = startIndex;\n this.curLine = startLine;\n this.lineStart = -startColumn;\n this.startLoc = this.endLoc = new Position(\n startLine,\n startColumn,\n startIndex,\n );\n }\n\n errors: ParseError[] = [];\n\n // Used to signify the start of a potential arrow function\n potentialArrowAt: number = -1;\n\n // Used to signify the start of an expression which looks like a\n // typed arrow function, but it isn't\n // e.g. a ? (b) : c => d\n // ^\n noArrowAt: number[] = [];\n\n // Used to signify the start of an expression whose params, if it looks like\n // an arrow function, shouldn't be converted to assignable nodes.\n // This is used to defer the validation of typed arrow functions inside\n // conditional expressions.\n // e.g. a ? (b) : c => d\n // ^\n noArrowParamsConversionAt: number[] = [];\n\n // Flags to track\n @bit accessor maybeInArrowParameters = false;\n @bit accessor inType = false;\n @bit accessor noAnonFunctionType = false;\n @bit accessor hasFlowComment = false;\n @bit accessor isAmbientContext = false;\n @bit accessor inAbstractClass = false;\n @bit accessor inDisallowConditionalTypesContext = false;\n\n // For the Hack-style pipelines plugin\n topicContext: TopicContextState = {\n maxNumOfResolvableTopics: 0,\n maxTopicIndex: null,\n };\n\n // For the F#-style pipelines plugin\n @bit accessor soloAwait = false;\n @bit accessor inFSharpPipelineDirectBody = false;\n\n // Labels in scope.\n labels: {\n kind: LoopLabelKind | null;\n name?: string | null;\n statementStart?: number;\n }[] = [];\n\n commentsLen = 0;\n // Comment attachment store\n commentStack: CommentWhitespace[] = [];\n\n // The current position of the tokenizer in the input.\n pos: number = 0;\n\n // Properties of the current token:\n // Its type\n type: TokenType = tt.eof;\n\n // For tokens that include more information than their type, the value\n value: any = null;\n\n // Its start and end offset\n start: number = 0;\n end: number = 0;\n\n // Position information for the previous token\n // this is initialized when generating the second token.\n lastTokEndLoc: Position | null = null;\n // this is initialized when generating the second token.\n lastTokStartLoc: Position | null = null;\n\n // The context stack is used to track whether the apostrophe \"`\" starts\n // or ends a string template\n context: TokContext[] = [ct.brace];\n\n // Used to track whether a JSX element is allowed to form\n @bit accessor canStartJSXElement = true;\n\n // Used to signal to callers of `readWord1` whether the word\n // contained any escape sequences. This is needed because words with\n // escape sequences must not be interpreted as keywords.\n @bit accessor containsEsc = false;\n\n // Used to track invalid escape sequences in template literals,\n // that must be reported if the template is not tagged.\n firstInvalidTemplateEscapePos: null | Position = null;\n\n @bit accessor hasTopLevelAwait = false;\n\n // This property is used to track the following errors\n // - StrictNumericEscape\n // - StrictOctalLiteral\n //\n // in a literal that occurs prior to/immediately after a \"use strict\" directive.\n\n // todo(JLHwung): set strictErrors to null and avoid recording string errors\n // after a non-directive is parsed\n strictErrors = new Map();\n\n // Tokens length in token store\n tokensLength: number = 0;\n\n /**\n * When we add a new property, we must manually update the `clone` method\n * @see State#clone\n */\n\n curPosition(): Position {\n return new Position(\n this.curLine,\n this.pos - this.lineStart,\n this.pos + this.startIndex,\n );\n }\n\n clone(): State {\n const state = new State();\n state.flags = this.flags;\n state.startIndex = this.startIndex;\n state.curLine = this.curLine;\n state.lineStart = this.lineStart;\n state.startLoc = this.startLoc;\n state.endLoc = this.endLoc;\n state.errors = this.errors.slice();\n state.potentialArrowAt = this.potentialArrowAt;\n state.noArrowAt = this.noArrowAt.slice();\n state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();\n state.topicContext = this.topicContext;\n state.labels = this.labels.slice();\n state.commentsLen = this.commentsLen;\n state.commentStack = this.commentStack.slice();\n state.pos = this.pos;\n state.type = this.type;\n state.value = this.value;\n state.start = this.start;\n state.end = this.end;\n state.lastTokEndLoc = this.lastTokEndLoc;\n state.lastTokStartLoc = this.lastTokStartLoc;\n state.context = this.context.slice();\n state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;\n state.strictErrors = this.strictErrors;\n state.tokensLength = this.tokensLength;\n\n return state;\n }\n}\n\nexport type LookaheadState = {\n pos: number;\n value: any;\n type: TokenType;\n start: number;\n end: number;\n context: TokContext[];\n startLoc: Position;\n lastTokEndLoc: Position | null;\n curLine: number;\n lineStart: number;\n curPosition: State[\"curPosition\"];\n /* Used only in readToken_mult_modulo */\n inType: boolean;\n // These boolean properties are not initialized in createLookaheadState()\n // instead they will only be set by the tokenizer\n containsEsc?: boolean;\n};\n","// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// The following character codes are forbidden from being\n// an immediate sibling of NumericLiteralSeparator _\nconst forbiddenNumericSeparatorSiblings = {\n decBinOct: new Set([\n charCodes.dot,\n charCodes.uppercaseB,\n charCodes.uppercaseE,\n charCodes.uppercaseO,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseB,\n charCodes.lowercaseE,\n charCodes.lowercaseO,\n ]),\n hex: new Set([\n charCodes.dot,\n charCodes.uppercaseX,\n charCodes.underscore, // multiple separators are not allowed\n charCodes.lowercaseX,\n ]),\n};\n\nconst isAllowedNumericSeparatorSibling = {\n // 0 - 1\n bin: (ch: number) => ch === charCodes.digit0 || ch === charCodes.digit1,\n\n // 0 - 7\n oct: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit7,\n\n // 0 - 9\n dec: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit9,\n\n // 0 - 9, A - F, a - f,\n hex: (ch: number) =>\n (ch >= charCodes.digit0 && ch <= charCodes.digit9) ||\n (ch >= charCodes.uppercaseA && ch <= charCodes.uppercaseF) ||\n (ch >= charCodes.lowercaseA && ch <= charCodes.lowercaseF),\n};\n\nexport type StringContentsErrorHandlers = EscapedCharErrorHandlers & {\n unterminated(\n initialPos: number,\n initialLineStart: number,\n initialCurLine: number,\n ): void;\n};\n\nexport function readStringContents(\n type: \"single\" | \"double\" | \"template\",\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n errors: StringContentsErrorHandlers,\n) {\n const initialPos = pos;\n const initialLineStart = lineStart;\n const initialCurLine = curLine;\n\n let out = \"\";\n let firstInvalidLoc = null;\n let chunkStart = pos;\n const { length } = input;\n for (;;) {\n if (pos >= length) {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n out += input.slice(chunkStart, pos);\n break;\n }\n const ch = input.charCodeAt(pos);\n if (isStringEnd(type, ch, input, pos)) {\n out += input.slice(chunkStart, pos);\n break;\n }\n if (ch === charCodes.backslash) {\n out += input.slice(chunkStart, pos);\n const res = readEscapedChar(\n input,\n pos,\n lineStart,\n curLine,\n type === \"template\",\n errors,\n );\n if (res.ch === null && !firstInvalidLoc) {\n firstInvalidLoc = { pos, lineStart, curLine };\n } else {\n out += res.ch;\n }\n ({ pos, lineStart, curLine } = res);\n chunkStart = pos;\n } else if (\n ch === charCodes.lineSeparator ||\n ch === charCodes.paragraphSeparator\n ) {\n ++pos;\n ++curLine;\n lineStart = pos;\n } else if (ch === charCodes.lineFeed || ch === charCodes.carriageReturn) {\n if (type === \"template\") {\n out += input.slice(chunkStart, pos) + \"\\n\";\n ++pos;\n if (\n ch === charCodes.carriageReturn &&\n input.charCodeAt(pos) === charCodes.lineFeed\n ) {\n ++pos;\n }\n ++curLine;\n chunkStart = lineStart = pos;\n } else {\n errors.unterminated(initialPos, initialLineStart, initialCurLine);\n }\n } else {\n ++pos;\n }\n }\n return process.env.BABEL_8_BREAKING\n ? { pos, str: out, firstInvalidLoc, lineStart, curLine }\n : {\n pos,\n str: out,\n firstInvalidLoc,\n lineStart,\n curLine,\n containsInvalid: !!firstInvalidLoc,\n };\n}\n\nfunction isStringEnd(\n type: \"single\" | \"double\" | \"template\",\n ch: number,\n input: string,\n pos: number,\n) {\n if (type === \"template\") {\n return (\n ch === charCodes.graveAccent ||\n (ch === charCodes.dollarSign &&\n input.charCodeAt(pos + 1) === charCodes.leftCurlyBrace)\n );\n }\n return (\n ch === (type === \"double\" ? charCodes.quotationMark : charCodes.apostrophe)\n );\n}\n\ntype EscapedCharErrorHandlers = HexCharErrorHandlers &\n CodePointErrorHandlers & {\n strictNumericEscape(pos: number, lineStart: number, curLine: number): void;\n };\n\nfunction readEscapedChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n inTemplate: boolean,\n errors: EscapedCharErrorHandlers,\n) {\n const throwOnInvalid = !inTemplate;\n pos++; // skip '\\'\n\n const res = (ch: string | null) => ({ pos, ch, lineStart, curLine });\n\n const ch = input.charCodeAt(pos++);\n switch (ch) {\n case charCodes.lowercaseN:\n return res(\"\\n\");\n case charCodes.lowercaseR:\n return res(\"\\r\");\n case charCodes.lowercaseX: {\n let code;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 2,\n false,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCharCode(code));\n }\n case charCodes.lowercaseU: {\n let code;\n ({ code, pos } = readCodePoint(\n input,\n pos,\n lineStart,\n curLine,\n throwOnInvalid,\n errors,\n ));\n return res(code === null ? null : String.fromCodePoint(code));\n }\n case charCodes.lowercaseT:\n return res(\"\\t\");\n case charCodes.lowercaseB:\n return res(\"\\b\");\n case charCodes.lowercaseV:\n return res(\"\\u000b\");\n case charCodes.lowercaseF:\n return res(\"\\f\");\n case charCodes.carriageReturn:\n if (input.charCodeAt(pos) === charCodes.lineFeed) {\n ++pos;\n }\n // fall through\n case charCodes.lineFeed:\n lineStart = pos;\n ++curLine;\n // fall through\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n return res(\"\");\n case charCodes.digit8:\n case charCodes.digit9:\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(pos - 1, lineStart, curLine);\n }\n // fall through\n default:\n if (ch >= charCodes.digit0 && ch <= charCodes.digit7) {\n const startPos = pos - 1;\n const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));\n\n let octalStr = match[0];\n\n let octal = parseInt(octalStr, 8);\n if (octal > 255) {\n octalStr = octalStr.slice(0, -1);\n octal = parseInt(octalStr, 8);\n }\n pos += octalStr.length - 1;\n const next = input.charCodeAt(pos);\n if (\n octalStr !== \"0\" ||\n next === charCodes.digit8 ||\n next === charCodes.digit9\n ) {\n if (inTemplate) {\n return res(null);\n } else {\n errors.strictNumericEscape(startPos, lineStart, curLine);\n }\n }\n\n return res(String.fromCharCode(octal));\n }\n\n return res(String.fromCharCode(ch));\n }\n}\n\ntype HexCharErrorHandlers = IntErrorHandlers & {\n invalidEscapeSequence(pos: number, lineStart: number, curLine: number): void;\n};\n\n// Used to read character escape sequences ('\\x', '\\u').\nfunction readHexChar(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n len: number,\n forceLen: boolean,\n throwOnInvalid: boolean,\n errors: HexCharErrorHandlers,\n) {\n const initialPos = pos;\n let n;\n ({ n, pos } = readInt(\n input,\n pos,\n lineStart,\n curLine,\n 16,\n len,\n forceLen,\n false,\n errors,\n /* bailOnError */ !throwOnInvalid,\n ));\n if (n === null) {\n if (throwOnInvalid) {\n errors.invalidEscapeSequence(initialPos, lineStart, curLine);\n } else {\n pos = initialPos - 1;\n }\n }\n return { code: n, pos };\n}\n\nexport type IntErrorHandlers = {\n numericSeparatorInEscapeSequence(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n unexpectedNumericSeparator(\n pos: number,\n lineStart: number,\n curLine: number,\n ): void;\n // It can return \"true\" to indicate that the error was handled\n // and the int parsing should continue.\n invalidDigit(\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n ): boolean;\n};\n\nexport function readInt(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n radix: number,\n len: number | undefined,\n forceLen: boolean,\n allowNumSeparator: boolean | \"bail\",\n errors: IntErrorHandlers,\n bailOnError: boolean,\n) {\n const start = pos;\n const forbiddenSiblings =\n radix === 16\n ? forbiddenNumericSeparatorSiblings.hex\n : forbiddenNumericSeparatorSiblings.decBinOct;\n const isAllowedSibling =\n radix === 16\n ? isAllowedNumericSeparatorSibling.hex\n : radix === 10\n ? isAllowedNumericSeparatorSibling.dec\n : radix === 8\n ? isAllowedNumericSeparatorSibling.oct\n : isAllowedNumericSeparatorSibling.bin;\n\n let invalid = false;\n let total = 0;\n\n for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {\n const code = input.charCodeAt(pos);\n let val;\n\n if (code === charCodes.underscore && allowNumSeparator !== \"bail\") {\n const prev = input.charCodeAt(pos - 1);\n const next = input.charCodeAt(pos + 1);\n\n if (!allowNumSeparator) {\n if (bailOnError) return { n: null, pos };\n errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);\n } else if (\n Number.isNaN(next) ||\n !isAllowedSibling(next) ||\n forbiddenSiblings.has(prev) ||\n forbiddenSiblings.has(next)\n ) {\n if (bailOnError) return { n: null, pos };\n errors.unexpectedNumericSeparator(pos, lineStart, curLine);\n }\n\n // Ignore this _ character\n ++pos;\n continue;\n }\n\n if (code >= charCodes.lowercaseA) {\n val = code - charCodes.lowercaseA + charCodes.lineFeed;\n } else if (code >= charCodes.uppercaseA) {\n val = code - charCodes.uppercaseA + charCodes.lineFeed;\n } else if (charCodes.isDigit(code)) {\n val = code - charCodes.digit0; // 0-9\n } else {\n val = Infinity;\n }\n if (val >= radix) {\n // If we found a digit which is too big, errors.invalidDigit can return true to avoid\n // breaking the loop (this is used for error recovery).\n if (val <= 9 && bailOnError) {\n return { n: null, pos };\n } else if (\n val <= 9 &&\n errors.invalidDigit(pos, lineStart, curLine, radix)\n ) {\n val = 0;\n } else if (forceLen) {\n val = 0;\n invalid = true;\n } else {\n break;\n }\n }\n ++pos;\n total = total * radix + val;\n }\n if (pos === start || (len != null && pos - start !== len) || invalid) {\n return { n: null, pos };\n }\n\n return { n: total, pos };\n}\n\nexport type CodePointErrorHandlers = HexCharErrorHandlers & {\n invalidCodePoint(pos: number, lineStart: number, curLine: number): void;\n};\n\nexport function readCodePoint(\n input: string,\n pos: number,\n lineStart: number,\n curLine: number,\n throwOnInvalid: boolean,\n errors: CodePointErrorHandlers,\n) {\n const ch = input.charCodeAt(pos);\n let code;\n\n if (ch === charCodes.leftCurlyBrace) {\n ++pos;\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n input.indexOf(\"}\", pos) - pos,\n true,\n throwOnInvalid,\n errors,\n ));\n ++pos;\n if (code !== null && code > 0x10ffff) {\n if (throwOnInvalid) {\n errors.invalidCodePoint(pos, lineStart, curLine);\n } else {\n return { code: null, pos };\n }\n }\n } else {\n ({ code, pos } = readHexChar(\n input,\n pos,\n lineStart,\n curLine,\n 4,\n false,\n throwOnInvalid,\n errors,\n ));\n }\n return { code, pos };\n}\n","/*:: declare var invariant; */\n\nimport type { OptionsWithDefaults } from \"../options.ts\";\nimport { OptionFlags } from \"../options.ts\";\nimport {\n Position,\n SourceLocation,\n createPositionWithColumnOffset,\n} from \"../util/location.ts\";\nimport CommentsParser, { type CommentWhitespace } from \"../parser/comments.ts\";\nimport type * as N from \"../types.ts\";\nimport * as charCodes from \"charcodes\";\nimport { isIdentifierStart, isIdentifierChar } from \"../util/identifier.ts\";\nimport {\n tokenIsKeyword,\n tokenLabelName,\n tt,\n keywords as keywordTypes,\n type TokenType,\n} from \"./types.ts\";\nimport type { TokContext } from \"./context.ts\";\nimport {\n Errors,\n type ParseError,\n type ParseErrorConstructor,\n} from \"../parse-error.ts\";\nimport {\n lineBreakG,\n isNewLine,\n isWhitespace,\n skipWhiteSpace,\n skipWhiteSpaceInLine,\n} from \"../util/whitespace.ts\";\nimport State from \"./state.ts\";\nimport type { LookaheadState, DeferredStrictError } from \"./state.ts\";\nimport type { Undone } from \"../parser/node.ts\";\nimport type { Node } from \"../types.ts\";\n\nimport {\n readInt,\n readCodePoint,\n readStringContents,\n type IntErrorHandlers,\n type CodePointErrorHandlers,\n type StringContentsErrorHandlers,\n} from \"@babel/helper-string-parser\";\n\nimport type { Plugin } from \"../typings.ts\";\n\nfunction buildPosition(pos: number, lineStart: number, curLine: number) {\n return new Position(curLine, pos - lineStart, pos);\n}\n\nconst VALID_REGEX_FLAGS = new Set([\n charCodes.lowercaseG,\n charCodes.lowercaseM,\n charCodes.lowercaseS,\n charCodes.lowercaseI,\n charCodes.lowercaseY,\n charCodes.lowercaseU,\n charCodes.lowercaseD,\n charCodes.lowercaseV,\n]);\n\n// Object type used to represent tokens. Note that normally, tokens\n// simply exist as properties on the parser object. This is only\n// used for the onToken callback and the external tokenizer.\n\nexport class Token {\n constructor(state: State) {\n const startIndex = state.startIndex || 0;\n this.type = state.type;\n this.value = state.value;\n this.start = startIndex + state.start;\n this.end = startIndex + state.end;\n this.loc = new SourceLocation(state.startLoc, state.endLoc);\n }\n\n declare type: TokenType;\n declare value: any;\n declare start: number;\n declare end: number;\n declare loc: SourceLocation;\n}\n\n// ## Tokenizer\n\nexport default abstract class Tokenizer extends CommentsParser {\n isLookahead: boolean;\n\n // Token store.\n tokens: (Token | N.Comment)[] = [];\n\n constructor(options: OptionsWithDefaults, input: string) {\n super();\n this.state = new State();\n this.state.init(options);\n this.input = input;\n this.length = input.length;\n this.comments = [];\n this.isLookahead = false;\n }\n\n pushToken(token: Token | N.Comment) {\n // Pop out invalid tokens trapped by try-catch parsing.\n // Those parsing branches are mainly created by typescript and flow plugins.\n this.tokens.length = this.state.tokensLength;\n this.tokens.push(token);\n ++this.state.tokensLength;\n }\n\n // Move to the next token\n\n next(): void {\n this.checkKeywordEscapes();\n if (this.optionFlags & OptionFlags.Tokens) {\n this.pushToken(new Token(this.state));\n }\n\n this.state.lastTokEndLoc = this.state.endLoc;\n this.state.lastTokStartLoc = this.state.startLoc;\n this.nextToken();\n }\n\n eat(type: TokenType): boolean {\n if (this.match(type)) {\n this.next();\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Whether current token matches given type\n */\n match(type: TokenType): boolean {\n return this.state.type === type;\n }\n\n /**\n * Create a LookaheadState from current parser state\n */\n createLookaheadState(state: State): LookaheadState {\n return {\n pos: state.pos,\n value: null,\n type: state.type,\n start: state.start,\n end: state.end,\n context: [this.curContext()],\n inType: state.inType,\n startLoc: state.startLoc,\n lastTokEndLoc: state.lastTokEndLoc,\n curLine: state.curLine,\n lineStart: state.lineStart,\n curPosition: state.curPosition,\n };\n }\n\n /**\n * lookahead peeks the next token, skipping changes to token context and\n * comment stack. For performance it returns a limited LookaheadState\n * instead of full parser state.\n *\n * The { column, line } Loc info is not included in lookahead since such usage\n * is rare. Although it may return other location properties e.g. `curLine` and\n * `lineStart`, these properties are not listed in the LookaheadState interface\n * and thus the returned value is _NOT_ reliable.\n *\n * The tokenizer should make best efforts to avoid using any parser state\n * other than those defined in LookaheadState\n */\n lookahead(): LookaheadState {\n const old = this.state;\n // @ts-expect-error For performance we use a simplified tokenizer state structure\n this.state = this.createLookaheadState(old);\n\n this.isLookahead = true;\n this.nextToken();\n this.isLookahead = false;\n\n const curr = this.state;\n this.state = old;\n return curr;\n }\n\n nextTokenStart(): number {\n return this.nextTokenStartSince(this.state.pos);\n }\n\n nextTokenStartSince(pos: number): number {\n skipWhiteSpace.lastIndex = pos;\n return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;\n }\n\n lookaheadCharCode(): number {\n return this.lookaheadCharCodeSince(this.state.pos);\n }\n\n lookaheadCharCodeSince(pos: number): number {\n return this.input.charCodeAt(this.nextTokenStartSince(pos));\n }\n\n /**\n * Similar to nextToken, but it will stop at line break when it is seen before the next token\n *\n * @returns {number} position of the next token start or line break, whichever is seen first.\n * @memberof Tokenizer\n */\n nextTokenInLineStart(): number {\n return this.nextTokenInLineStartSince(this.state.pos);\n }\n\n nextTokenInLineStartSince(pos: number): number {\n skipWhiteSpaceInLine.lastIndex = pos;\n return skipWhiteSpaceInLine.test(this.input)\n ? skipWhiteSpaceInLine.lastIndex\n : pos;\n }\n\n /**\n * Similar to lookaheadCharCode, but it will return the char code of line break if it is\n * seen before the next token\n *\n * @returns {number} char code of the next token start or line break, whichever is seen first.\n * @memberof Tokenizer\n */\n lookaheadInLineCharCode(): number {\n return this.input.charCodeAt(this.nextTokenInLineStart());\n }\n\n codePointAtPos(pos: number): number {\n // The implementation is based on\n // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n // since `input` is mostly ASCII, an inlined `charCodeAt` wins here\n let cp = this.input.charCodeAt(pos);\n if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {\n const trail = this.input.charCodeAt(pos);\n if ((trail & 0xfc00) === 0xdc00) {\n cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n }\n }\n return cp;\n }\n\n // Toggle strict mode. Re-reads the next number or string to please\n // pedantic tests (`\"use strict\"; 010;` should fail).\n\n setStrict(strict: boolean): void {\n this.state.strict = strict;\n if (strict) {\n // Throw an error for any string decimal escape found before/immediately\n // after a \"use strict\" directive. Strict mode will be set at parse\n // time for any literals that occur after the next node of the strict\n // directive.\n this.state.strictErrors.forEach(([toParseError, at]) =>\n this.raise(toParseError, at),\n );\n this.state.strictErrors.clear();\n }\n }\n\n curContext(): TokContext {\n return this.state.context[this.state.context.length - 1];\n }\n\n // Read a single token, updating the parser object's token-related properties.\n nextToken(): void {\n this.skipSpace();\n this.state.start = this.state.pos;\n if (!this.isLookahead) this.state.startLoc = this.state.curPosition();\n if (this.state.pos >= this.length) {\n this.finishToken(tt.eof);\n return;\n }\n\n this.getTokenFromCode(this.codePointAtPos(this.state.pos));\n }\n\n // Skips a block comment, whose end is marked by commentEnd.\n // *-/ is used by the Flow plugin, when parsing block comments nested\n // inside Flow comments.\n skipBlockComment(commentEnd: \"*/\" | \"*-/\"): N.CommentBlock | undefined {\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n const start = this.state.pos;\n const end = this.input.indexOf(commentEnd, start + 2);\n if (end === -1) {\n // We have to call this again here because startLoc may not be set...\n // This seems to be for performance reasons:\n // https://github.com/babel/babel/commit/acf2a10899f696a8aaf34df78bf9725b5ea7f2da\n throw this.raise(Errors.UnterminatedComment, this.state.curPosition());\n }\n\n this.state.pos = end + commentEnd.length;\n lineBreakG.lastIndex = start + 2;\n while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {\n ++this.state.curLine;\n this.state.lineStart = lineBreakG.lastIndex;\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n /*:: invariant(startLoc) */\n\n const comment: N.CommentBlock = {\n type: \"CommentBlock\",\n value: this.input.slice(start + 2, end),\n start: this.sourceToOffsetPos(start),\n end: this.sourceToOffsetPos(end + commentEnd.length),\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n loc: new SourceLocation(startLoc!, this.state.curPosition()),\n };\n if (this.optionFlags & OptionFlags.Tokens) this.pushToken(comment);\n return comment;\n }\n\n skipLineComment(startSkip: number): N.CommentLine | undefined {\n const start = this.state.pos;\n let startLoc;\n if (!this.isLookahead) startLoc = this.state.curPosition();\n let ch = this.input.charCodeAt((this.state.pos += startSkip));\n if (this.state.pos < this.length) {\n while (!isNewLine(ch) && ++this.state.pos < this.length) {\n ch = this.input.charCodeAt(this.state.pos);\n }\n }\n\n // If we are doing a lookahead right now we need to advance the position (above code)\n // but we do not want to push the comment to the state.\n if (this.isLookahead) return;\n\n const end = this.state.pos;\n const value = this.input.slice(start + startSkip, end);\n\n const comment: N.CommentLine = {\n type: \"CommentLine\",\n value,\n start: this.sourceToOffsetPos(start),\n end: this.sourceToOffsetPos(end),\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n loc: new SourceLocation(startLoc!, this.state.curPosition()),\n };\n if (this.optionFlags & OptionFlags.Tokens) this.pushToken(comment);\n return comment;\n }\n\n // Called at the start of the parse and after every token. Skips\n // whitespace and comments, and.\n\n skipSpace(): void {\n const spaceStart = this.state.pos;\n const comments: N.Comment[] | null =\n this.optionFlags & OptionFlags.AttachComment ? [] : null;\n loop: while (this.state.pos < this.length) {\n const ch = this.input.charCodeAt(this.state.pos);\n switch (ch) {\n case charCodes.space:\n case charCodes.nonBreakingSpace:\n case charCodes.tab:\n ++this.state.pos;\n break;\n case charCodes.carriageReturn:\n if (\n this.input.charCodeAt(this.state.pos + 1) === charCodes.lineFeed\n ) {\n ++this.state.pos;\n }\n // fall through\n case charCodes.lineFeed:\n case charCodes.lineSeparator:\n case charCodes.paragraphSeparator:\n ++this.state.pos;\n ++this.state.curLine;\n this.state.lineStart = this.state.pos;\n break;\n\n case charCodes.slash:\n switch (this.input.charCodeAt(this.state.pos + 1)) {\n case charCodes.asterisk: {\n const comment = this.skipBlockComment(\"*/\");\n if (comment !== undefined) {\n this.addComment(comment);\n comments?.push(comment);\n }\n break;\n }\n\n case charCodes.slash: {\n const comment = this.skipLineComment(2);\n if (comment !== undefined) {\n this.addComment(comment);\n comments?.push(comment);\n }\n break;\n }\n\n default:\n break loop;\n }\n break;\n\n default:\n if (isWhitespace(ch)) {\n ++this.state.pos;\n } else if (\n ch === charCodes.dash &&\n !this.inModule &&\n this.optionFlags & OptionFlags.AnnexB\n ) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.dash &&\n this.input.charCodeAt(pos + 2) === charCodes.greaterThan &&\n (spaceStart === 0 || this.state.lineStart > spaceStart)\n ) {\n // A `-->` line comment\n const comment = this.skipLineComment(3);\n if (comment !== undefined) {\n this.addComment(comment);\n comments?.push(comment);\n }\n } else {\n break loop;\n }\n } else if (\n ch === charCodes.lessThan &&\n !this.inModule &&\n this.optionFlags & OptionFlags.AnnexB\n ) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.exclamationMark &&\n this.input.charCodeAt(pos + 2) === charCodes.dash &&\n this.input.charCodeAt(pos + 3) === charCodes.dash\n ) {\n // ` + +The Standard Schema project is a set of interfaces that standardize the provision and consumption of shared functionality in the TypeScript ecosystem. + +Its goal is to allow tools to accept a single input that includes all the types and capabilities they need— no library-specific adapters, no extra dependencies. The result is an ecosystem that's fair for implementers, friendly for consumers, and open for end users. + +## The specifications + +The specifications can be found below in their entirety. Libraries wishing to implement a spec can copy/paste the code block below into their codebase. They're also available at `@standard-schema/spec` on [npm](https://www.npmjs.com/package/@standard-schema/spec) and [JSR](https://jsr.io/@standard-schema/spec). + +```ts +// ######################### +// ### Standard Typed ### +// ######################### + +/** The Standard Typed interface. This is a base type extended by other specs. */ +export interface StandardTypedV1 { + /** The Standard properties. */ + readonly "~standard": StandardTypedV1.Props; +} + +export declare namespace StandardTypedV1 { + /** The Standard Typed properties interface. */ + export interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + + /** The Standard Typed types interface. */ + export interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + + /** Infers the input type of a Standard Typed. */ + export type InferInput = NonNullable< + Schema["~standard"]["types"] + >["input"]; + + /** Infers the output type of a Standard Typed. */ + export type InferOutput = NonNullable< + Schema["~standard"]["types"] + >["output"]; +} + +// ########################## +// ### Standard Schema ### +// ########################## + +/** The Standard Schema interface. */ +export interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly "~standard": StandardSchemaV1.Props; +} + +export declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + export interface Props + extends StandardTypedV1.Props { + /** Validates unknown input values. */ + readonly validate: ( + value: unknown, + options?: StandardSchemaV1.Options | undefined + ) => Result | Promise>; + } + + /** The result interface of the validate function. */ + export type Result = SuccessResult | FailureResult; + + /** The result interface if validation succeeds. */ + export interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + + export interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + + /** The result interface if validation fails. */ + export interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + + /** The issue interface of the failure output. */ + export interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + + /** The path segment interface of the issue. */ + export interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + + /** The Standard types interface. */ + export interface Types + extends StandardTypedV1.Types {} + + /** Infers the input type of a Standard. */ + export type InferInput = + StandardTypedV1.InferInput; + + /** Infers the output type of a Standard. */ + export type InferOutput = + StandardTypedV1.InferOutput; +} + +// ############################### +// ### Standard JSON Schema ### +// ############################### + +/** The Standard JSON Schema interface. */ +export interface StandardJSONSchemaV1 { + /** The Standard JSON Schema properties. */ + readonly "~standard": StandardJSONSchemaV1.Props; +} + +export declare namespace StandardJSONSchemaV1 { + /** The Standard JSON Schema properties interface. */ + export interface Props + extends StandardTypedV1.Props { + /** Methods for generating the input/output JSON Schema. */ + readonly jsonSchema: StandardJSONSchemaV1.Converter; + } + + /** The Standard JSON Schema converter interface. */ + export interface Converter { + /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ + readonly input: ( + options: StandardJSONSchemaV1.Options + ) => Record; + /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ + readonly output: ( + options: StandardJSONSchemaV1.Options + ) => Record; + } + + /** + * The target version of the generated JSON Schema. + * + * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. + * + * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. + */ + export type Target = + | "draft-2020-12" + | "draft-07" + | "openapi-3.0" + // Accepts any string for future targets while preserving autocomplete + | ({} & string); + + /** The options for the input/output methods. */ + export interface Options { + /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ + readonly target: Target; + + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + + /** The Standard types interface. */ + export interface Types + extends StandardTypedV1.Types {} + + /** Infers the input type of a Standard. */ + export type InferInput = + StandardTypedV1.InferInput; + + /** Infers the output type of a Standard. */ + export type InferOutput = + StandardTypedV1.InferOutput; +} +``` diff --git a/vanilla/node_modules/@standard-schema/spec/dist/index.cjs b/vanilla/node_modules/@standard-schema/spec/dist/index.cjs new file mode 100644 index 0000000..321666e --- /dev/null +++ b/vanilla/node_modules/@standard-schema/spec/dist/index.cjs @@ -0,0 +1,18 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +module.exports = __toCommonJS(src_exports); diff --git a/vanilla/node_modules/@standard-schema/spec/dist/index.d.cts b/vanilla/node_modules/@standard-schema/spec/dist/index.d.cts new file mode 100644 index 0000000..5e4acaa --- /dev/null +++ b/vanilla/node_modules/@standard-schema/spec/dist/index.d.cts @@ -0,0 +1,119 @@ +/** The Standard Typed interface. This is a base type extended by other specs. */ +interface StandardTypedV1 { + /** The Standard properties. */ + readonly "~standard": StandardTypedV1.Props; +} +declare namespace StandardTypedV1 { + /** The Standard Typed properties interface. */ + interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + /** The Standard Typed types interface. */ + interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + /** Infers the input type of a Standard Typed. */ + type InferInput = NonNullable["input"]; + /** Infers the output type of a Standard Typed. */ + type InferOutput = NonNullable["output"]; +} +/** The Standard Schema interface. */ +interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly "~standard": StandardSchemaV1.Props; +} +declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Validates unknown input values. */ + readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result | Promise>; + } + /** The result interface of the validate function. */ + type Result = SuccessResult | FailureResult; + /** The result interface if validation succeeds. */ + interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The result interface if validation fails. */ + interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + /** The issue interface of the failure output. */ + interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + /** The path segment interface of the issue. */ + interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} +/** The Standard JSON Schema interface. */ +interface StandardJSONSchemaV1 { + /** The Standard JSON Schema properties. */ + readonly "~standard": StandardJSONSchemaV1.Props; +} +declare namespace StandardJSONSchemaV1 { + /** The Standard JSON Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Methods for generating the input/output JSON Schema. */ + readonly jsonSchema: StandardJSONSchemaV1.Converter; + } + /** The Standard JSON Schema converter interface. */ + interface Converter { + /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ + readonly input: (options: StandardJSONSchemaV1.Options) => Record; + /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ + readonly output: (options: StandardJSONSchemaV1.Options) => Record; + } + /** + * The target version of the generated JSON Schema. + * + * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. + * + * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. + */ + type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string); + /** The options for the input/output methods. */ + interface Options { + /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ + readonly target: Target; + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} + +export { StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1 }; diff --git a/vanilla/node_modules/@standard-schema/spec/dist/index.d.ts b/vanilla/node_modules/@standard-schema/spec/dist/index.d.ts new file mode 100644 index 0000000..5e4acaa --- /dev/null +++ b/vanilla/node_modules/@standard-schema/spec/dist/index.d.ts @@ -0,0 +1,119 @@ +/** The Standard Typed interface. This is a base type extended by other specs. */ +interface StandardTypedV1 { + /** The Standard properties. */ + readonly "~standard": StandardTypedV1.Props; +} +declare namespace StandardTypedV1 { + /** The Standard Typed properties interface. */ + interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + /** The Standard Typed types interface. */ + interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + /** Infers the input type of a Standard Typed. */ + type InferInput = NonNullable["input"]; + /** Infers the output type of a Standard Typed. */ + type InferOutput = NonNullable["output"]; +} +/** The Standard Schema interface. */ +interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly "~standard": StandardSchemaV1.Props; +} +declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Validates unknown input values. */ + readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result | Promise>; + } + /** The result interface of the validate function. */ + type Result = SuccessResult | FailureResult; + /** The result interface if validation succeeds. */ + interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The result interface if validation fails. */ + interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + /** The issue interface of the failure output. */ + interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + /** The path segment interface of the issue. */ + interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} +/** The Standard JSON Schema interface. */ +interface StandardJSONSchemaV1 { + /** The Standard JSON Schema properties. */ + readonly "~standard": StandardJSONSchemaV1.Props; +} +declare namespace StandardJSONSchemaV1 { + /** The Standard JSON Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Methods for generating the input/output JSON Schema. */ + readonly jsonSchema: StandardJSONSchemaV1.Converter; + } + /** The Standard JSON Schema converter interface. */ + interface Converter { + /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ + readonly input: (options: StandardJSONSchemaV1.Options) => Record; + /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ + readonly output: (options: StandardJSONSchemaV1.Options) => Record; + } + /** + * The target version of the generated JSON Schema. + * + * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. + * + * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. + */ + type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string); + /** The options for the input/output methods. */ + interface Options { + /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ + readonly target: Target; + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} + +export { StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1 }; diff --git a/vanilla/node_modules/@standard-schema/spec/dist/index.js b/vanilla/node_modules/@standard-schema/spec/dist/index.js new file mode 100644 index 0000000..e69de29 diff --git a/vanilla/node_modules/@standard-schema/spec/package.json b/vanilla/node_modules/@standard-schema/spec/package.json new file mode 100644 index 0000000..62bb551 --- /dev/null +++ b/vanilla/node_modules/@standard-schema/spec/package.json @@ -0,0 +1,52 @@ +{ + "name": "@standard-schema/spec", + "description": "A family of specs for interoperable TypeScript", + "version": "1.1.0", + "license": "MIT", + "author": "Colin McDonnell", + "homepage": "https://standardschema.dev", + "repository": { + "type": "git", + "url": "https://github.com/standard-schema/standard-schema" + }, + "keywords": [ + "typescript", + "schema", + "validation", + "standard", + "interface" + ], + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "standard-schema-spec": "./src/index.ts", + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, + "sideEffects": false, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "tsup": "^8.3.0", + "typescript": "^5.6.2" + }, + "scripts": { + "lint": "pnpm biome lint ./src", + "format": "pnpm biome format --write ./src", + "check": "pnpm biome check ./src", + "build": "tsup" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/@types/chai/LICENSE b/vanilla/node_modules/@types/chai/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/vanilla/node_modules/@types/chai/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/vanilla/node_modules/@types/chai/README.md b/vanilla/node_modules/@types/chai/README.md new file mode 100644 index 0000000..27c1356 --- /dev/null +++ b/vanilla/node_modules/@types/chai/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/chai` + +# Summary +This package contains type definitions for chai (http://chaijs.com/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/chai. + +### Additional Details + * Last updated: Mon, 20 Oct 2025 23:32:35 GMT + * Dependencies: [@types/deep-eql](https://npmjs.com/package/@types/deep-eql), [assertion-error](https://npmjs.com/package/assertion-error) + +# Credits +These definitions were written by [Bart van der Schoor](https://github.com/Bartvds), [Andrew Brown](https://github.com/AGBrown), [Olivier Chevet](https://github.com/olivr70), [Matt Wistrand](https://github.com/mwistrand), [Shaun Luttin](https://github.com/shaunluttin), [Satana Charuwichitratana](https://github.com/micksatana), [Erik Schierboom](https://github.com/ErikSchierboom), [Bogdan Paranytsia](https://github.com/bparan), [CXuesong](https://github.com/CXuesong), and [Joey Kilpatrick](https://github.com/joeykilpatrick). diff --git a/vanilla/node_modules/@types/chai/index.d.ts b/vanilla/node_modules/@types/chai/index.d.ts new file mode 100644 index 0000000..4fed6b9 --- /dev/null +++ b/vanilla/node_modules/@types/chai/index.d.ts @@ -0,0 +1,2145 @@ +import deepEqual = require("deep-eql"); +import { AssertionError as ImportedAssertionError } from "assertion-error"; + +declare global { + namespace Chai { + export type Message = string | (() => string); + export type ObjectProperty = string | symbol | number; + + export interface PathInfo { + parent: object; + name: string; + value?: any; + exists: boolean; + } + + export interface Constructor { + new(...args: any[]): T; + } + + export interface ErrorConstructor { + new(...args: any[]): Error; + } + + export interface ChaiUtils { + addChainableMethod( + // object to define the method on, e.g. chai.Assertion.prototype + ctx: object, + // method name + name: string, + // method itself; any arguments + method: (...args: any[]) => void, + // called when property is accessed + chainingBehavior?: () => void, + ): void; + overwriteChainableMethod( + ctx: object, + name: string, + method: (...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + addLengthGuard( + fn: Function, + assertionName: string, + isChainable: boolean, + ): void; + addMethod(ctx: object, name: string, method: Function): void; + addProperty(ctx: object, name: string, getter: () => any): void; + overwriteMethod(ctx: object, name: string, method: Function): void; + overwriteProperty(ctx: object, name: string, getter: (this: AssertionStatic, _super: any) => any): void; + compareByInspect(a: object, b: object): -1 | 1; + expectTypes(obj: object, types: string[]): void; + flag(obj: object, key: string, value?: any): any; + getActual(obj: object, args: AssertionArgs): any; + getProperties(obj: object): string[]; + getEnumerableProperties(obj: object): string[]; + getOwnEnumerablePropertySymbols(obj: object): symbol[]; + getOwnEnumerableProperties(obj: object): Array; + getMessage(errorLike: Error | string): string; + getMessage(obj: any, args: AssertionArgs): string; + inspect(obj: any, showHidden?: boolean, depth?: number, colors?: boolean): string; + isProxyEnabled(): boolean; + objDisplay(obj: object): void; + proxify(obj: object, nonChainableMethodName: string): object; + test(obj: object, args: AssertionArgs): boolean; + transferFlags(assertion: Assertion, obj: object, includeAll?: boolean): void; + compatibleInstance(thrown: Error, errorLike: Error | ErrorConstructor): boolean; + compatibleConstructor(thrown: Error, errorLike: Error | ErrorConstructor): boolean; + compatibleMessage(thrown: Error, errMatcher: string | RegExp): boolean; + getConstructorName(constructorFn: Function): string; + getFuncName(constructorFn: Function): string | null; + + // Reexports from pathval: + hasProperty(obj: object | undefined | null, name: ObjectProperty): boolean; + getPathInfo(obj: object, path: string): PathInfo; + getPathValue(obj: object, path: string): object | undefined; + + eql: typeof deepEqual; + } + + export type ChaiPlugin = (chai: ChaiStatic, utils: ChaiUtils) => void; + + export interface ChaiStatic { + expect: ExpectStatic; + should(): Should; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: ChaiPlugin): ChaiStatic; + util: ChaiUtils; + assert: AssertStatic; + config: Config; + Assertion: AssertionStatic; + AssertionError: typeof AssertionError; + version: string; + } + + export interface ExpectStatic { + (val: any, message?: string): Assertion; + fail(message?: string): never; + fail(actual: any, expected: any, message?: string, operator?: Operator): never; + } + + export interface AssertStatic extends Assert { + } + + // chai.Assertion.prototype.assert arguments + export type AssertionArgs = [ + any, // expression to be tested + Message, // message or function that returns message to display if expression fails + Message, // negatedMessage or function that returns negatedMessage to display if expression fails + any?, // expected value + any?, // actual value + boolean?, // showDiff, when set to `true`, assert will display a diff in addition to the message if expression fails + ]; + + export interface AssertionPrototype { + assert(...args: AssertionArgs): void; + _obj: any; + } + + export interface AssertionStatic extends AssertionPrototype { + prototype: AssertionPrototype; + + new(target: any, message?: string, ssfi?: Function, lockSsfi?: boolean): Assertion; + + // Deprecated properties: + includeStack: boolean; + showDiff: boolean; + + // Partials of functions on ChaiUtils: + addProperty(name: string, getter: (this: AssertionStatic) => any): void; + addMethod(name: string, method: (this: AssertionStatic, ...args: any[]) => any): void; + addChainableMethod( + name: string, + method: (this: AssertionStatic, ...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + overwriteProperty(name: string, getter: (this: AssertionStatic, _super: any) => any): void; + overwriteMethod(name: string, method: (this: AssertionStatic, ...args: any[]) => any): void; + overwriteChainableMethod( + name: string, + method: (this: AssertionStatic, ...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + } + + export type Operator = string; // "==" | "===" | ">" | ">=" | "<" | "<=" | "!=" | "!=="; + + export type OperatorComparable = boolean | null | number | string | undefined | Date; + + export interface ShouldAssertion { + equal(value1: any, value2: any, message?: string): void; + Throw: ShouldThrow; + throw: ShouldThrow; + exist(value: any, message?: string): void; + } + + export interface Should extends ShouldAssertion { + not: ShouldAssertion; + fail(message?: string): never; + fail(actual: any, expected: any, message?: string, operator?: Operator): never; + } + + export interface ShouldThrow { + (actual: Function, expected?: string | RegExp, message?: string): void; + (actual: Function, constructor: Error | Function, expected?: string | RegExp, message?: string): void; + } + + export interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; + deep: Deep; + ordered: Ordered; + nested: Nested; + own: Own; + any: KeyFilter; + all: KeyFilter; + a: Assertion; + an: Assertion; + include: Include; + includes: Include; + contain: Include; + contains: Include; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + NaN: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; + finite: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + eql: Equal; + eqls: Equal; + containSubset: ContainSubset; + property: Property; + ownProperty: Property; + haveOwnProperty: Property; + ownPropertyDescriptor: OwnPropertyDescriptor; + haveOwnPropertyDescriptor: OwnPropertyDescriptor; + length: Length; + lengthOf: Length; + match: Match; + matches: Match; + string(string: string, message?: string): Assertion; + keys: Keys; + key(string: string): Assertion; + throw: Throw; + throws: Throw; + Throw: Throw; + respondTo: RespondTo; + respondsTo: RespondTo; + itself: Assertion; + satisfy: Satisfy; + satisfies: Satisfy; + closeTo: CloseTo; + approximately: CloseTo; + members: Members; + increase: PropertyChange; + increases: PropertyChange; + decrease: PropertyChange; + decreases: PropertyChange; + change: PropertyChange; + changes: PropertyChange; + extensible: Assertion; + sealed: Assertion; + frozen: Assertion; + oneOf: OneOf; + } + + export interface LanguageChains { + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; + but: Assertion; + does: Assertion; + } + + export interface NumericComparison { + above: NumberComparer; + gt: NumberComparer; + greaterThan: NumberComparer; + least: NumberComparer; + gte: NumberComparer; + greaterThanOrEqual: NumberComparer; + below: NumberComparer; + lt: NumberComparer; + lessThan: NumberComparer; + most: NumberComparer; + lte: NumberComparer; + lessThanOrEqual: NumberComparer; + within(start: number, finish: number, message?: string): Assertion; + within(start: Date, finish: Date, message?: string): Assertion; + } + + export interface NumberComparer { + (value: number | Date, message?: string): Assertion; + } + + export interface TypeComparison { + (type: string, message?: string): Assertion; + instanceof: InstanceOf; + instanceOf: InstanceOf; + } + + export interface InstanceOf { + (constructor: any, message?: string): Assertion; + } + + export interface CloseTo { + (expected: number, delta: number, message?: string): Assertion; + } + + export interface Nested { + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + members: Members; + } + + export interface Own { + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + } + + export interface Deep extends KeyFilter { + be: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + ordered: Ordered; + nested: Nested; + oneOf: OneOf; + own: Own; + } + + export interface Ordered { + members: Members; + } + + export interface KeyFilter { + keys: Keys; + members: Members; + } + + export interface Equal { + (value: any, message?: string): Assertion; + } + + export interface ContainSubset { + (expected: any): Assertion; + } + + export interface Property { + (name: string | symbol, value: any, message?: string): Assertion; + (name: string | symbol, message?: string): Assertion; + } + + export interface OwnPropertyDescriptor { + (name: string | symbol, descriptor: PropertyDescriptor, message?: string): Assertion; + (name: string | symbol, message?: string): Assertion; + } + + export interface Length extends LanguageChains, NumericComparison { + (length: number, message?: string): Assertion; + } + + export interface Include { + (value: any, message?: string): Assertion; + keys: Keys; + deep: Deep; + ordered: Ordered; + members: Members; + any: KeyFilter; + all: KeyFilter; + oneOf: OneOf; + } + + export interface OneOf { + (list: readonly unknown[], message?: string): Assertion; + } + + export interface Match { + (regexp: RegExp, message?: string): Assertion; + } + + export interface Keys { + (...keys: string[]): Assertion; + (keys: readonly any[] | Object): Assertion; + } + + export interface Throw { + (expected?: string | RegExp, message?: string): Assertion; + (constructor: Error | Function, expected?: string | RegExp, message?: string): Assertion; + } + + export interface RespondTo { + (method: string, message?: string): Assertion; + } + + export interface Satisfy { + (matcher: Function, message?: string): Assertion; + } + + export interface Members { + (set: readonly any[], message?: string): Assertion; + } + + export interface PropertyChange { + (object: Object, property?: string, message?: string): DeltaAssertion; + } + + export interface DeltaAssertion extends Assertion { + by(delta: number, msg?: string): Assertion; + } + + export interface Assert { + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): asserts expression; + + /** + * Throws a failure. + * + * @param message Message to display on error. + * @remarks Node.js assert module-compatible. + */ + fail(message?: string): never; + + /** + * Throws a failure. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + * @param operator Comparison operator, if not strict equality. + * @remarks Node.js assert module-compatible. + */ + fail(actual: T, expected: T, message?: string, operator?: Operator): never; + + /** + * Asserts that object is truthy. + * + * @param object Object to test. + * @param message Message to display on error. + */ + isOk(value: unknown, message?: string): asserts value; + + /** + * Asserts that object is truthy. + * + * @param object Object to test. + * @param message Message to display on error. + */ + ok(value: unknown, message?: string): asserts value; + + /** + * Asserts that object is falsy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotOk(value: T, message?: string): void; + + /** + * Asserts that object is falsy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + notOk(value: T, message?: string): void; + + /** + * Asserts non-strict equality (==) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + equal(actual: T, expected: T, message?: string): void; + + /** + * Asserts non-strict inequality (!=) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts strict equality (===) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + strictEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts strict inequality (!==) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notStrictEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts that actual is deeply equal to expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts that actual is not deeply equal to expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notDeepEqual(actual: T, expected: T, message?: string): void; + + /** + * Alias to deepEqual + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepStrictEqual(actual: T, expected: T, message?: string): void; + + /** + * Partially matches actual and expected. + * + * @param actual Actual value. + * @param expected Potential subset of the value. + * @param message Message to display on error. + */ + containSubset(val: any, exp: any, msg?: string): void; + + /** + * Partially matches actual and expected. + * + * @param actual Actual value. + * @param expected Potential subset of the value. + * @param message Message to display on error. + */ + containsSubset(val: any, exp: any, msg?: string): void; + + /** + * No partial match between actual and expected exists. + * + * @param actual Actual value. + * @param expected Potential subset of the value. + * @param message Message to display on error. + */ + doesNotContainSubset(val: any, exp: any, msg?: string): void; + + /** + * Asserts valueToCheck is strictly greater than (>) valueToBeAbove. + * + * @param valueToCheck Actual value. + * @param valueToBeAbove Minimum Potential expected value. + * @param message Message to display on error. + */ + isAbove(valueToCheck: number, valueToBeAbove: number, message?: string): void; + + /** + * Asserts valueToCheck is greater than or equal to (>=) valueToBeAtLeast. + * + * @param valueToCheck Actual value. + * @param valueToBeAtLeast Minimum Potential expected value. + * @param message Message to display on error. + */ + isAtLeast(valueToCheck: number, valueToBeAtLeast: number, message?: string): void; + + /** + * Asserts valueToCheck is strictly less than (<) valueToBeBelow. + * + * @param valueToCheck Actual value. + * @param valueToBeBelow Minimum Potential expected value. + * @param message Message to display on error. + */ + isBelow(valueToCheck: number, valueToBeBelow: number, message?: string): void; + + /** + * Asserts valueToCheck is less than or equal to (<=) valueToBeAtMost. + * + * @param valueToCheck Actual value. + * @param valueToBeAtMost Minimum Potential expected value. + * @param message Message to display on error. + */ + isAtMost(valueToCheck: number, valueToBeAtMost: number, message?: string): void; + + /** + * Asserts that value is true. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isTrue(value: unknown, message?: string): asserts value is true; + + /** + * Asserts that value is false. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isFalse(value: unknown, message?: string): asserts value is false; + + /** + * Asserts that value is not true. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotTrue(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is not false. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isNotFalse(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is null. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isNull(value: unknown, message?: string): asserts value is null; + + /** + * Asserts that value is not null. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNull(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is NaN. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNaN(value: T, message?: string): void; + + /** + * Asserts that value is not NaN. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNaN(value: T, message?: string): void; + + /** + * Asserts that the target is neither null nor undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + exists(value: T, message?: string): asserts value is NonNullable; + + /** + * Asserts that the target is either null or undefined. + * + * @param value Actual value. + * @param message Message to display on error. + */ + notExists(value: unknown, message?: string): asserts value is + | null + | undefined; + + /** + * Asserts that value is undefined. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isUndefined(value: unknown, message?: string): asserts value is undefined; + + /** + * Asserts that value is not undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isDefined(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is a function. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isFunction(value: T, message?: string): void; + + /** + * Asserts that value is not a function. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotFunction(value: T, message?: string): void; + + /** + * Asserts that value is an object of type 'Object' + * (as revealed by Object.prototype.toString). + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + * @remarks The assertion does not match subclassed objects. + */ + isObject(value: T, message?: string): void; + + /** + * Asserts that value is not an object of type 'Object' + * (as revealed by Object.prototype.toString). + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotObject(value: T, message?: string): void; + + /** + * Asserts that value is an array. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isArray(value: T, message?: string): void; + + /** + * Asserts that value is not an array. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotArray(value: T, message?: string): void; + + /** + * Asserts that value is a string. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isString(value: T, message?: string): void; + + /** + * Asserts that value is not a string. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotString(value: T, message?: string): void; + + /** + * Asserts that value is a number. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNumber(value: T, message?: string): void; + + /** + * Asserts that value is not a number. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNumber(value: T, message?: string): void; + + /** + * Asserts that value is a finite number. + * Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. + * + * T Type of value + * @param value Actual value + * @param message Message to display on error. + */ + isFinite(value: T, message?: string): void; + + /** + * Asserts that value is a boolean. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isBoolean(value: T, message?: string): void; + + /** + * Asserts that value is not a boolean. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotBoolean(value: T, message?: string): void; + + /** + * Asserts that value's type is name, as determined by Object.prototype.toString. + * + * T Type of value. + * @param value Actual value. + * @param name Potential expected type name of value. + * @param message Message to display on error. + */ + typeOf(value: T, name: string, message?: string): void; + + /** + * Asserts that value's type is not name, as determined by Object.prototype.toString. + * + * T Type of value. + * @param value Actual value. + * @param name Potential expected type name of value. + * @param message Message to display on error. + */ + notTypeOf(value: T, name: string, message?: string): void; + + /** + * Asserts that value is an instance of constructor. + * + * T Expected type of value. + * @param value Actual value. + * @param constructor Potential expected contructor of value. + * @param message Message to display on error. + */ + instanceOf( + value: unknown, + constructor: Constructor, + message?: string, + ): asserts value is T; + + /** + * Asserts that value is not an instance of constructor. + * + * T Type of value. + * U Type that value shouldn't be an instance of. + * @param value Actual value. + * @param constructor Potential expected contructor of value. + * @param message Message to display on error. + */ + notInstanceOf(value: T, type: Constructor, message?: string): asserts value is Exclude; + + /** + * Asserts that haystack includes needle. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + */ + include(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + include( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of values in haystack. + * @param haystack WeakSet container. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + include(haystack: WeakSet, needle: T, message?: string): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + include(haystack: T, needle: Partial, message?: string): void; + + /** + * Asserts that haystack does not include needle. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + */ + notInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack does not include needle. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notInclude( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack does not include needle. + * + * T Type of values in haystack. + * @param haystack WeakSet container. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notInclude(haystack: WeakSet, needle: T, message?: string): void; + + /** + * Asserts that haystack does not include needle. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + notInclude(haystack: T, needle: Partial, message?: string): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + * + * @deprecated Does not have any effect on string. Use {@link Assert#include} instead. + */ + deepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + deepInclude( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + deepInclude(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string): void; + + /** + * Asserts that haystack does not include needle. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + * + * @deprecated Does not have any effect on string. Use {@link Assert#notInclude} instead. + */ + notDeepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack does not include needle. Deep equality is used. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notDeepInclude( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack does not include needle. Deep equality is used. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + notDeepInclude(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + nestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while checking for deep equality + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object while checking for deep equality. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + ownInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties and checking for deep + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties and checking for deep equality. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that value matches the regular expression regexp. + * + * @param value Actual value. + * @param regexp Potential match of value. + * @param message Message to display on error. + */ + match(value: string, regexp: RegExp, message?: string): void; + + /** + * Asserts that value does not match the regular expression regexp. + * + * @param value Actual value. + * @param regexp Potential match of value. + * @param message Message to display on error. + */ + notMatch(expected: any, regexp: RegExp, message?: string): void; + + /** + * Asserts that object has a property named by property. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + property(object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that object does not have a property named by property. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + notProperty(object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that object has a property named by property, which can be a string + * using dot- and bracket-notation for deep reference. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + deepProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object does not have a property named by property, which can be a + * string using dot- and bracket-notation for deep reference. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + notDeepProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + propertyVal(object: T, property: string, /* keyof T */ value: V, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + notPropertyVal(object: T, property: string, /* keyof T */ value: V, message?: string): void; + + /** + * Asserts that object has a property named by property, which can be a string + * using dot- and bracket-notation for deep reference. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + deepPropertyVal(object: T, property: string, value: V, message?: string): void; + + /** + * Asserts that object does not have a property named by property, which can be a + * string using dot- and bracket-notation for deep reference. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + notDeepPropertyVal(object: T, property: string, value: V, message?: string): void; + + /** + * Asserts that object has a length property with the expected value. + * + * T Type of object. + * @param object Container object. + * @param length Potential expected length of object. + * @param message Message to display on error. + */ + lengthOf( + object: T, + length: number, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + throw(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + throw( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + throws(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + throws( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + Throw(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + Throw( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will not throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + doesNotThrow(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will not throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + doesNotThrow( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Compares two values using operator. + * + * @param val1 Left value during comparison. + * @param operator Comparison operator. + * @param val2 Right value during comparison. + * @param message Message to display on error. + */ + operator(val1: OperatorComparable, operator: Operator, val2: OperatorComparable, message?: string): void; + + /** + * Asserts that the target is equal to expected, to within a +/- delta range. + * + * @param actual Actual value + * @param expected Potential expected value. + * @param delta Maximum differenced between values. + * @param message Message to display on error. + */ + closeTo(actual: number, expected: number, delta: number, message?: string): void; + + /** + * Asserts that the target is equal to expected, to within a +/- delta range. + * + * @param actual Actual value + * @param expected Potential expected value. + * @param delta Maximum differenced between values. + * @param message Message to display on error. + */ + approximately(act: number, exp: number, delta: number, message?: string): void; + + /** + * Asserts that set1 and set2 have the same members. Order is not take into account. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members using deep equality checking. + * Order is not take into account. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameDeepMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 + * @param set2 + * @param message + */ + notSameDeepMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset. Order is not take into account. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in any order. + * Uses a strict equality check (===). Duplicates are ignored. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential not contained set of values. + * @param message Message to display on error. + */ + notIncludeMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset using deep equality checking. + * Order is not take into account. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeDeepMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * deep equality check. Duplicates are ignored. + * + * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeDeepMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that non-object, non-array value inList appears in the flat array list. + * + * T Type of list values. + * @param inList Value expected to be in the list. + * @param list List of values. + * @param message Message to display on error. + */ + oneOf(inList: T, list: T[], message?: string): void; + + /** + * Asserts that a function changes the value of a property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be modified. + * @param message Message to display on error. + */ + changes(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function changes the value of a property by an amount (delta). + * + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + changesBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + changesBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not change the value of a property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be modified. + * @param message Message to display on error. + */ + doesNotChange(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function increases an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be increased. + * @param message Message to display on error. + */ + increases(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + increasesBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + increasesBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not increase an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be increased. + * @param message Message to display on error. + */ + doesNotIncrease(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + increasesButNotBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + increasesButNotBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function decreases an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be decreased. + * @param message Message to display on error. + */ + decreases(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + decreasesBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + decreasesBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not decrease an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be decreased. + * @param message Message to display on error. + */ + doesNotDecrease(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + doesNotDecreaseBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + doesNotDecreaseBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + decreasesButNotBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + decreasesButNotBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts if value is not a false value, and throws if it is a true value. + * + * T Type of object. + * @param object Actual value. + * @param message Message to display on error. + * @remarks This is added to allow for chai to be a drop-in replacement for + * Node’s assert class. + */ + ifError(object: T, message?: string): void; + + /** + * Asserts that object is extensible (can have new properties added to it). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isExtensible(object: T, message?: string): void; + + /** + * Asserts that object is extensible (can have new properties added to it). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + extensible(object: T, message?: string): void; + + /** + * Asserts that object is not extensible. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotExtensible(object: T, message?: string): void; + + /** + * Asserts that object is not extensible. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notExtensible(object: T, message?: string): void; + + /** + * Asserts that object is sealed (can have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isSealed(object: T, message?: string): void; + + /** + * Asserts that object is sealed (can have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + sealed(object: T, message?: string): void; + + /** + * Asserts that object is not sealed. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotSealed(object: T, message?: string): void; + + /** + * Asserts that object is not sealed. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notSealed(object: T, message?: string): void; + + /** + * Asserts that object is frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isFrozen(object: T, message?: string): void; + + /** + * Asserts that object is frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + frozen(object: T, message?: string): void; + + /** + * Asserts that object is not frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotFrozen(object: T, message?: string): void; + + /** + * Asserts that object is not frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notFrozen(object: T, message?: string): void; + + /** + * Asserts that the target does not contain any values. For arrays and + * strings, it checks the length property. For Map and Set instances, it + * checks the size property. For non-function objects, it gets the count + * of own enumerable string keys. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isEmpty(object: T, message?: string): void; + + /** + * Asserts that the target contains values. For arrays and strings, it checks + * the length property. For Map and Set instances, it checks the size property. + * For non-function objects, it gets the count of own enumerable string keys. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotEmpty(object: T, message?: string): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that object has a direct or inherited property named by property, + * which can be a string using dot- and bracket-notation for nested reference. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param message Message to display on error. + */ + nestedProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object does not have a property named by property, + * which can be a string using dot- and bracket-notation for nested reference. + * The property cannot exist on the object nor anywhere in its prototype chain. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param message Message to display on error. + */ + notNestedProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a strict equality check (===). + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + nestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object does not have a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a strict equality check (===). + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + notNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object has a property named by property with a value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a deep equality check. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + deepNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object does not have a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a deep equality check. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + notDeepNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + } + + export interface Config { + /** + * Default: false + */ + includeStack: boolean; + + /** + * Default: true + */ + showDiff: boolean; + + /** + * Default: 40 + */ + truncateThreshold: number; + + /** + * Default: true + */ + useProxy: boolean; + + /** + * Default: ['then', 'catch', 'inspect', 'toJSON'] + */ + proxyExcludedKeys: string[]; + + deepEqual: (expected: L, actual: R) => void; + } + + export type { ImportedAssertionError as AssertionError }; + } +} + +export function use(fn: Chai.ChaiPlugin): Chai.ChaiStatic; + +export const util: Chai.ChaiUtils; +export const config: Chai.Config; +export const Assertion: Chai.AssertionStatic; +export const AssertionError: typeof ImportedAssertionError; +export function should(): Chai.Should; +export function Should(): Chai.Should; +export const assert: Chai.AssertStatic; +export const expect: Chai.ExpectStatic; diff --git a/vanilla/node_modules/@types/chai/package.json b/vanilla/node_modules/@types/chai/package.json new file mode 100644 index 0000000..7aec8d1 --- /dev/null +++ b/vanilla/node_modules/@types/chai/package.json @@ -0,0 +1,75 @@ +{ + "name": "@types/chai", + "version": "5.2.3", + "description": "TypeScript definitions for chai", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/chai", + "license": "MIT", + "contributors": [ + { + "name": "Bart van der Schoor", + "githubUsername": "Bartvds", + "url": "https://github.com/Bartvds" + }, + { + "name": "Andrew Brown", + "githubUsername": "AGBrown", + "url": "https://github.com/AGBrown" + }, + { + "name": "Olivier Chevet", + "githubUsername": "olivr70", + "url": "https://github.com/olivr70" + }, + { + "name": "Matt Wistrand", + "githubUsername": "mwistrand", + "url": "https://github.com/mwistrand" + }, + { + "name": "Shaun Luttin", + "githubUsername": "shaunluttin", + "url": "https://github.com/shaunluttin" + }, + { + "name": "Satana Charuwichitratana", + "githubUsername": "micksatana", + "url": "https://github.com/micksatana" + }, + { + "name": "Erik Schierboom", + "githubUsername": "ErikSchierboom", + "url": "https://github.com/ErikSchierboom" + }, + { + "name": "Bogdan Paranytsia", + "githubUsername": "bparan", + "url": "https://github.com/bparan" + }, + { + "name": "CXuesong", + "githubUsername": "CXuesong", + "url": "https://github.com/CXuesong" + }, + { + "name": "Joey Kilpatrick", + "githubUsername": "joeykilpatrick", + "url": "https://github.com/joeykilpatrick" + } + ], + "type": "module", + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/chai" + }, + "scripts": {}, + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "d9d83f1594f42010e624e46e4c8cfeee284bdd04cb05eb0730aec14140f2a833", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/vanilla/node_modules/@types/chai/register-should.d.ts b/vanilla/node_modules/@types/chai/register-should.d.ts new file mode 100644 index 0000000..1e14f93 --- /dev/null +++ b/vanilla/node_modules/@types/chai/register-should.d.ts @@ -0,0 +1,7 @@ +declare global { + interface Object { + should: Chai.Assertion; + } +} + +export {}; diff --git a/vanilla/node_modules/@types/deep-eql/LICENSE b/vanilla/node_modules/@types/deep-eql/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/vanilla/node_modules/@types/deep-eql/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/vanilla/node_modules/@types/deep-eql/README.md b/vanilla/node_modules/@types/deep-eql/README.md new file mode 100644 index 0000000..48d96fc --- /dev/null +++ b/vanilla/node_modules/@types/deep-eql/README.md @@ -0,0 +1,57 @@ +# Installation +> `npm install --save @types/deep-eql` + +# Summary +This package contains type definitions for deep-eql (https://github.com/chaijs/deep-eql). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/deep-eql. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/deep-eql/index.d.ts) +````ts +declare namespace deepEqual { + /** + * Memoization class used to speed up comparison. + */ + class MemoizeMap extends WeakMap {} + + interface DeepEqualOptions { + /** + * Override default algorithm, determining custom equality. + */ + comparator?: (leftHandOperand: T1, rightHandOperand: T2) => boolean | null; + + /** + * Provide a custom memoization object which will cache the results of + * complex objects for a speed boost. + * + * By passing `false` you can disable memoization, but this will cause circular + * references to blow the stack. + */ + memoize?: MemoizeMap | false; + } +} + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param leftHandOperand + * @param rightHandOperand + * @param [options] Additional options + * @return equal match + */ +declare function deepEqual( + leftHandOperand: T1, + rightHandOperand: T2, + options?: deepEqual.DeepEqualOptions, +): boolean; + +export = deepEqual; + +```` + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:05 GMT + * Dependencies: none + +# Credits +These definitions were written by [Rodrigo Pietnechuk](https://github.com/ghnoob). diff --git a/vanilla/node_modules/@types/deep-eql/index.d.ts b/vanilla/node_modules/@types/deep-eql/index.d.ts new file mode 100644 index 0000000..0cdbefe --- /dev/null +++ b/vanilla/node_modules/@types/deep-eql/index.d.ts @@ -0,0 +1,38 @@ +declare namespace deepEqual { + /** + * Memoization class used to speed up comparison. + */ + class MemoizeMap extends WeakMap {} + + interface DeepEqualOptions { + /** + * Override default algorithm, determining custom equality. + */ + comparator?: (leftHandOperand: T1, rightHandOperand: T2) => boolean | null; + + /** + * Provide a custom memoization object which will cache the results of + * complex objects for a speed boost. + * + * By passing `false` you can disable memoization, but this will cause circular + * references to blow the stack. + */ + memoize?: MemoizeMap | false; + } +} + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param leftHandOperand + * @param rightHandOperand + * @param [options] Additional options + * @return equal match + */ +declare function deepEqual( + leftHandOperand: T1, + rightHandOperand: T2, + options?: deepEqual.DeepEqualOptions, +): boolean; + +export = deepEqual; diff --git a/vanilla/node_modules/@types/deep-eql/package.json b/vanilla/node_modules/@types/deep-eql/package.json new file mode 100644 index 0000000..8761581 --- /dev/null +++ b/vanilla/node_modules/@types/deep-eql/package.json @@ -0,0 +1,25 @@ +{ + "name": "@types/deep-eql", + "version": "4.0.2", + "description": "TypeScript definitions for deep-eql", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/deep-eql", + "license": "MIT", + "contributors": [ + { + "name": "Rodrigo Pietnechuk", + "githubUsername": "ghnoob", + "url": "https://github.com/ghnoob" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/deep-eql" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "3b8981ce557947fc00ca08cbd93b4206bfc0943360956867381a0a3f6b1eabf5", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/vanilla/node_modules/@types/estree/LICENSE b/vanilla/node_modules/@types/estree/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/vanilla/node_modules/@types/estree/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/vanilla/node_modules/@types/estree/README.md b/vanilla/node_modules/@types/estree/README.md new file mode 100644 index 0000000..2af760b --- /dev/null +++ b/vanilla/node_modules/@types/estree/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/estree` + +# Summary +This package contains type definitions for estree (https://github.com/estree/estree). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree. + +### Additional Details + * Last updated: Fri, 06 Jun 2025 00:04:33 GMT + * Dependencies: none + +# Credits +These definitions were written by [RReverser](https://github.com/RReverser). diff --git a/vanilla/node_modules/@types/estree/flow.d.ts b/vanilla/node_modules/@types/estree/flow.d.ts new file mode 100644 index 0000000..9d001a9 --- /dev/null +++ b/vanilla/node_modules/@types/estree/flow.d.ts @@ -0,0 +1,167 @@ +declare namespace ESTree { + interface FlowTypeAnnotation extends Node {} + + interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} + + interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {} + + interface FlowDeclaration extends Declaration {} + + interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ArrayTypeAnnotation extends FlowTypeAnnotation { + elementType: FlowTypeAnnotation; + } + + interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ClassImplements extends Node { + id: Identifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface ClassProperty { + key: Expression; + value?: Expression | null; + typeAnnotation?: TypeAnnotation | null; + computed: boolean; + static: boolean; + } + + interface DeclareClass extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + body: ObjectTypeAnnotation; + extends: InterfaceExtends[]; + } + + interface DeclareFunction extends FlowDeclaration { + id: Identifier; + } + + interface DeclareModule extends FlowDeclaration { + id: Literal | Identifier; + body: BlockStatement; + } + + interface DeclareVariable extends FlowDeclaration { + id: Identifier; + } + + interface FunctionTypeAnnotation extends FlowTypeAnnotation { + params: FunctionTypeParam[]; + returnType: FlowTypeAnnotation; + rest?: FunctionTypeParam | null; + typeParameters?: TypeParameterDeclaration | null; + } + + interface FunctionTypeParam { + name: Identifier; + typeAnnotation: FlowTypeAnnotation; + optional: boolean; + } + + interface GenericTypeAnnotation extends FlowTypeAnnotation { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceExtends extends Node { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceDeclaration extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + extends: InterfaceExtends[]; + body: ObjectTypeAnnotation; + } + + interface IntersectionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface NullableTypeAnnotation extends FlowTypeAnnotation { + typeAnnotation: TypeAnnotation; + } + + interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface StringTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface TupleTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface TypeofTypeAnnotation extends FlowTypeAnnotation { + argument: FlowTypeAnnotation; + } + + interface TypeAlias extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + right: FlowTypeAnnotation; + } + + interface TypeAnnotation extends Node { + typeAnnotation: FlowTypeAnnotation; + } + + interface TypeCastExpression extends Expression { + expression: Expression; + typeAnnotation: TypeAnnotation; + } + + interface TypeParameterDeclaration extends Node { + params: Identifier[]; + } + + interface TypeParameterInstantiation extends Node { + params: FlowTypeAnnotation[]; + } + + interface ObjectTypeAnnotation extends FlowTypeAnnotation { + properties: ObjectTypeProperty[]; + indexers: ObjectTypeIndexer[]; + callProperties: ObjectTypeCallProperty[]; + } + + interface ObjectTypeCallProperty extends Node { + value: FunctionTypeAnnotation; + static: boolean; + } + + interface ObjectTypeIndexer extends Node { + id: Identifier; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; + static: boolean; + } + + interface ObjectTypeProperty extends Node { + key: Expression; + value: FlowTypeAnnotation; + optional: boolean; + static: boolean; + } + + interface QualifiedTypeIdentifier extends Node { + qualification: Identifier | QualifiedTypeIdentifier; + id: Identifier; + } + + interface UnionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {} +} diff --git a/vanilla/node_modules/@types/estree/index.d.ts b/vanilla/node_modules/@types/estree/index.d.ts new file mode 100644 index 0000000..2bc66fb --- /dev/null +++ b/vanilla/node_modules/@types/estree/index.d.ts @@ -0,0 +1,694 @@ +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +export interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; +} + +export interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Comment[] | undefined; + trailingComments?: Comment[] | undefined; +} + +export interface NodeMap { + AssignmentProperty: AssignmentProperty; + CatchClause: CatchClause; + Class: Class; + ClassBody: ClassBody; + Expression: Expression; + Function: Function; + Identifier: Identifier; + Literal: Literal; + MethodDefinition: MethodDefinition; + ModuleDeclaration: ModuleDeclaration; + ModuleSpecifier: ModuleSpecifier; + Pattern: Pattern; + PrivateIdentifier: PrivateIdentifier; + Program: Program; + Property: Property; + PropertyDefinition: PropertyDefinition; + SpreadElement: SpreadElement; + Statement: Statement; + Super: Super; + SwitchCase: SwitchCase; + TemplateElement: TemplateElement; + VariableDeclarator: VariableDeclarator; +} + +export type Node = NodeMap[keyof NodeMap]; + +export interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +export interface SourceLocation { + source?: string | null | undefined; + start: Position; + end: Position; +} + +export interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +export interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Comment[] | undefined; +} + +export interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +export interface BaseFunction extends BaseNode { + params: Pattern[]; + generator?: boolean | undefined; + async?: boolean | undefined; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +export type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +export type Statement = + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | Declaration; + +export interface BaseStatement extends BaseNode {} + +export interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +export interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Statement[]; + innerComments?: Comment[] | undefined; +} + +export interface StaticBlock extends Omit { + type: "StaticBlock"; +} + +export interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +export interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null | undefined; +} + +export interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +export interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null | undefined; +} + +export interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null | undefined; +} + +export interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +export interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +export interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null | undefined; +} + +export interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +export interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null | undefined; + finalizer?: BlockStatement | null | undefined; +} + +export interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +export interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +export interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null | undefined; + test?: Expression | null | undefined; + update?: Expression | null | undefined; + body: Statement; +} + +export interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +export interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +export interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +export interface BaseDeclaration extends BaseStatement {} + +export interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +export interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { + id: Identifier; +} + +export interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const" | "using" | "await using"; +} + +export interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null | undefined; +} + +export interface ExpressionMap { + ArrayExpression: ArrayExpression; + ArrowFunctionExpression: ArrowFunctionExpression; + AssignmentExpression: AssignmentExpression; + AwaitExpression: AwaitExpression; + BinaryExpression: BinaryExpression; + CallExpression: CallExpression; + ChainExpression: ChainExpression; + ClassExpression: ClassExpression; + ConditionalExpression: ConditionalExpression; + FunctionExpression: FunctionExpression; + Identifier: Identifier; + ImportExpression: ImportExpression; + Literal: Literal; + LogicalExpression: LogicalExpression; + MemberExpression: MemberExpression; + MetaProperty: MetaProperty; + NewExpression: NewExpression; + ObjectExpression: ObjectExpression; + SequenceExpression: SequenceExpression; + TaggedTemplateExpression: TaggedTemplateExpression; + TemplateLiteral: TemplateLiteral; + ThisExpression: ThisExpression; + UnaryExpression: UnaryExpression; + UpdateExpression: UpdateExpression; + YieldExpression: YieldExpression; +} + +export type Expression = ExpressionMap[keyof ExpressionMap]; + +export interface BaseExpression extends BaseNode {} + +export type ChainElement = SimpleCallExpression | MemberExpression; + +export interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +export interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +export interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +export interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +export interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +export interface Property extends BaseNode { + type: "Property"; + key: Expression | PrivateIdentifier; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +export interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null | undefined; + computed: boolean; + static: boolean; +} + +export interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null | undefined; + type: "FunctionExpression"; + body: BlockStatement; +} + +export interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Expression[]; +} + +export interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +export interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression | PrivateIdentifier; + right: Expression; +} + +export interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +export interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +export interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +export interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +export interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +export type CallExpression = SimpleCallExpression | NewExpression; + +export interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +export interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +export interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +export type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; + +export interface BasePattern extends BaseNode {} + +export interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null | undefined; + consequent: Statement[]; +} + +export interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +export interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +export interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string | undefined; +} + +export interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null | undefined; + regex: { + pattern: string; + flags: string; + }; + raw?: string | undefined; +} + +export interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null | undefined; + bigint: string; + raw?: string | undefined; +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +export type BinaryOperator = + | "==" + | "!=" + | "===" + | "!==" + | "<" + | "<=" + | ">" + | ">=" + | "<<" + | ">>" + | ">>>" + | "+" + | "-" + | "*" + | "/" + | "%" + | "**" + | "|" + | "^" + | "&" + | "in" + | "instanceof"; + +export type LogicalOperator = "||" | "&&" | "??"; + +export type AssignmentOperator = + | "=" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "**=" + | "<<=" + | ">>=" + | ">>>=" + | "|=" + | "^=" + | "&=" + | "||=" + | "&&=" + | "??="; + +export type UpdateOperator = "++" | "--"; + +export interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +export interface Super extends BaseNode { + type: "Super"; +} + +export interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +export interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +export interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null | undefined; + delegate: boolean; +} + +export interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +export interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +export interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null | undefined; + raw: string; + }; +} + +export interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +export interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +export interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +export interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +export interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +export type Class = ClassDeclaration | ClassExpression; +export interface BaseClass extends BaseNode { + superClass?: Expression | null | undefined; + body: ClassBody; +} + +export interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +export interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +export interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +export interface ClassDeclaration extends MaybeNamedClassDeclaration { + id: Identifier; +} + +export interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null | undefined; +} + +export interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +export type ModuleDeclaration = + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration; +export interface BaseModuleDeclaration extends BaseNode {} + +export type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; +export interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +export interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + attributes: ImportAttribute[]; + source: Literal; +} + +export interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier | Literal; +} + +export interface ImportAttribute extends BaseNode { + type: "ImportAttribute"; + key: Identifier | Literal; + value: Literal; +} + +export interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; + options?: Expression | null | undefined; +} + +export interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +export interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +export interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null | undefined; + specifiers: ExportSpecifier[]; + attributes: ImportAttribute[]; + source?: Literal | null | undefined; +} + +export interface ExportSpecifier extends Omit { + type: "ExportSpecifier"; + local: Identifier | Literal; + exported: Identifier | Literal; +} + +export interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; +} + +export interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + exported: Identifier | Literal | null; + attributes: ImportAttribute[]; + source: Literal; +} + +export interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} diff --git a/vanilla/node_modules/@types/estree/package.json b/vanilla/node_modules/@types/estree/package.json new file mode 100644 index 0000000..68c0782 --- /dev/null +++ b/vanilla/node_modules/@types/estree/package.json @@ -0,0 +1,27 @@ +{ + "name": "@types/estree", + "version": "1.0.8", + "description": "TypeScript definitions for estree", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree", + "license": "MIT", + "contributors": [ + { + "name": "RReverser", + "githubUsername": "RReverser", + "url": "https://github.com/RReverser" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/estree" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "7a167b6e4a4d9f6e9a2cb9fd3fc45c885f89cbdeb44b3e5961bb057a45c082fd", + "typeScriptVersion": "5.1", + "nonNpm": true +} \ No newline at end of file diff --git a/vanilla/node_modules/@vitest/coverage-v8/LICENSE b/vanilla/node_modules/@vitest/coverage-v8/LICENSE new file mode 100644 index 0000000..0e5771d --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/browser.d.ts b/vanilla/node_modules/@vitest/coverage-v8/dist/browser.d.ts new file mode 100644 index 0000000..e6c7069 --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/dist/browser.d.ts @@ -0,0 +1,5 @@ +import { CoverageProviderModule } from 'vitest/node'; + +declare const mod: CoverageProviderModule; + +export { mod as default }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/browser.js b/vanilla/node_modules/@vitest/coverage-v8/dist/browser.js new file mode 100644 index 0000000..a57a3e1 --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/dist/browser.js @@ -0,0 +1,58 @@ +import { cdp } from 'vitest/browser'; +import { l as loadProvider } from './load-provider-CdgAx3rL.js'; + +const session = cdp(); +let enabled = false; +const mod = { + async startCoverage() { + if (enabled) { + return; + } + enabled = true; + await session.send("Profiler.enable"); + await session.send("Profiler.startPreciseCoverage", { + callCount: true, + detailed: true + }); + }, + async takeCoverage() { + const coverage = await session.send("Profiler.takePreciseCoverage"); + const result = []; + // Reduce amount of data sent over rpc by doing some early result filtering + for (const entry of coverage.result) { + if (filterResult(entry)) { + result.push({ + ...entry, + url: decodeURIComponent(entry.url.replace(window.location.origin, "")) + }); + } + } + return { result }; + }, + stopCoverage() { + // Browser mode should not stop coverage as same V8 instance is shared between tests + }, + async getProvider() { + return loadProvider(); + } +}; +function filterResult(coverage) { + if (!coverage.url.startsWith(window.location.origin)) { + return false; + } + if (coverage.url.includes("/node_modules/")) { + return false; + } + if (coverage.url.includes("__vitest_browser__")) { + return false; + } + if (coverage.url.includes("__vitest__/assets")) { + return false; + } + if (coverage.url === window.location.href) { + return false; + } + return true; +} + +export { mod as default }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/index.d.ts b/vanilla/node_modules/@vitest/coverage-v8/dist/index.d.ts new file mode 100644 index 0000000..e6c7069 --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/dist/index.d.ts @@ -0,0 +1,5 @@ +import { CoverageProviderModule } from 'vitest/node'; + +declare const mod: CoverageProviderModule; + +export { mod as default }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/index.js b/vanilla/node_modules/@vitest/coverage-v8/dist/index.js new file mode 100644 index 0000000..85d9c9d --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/dist/index.js @@ -0,0 +1,61 @@ +import inspector from 'node:inspector/promises'; +import { fileURLToPath } from 'node:url'; +import { provider } from 'std-env'; +import { l as loadProvider } from './load-provider-CdgAx3rL.js'; +import { n as normalize } from './pathe.M-eThtNZ-BTaAGrLg.js'; + +const session = new inspector.Session(); +let enabled = false; +const mod = { + async startCoverage({ isolate }) { + if (isolate === false && enabled) { + return; + } + enabled = true; + session.connect(); + await session.post("Profiler.enable"); + await session.post("Profiler.startPreciseCoverage", { + callCount: true, + detailed: true + }); + }, + async takeCoverage(options) { + if (provider === "stackblitz") { + return { result: [] }; + } + const coverage = await session.post("Profiler.takePreciseCoverage"); + const result = []; + // Reduce amount of data sent over rpc by doing some early result filtering + for (const entry of coverage.result) { + if (filterResult(entry)) { + result.push({ + ...entry, + startOffset: options?.moduleExecutionInfo?.get(normalize(fileURLToPath(entry.url)))?.startOffset || 0 + }); + } + } + return { result }; + }, + async stopCoverage({ isolate }) { + if (isolate === false) { + return; + } + await session.post("Profiler.stopPreciseCoverage"); + await session.post("Profiler.disable"); + session.disconnect(); + }, + async getProvider() { + return loadProvider(); + } +}; +function filterResult(coverage) { + if (!coverage.url.startsWith("file://")) { + return false; + } + if (coverage.url.includes("/node_modules/")) { + return false; + } + return true; +} + +export { mod as default }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/load-provider-CdgAx3rL.js b/vanilla/node_modules/@vitest/coverage-v8/dist/load-provider-CdgAx3rL.js new file mode 100644 index 0000000..005a532 --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/dist/load-provider-CdgAx3rL.js @@ -0,0 +1,11 @@ +// to not bundle the provider +const name = "./provider.js"; +async function loadProvider() { + const { V8CoverageProvider } = await import( + /* @vite-ignore */ + name +); + return new V8CoverageProvider(); +} + +export { loadProvider as l }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/pathe.M-eThtNZ-BTaAGrLg.js b/vanilla/node_modules/@vitest/coverage-v8/dist/pathe.M-eThtNZ-BTaAGrLg.js new file mode 100644 index 0000000..3f82a78 --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/dist/pathe.M-eThtNZ-BTaAGrLg.js @@ -0,0 +1,104 @@ +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} + +const _UNC_REGEX = /^[/\\]{2}/; +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; +const normalize = function(path) { + if (path.length === 0) { + return "."; + } + path = normalizeWindowsPath(path); + const isUNCPath = path.match(_UNC_REGEX); + const isPathAbsolute = isAbsolute(path); + const trailingSeparator = path[path.length - 1] === "/"; + path = normalizeString(path, !isPathAbsolute); + if (path.length === 0) { + if (isPathAbsolute) { + return "/"; + } + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) { + path += "/"; + } + if (_DRIVE_LETTER_RE.test(path)) { + path += "/"; + } + if (isUNCPath) { + if (!isPathAbsolute) { + return `//./${path}`; + } + return `//${path}`; + } + return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; + +export { normalize as n }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/provider.d.ts b/vanilla/node_modules/@vitest/coverage-v8/dist/provider.d.ts new file mode 100644 index 0000000..4b9f969 --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/dist/provider.d.ts @@ -0,0 +1,25 @@ +import { CoverageMap } from 'istanbul-lib-coverage'; +import { ProxifiedModule } from 'magicast'; +import { Profiler } from 'node:inspector'; +import { ResolvedCoverageOptions, CoverageProvider, Vitest, ReportContext } from 'vitest/node'; +import { BaseCoverageProvider } from 'vitest/coverage'; + +interface ScriptCoverageWithOffset extends Profiler.ScriptCoverage { + startOffset: number; +} +declare class V8CoverageProvider extends BaseCoverageProvider> implements CoverageProvider { + name: "v8"; + version: string; + initialize(ctx: Vitest): void; + createCoverageMap(): CoverageMap; + generateCoverage({ allTestsRun }: ReportContext): Promise; + generateReports(coverageMap: CoverageMap, allTestsRun?: boolean): Promise; + parseConfigModule(configFilePath: string): Promise>; + private getCoverageMapForUncoveredFiles; + private remapCoverage; + private getSources; + private convertCoverage; +} + +export { V8CoverageProvider }; +export type { ScriptCoverageWithOffset }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/provider.js b/vanilla/node_modules/@vitest/coverage-v8/dist/provider.js new file mode 100644 index 0000000..4230309 --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/dist/provider.js @@ -0,0 +1,296 @@ +import { existsSync, promises } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { mergeProcessCovs } from '@bcoe/v8-coverage'; +import astV8ToIstanbul from 'ast-v8-to-istanbul'; +import libCoverage from 'istanbul-lib-coverage'; +import libReport from 'istanbul-lib-report'; +import reports from 'istanbul-reports'; +import { parseModule } from 'magicast'; +import { createDebug } from 'obug'; +import { provider } from 'std-env'; +import c from 'tinyrainbow'; +import { BaseCoverageProvider } from 'vitest/coverage'; +import { parseAstAsync } from 'vitest/node'; +import { n as normalize } from './pathe.M-eThtNZ-BTaAGrLg.js'; + +var version = "4.0.18"; + +const FILE_PROTOCOL = "file://"; +const debug = createDebug("vitest:coverage"); +class V8CoverageProvider extends BaseCoverageProvider { + name = "v8"; + version = version; + initialize(ctx) { + this._initialize(ctx); + } + createCoverageMap() { + return libCoverage.createCoverageMap({}); + } + async generateCoverage({ allTestsRun }) { + const start = debug.enabled ? performance.now() : 0; + const coverageMap = this.createCoverageMap(); + let merged = { result: [] }; + await this.readCoverageFiles({ + onFileRead(coverage) { + merged = mergeProcessCovs([merged, coverage]); + // mergeProcessCovs sometimes loses startOffset, e.g. in vue + merged.result.forEach((result) => { + if (!result.startOffset) { + const original = coverage.result.find((r) => r.url === result.url); + result.startOffset = original?.startOffset || 0; + } + }); + }, + onFinished: async (project, environment) => { + // Source maps can change based on projectName and transform mode. + // Coverage transform re-uses source maps so we need to separate transforms from each other. + const converted = await this.convertCoverage(merged, project, environment); + coverageMap.merge(converted); + merged = { result: [] }; + }, + onDebug: debug + }); + // Include untested files when all tests were run (not a single file re-run) + // or if previous results are preserved by "cleanOnRerun: false" + if (this.options.include != null && (allTestsRun || !this.options.cleanOnRerun)) { + const coveredFiles = coverageMap.files(); + const untestedCoverage = await this.getCoverageMapForUncoveredFiles(coveredFiles); + coverageMap.merge(untestedCoverage); + } + coverageMap.filter((filename) => { + const exists = existsSync(filename); + if (this.options.excludeAfterRemap) { + return exists && this.isIncluded(filename); + } + return exists; + }); + if (debug.enabled) { + debug(`Generate coverage total time ${(performance.now() - start).toFixed()} ms`); + } + return coverageMap; + } + async generateReports(coverageMap, allTestsRun) { + if (provider === "stackblitz") { + this.ctx.logger.log(c.blue(" % ") + c.yellow("@vitest/coverage-v8 does not work on Stackblitz. Report will be empty.")); + } + const context = libReport.createContext({ + dir: this.options.reportsDirectory, + coverageMap, + watermarks: this.options.watermarks + }); + if (this.hasTerminalReporter(this.options.reporter)) { + this.ctx.logger.log(c.blue(" % ") + c.dim("Coverage report from ") + c.yellow(this.name)); + } + for (const reporter of this.options.reporter) { + // Type assertion required for custom reporters + reports.create(reporter[0], { + skipFull: this.options.skipFull, + projectRoot: this.ctx.config.root, + ...reporter[1] + }).execute(context); + } + if (this.options.thresholds) { + await this.reportThresholds(coverageMap, allTestsRun); + } + } + async parseConfigModule(configFilePath) { + return parseModule(await promises.readFile(configFilePath, "utf8")); + } + async getCoverageMapForUncoveredFiles(testedFiles) { + const transform = this.createUncoveredFileTransformer(this.ctx); + const uncoveredFiles = await this.getUntestedFiles(testedFiles); + let index = 0; + const coverageMap = this.createCoverageMap(); + for (const chunk of this.toSlices(uncoveredFiles, this.options.processingConcurrency)) { + if (debug.enabled) { + index += chunk.length; + debug("Uncovered files %d/%d", index, uncoveredFiles.length); + } + await Promise.all(chunk.map(async (filename) => { + let timeout; + let start; + if (debug.enabled) { + start = performance.now(); + timeout = setTimeout(() => debug(c.bgRed(`File "${filename}" is taking longer than 3s`)), 3e3); + } + // Do not use pathToFileURL to avoid encoding filename parts + const url = `file://${filename[0] === "/" ? "" : "/"}${filename}`; + const sources = await this.getSources(url, transform); + coverageMap.merge(await this.remapCoverage(url, 0, sources, [])); + if (debug.enabled) { + clearTimeout(timeout); + const diff = performance.now() - start; + const color = diff > 500 ? c.bgRed : c.bgGreen; + debug(`${color(` ${diff.toFixed()} ms `)} ${filename}`); + } + })); + } + return coverageMap; + } + async remapCoverage(filename, wrapperLength, result, functions) { + let ast; + try { + ast = await parseAstAsync(result.code); + } catch (error) { + this.ctx.logger.error(`Failed to parse ${filename}. Excluding it from coverage.\n`, error); + return {}; + } + return await astV8ToIstanbul({ + code: result.code, + sourceMap: result.map, + ast, + coverage: { + functions, + url: filename + }, + ignoreClassMethods: this.options.ignoreClassMethods, + wrapperLength, + ignoreNode: (node, type) => { + // SSR transformed imports + if (type === "statement" && node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.id.name.startsWith("__vite_ssr_import_")) { + return true; + } + // SSR transformed exports vite@>6.3.5 + if (type === "statement" && node.type === "ExpressionStatement" && node.expression.type === "AssignmentExpression" && node.expression.left.type === "MemberExpression" && node.expression.left.object.type === "Identifier" && node.expression.left.object.name === "__vite_ssr_exports__") { + return true; + } + // SSR transformed exports vite@^6.3.5 + if (type === "statement" && node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.id.name === "__vite_ssr_export_default__") { + return true; + } + // CJS imports as ternaries - e.g. + // const React = __vite__cjsImport0_react.__esModule ? __vite__cjsImport0_react.default : __vite__cjsImport0_react; + if (type === "branch" && node.type === "ConditionalExpression" && node.test.type === "MemberExpression" && node.test.object.type === "Identifier" && node.test.object.name.startsWith("__vite__cjsImport") && node.test.property.type === "Identifier" && node.test.property.name === "__esModule") { + return true; + } + // in-source test with "if (import.meta.vitest)" + if ((type === "branch" || type === "statement") && node.type === "IfStatement" && node.test.type === "MemberExpression" && node.test.property.type === "Identifier" && node.test.property.name === "vitest") { + // SSR + if (node.test.object.type === "Identifier" && node.test.object.name === "__vite_ssr_import_meta__") { + return "ignore-this-and-nested-nodes"; + } + // Web + if (node.test.object.type === "MetaProperty" && node.test.object.meta.name === "import" && node.test.object.property.name === "meta") { + return "ignore-this-and-nested-nodes"; + } + } + // Browser mode's "import.meta.env =" + if (type === "statement" && node.type === "ExpressionStatement" && node.expression.type === "AssignmentExpression" && node.expression.left.type === "MemberExpression" && node.expression.left.object.type === "MetaProperty" && node.expression.left.object.meta.name === "import" && node.expression.left.object.property.name === "meta" && node.expression.left.property.type === "Identifier" && node.expression.left.property.name === "env") { + return true; + } + // SSR mode's "import.meta.env =" + if (type === "statement" && node.type === "ExpressionStatement" && node.expression.type === "AssignmentExpression" && node.expression.left.type === "MemberExpression" && node.expression.left.object.type === "Identifier" && node.expression.left.object.name === "__vite_ssr_import_meta__") { + return true; + } + // SWC's decorators + if (type === "statement" && node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "_ts_decorate") { + return "ignore-this-and-nested-nodes"; + } + } + }); + } + async getSources(url, onTransform, functions = []) { + const transformResult = await onTransform(removeStartsWith(url, FILE_PROTOCOL)).catch(() => undefined); + const map = transformResult?.map; + const code = transformResult?.code; + if (code == null) { + const filePath = normalize(fileURLToPath(url)); + const original = await promises.readFile(filePath, "utf-8").catch(() => { + // If file does not exist construct a dummy source for it. + // These can be files that were generated dynamically during the test run and were removed after it. + const length = findLongestFunctionLength(functions); + return "/".repeat(length); + }); + return { code: original }; + } + // Vue needs special handling for "map.sources" + if (map) { + map.sources ||= []; + map.sources = map.sources.filter((source) => source != null).map((source) => new URL(source, url).href); + if (map.sources.length === 0) { + map.sources.push(url); + } + } + return { + code, + map + }; + } + async convertCoverage(coverage, project = this.ctx.getRootProject(), environment) { + if (environment === "__browser__" && !project.browser) { + throw new Error(`Cannot access browser module graph because it was torn down.`); + } + async function onTransform(filepath) { + if (environment === "__browser__" && project.browser) { + const result = await project.browser.vite.transformRequest(removeStartsWith(filepath, project.config.root)); + if (result) { + return { + ...result, + code: `${result.code}// ` + }; + } + } + return project.vite.environments[environment].transformRequest(filepath); + } + const scriptCoverages = []; + for (const result of coverage.result) { + if (environment === "__browser__") { + if (result.url.startsWith("/@fs")) { + result.url = `${FILE_PROTOCOL}${removeStartsWith(result.url, "/@fs")}`; + } else if (result.url.startsWith(project.config.root)) { + result.url = `${FILE_PROTOCOL}${result.url}`; + } else { + result.url = `${FILE_PROTOCOL}${project.config.root}${result.url}`; + } + } + if (this.isIncluded(fileURLToPath(result.url))) { + scriptCoverages.push({ + ...result, + url: decodeURIComponent(result.url) + }); + } + } + const coverageMap = this.createCoverageMap(); + let index = 0; + for (const chunk of this.toSlices(scriptCoverages, this.options.processingConcurrency)) { + if (debug.enabled) { + index += chunk.length; + debug("Converting %d/%d", index, scriptCoverages.length); + } + await Promise.all(chunk.map(async ({ url, functions, startOffset }) => { + let timeout; + let start; + if (debug.enabled) { + start = performance.now(); + timeout = setTimeout(() => debug(c.bgRed(`File "${fileURLToPath(url)}" is taking longer than 3s`)), 3e3); + } + const sources = await this.getSources(url, onTransform, functions); + coverageMap.merge(await this.remapCoverage(url, startOffset, sources, functions)); + if (debug.enabled) { + clearTimeout(timeout); + const diff = performance.now() - start; + const color = diff > 500 ? c.bgRed : c.bgGreen; + debug(`${color(` ${diff.toFixed()} ms `)} ${fileURLToPath(url)}`); + } + })); + } + return coverageMap; + } +} +/** +* Find the function with highest `endOffset` to determine the length of the file +*/ +function findLongestFunctionLength(functions) { + return functions.reduce((previous, current) => { + const maxEndOffset = current.ranges.reduce((endOffset, range) => Math.max(endOffset, range.endOffset), 0); + return Math.max(previous, maxEndOffset); + }, 0); +} +function removeStartsWith(filepath, start) { + if (filepath.startsWith(start)) { + return filepath.slice(start.length); + } + return filepath; +} + +export { V8CoverageProvider }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/package.json b/vanilla/node_modules/@vitest/coverage-v8/package.json new file mode 100644 index 0000000..4bb7283 --- /dev/null +++ b/vanilla/node_modules/@vitest/coverage-v8/package.json @@ -0,0 +1,76 @@ +{ + "name": "@vitest/coverage-v8", + "type": "module", + "version": "4.0.18", + "description": "V8 coverage provider for Vitest", + "author": "Anthony Fu ", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/coverage-v8#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/coverage-v8" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vite", + "vitest", + "test", + "coverage", + "v8" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./browser": { + "types": "./dist/browser.d.ts", + "default": "./dist/browser.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "peerDependencies": { + "@vitest/browser": "4.0.18", + "vitest": "4.0.18" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + }, + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "ast-v8-to-istanbul": "^0.3.10", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.1", + "obug": "^2.1.1", + "std-env": "^3.10.0", + "tinyrainbow": "^3.0.3", + "@vitest/utils": "4.0.18" + }, + "devDependencies": { + "@types/istanbul-lib-coverage": "^2.0.6", + "@types/istanbul-lib-report": "^3.0.3", + "@types/istanbul-reports": "^3.0.4", + "pathe": "^2.0.3", + "@vitest/browser": "4.0.18", + "vitest": "4.0.18" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch --watch.include 'src/**'" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/@vitest/expect/LICENSE b/vanilla/node_modules/@vitest/expect/LICENSE new file mode 100644 index 0000000..0e5771d --- /dev/null +++ b/vanilla/node_modules/@vitest/expect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vanilla/node_modules/@vitest/expect/README.md b/vanilla/node_modules/@vitest/expect/README.md new file mode 100644 index 0000000..4d7143b --- /dev/null +++ b/vanilla/node_modules/@vitest/expect/README.md @@ -0,0 +1,21 @@ +# @vitest/expect + +Jest's expect matchers as a Chai plugin. + +## Usage + +```js +import { + JestAsymmetricMatchers, + JestChaiExpect, + JestExtend, +} from '@vitest/expect' +import * as chai from 'chai' + +// allows using expect.extend instead of chai.use to extend plugins +chai.use(JestExtend) +// adds all jest matchers to expect +chai.use(JestChaiExpect) +// adds asymmetric matchers like stringContaining, objectContaining +chai.use(JestAsymmetricMatchers) +``` diff --git a/vanilla/node_modules/@vitest/expect/dist/index.d.ts b/vanilla/node_modules/@vitest/expect/dist/index.d.ts new file mode 100644 index 0000000..a296d58 --- /dev/null +++ b/vanilla/node_modules/@vitest/expect/dist/index.d.ts @@ -0,0 +1,806 @@ +import { Test } from '@vitest/runner'; +import { MockInstance } from '@vitest/spy'; +import { Constructable } from '@vitest/utils'; +import { Formatter } from 'tinyrainbow'; +import { StandardSchemaV1 } from '@standard-schema/spec'; +import { diff, printDiffOrStringify } from '@vitest/utils/diff'; +export { DiffOptions } from '@vitest/utils/diff'; +import { stringify } from '@vitest/utils/display'; +import * as chai from 'chai'; +export { chai }; + +declare const MATCHERS_OBJECT: unique symbol; +declare const JEST_MATCHERS_OBJECT: unique symbol; +declare const GLOBAL_EXPECT: unique symbol; +declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol; + +interface AsymmetricMatcherInterface { + asymmetricMatch: (other: unknown, customTesters?: Array) => boolean; + toString: () => string; + getExpectedType?: () => string; + toAsymmetricMatcher?: () => string; +} +declare abstract class AsymmetricMatcher< + T, + State extends MatcherState = MatcherState +> implements AsymmetricMatcherInterface { + protected sample: T; + protected inverse: boolean; + $$typeof: symbol; + constructor(sample: T, inverse?: boolean); + protected getMatcherContext(expect?: Chai.ExpectStatic): State; + abstract asymmetricMatch(other: unknown, customTesters?: Array): boolean; + abstract toString(): string; + getExpectedType?(): string; + toAsymmetricMatcher?(): string; +} +declare class StringContaining extends AsymmetricMatcher { + constructor(sample: string, inverse?: boolean); + asymmetricMatch(other: string): boolean; + toString(): string; + getExpectedType(): string; +} +declare class Anything extends AsymmetricMatcher { + asymmetricMatch(other: unknown): boolean; + toString(): string; + toAsymmetricMatcher(): string; +} +declare class ObjectContaining extends AsymmetricMatcher> { + constructor(sample: Record, inverse?: boolean); + getPrototype(obj: object): any; + hasProperty(obj: object | null, property: string | symbol): boolean; + getProperties(obj: object): (string | symbol)[]; + asymmetricMatch(other: any, customTesters?: Array): boolean; + toString(): string; + getExpectedType(): string; +} +declare class ArrayContaining extends AsymmetricMatcher> { + constructor(sample: Array, inverse?: boolean); + asymmetricMatch(other: Array, customTesters?: Array): boolean; + toString(): string; + getExpectedType(): string; +} +declare class Any extends AsymmetricMatcher { + constructor(sample: unknown); + fnNameFor(func: Function): string; + asymmetricMatch(other: unknown): boolean; + toString(): string; + getExpectedType(): string; + toAsymmetricMatcher(): string; +} +declare class StringMatching extends AsymmetricMatcher { + constructor(sample: string | RegExp, inverse?: boolean); + asymmetricMatch(other: string): boolean; + toString(): string; + getExpectedType(): string; +} +declare class SchemaMatching extends AsymmetricMatcher> { + private result; + constructor(sample: StandardSchemaV1, inverse?: boolean); + asymmetricMatch(other: unknown): boolean; + toString(): string; + getExpectedType(): string; + toAsymmetricMatcher(): string; +} +declare const JestAsymmetricMatchers: ChaiPlugin; + +declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string; +declare function printReceived(object: unknown): string; +declare function printExpected(value: unknown): string; +declare function getMatcherUtils(): { + EXPECTED_COLOR: Formatter; + RECEIVED_COLOR: Formatter; + INVERTED_COLOR: Formatter; + BOLD_WEIGHT: Formatter; + DIM_COLOR: Formatter; + diff: typeof diff; + matcherHint: typeof matcherHint; + printReceived: typeof printReceived; + printExpected: typeof printExpected; + printDiffOrStringify: typeof printDiffOrStringify; + printWithType: typeof printWithType; +}; +declare function printWithType(name: string, value: T, print: (value: T) => string): string; +declare function addCustomEqualityTesters(newTesters: Array): void; + +/** +* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +* +*/ + +type ChaiPlugin = Chai.ChaiPlugin; +type Tester = (this: TesterContext, a: any, b: any, customTesters: Array) => boolean | undefined; +interface TesterContext { + equals: (a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean) => boolean; +} + +interface MatcherHintOptions { + comment?: string; + expectedColor?: Formatter; + isDirectExpectCall?: boolean; + isNot?: boolean; + promise?: string; + receivedColor?: Formatter; + secondArgument?: string; + secondArgumentColor?: Formatter; +} +interface MatcherState { + customTesters: Array; + assertionCalls: number; + currentTestName?: string; + dontThrow?: () => void; + error?: Error; + equals: (a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean) => boolean; + expand?: boolean; + expectedAssertionsNumber?: number | null; + expectedAssertionsNumberErrorGen?: (() => Error) | null; + isExpectingAssertions?: boolean; + isExpectingAssertionsError?: Error | null; + isNot: boolean; + promise: string; + suppressedErrors: Array; + testPath?: string; + utils: ReturnType & { + diff: typeof diff; + stringify: typeof stringify; + iterableEquality: Tester; + subsetEquality: Tester; + }; + soft?: boolean; + poll?: boolean; + task?: Readonly; +} +interface SyncExpectationResult { + pass: boolean; + message: () => string; + actual?: any; + expected?: any; +} +type AsyncExpectationResult = Promise; +type ExpectationResult = SyncExpectationResult | AsyncExpectationResult; +interface RawMatcherFn< + T extends MatcherState = MatcherState, + E extends Array = Array +> { + (this: T, received: any, ...expected: E): ExpectationResult; +} +interface Matchers {} +type MatchersObject = Record> & ThisType & { [K in keyof Matchers]? : RawMatcherFn[K]>> }; +interface ExpectStatic extends Chai.ExpectStatic, Matchers, AsymmetricMatchersContaining { + (actual: T, message?: string): Assertion; + extend: (expects: MatchersObject) => void; + anything: () => any; + any: (constructor: unknown) => any; + getState: () => MatcherState; + setState: (state: Partial) => void; + not: AsymmetricMatchersContaining; +} +interface CustomMatcher { + /** + * Checks that a value satisfies a custom matcher function. + * + * @param matcher - A function returning a boolean based on the custom condition + * @param message - Optional custom error message on failure + * + * @example + * expect(age).toSatisfy(val => val >= 18, 'Age must be at least 18'); + * expect(age).toEqual(expect.toSatisfy(val => val >= 18, 'Age must be at least 18')); + */ + toSatisfy: (matcher: (value: any) => boolean, message?: string) => any; + /** + * Matches if the received value is one of the values in the expected array or set. + * + * @example + * expect(1).toBeOneOf([1, 2, 3]) + * expect('foo').toBeOneOf([expect.any(String)]) + * expect({ a: 1 }).toEqual({ a: expect.toBeOneOf(['1', '2', '3']) }) + */ + toBeOneOf: (sample: Array | Set) => any; +} +interface AsymmetricMatchersContaining extends CustomMatcher { + /** + * Matches if the received string contains the expected substring. + * + * @example + * expect('I have an apple').toEqual(expect.stringContaining('apple')); + * expect({ a: 'test string' }).toEqual({ a: expect.stringContaining('test') }); + */ + stringContaining: (expected: string) => any; + /** + * Matches if the received object contains all properties of the expected object. + * + * @example + * expect({ a: '1', b: 2 }).toEqual(expect.objectContaining({ a: '1' })) + */ + objectContaining: (expected: DeeplyAllowMatchers) => any; + /** + * Matches if the received array contains all elements in the expected array. + * + * @example + * expect(['a', 'b', 'c']).toEqual(expect.arrayContaining(['b', 'a'])); + */ + arrayContaining: (expected: Array>) => any; + /** + * Matches if the received string or regex matches the expected pattern. + * + * @example + * expect('hello world').toEqual(expect.stringMatching(/^hello/)); + * expect('hello world').toEqual(expect.stringMatching('hello')); + */ + stringMatching: (expected: string | RegExp) => any; + /** + * Matches if the received number is within a certain precision of the expected number. + * + * @param precision - Optional decimal precision for comparison. Default is 2. + * + * @example + * expect(10.45).toEqual(expect.closeTo(10.5, 1)); + * expect(5.11).toEqual(expect.closeTo(5.12)); // with default precision + */ + closeTo: (expected: number, precision?: number) => any; + /** + * Matches if the received value validates against a Standard Schema. + * + * @param schema - A Standard Schema V1 compatible schema object + * + * @example + * expect(user).toEqual(expect.schemaMatching(z.object({ name: z.string() }))) + * expect(['hello', 'world']).toEqual([expect.schemaMatching(z.string()), expect.schemaMatching(z.string())]) + */ + schemaMatching: (schema: unknown) => any; +} +type WithAsymmetricMatcher = T | AsymmetricMatcher; +type DeeplyAllowMatchers = T extends Array ? WithAsymmetricMatcher | DeeplyAllowMatchers[] : T extends object ? WithAsymmetricMatcher | { [K in keyof T] : DeeplyAllowMatchers } : WithAsymmetricMatcher; +interface JestAssertion extends jest.Matchers, CustomMatcher { + /** + * Used when you want to check that two objects have the same value. + * This matcher recursively checks the equality of all fields, rather than checking for object identity. + * + * @example + * expect(user).toEqual({ name: 'Alice', age: 30 }); + */ + toEqual: (expected: E) => void; + /** + * Use to test that objects have the same types as well as structure. + * + * @example + * expect(user).toStrictEqual({ name: 'Alice', age: 30 }); + */ + toStrictEqual: (expected: E) => void; + /** + * Checks that a value is what you expect. It calls `Object.is` to compare values. + * Don't use `toBe` with floating-point numbers. + * + * @example + * expect(result).toBe(42); + * expect(status).toBe(true); + */ + toBe: (expected: E) => void; + /** + * Check that a string matches a regular expression. + * + * @example + * expect(message).toMatch(/hello/); + * expect(greeting).toMatch('world'); + */ + toMatch: (expected: string | RegExp) => void; + /** + * Used to check that a JavaScript object matches a subset of the properties of an object + * + * @example + * expect(user).toMatchObject({ + * name: 'Alice', + * address: { city: 'Wonderland' } + * }); + */ + toMatchObject: (expected: E) => void; + /** + * Used when you want to check that an item is in a list. + * For testing the items in the list, this uses `===`, a strict equality check. + * + * @example + * expect(items).toContain('apple'); + * expect(numbers).toContain(5); + */ + toContain: (item: E) => void; + /** + * Used when you want to check that an item is in a list. + * For testing the items in the list, this matcher recursively checks the + * equality of all fields, rather than checking for object identity. + * + * @example + * expect(items).toContainEqual({ name: 'apple', quantity: 1 }); + */ + toContainEqual: (item: E) => void; + /** + * Use when you don't care what a value is, you just want to ensure a value + * is true in a boolean context. In JavaScript, there are six falsy values: + * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. + * + * @example + * expect(user.isActive).toBeTruthy(); + */ + toBeTruthy: () => void; + /** + * When you don't care what a value is, you just want to + * ensure a value is false in a boolean context. + * + * @example + * expect(user.isActive).toBeFalsy(); + */ + toBeFalsy: () => void; + /** + * For comparing floating point numbers. + * + * @example + * expect(score).toBeGreaterThan(10); + */ + toBeGreaterThan: (num: number | bigint) => void; + /** + * For comparing floating point numbers. + * + * @example + * expect(score).toBeGreaterThanOrEqual(10); + */ + toBeGreaterThanOrEqual: (num: number | bigint) => void; + /** + * For comparing floating point numbers. + * + * @example + * expect(score).toBeLessThan(10); + */ + toBeLessThan: (num: number | bigint) => void; + /** + * For comparing floating point numbers. + * + * @example + * expect(score).toBeLessThanOrEqual(10); + */ + toBeLessThanOrEqual: (num: number | bigint) => void; + /** + * Used to check that a variable is NaN. + * + * @example + * expect(value).toBeNaN(); + */ + toBeNaN: () => void; + /** + * Used to check that a variable is undefined. + * + * @example + * expect(value).toBeUndefined(); + */ + toBeUndefined: () => void; + /** + * This is the same as `.toBe(null)` but the error messages are a bit nicer. + * So use `.toBeNull()` when you want to check that something is null. + * + * @example + * expect(value).toBeNull(); + */ + toBeNull: () => void; + /** + * Used to check that a variable is nullable (null or undefined). + * + * @example + * expect(value).toBeNullable(); + */ + toBeNullable: () => void; + /** + * Ensure that a variable is not undefined. + * + * @example + * expect(value).toBeDefined(); + */ + toBeDefined: () => void; + /** + * Ensure that an object is an instance of a class. + * This matcher uses `instanceof` underneath. + * + * @example + * expect(new Date()).toBeInstanceOf(Date); + */ + toBeInstanceOf: (expected: E) => void; + /** + * Used to check that an object has a `.length` property + * and it is set to a certain numeric value. + * + * @example + * expect([1, 2, 3]).toHaveLength(3); + * expect('hello').toHaveLength(5); + */ + toHaveLength: (length: number) => void; + /** + * Use to check if a property at the specified path exists on an object. + * For checking deeply nested properties, you may use dot notation or an array containing + * the path segments for deep references. + * + * Optionally, you can provide a value to check if it matches the value present at the path + * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks + * the equality of all fields. + * + * @example + * expect(user).toHaveProperty('address.city', 'New York'); + * expect(config).toHaveProperty(['settings', 'theme'], 'dark'); + */ + toHaveProperty: (property: string | (string | number)[], value?: E) => void; + /** + * Using exact equality with floating point numbers is a bad idea. + * Rounding means that intuitive things fail. + * The default for `numDigits` is 2. + * + * @example + * expect(price).toBeCloseTo(9.99, 2); + */ + toBeCloseTo: (number: number, numDigits?: number) => void; + /** + * Ensures that a mock function is called an exact number of times. + * + * Also under the alias `expect.toBeCalledTimes`. + * + * @example + * expect(mockFunc).toHaveBeenCalledTimes(2); + */ + toHaveBeenCalledTimes: (times: number) => void; + /** + * Ensures that a mock function is called an exact number of times. + * + * Alias for `expect.toHaveBeenCalledTimes`. + * + * @example + * expect(mockFunc).toBeCalledTimes(2); + */ + toBeCalledTimes: (times: number) => void; + /** + * Ensures that a mock function is called. + * + * Also under the alias `expect.toBeCalled`. + * + * @example + * expect(mockFunc).toHaveBeenCalled(); + */ + toHaveBeenCalled: () => void; + /** + * Ensures that a mock function is called. + * + * Alias for `expect.toHaveBeenCalled`. + * + * @example + * expect(mockFunc).toBeCalled(); + */ + toBeCalled: () => void; + /** + * Ensure that a mock function is called with specific arguments. + * + * Also under the alias `expect.toBeCalledWith`. + * + * @example + * expect(mockFunc).toHaveBeenCalledWith('arg1', 42); + */ + toHaveBeenCalledWith: (...args: E) => void; + /** + * Ensure that a mock function is called with specific arguments. + * + * Alias for `expect.toHaveBeenCalledWith`. + * + * @example + * expect(mockFunc).toBeCalledWith('arg1', 42); + */ + toBeCalledWith: (...args: E) => void; + /** + * Ensure that a mock function is called with specific arguments on an Nth call. + * + * Also under the alias `expect.nthCalledWith`. + * + * @example + * expect(mockFunc).toHaveBeenNthCalledWith(2, 'secondArg'); + */ + toHaveBeenNthCalledWith: (n: number, ...args: E) => void; + /** + * Ensure that a mock function is called with specific arguments on an Nth call. + * + * Alias for `expect.toHaveBeenNthCalledWith`. + * + * @example + * expect(mockFunc).nthCalledWith(2, 'secondArg'); + */ + nthCalledWith: (nthCall: number, ...args: E) => void; + /** + * If you have a mock function, you can use `.toHaveBeenLastCalledWith` + * to test what arguments it was last called with. + * + * Also under the alias `expect.lastCalledWith`. + * + * @example + * expect(mockFunc).toHaveBeenLastCalledWith('lastArg'); + */ + toHaveBeenLastCalledWith: (...args: E) => void; + /** + * If you have a mock function, you can use `.lastCalledWith` + * to test what arguments it was last called with. + * + * Alias for `expect.toHaveBeenLastCalledWith`. + * + * @example + * expect(mockFunc).lastCalledWith('lastArg'); + */ + lastCalledWith: (...args: E) => void; + /** + * Used to test that a function throws when it is called. + * + * Also under the alias `expect.toThrowError`. + * + * @example + * expect(() => functionWithError()).toThrow('Error message'); + * expect(() => parseJSON('invalid')).toThrow(SyntaxError); + */ + toThrow: (expected?: string | Constructable | RegExp | Error) => void; + /** + * Used to test that a function throws when it is called. + * + * Alias for `expect.toThrow`. + * + * @example + * expect(() => functionWithError()).toThrowError('Error message'); + * expect(() => parseJSON('invalid')).toThrowError(SyntaxError); + */ + toThrowError: (expected?: string | Constructable | RegExp | Error) => void; + /** + * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time + * + * Alias for `expect.toHaveReturned`. + * + * @example + * expect(mockFunc).toReturn(); + */ + toReturn: () => void; + /** + * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time + * + * Also under the alias `expect.toReturn`. + * + * @example + * expect(mockFunc).toHaveReturned(); + */ + toHaveReturned: () => void; + /** + * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. + * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. + * + * Alias for `expect.toHaveReturnedTimes`. + * + * @example + * expect(mockFunc).toReturnTimes(3); + */ + toReturnTimes: (times: number) => void; + /** + * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. + * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. + * + * Also under the alias `expect.toReturnTimes`. + * + * @example + * expect(mockFunc).toHaveReturnedTimes(3); + */ + toHaveReturnedTimes: (times: number) => void; + /** + * Use to ensure that a mock function returned a specific value. + * + * Alias for `expect.toHaveReturnedWith`. + * + * @example + * expect(mockFunc).toReturnWith('returnValue'); + */ + toReturnWith: (value: E) => void; + /** + * Use to ensure that a mock function returned a specific value. + * + * Also under the alias `expect.toReturnWith`. + * + * @example + * expect(mockFunc).toHaveReturnedWith('returnValue'); + */ + toHaveReturnedWith: (value: E) => void; + /** + * Use to test the specific value that a mock function last returned. + * If the last call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. + * + * Also under the alias `expect.lastReturnedWith`. + * + * @example + * expect(mockFunc).toHaveLastReturnedWith('lastValue'); + */ + toHaveLastReturnedWith: (value: E) => void; + /** + * Use to test the specific value that a mock function last returned. + * If the last call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. + * + * Alias for `expect.toHaveLastReturnedWith`. + * + * @example + * expect(mockFunc).lastReturnedWith('lastValue'); + */ + lastReturnedWith: (value: E) => void; + /** + * Use to test the specific value that a mock function returned for the nth call. + * If the nth call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. + * + * Also under the alias `expect.nthReturnedWith`. + * + * @example + * expect(mockFunc).toHaveNthReturnedWith(2, 'nthValue'); + */ + toHaveNthReturnedWith: (nthCall: number, value: E) => void; + /** + * Use to test the specific value that a mock function returned for the nth call. + * If the nth call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. + * + * Alias for `expect.toHaveNthReturnedWith`. + * + * @example + * expect(mockFunc).nthReturnedWith(2, 'nthValue'); + */ + nthReturnedWith: (nthCall: number, value: E) => void; +} +type VitestAssertion< + A, + T +> = { [K in keyof A] : A[K] extends Chai.Assertion ? Assertion : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion } & ((type: string, message?: string) => Assertion); +type Promisify = { [K in keyof O] : O[K] extends (...args: infer A) => infer R ? Promisify & ((...args: A) => Promise) : O[K] }; +type PromisifyAssertion = Promisify>; +interface Assertion extends VitestAssertion, JestAssertion, Matchers { + /** + * Ensures a value is of a specific type. + * + * @example + * expect(value).toBeTypeOf('string'); + * expect(number).toBeTypeOf('number'); + */ + toBeTypeOf: (expected: "bigint" | "boolean" | "function" | "number" | "object" | "string" | "symbol" | "undefined") => void; + /** + * Asserts that a mock function was called exactly once. + * + * @example + * expect(mockFunc).toHaveBeenCalledOnce(); + */ + toHaveBeenCalledOnce: () => void; + /** + * Ensure that a mock function is called with specific arguments and called + * exactly once. + * + * @example + * expect(mockFunc).toHaveBeenCalledExactlyOnceWith('arg1', 42); + */ + toHaveBeenCalledExactlyOnceWith: (...args: E) => void; + /** + * This assertion checks if a `Mock` was called before another `Mock`. + * @param mock - A mock function created by `vi.spyOn` or `vi.fn` + * @param failIfNoFirstInvocation - Fail if the first mock was never called + * @example + * const mock1 = vi.fn() + * const mock2 = vi.fn() + * + * mock1() + * mock2() + * mock1() + * + * expect(mock1).toHaveBeenCalledBefore(mock2) + */ + toHaveBeenCalledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void; + /** + * This assertion checks if a `Mock` was called after another `Mock`. + * @param mock - A mock function created by `vi.spyOn` or `vi.fn` + * @param failIfNoFirstInvocation - Fail if the first mock was never called + * @example + * const mock1 = vi.fn() + * const mock2 = vi.fn() + * + * mock2() + * mock1() + * mock2() + * + * expect(mock1).toHaveBeenCalledAfter(mock2) + */ + toHaveBeenCalledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void; + /** + * Checks that a promise resolves successfully at least once. + * + * @example + * await expect(promise).toHaveResolved(); + */ + toHaveResolved: () => void; + /** + * Checks that a promise resolves to a specific value. + * + * @example + * await expect(promise).toHaveResolvedWith('success'); + */ + toHaveResolvedWith: (value: E) => void; + /** + * Ensures a promise resolves a specific number of times. + * + * @example + * expect(mockAsyncFunc).toHaveResolvedTimes(3); + */ + toHaveResolvedTimes: (times: number) => void; + /** + * Asserts that the last resolved value of a promise matches an expected value. + * + * @example + * await expect(mockAsyncFunc).toHaveLastResolvedWith('finalResult'); + */ + toHaveLastResolvedWith: (value: E) => void; + /** + * Ensures a specific value was returned by a promise on the nth resolution. + * + * @example + * await expect(mockAsyncFunc).toHaveNthResolvedWith(2, 'secondResult'); + */ + toHaveNthResolvedWith: (nthCall: number, value: E) => void; + /** + * Verifies that a promise resolves. + * + * @example + * await expect(someAsyncFunc).resolves.toBe(42); + */ + resolves: PromisifyAssertion; + /** + * Verifies that a promise rejects. + * + * @example + * await expect(someAsyncFunc).rejects.toThrow('error'); + */ + rejects: PromisifyAssertion; +} +declare global { + namespace jest { + interface Matchers< + R, + T = {} + > {} + } +} + +declare const customMatchers: MatchersObject; + +declare const JestChaiExpect: ChaiPlugin; + +declare const JestExtend: ChaiPlugin; + +declare function equals(a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean): boolean; +declare function isAsymmetric(obj: any): obj is AsymmetricMatcher; +declare function hasAsymmetric(obj: any, seen?: Set): boolean; +declare function isA(typeName: string, value: unknown): boolean; +declare function fnNameFor(func: Function): string; +declare function hasProperty(obj: object | null, property: string): boolean; +declare function isImmutableUnorderedKeyed(maybeKeyed: any): boolean; +declare function isImmutableUnorderedSet(maybeSet: any): boolean; +declare function iterableEquality(a: any, b: any, customTesters?: Array, aStack?: Array, bStack?: Array): boolean | undefined; +declare function subsetEquality(object: unknown, subset: unknown, customTesters?: Array): boolean | undefined; +declare function typeEquality(a: any, b: any): boolean | undefined; +declare function arrayBufferEquality(a: unknown, b: unknown): boolean | undefined; +declare function sparseArrayEquality(a: unknown, b: unknown, customTesters?: Array): boolean | undefined; +declare function generateToBeMessage(deepEqualityName: string, expected?: string, actual?: string): string; +declare function pluralize(word: string, count: number): string; +declare function getObjectKeys(object: object): Array; +declare function getObjectSubset(object: any, subset: any, customTesters: Array): { + subset: any; + stripped: number; +}; +/** +* Detects if an object is a Standard Schema V1 compatible schema +*/ +declare function isStandardSchema(obj: any): obj is StandardSchemaV1; + +declare function getState(expect: ExpectStatic): State; +declare function setState(state: Partial, expect: ExpectStatic): void; + +export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality }; +export type { Assertion, AsymmetricMatcherInterface, AsymmetricMatchersContaining, AsyncExpectationResult, ChaiPlugin, DeeplyAllowMatchers, ExpectStatic, ExpectationResult, JestAssertion, MatcherHintOptions, MatcherState, Matchers, MatchersObject, PromisifyAssertion, RawMatcherFn, SyncExpectationResult, Tester, TesterContext }; diff --git a/vanilla/node_modules/@vitest/expect/dist/index.js b/vanilla/node_modules/@vitest/expect/dist/index.js new file mode 100644 index 0000000..ec7e5f9 --- /dev/null +++ b/vanilla/node_modules/@vitest/expect/dist/index.js @@ -0,0 +1,1875 @@ +import { printDiffOrStringify, diff } from '@vitest/utils/diff'; +import { stringify } from '@vitest/utils/display'; +import { getType, isObject, noop, assertTypes } from '@vitest/utils/helpers'; +import c from 'tinyrainbow'; +import { isMockFunction } from '@vitest/spy'; +import { processError } from '@vitest/utils/error'; +import { use, util } from 'chai'; +import * as chai from 'chai'; +export { chai }; + +const MATCHERS_OBJECT = Symbol.for("matchers-object"); +const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object"); +const GLOBAL_EXPECT = Symbol.for("expect-global"); +const ASYMMETRIC_MATCHERS_OBJECT = Symbol.for("asymmetric-matchers-object"); + +// selectively ported from https://github.com/jest-community/jest-extended +const customMatchers = { + toSatisfy(actual, expected, message) { + const { printReceived, printExpected, matcherHint } = this.utils; + const pass = expected(actual); + return { + pass, + message: () => pass ? `\ +${matcherHint(".not.toSatisfy", "received", "")} + +Expected value to not satisfy: +${message || printExpected(expected)} +Received: +${printReceived(actual)}` : `\ +${matcherHint(".toSatisfy", "received", "")} + +Expected value to satisfy: +${message || printExpected(expected)} + +Received: +${printReceived(actual)}` + }; + }, + toBeOneOf(actual, expected) { + const { equals, customTesters } = this; + const { printReceived, printExpected, matcherHint } = this.utils; + let pass; + if (Array.isArray(expected)) { + pass = expected.length === 0 || expected.some((item) => equals(item, actual, customTesters)); + } else if (expected instanceof Set) { + pass = expected.size === 0 || expected.has(actual) || [...expected].some((item) => equals(item, actual, customTesters)); + } else { + throw new TypeError(`You must provide an array or set to ${matcherHint(".toBeOneOf")}, not '${typeof expected}'.`); + } + return { + pass, + message: () => pass ? `\ +${matcherHint(".not.toBeOneOf", "received", "")} + +Expected value to not be one of: +${printExpected(expected)} +Received: +${printReceived(actual)}` : `\ +${matcherHint(".toBeOneOf", "received", "")} + +Expected value to be one of: +${printExpected(expected)} + +Received: +${printReceived(actual)}` + }; + } +}; + +const EXPECTED_COLOR = c.green; +const RECEIVED_COLOR = c.red; +const INVERTED_COLOR = c.inverse; +const BOLD_WEIGHT = c.bold; +const DIM_COLOR = c.dim; +function matcherHint(matcherName, received = "received", expected = "expected", options = {}) { + const { comment = "", isDirectExpectCall = false, isNot = false, promise = "", secondArgument = "", expectedColor = EXPECTED_COLOR, receivedColor = RECEIVED_COLOR, secondArgumentColor = EXPECTED_COLOR } = options; + let hint = ""; + let dimString = "expect"; + if (!isDirectExpectCall && received !== "") { + hint += DIM_COLOR(`${dimString}(`) + receivedColor(received); + dimString = ")"; + } + if (promise !== "") { + hint += DIM_COLOR(`${dimString}.`) + promise; + dimString = ""; + } + if (isNot) { + hint += `${DIM_COLOR(`${dimString}.`)}not`; + dimString = ""; + } + if (matcherName.includes(".")) { + // Old format: for backward compatibility, + // especially without promise or isNot options + dimString += matcherName; + } else { + // New format: omit period from matcherName arg + hint += DIM_COLOR(`${dimString}.`) + matcherName; + dimString = ""; + } + if (expected === "") { + dimString += "()"; + } else { + hint += DIM_COLOR(`${dimString}(`) + expectedColor(expected); + if (secondArgument) { + hint += DIM_COLOR(", ") + secondArgumentColor(secondArgument); + } + dimString = ")"; + } + if (comment !== "") { + dimString += ` // ${comment}`; + } + if (dimString !== "") { + hint += DIM_COLOR(dimString); + } + return hint; +} +const SPACE_SYMBOL = "·"; +// Instead of inverse highlight which now implies a change, +// replace common spaces with middle dot at the end of any line. +function replaceTrailingSpaces(text) { + return text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length)); +} +function printReceived(object) { + return RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); +} +function printExpected(value) { + return EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); +} +function getMatcherUtils() { + return { + EXPECTED_COLOR, + RECEIVED_COLOR, + INVERTED_COLOR, + BOLD_WEIGHT, + DIM_COLOR, + diff, + matcherHint, + printReceived, + printExpected, + printDiffOrStringify, + printWithType + }; +} +function printWithType(name, value, print) { + const type = getType(value); + const hasType = type !== "null" && type !== "undefined" ? `${name} has type: ${type}\n` : ""; + const hasValue = `${name} has value: ${print(value)}`; + return hasType + hasValue; +} +function addCustomEqualityTesters(newTesters) { + if (!Array.isArray(newTesters)) { + throw new TypeError(`expect.customEqualityTesters: Must be set to an array of Testers. Was given "${getType(newTesters)}"`); + } + globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters.push(...newTesters); +} +function getCustomEqualityTesters() { + return globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters; +} + +// Extracted out of jasmine 2.5.2 +function equals(a, b, customTesters, strictCheck) { + customTesters = customTesters || []; + return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey); +} +const functionToString = Function.prototype.toString; +function isAsymmetric(obj) { + return !!obj && typeof obj === "object" && "asymmetricMatch" in obj && isA("Function", obj.asymmetricMatch); +} +function hasAsymmetric(obj, seen = new Set()) { + if (seen.has(obj)) { + return false; + } + seen.add(obj); + if (isAsymmetric(obj)) { + return true; + } + if (Array.isArray(obj)) { + return obj.some((i) => hasAsymmetric(i, seen)); + } + if (obj instanceof Set) { + return Array.from(obj).some((i) => hasAsymmetric(i, seen)); + } + if (isObject(obj)) { + return Object.values(obj).some((v) => hasAsymmetric(v, seen)); + } + return false; +} +function asymmetricMatch(a, b, customTesters) { + const asymmetricA = isAsymmetric(a); + const asymmetricB = isAsymmetric(b); + if (asymmetricA && asymmetricB) { + return undefined; + } + if (asymmetricA) { + return a.asymmetricMatch(b, customTesters); + } + if (asymmetricB) { + return b.asymmetricMatch(a, customTesters); + } +} +// Equality function lovingly adapted from isEqual in +// [Underscore](http://underscorejs.org) +function eq(a, b, aStack, bStack, customTesters, hasKey) { + let result = true; + const asymmetricResult = asymmetricMatch(a, b, customTesters); + if (asymmetricResult !== undefined) { + return asymmetricResult; + } + const testerContext = { equals }; + for (let i = 0; i < customTesters.length; i++) { + const customTesterResult = customTesters[i].call(testerContext, a, b, customTesters); + if (customTesterResult !== undefined) { + return customTesterResult; + } + } + if (typeof URL === "function" && a instanceof URL && b instanceof URL) { + return a.href === b.href; + } + if (Object.is(a, b)) { + return true; + } + // A strict comparison is necessary because `null == undefined`. + if (a === null || b === null) { + return a === b; + } + const className = Object.prototype.toString.call(a); + if (className !== Object.prototype.toString.call(b)) { + return false; + } + switch (className) { + case "[object Boolean]": + case "[object String]": + case "[object Number]": if (typeof a !== typeof b) { + // One is a primitive, one a `new Primitive()` + return false; + } else if (typeof a !== "object" && typeof b !== "object") { + // both are proper primitives + return Object.is(a, b); + } else { + // both are `new Primitive()`s + return Object.is(a.valueOf(), b.valueOf()); + } + case "[object Date]": { + const numA = +a; + const numB = +b; + // Coerce dates to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are equivalent. + return numA === numB || Number.isNaN(numA) && Number.isNaN(numB); + } + case "[object RegExp]": return a.source === b.source && a.flags === b.flags; + case "[object Temporal.Instant]": + case "[object Temporal.ZonedDateTime]": + case "[object Temporal.PlainDateTime]": + case "[object Temporal.PlainDate]": + case "[object Temporal.PlainTime]": + case "[object Temporal.PlainYearMonth]": + case "[object Temporal.PlainMonthDay]": return a.equals(b); + case "[object Temporal.Duration]": return a.toString() === b.toString(); + } + if (typeof a !== "object" || typeof b !== "object") { + return false; + } + // Use DOM3 method isEqualNode (IE>=9) + if (isDomNode(a) && isDomNode(b)) { + return a.isEqualNode(b); + } + // Used to detect circular references. + let length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + // circular references at same depth are equal + // circular reference is not equal to non-circular one + if (aStack[length] === a) { + return bStack[length] === b; + } else if (bStack[length] === b) { + return false; + } + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + // Recursively compare objects and arrays. + // Compare array lengths to determine if a deep comparison is necessary. + if (className === "[object Array]" && a.length !== b.length) { + return false; + } + if (a instanceof Error && b instanceof Error) { + try { + return isErrorEqual(a, b, aStack, bStack, customTesters, hasKey); + } finally { + aStack.pop(); + bStack.pop(); + } + } + // Deep compare objects. + const aKeys = keys(a, hasKey); + let key; + let size = aKeys.length; + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (keys(b, hasKey).length !== size) { + return false; + } + while (size--) { + key = aKeys[size]; + // Deep compare each member + result = hasKey(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey); + if (!result) { + return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return result; +} +function isErrorEqual(a, b, aStack, bStack, customTesters, hasKey) { + // https://nodejs.org/docs/latest-v22.x/api/assert.html#comparison-details + // - [[Prototype]] of objects are compared using the === operator. + // - Only enumerable "own" properties are considered. + // - Error names, messages, causes, and errors are always compared, even if these are not enumerable properties. errors is also compared. + let result = Object.getPrototypeOf(a) === Object.getPrototypeOf(b) && a.name === b.name && a.message === b.message; + // check Error.cause asymmetrically + if (typeof b.cause !== "undefined") { + result && (result = eq(a.cause, b.cause, aStack, bStack, customTesters, hasKey)); + } + // AggregateError.errors + if (a instanceof AggregateError && b instanceof AggregateError) { + result && (result = eq(a.errors, b.errors, aStack, bStack, customTesters, hasKey)); + } + // spread to compare enumerable properties + result && (result = eq({ ...a }, { ...b }, aStack, bStack, customTesters, hasKey)); + return result; +} +function keys(obj, hasKey) { + const keys = []; + for (const key in obj) { + if (hasKey(obj, key)) { + keys.push(key); + } + } + return keys.concat(Object.getOwnPropertySymbols(obj).filter((symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable)); +} +function hasDefinedKey(obj, key) { + return hasKey(obj, key) && obj[key] !== undefined; +} +function hasKey(obj, key) { + return Object.hasOwn(obj, key); +} +function isA(typeName, value) { + return Object.prototype.toString.apply(value) === `[object ${typeName}]`; +} +function isDomNode(obj) { + return obj !== null && typeof obj === "object" && "nodeType" in obj && typeof obj.nodeType === "number" && "nodeName" in obj && typeof obj.nodeName === "string" && "isEqualNode" in obj && typeof obj.isEqualNode === "function"; +} +function fnNameFor(func) { + if (func.name) { + return func.name; + } + const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*(?:\*\s*)?([\w$]+)\s*\(/); + return matches ? matches[1] : ""; +} +function getPrototype(obj) { + if (Object.getPrototypeOf) { + return Object.getPrototypeOf(obj); + } + if (obj.constructor.prototype === obj) { + return null; + } + return obj.constructor.prototype; +} +function hasProperty(obj, property) { + if (!obj) { + return false; + } + if (Object.hasOwn(obj, property)) { + return true; + } + return hasProperty(getPrototype(obj), property); +} +// SENTINEL constants are from https://github.com/facebook/immutable-js +const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@"; +const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@"; +const IS_LIST_SENTINEL = "@@__IMMUTABLE_LIST__@@"; +const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@"; +const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@"; +function isImmutableUnorderedKeyed(maybeKeyed) { + return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL] && !maybeKeyed[IS_ORDERED_SENTINEL]); +} +function isImmutableUnorderedSet(maybeSet) { + return !!(maybeSet && maybeSet[IS_SET_SENTINEL] && !maybeSet[IS_ORDERED_SENTINEL]); +} +function isObjectLiteral(source) { + return source != null && typeof source === "object" && !Array.isArray(source); +} +function isImmutableList(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_LIST_SENTINEL]); +} +function isImmutableOrderedKeyed(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_KEYED_SENTINEL] && source[IS_ORDERED_SENTINEL]); +} +function isImmutableOrderedSet(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_SET_SENTINEL] && source[IS_ORDERED_SENTINEL]); +} +function isImmutableRecord(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_RECORD_SYMBOL]); +} +/** +* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +* +*/ +const IteratorSymbol = Symbol.iterator; +function hasIterator(object) { + return !!(object != null && object[IteratorSymbol]); +} +function iterableEquality(a, b, customTesters = [], aStack = [], bStack = []) { + if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b)) { + return undefined; + } + if (a.constructor !== b.constructor) { + return false; + } + let length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + // circular references at same depth are equal + // circular reference is not equal to non-circular one + if (aStack[length] === a) { + return bStack[length] === b; + } + } + aStack.push(a); + bStack.push(b); + const filteredCustomTesters = [...customTesters.filter((t) => t !== iterableEquality), iterableEqualityWithStack]; + function iterableEqualityWithStack(a, b) { + return iterableEquality(a, b, [...customTesters], [...aStack], [...bStack]); + } + if (a.size !== undefined) { + if (a.size !== b.size) { + return false; + } else if (isA("Set", a) || isImmutableUnorderedSet(a)) { + let allFound = true; + for (const aValue of a) { + if (!b.has(aValue)) { + let has = false; + for (const bValue of b) { + const isEqual = equals(aValue, bValue, filteredCustomTesters); + if (isEqual === true) { + has = true; + } + } + if (has === false) { + allFound = false; + break; + } + } + } + // Remove the first value from the stack of traversed values. + aStack.pop(); + bStack.pop(); + return allFound; + } else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) { + let allFound = true; + for (const aEntry of a) { + if (!b.has(aEntry[0]) || !equals(aEntry[1], b.get(aEntry[0]), filteredCustomTesters)) { + let has = false; + for (const bEntry of b) { + const matchedKey = equals(aEntry[0], bEntry[0], filteredCustomTesters); + let matchedValue = false; + if (matchedKey === true) { + matchedValue = equals(aEntry[1], bEntry[1], filteredCustomTesters); + } + if (matchedValue === true) { + has = true; + } + } + if (has === false) { + allFound = false; + break; + } + } + } + // Remove the first value from the stack of traversed values. + aStack.pop(); + bStack.pop(); + return allFound; + } + } + const bIterator = b[IteratorSymbol](); + for (const aValue of a) { + const nextB = bIterator.next(); + if (nextB.done || !equals(aValue, nextB.value, filteredCustomTesters)) { + return false; + } + } + if (!bIterator.next().done) { + return false; + } + if (!isImmutableList(a) && !isImmutableOrderedKeyed(a) && !isImmutableOrderedSet(a) && !isImmutableRecord(a)) { + const aEntries = Object.entries(a); + const bEntries = Object.entries(b); + if (!equals(aEntries, bEntries, filteredCustomTesters)) { + return false; + } + } + // Remove the first value from the stack of traversed values. + aStack.pop(); + bStack.pop(); + return true; +} +/** +* Checks if `hasOwnProperty(object, key)` up the prototype chain, stopping at `Object.prototype`. +*/ +function hasPropertyInObject(object, key) { + const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype; + if (shouldTerminate) { + return false; + } + return Object.hasOwn(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key); +} +function isObjectWithKeys(a) { + return isObject(a) && !(a instanceof Error) && !Array.isArray(a) && !(a instanceof Date); +} +function subsetEquality(object, subset, customTesters = []) { + const filteredCustomTesters = customTesters.filter((t) => t !== subsetEquality); + // subsetEquality needs to keep track of the references + // it has already visited to avoid infinite loops in case + // there are circular references in the subset passed to it. + const subsetEqualityWithContext = (seenReferences = new WeakMap()) => (object, subset) => { + if (!isObjectWithKeys(subset)) { + return undefined; + } + return Object.keys(subset).every((key) => { + if (subset[key] != null && typeof subset[key] === "object") { + if (seenReferences.has(subset[key])) { + return equals(object[key], subset[key], filteredCustomTesters); + } + seenReferences.set(subset[key], true); + } + const result = object != null && hasPropertyInObject(object, key) && equals(object[key], subset[key], [...filteredCustomTesters, subsetEqualityWithContext(seenReferences)]); + // The main goal of using seenReference is to avoid circular node on tree. + // It will only happen within a parent and its child, not a node and nodes next to it (same level) + // We should keep the reference for a parent and its child only + // Thus we should delete the reference immediately so that it doesn't interfere + // other nodes within the same level on tree. + seenReferences.delete(subset[key]); + return result; + }); + }; + return subsetEqualityWithContext()(object, subset); +} +function typeEquality(a, b) { + if (a == null || b == null || a.constructor === b.constructor) { + return undefined; + } + return false; +} +function arrayBufferEquality(a, b) { + let dataViewA = a; + let dataViewB = b; + if (!(a instanceof DataView && b instanceof DataView)) { + if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) { + return undefined; + } + try { + dataViewA = new DataView(a); + dataViewB = new DataView(b); + } catch { + return undefined; + } + } + // Buffers are not equal when they do not have the same byte length + if (dataViewA.byteLength !== dataViewB.byteLength) { + return false; + } + // Check if every byte value is equal to each other + for (let i = 0; i < dataViewA.byteLength; i++) { + if (dataViewA.getUint8(i) !== dataViewB.getUint8(i)) { + return false; + } + } + return true; +} +function sparseArrayEquality(a, b, customTesters = []) { + if (!Array.isArray(a) || !Array.isArray(b)) { + return undefined; + } + // A sparse array [, , 1] will have keys ["2"] whereas [undefined, undefined, 1] will have keys ["0", "1", "2"] + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + const filteredCustomTesters = customTesters.filter((t) => t !== sparseArrayEquality); + return equals(a, b, filteredCustomTesters, true) && equals(aKeys, bKeys); +} +function generateToBeMessage(deepEqualityName, expected = "#{this}", actual = "#{exp}") { + const toBeMessage = `expected ${expected} to be ${actual} // Object.is equality`; + if (["toStrictEqual", "toEqual"].includes(deepEqualityName)) { + return `${toBeMessage}\n\nIf it should pass with deep equality, replace "toBe" with "${deepEqualityName}"\n\nExpected: ${expected}\nReceived: serializes to the same string\n`; + } + return toBeMessage; +} +function pluralize(word, count) { + return `${count} ${word}${count === 1 ? "" : "s"}`; +} +function getObjectKeys(object) { + return [...Object.keys(object), ...Object.getOwnPropertySymbols(object).filter((s) => { + var _Object$getOwnPropert; + return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(object, s)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.enumerable; + })]; +} +function getObjectSubset(object, subset, customTesters) { + let stripped = 0; + const getObjectSubsetWithContext = (seenReferences = new WeakMap()) => (object, subset) => { + if (Array.isArray(object)) { + if (Array.isArray(subset) && subset.length === object.length) { + // The map method returns correct subclass of subset. + return subset.map((sub, i) => getObjectSubsetWithContext(seenReferences)(object[i], sub)); + } + } else if (object instanceof Date) { + return object; + } else if (isObject(object) && isObject(subset)) { + if (equals(object, subset, [ + ...customTesters, + iterableEquality, + subsetEquality + ])) { + // return "expected" subset to avoid showing irrelevant toMatchObject diff + return subset; + } + const trimmed = {}; + seenReferences.set(object, trimmed); + // preserve constructor for toMatchObject diff + if (typeof object.constructor === "function" && typeof object.constructor.name === "string") { + Object.defineProperty(trimmed, "constructor", { + enumerable: false, + value: object.constructor + }); + } + for (const key of getObjectKeys(object)) { + if (hasPropertyInObject(subset, key)) { + trimmed[key] = seenReferences.has(object[key]) ? seenReferences.get(object[key]) : getObjectSubsetWithContext(seenReferences)(object[key], subset[key]); + } else { + if (!seenReferences.has(object[key])) { + stripped += 1; + if (isObject(object[key])) { + stripped += getObjectKeys(object[key]).length; + } + getObjectSubsetWithContext(seenReferences)(object[key], subset[key]); + } + } + } + if (getObjectKeys(trimmed).length > 0) { + return trimmed; + } + } + return object; + }; + return { + subset: getObjectSubsetWithContext()(object, subset), + stripped + }; +} +/** +* Detects if an object is a Standard Schema V1 compatible schema +*/ +function isStandardSchema(obj) { + return !!obj && (typeof obj === "object" || typeof obj === "function") && obj["~standard"] && typeof obj["~standard"].validate === "function"; +} + +if (!Object.hasOwn(globalThis, MATCHERS_OBJECT)) { + const globalState = new WeakMap(); + const matchers = Object.create(null); + const customEqualityTesters = []; + const asymmetricMatchers = Object.create(null); + Object.defineProperty(globalThis, MATCHERS_OBJECT, { get: () => globalState }); + Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, { + configurable: true, + get: () => ({ + state: globalState.get(globalThis[GLOBAL_EXPECT]), + matchers, + customEqualityTesters + }) + }); + Object.defineProperty(globalThis, ASYMMETRIC_MATCHERS_OBJECT, { get: () => asymmetricMatchers }); +} +function getState(expect) { + return globalThis[MATCHERS_OBJECT].get(expect); +} +function setState(state, expect) { + const map = globalThis[MATCHERS_OBJECT]; + const current = map.get(expect) || {}; + // so it keeps getters from `testPath` + const results = Object.defineProperties(current, { + ...Object.getOwnPropertyDescriptors(current), + ...Object.getOwnPropertyDescriptors(state) + }); + map.set(expect, results); +} + +class AsymmetricMatcher { + // should have "jest" to be compatible with its ecosystem + $$typeof = Symbol.for("jest.asymmetricMatcher"); + constructor(sample, inverse = false) { + this.sample = sample; + this.inverse = inverse; + } + getMatcherContext(expect) { + return { + ...getState(expect || globalThis[GLOBAL_EXPECT]), + equals, + isNot: this.inverse, + customTesters: getCustomEqualityTesters(), + utils: { + ...getMatcherUtils(), + diff, + stringify, + iterableEquality, + subsetEquality + } + }; + } +} +// implement custom chai/loupe inspect for better AssertionError.message formatting +// https://github.com/chaijs/loupe/blob/9b8a6deabcd50adc056a64fb705896194710c5c6/src/index.ts#L29 +// @ts-expect-error computed properties is not supported when isolatedDeclarations is enabled +// FIXME: https://github.com/microsoft/TypeScript/issues/61068 +AsymmetricMatcher.prototype[Symbol.for("chai/inspect")] = function(options) { + // minimal pretty-format with simple manual truncation + const result = stringify(this, options.depth, { min: true }); + if (result.length <= options.truncate) { + return result; + } + return `${this.toString()}{…}`; +}; +class StringContaining extends AsymmetricMatcher { + constructor(sample, inverse = false) { + if (!isA("String", sample)) { + throw new Error("Expected is not a string"); + } + super(sample, inverse); + } + asymmetricMatch(other) { + const result = isA("String", other) && other.includes(this.sample); + return this.inverse ? !result : result; + } + toString() { + return `String${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "string"; + } +} +class Anything extends AsymmetricMatcher { + asymmetricMatch(other) { + return other != null; + } + toString() { + return "Anything"; + } + toAsymmetricMatcher() { + return "Anything"; + } +} +class ObjectContaining extends AsymmetricMatcher { + constructor(sample, inverse = false) { + super(sample, inverse); + } + getPrototype(obj) { + if (Object.getPrototypeOf) { + return Object.getPrototypeOf(obj); + } + if (obj.constructor.prototype === obj) { + return null; + } + return obj.constructor.prototype; + } + hasProperty(obj, property) { + if (!obj) { + return false; + } + if (Object.hasOwn(obj, property)) { + return true; + } + return this.hasProperty(this.getPrototype(obj), property); + } + getProperties(obj) { + return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj).filter((s) => { + var _Object$getOwnPropert; + return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(obj, s)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.enumerable; + })]; + } + asymmetricMatch(other, customTesters) { + if (typeof this.sample !== "object") { + throw new TypeError(`You must provide an object to ${this.toString()}, not '${typeof this.sample}'.`); + } + let result = true; + const properties = this.getProperties(this.sample); + for (const property of properties) { + var _Object$getOwnPropert2, _Object$getOwnPropert3; + if (!this.hasProperty(other, property)) { + result = false; + break; + } + const value = ((_Object$getOwnPropert2 = Object.getOwnPropertyDescriptor(this.sample, property)) === null || _Object$getOwnPropert2 === void 0 ? void 0 : _Object$getOwnPropert2.value) ?? this.sample[property]; + const otherValue = ((_Object$getOwnPropert3 = Object.getOwnPropertyDescriptor(other, property)) === null || _Object$getOwnPropert3 === void 0 ? void 0 : _Object$getOwnPropert3.value) ?? other[property]; + if (!equals(value, otherValue, customTesters)) { + result = false; + break; + } + } + return this.inverse ? !result : result; + } + toString() { + return `Object${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "object"; + } +} +class ArrayContaining extends AsymmetricMatcher { + constructor(sample, inverse = false) { + super(sample, inverse); + } + asymmetricMatch(other, customTesters) { + if (!Array.isArray(this.sample)) { + throw new TypeError(`You must provide an array to ${this.toString()}, not '${typeof this.sample}'.`); + } + const result = this.sample.length === 0 || Array.isArray(other) && this.sample.every((item) => other.some((another) => equals(item, another, customTesters))); + return this.inverse ? !result : result; + } + toString() { + return `Array${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "array"; + } +} +class Any extends AsymmetricMatcher { + constructor(sample) { + if (typeof sample === "undefined") { + throw new TypeError("any() expects to be passed a constructor function. " + "Please pass one or use anything() to match any object."); + } + super(sample); + } + fnNameFor(func) { + if (func.name) { + return func.name; + } + const functionToString = Function.prototype.toString; + const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*(?:\*\s*)?([\w$]+)\s*\(/); + return matches ? matches[1] : ""; + } + asymmetricMatch(other) { + if (this.sample === String) { + return typeof other == "string" || other instanceof String; + } + if (this.sample === Number) { + return typeof other == "number" || other instanceof Number; + } + if (this.sample === Function) { + return typeof other == "function" || typeof other === "function"; + } + if (this.sample === Boolean) { + return typeof other == "boolean" || other instanceof Boolean; + } + if (this.sample === BigInt) { + return typeof other == "bigint" || other instanceof BigInt; + } + if (this.sample === Symbol) { + return typeof other == "symbol" || other instanceof Symbol; + } + if (this.sample === Object) { + return typeof other == "object"; + } + return other instanceof this.sample; + } + toString() { + return "Any"; + } + getExpectedType() { + if (this.sample === String) { + return "string"; + } + if (this.sample === Number) { + return "number"; + } + if (this.sample === Function) { + return "function"; + } + if (this.sample === Object) { + return "object"; + } + if (this.sample === Boolean) { + return "boolean"; + } + return this.fnNameFor(this.sample); + } + toAsymmetricMatcher() { + return `Any<${this.fnNameFor(this.sample)}>`; + } +} +class StringMatching extends AsymmetricMatcher { + constructor(sample, inverse = false) { + if (!isA("String", sample) && !isA("RegExp", sample)) { + throw new Error("Expected is not a String or a RegExp"); + } + super(new RegExp(sample), inverse); + } + asymmetricMatch(other) { + const result = isA("String", other) && this.sample.test(other); + return this.inverse ? !result : result; + } + toString() { + return `String${this.inverse ? "Not" : ""}Matching`; + } + getExpectedType() { + return "string"; + } +} +class CloseTo extends AsymmetricMatcher { + precision; + constructor(sample, precision = 2, inverse = false) { + if (!isA("Number", sample)) { + throw new Error("Expected is not a Number"); + } + if (!isA("Number", precision)) { + throw new Error("Precision is not a Number"); + } + super(sample); + this.inverse = inverse; + this.precision = precision; + } + asymmetricMatch(other) { + if (!isA("Number", other)) { + return false; + } + let result = false; + if (other === Number.POSITIVE_INFINITY && this.sample === Number.POSITIVE_INFINITY) { + result = true; + } else if (other === Number.NEGATIVE_INFINITY && this.sample === Number.NEGATIVE_INFINITY) { + result = true; + } else { + result = Math.abs(this.sample - other) < 10 ** -this.precision / 2; + } + return this.inverse ? !result : result; + } + toString() { + return `Number${this.inverse ? "Not" : ""}CloseTo`; + } + getExpectedType() { + return "number"; + } + toAsymmetricMatcher() { + return [ + this.toString(), + this.sample, + `(${pluralize("digit", this.precision)})` + ].join(" "); + } +} +class SchemaMatching extends AsymmetricMatcher { + result; + constructor(sample, inverse = false) { + if (!isStandardSchema(sample)) { + throw new TypeError("SchemaMatching expected to receive a Standard Schema."); + } + super(sample, inverse); + } + asymmetricMatch(other) { + const result = this.sample["~standard"].validate(other); + // Check if the result is a Promise (async validation) + if (result instanceof Promise) { + throw new TypeError("Async schema validation is not supported in asymmetric matchers."); + } + this.result = result; + const pass = !this.result.issues || this.result.issues.length === 0; + return this.inverse ? !pass : pass; + } + toString() { + return `Schema${this.inverse ? "Not" : ""}Matching`; + } + getExpectedType() { + return "object"; + } + toAsymmetricMatcher() { + var _this$result; + const { utils } = this.getMatcherContext(); + const issues = ((_this$result = this.result) === null || _this$result === void 0 ? void 0 : _this$result.issues) || []; + if (issues.length > 0) { + return `${this.toString()} ${utils.stringify(this.result, undefined, { printBasicPrototype: false })}`; + } + return this.toString(); + } +} +const JestAsymmetricMatchers = (chai, utils) => { + utils.addMethod(chai.expect, "anything", () => new Anything()); + utils.addMethod(chai.expect, "any", (expected) => new Any(expected)); + utils.addMethod(chai.expect, "stringContaining", (expected) => new StringContaining(expected)); + utils.addMethod(chai.expect, "objectContaining", (expected) => new ObjectContaining(expected)); + utils.addMethod(chai.expect, "arrayContaining", (expected) => new ArrayContaining(expected)); + utils.addMethod(chai.expect, "stringMatching", (expected) => new StringMatching(expected)); + utils.addMethod(chai.expect, "closeTo", (expected, precision) => new CloseTo(expected, precision)); + utils.addMethod(chai.expect, "schemaMatching", (expected) => new SchemaMatching(expected)); + // defineProperty does not work + chai.expect.not = { + stringContaining: (expected) => new StringContaining(expected, true), + objectContaining: (expected) => new ObjectContaining(expected, true), + arrayContaining: (expected) => new ArrayContaining(expected, true), + stringMatching: (expected) => new StringMatching(expected, true), + closeTo: (expected, precision) => new CloseTo(expected, precision, true), + schemaMatching: (expected) => new SchemaMatching(expected, true) + }; +}; + +function createAssertionMessage(util, assertion, hasArgs) { + const not = util.flag(assertion, "negate") ? "not." : ""; + const name = `${util.flag(assertion, "_name")}(${hasArgs ? "expected" : ""})`; + const promiseName = util.flag(assertion, "promise"); + const promise = promiseName ? `.${promiseName}` : ""; + return `expect(actual)${promise}.${not}${name}`; +} +function recordAsyncExpect(_test, promise, assertion, error) { + const test = _test; + // record promise for test, that resolves before test ends + if (test && promise instanceof Promise) { + // if promise is explicitly awaited, remove it from the list + promise = promise.finally(() => { + if (!test.promises) { + return; + } + const index = test.promises.indexOf(promise); + if (index !== -1) { + test.promises.splice(index, 1); + } + }); + // record promise + if (!test.promises) { + test.promises = []; + } + test.promises.push(promise); + let resolved = false; + test.onFinished ?? (test.onFinished = []); + test.onFinished.push(() => { + if (!resolved) { + var _vitest_worker__; + const processor = ((_vitest_worker__ = globalThis.__vitest_worker__) === null || _vitest_worker__ === void 0 ? void 0 : _vitest_worker__.onFilterStackTrace) || ((s) => s || ""); + const stack = processor(error.stack); + console.warn([ + `Promise returned by \`${assertion}\` was not awaited. `, + "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ", + "Please remember to await the assertion.\n", + stack + ].join("")); + } + }); + return { + then(onFulfilled, onRejected) { + resolved = true; + return promise.then(onFulfilled, onRejected); + }, + catch(onRejected) { + return promise.catch(onRejected); + }, + finally(onFinally) { + return promise.finally(onFinally); + }, + [Symbol.toStringTag]: "Promise" + }; + } + return promise; +} +function handleTestError(test, err) { + var _test$result; + test.result || (test.result = { state: "fail" }); + test.result.state = "fail"; + (_test$result = test.result).errors || (_test$result.errors = []); + test.result.errors.push(processError(err)); +} +function wrapAssertion(utils, name, fn) { + return function(...args) { + // private + if (name !== "withTest") { + utils.flag(this, "_name", name); + } + if (!utils.flag(this, "soft")) { + return fn.apply(this, args); + } + const test = utils.flag(this, "vitest-test"); + if (!test) { + throw new Error("expect.soft() can only be used inside a test"); + } + try { + const result = fn.apply(this, args); + if (result && typeof result === "object" && typeof result.then === "function") { + return result.then(noop, (err) => { + handleTestError(test, err); + }); + } + return result; + } catch (err) { + handleTestError(test, err); + } + }; +} + +// Jest Expect Compact +const JestChaiExpect = (chai, utils) => { + const { AssertionError } = chai; + const customTesters = getCustomEqualityTesters(); + function def(name, fn) { + const addMethod = (n) => { + const softWrapper = wrapAssertion(utils, n, fn); + utils.addMethod(chai.Assertion.prototype, n, softWrapper); + utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, n, softWrapper); + }; + if (Array.isArray(name)) { + name.forEach((n) => addMethod(n)); + } else { + addMethod(name); + } + } + [ + "throw", + "throws", + "Throw" + ].forEach((m) => { + utils.overwriteMethod(chai.Assertion.prototype, m, (_super) => { + return function(...args) { + const promise = utils.flag(this, "promise"); + const object = utils.flag(this, "object"); + const isNot = utils.flag(this, "negate"); + if (promise === "rejects") { + utils.flag(this, "object", () => { + throw object; + }); + } else if (promise === "resolves" && typeof object !== "function") { + if (!isNot) { + const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't"; + const error = { showDiff: false }; + throw new AssertionError(message, error, utils.flag(this, "ssfi")); + } else { + return; + } + } + _super.apply(this, args); + }; + }); + }); + // @ts-expect-error @internal + def("withTest", function(test) { + utils.flag(this, "vitest-test", test); + return this; + }); + def("toEqual", function(expected) { + const actual = utils.flag(this, "object"); + const equal = equals(actual, expected, [...customTesters, iterableEquality]); + return this.assert(equal, "expected #{this} to deeply equal #{exp}", "expected #{this} to not deeply equal #{exp}", expected, actual); + }); + def("toStrictEqual", function(expected) { + const obj = utils.flag(this, "object"); + const equal = equals(obj, expected, [ + ...customTesters, + iterableEquality, + typeEquality, + sparseArrayEquality, + arrayBufferEquality + ], true); + return this.assert(equal, "expected #{this} to strictly equal #{exp}", "expected #{this} to not strictly equal #{exp}", expected, obj); + }); + def("toBe", function(expected) { + const actual = this._obj; + const pass = Object.is(actual, expected); + let deepEqualityName = ""; + if (!pass) { + const toStrictEqualPass = equals(actual, expected, [ + ...customTesters, + iterableEquality, + typeEquality, + sparseArrayEquality, + arrayBufferEquality + ], true); + if (toStrictEqualPass) { + deepEqualityName = "toStrictEqual"; + } else { + const toEqualPass = equals(actual, expected, [...customTesters, iterableEquality]); + if (toEqualPass) { + deepEqualityName = "toEqual"; + } + } + } + return this.assert(pass, generateToBeMessage(deepEqualityName), "expected #{this} not to be #{exp} // Object.is equality", expected, actual); + }); + def("toMatchObject", function(expected) { + const actual = this._obj; + const pass = equals(actual, expected, [ + ...customTesters, + iterableEquality, + subsetEquality + ]); + const isNot = utils.flag(this, "negate"); + const { subset: actualSubset, stripped } = getObjectSubset(actual, expected, customTesters); + if (pass && isNot || !pass && !isNot) { + const msg = utils.getMessage(this, [ + pass, + "expected #{this} to match object #{exp}", + "expected #{this} to not match object #{exp}", + expected, + actualSubset, + false + ]); + const message = stripped === 0 ? msg : `${msg}\n(${stripped} matching ${stripped === 1 ? "property" : "properties"} omitted from actual)`; + throw new AssertionError(message, { + showDiff: true, + expected, + actual: actualSubset + }); + } + }); + def("toMatch", function(expected) { + const actual = this._obj; + if (typeof actual !== "string") { + throw new TypeError(`.toMatch() expects to receive a string, but got ${typeof actual}`); + } + return this.assert(typeof expected === "string" ? actual.includes(expected) : actual.match(expected), `expected #{this} to match #{exp}`, `expected #{this} not to match #{exp}`, expected, actual); + }); + def("toContain", function(item) { + const actual = this._obj; + if (typeof Node !== "undefined" && actual instanceof Node) { + if (!(item instanceof Node)) { + throw new TypeError(`toContain() expected a DOM node as the argument, but got ${typeof item}`); + } + return this.assert(actual.contains(item), "expected #{this} to contain element #{exp}", "expected #{this} not to contain element #{exp}", item, actual); + } + if (typeof DOMTokenList !== "undefined" && actual instanceof DOMTokenList) { + assertTypes(item, "class name", ["string"]); + const isNot = utils.flag(this, "negate"); + const expectedClassList = isNot ? actual.value.replace(item, "").trim() : `${actual.value} ${item}`; + return this.assert(actual.contains(item), `expected "${actual.value}" to contain "${item}"`, `expected "${actual.value}" not to contain "${item}"`, expectedClassList, actual.value); + } + // handle simple case on our own using `this.assert` to include diff in error message + if (typeof actual === "string" && typeof item === "string") { + return this.assert(actual.includes(item), `expected #{this} to contain #{exp}`, `expected #{this} not to contain #{exp}`, item, actual); + } + // make "actual" indexable to have compatibility with jest + if (actual != null && typeof actual !== "string") { + utils.flag(this, "object", Array.from(actual)); + } + return this.contain(item); + }); + def("toContainEqual", function(expected) { + const obj = utils.flag(this, "object"); + const index = Array.from(obj).findIndex((item) => { + return equals(item, expected, customTesters); + }); + this.assert(index !== -1, "expected #{this} to deep equally contain #{exp}", "expected #{this} to not deep equally contain #{exp}", expected); + }); + def("toBeTruthy", function() { + const obj = utils.flag(this, "object"); + this.assert(Boolean(obj), "expected #{this} to be truthy", "expected #{this} to not be truthy", true, obj); + }); + def("toBeFalsy", function() { + const obj = utils.flag(this, "object"); + this.assert(!obj, "expected #{this} to be falsy", "expected #{this} to not be falsy", false, obj); + }); + def("toBeGreaterThan", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert(actual > expected, `expected ${actual} to be greater than ${expected}`, `expected ${actual} to be not greater than ${expected}`, expected, actual, false); + }); + def("toBeGreaterThanOrEqual", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert(actual >= expected, `expected ${actual} to be greater than or equal to ${expected}`, `expected ${actual} to be not greater than or equal to ${expected}`, expected, actual, false); + }); + def("toBeLessThan", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert(actual < expected, `expected ${actual} to be less than ${expected}`, `expected ${actual} to be not less than ${expected}`, expected, actual, false); + }); + def("toBeLessThanOrEqual", function(expected) { + const actual = this._obj; + assertTypes(actual, "actual", ["number", "bigint"]); + assertTypes(expected, "expected", ["number", "bigint"]); + return this.assert(actual <= expected, `expected ${actual} to be less than or equal to ${expected}`, `expected ${actual} to be not less than or equal to ${expected}`, expected, actual, false); + }); + def("toBeNaN", function() { + const obj = utils.flag(this, "object"); + this.assert(Number.isNaN(obj), "expected #{this} to be NaN", "expected #{this} not to be NaN", Number.NaN, obj); + }); + def("toBeUndefined", function() { + const obj = utils.flag(this, "object"); + this.assert(undefined === obj, "expected #{this} to be undefined", "expected #{this} not to be undefined", undefined, obj); + }); + def("toBeNull", function() { + const obj = utils.flag(this, "object"); + this.assert(obj === null, "expected #{this} to be null", "expected #{this} not to be null", null, obj); + }); + def("toBeNullable", function() { + const obj = utils.flag(this, "object"); + this.assert(obj == null, "expected #{this} to be nullish", "expected #{this} not to be nullish", null, obj); + }); + def("toBeDefined", function() { + const obj = utils.flag(this, "object"); + this.assert(typeof obj !== "undefined", "expected #{this} to be defined", "expected #{this} to be undefined", obj); + }); + def("toBeTypeOf", function(expected) { + const actual = typeof this._obj; + const equal = expected === actual; + return this.assert(equal, "expected #{this} to be type of #{exp}", "expected #{this} not to be type of #{exp}", expected, actual); + }); + def("toBeInstanceOf", function(obj) { + return this.instanceOf(obj); + }); + def("toHaveLength", function(length) { + return this.have.length(length); + }); + // destructuring, because it checks `arguments` inside, and value is passing as `undefined` + def("toHaveProperty", function(...args) { + if (Array.isArray(args[0])) { + args[0] = args[0].map((key) => String(key).replace(/([.[\]])/g, "\\$1")).join("."); + } + const actual = this._obj; + const [propertyName, expected] = args; + const getValue = () => { + const hasOwn = Object.hasOwn(actual, propertyName); + if (hasOwn) { + return { + value: actual[propertyName], + exists: true + }; + } + return utils.getPathInfo(actual, propertyName); + }; + const { value, exists } = getValue(); + const pass = exists && (args.length === 1 || equals(expected, value, customTesters)); + const valueString = args.length === 1 ? "" : ` with value ${utils.objDisplay(expected)}`; + return this.assert(pass, `expected #{this} to have property "${propertyName}"${valueString}`, `expected #{this} to not have property "${propertyName}"${valueString}`, expected, exists ? value : undefined); + }); + def("toBeCloseTo", function(received, precision = 2) { + const expected = this._obj; + let pass = false; + let expectedDiff = 0; + let receivedDiff = 0; + if (received === Number.POSITIVE_INFINITY && expected === Number.POSITIVE_INFINITY) { + pass = true; + } else if (received === Number.NEGATIVE_INFINITY && expected === Number.NEGATIVE_INFINITY) { + pass = true; + } else { + expectedDiff = 10 ** -precision / 2; + receivedDiff = Math.abs(expected - received); + pass = receivedDiff < expectedDiff; + } + return this.assert(pass, `expected #{this} to be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, `expected #{this} to not be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, received, expected, false); + }); + function assertIsMock(assertion) { + if (!isMockFunction(assertion._obj)) { + throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`); + } + } + function getSpy(assertion) { + assertIsMock(assertion); + return assertion._obj; + } + def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + return this.assert(callCount === number, `expected "${spyName}" to be called #{exp} times, but got ${callCount} times`, `expected "${spyName}" to not be called #{exp} times`, number, callCount, false); + }); + def("toHaveBeenCalledOnce", function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + return this.assert(callCount === 1, `expected "${spyName}" to be called once, but got ${callCount} times`, `expected "${spyName}" to not be called once`, 1, callCount, false); + }); + def(["toHaveBeenCalled", "toBeCalled"], function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + const called = callCount > 0; + const isNot = utils.flag(this, "negate"); + let msg = utils.getMessage(this, [ + called, + `expected "${spyName}" to be called at least once`, + `expected "${spyName}" to not be called at all, but actually been called ${callCount} times`, + true, + called + ]); + if (called && isNot) { + msg = formatCalls(spy, msg); + } + if (called && isNot || !called && !isNot) { + throw new AssertionError(msg); + } + }); + // manually compare array elements since `jestEquals` cannot + // apply asymmetric matcher to `undefined` array element. + function equalsArgumentArray(a, b) { + return a.length === b.length && a.every((aItem, i) => equals(aItem, b[i], [...customTesters, iterableEquality])); + } + def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = spy.mock.calls.some((callArg) => equalsArgumentArray(callArg, args)); + const isNot = utils.flag(this, "negate"); + const msg = utils.getMessage(this, [ + pass, + `expected "${spyName}" to be called with arguments: #{exp}`, + `expected "${spyName}" to not be called with arguments: #{exp}`, + args + ]); + if (pass && isNot || !pass && !isNot) { + throw new AssertionError(formatCalls(spy, msg, args)); + } + }); + def("toHaveBeenCalledExactlyOnceWith", function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + const hasCallWithArgs = spy.mock.calls.some((callArg) => equalsArgumentArray(callArg, args)); + const pass = hasCallWithArgs && callCount === 1; + const isNot = utils.flag(this, "negate"); + const msg = utils.getMessage(this, [ + pass, + `expected "${spyName}" to be called once with arguments: #{exp}`, + `expected "${spyName}" to not be called once with arguments: #{exp}`, + args + ]); + if (pass && isNot || !pass && !isNot) { + throw new AssertionError(formatCalls(spy, msg, args)); + } + }); + def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const nthCall = spy.mock.calls[times - 1]; + const callCount = spy.mock.calls.length; + const isCalled = times <= callCount; + this.assert(nthCall && equalsArgumentArray(nthCall, args), `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}${isCalled ? `` : `, but called only ${callCount} times`}`, `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall, isCalled); + }); + def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const lastCall = spy.mock.calls.at(-1); + this.assert(lastCall && equalsArgumentArray(lastCall, args), `expected last "${spyName}" call to have been called with #{exp}`, `expected last "${spyName}" call to not have been called with #{exp}`, args, lastCall); + }); + /** + * Used for `toHaveBeenCalledBefore` and `toHaveBeenCalledAfter` to determine if the expected spy was called before the result spy. + */ + function isSpyCalledBeforeAnotherSpy(beforeSpy, afterSpy, failIfNoFirstInvocation) { + const beforeInvocationCallOrder = beforeSpy.mock.invocationCallOrder; + const afterInvocationCallOrder = afterSpy.mock.invocationCallOrder; + if (beforeInvocationCallOrder.length === 0) { + return !failIfNoFirstInvocation; + } + if (afterInvocationCallOrder.length === 0) { + return false; + } + return beforeInvocationCallOrder[0] < afterInvocationCallOrder[0]; + } + def(["toHaveBeenCalledBefore"], function(resultSpy, failIfNoFirstInvocation = true) { + const expectSpy = getSpy(this); + if (!isMockFunction(resultSpy)) { + throw new TypeError(`${utils.inspect(resultSpy)} is not a spy or a call to a spy`); + } + this.assert(isSpyCalledBeforeAnotherSpy(expectSpy, resultSpy, failIfNoFirstInvocation), `expected "${expectSpy.getMockName()}" to have been called before "${resultSpy.getMockName()}"`, `expected "${expectSpy.getMockName()}" to not have been called before "${resultSpy.getMockName()}"`, resultSpy, expectSpy); + }); + def(["toHaveBeenCalledAfter"], function(resultSpy, failIfNoFirstInvocation = true) { + const expectSpy = getSpy(this); + if (!isMockFunction(resultSpy)) { + throw new TypeError(`${utils.inspect(resultSpy)} is not a spy or a call to a spy`); + } + this.assert(isSpyCalledBeforeAnotherSpy(resultSpy, expectSpy, failIfNoFirstInvocation), `expected "${expectSpy.getMockName()}" to have been called after "${resultSpy.getMockName()}"`, `expected "${expectSpy.getMockName()}" to not have been called after "${resultSpy.getMockName()}"`, resultSpy, expectSpy); + }); + def(["toThrow", "toThrowError"], function(expected) { + if (typeof expected === "string" || typeof expected === "undefined" || expected instanceof RegExp) { + // Fixes the issue related to `chai` + return this.throws(expected === "" ? /^$/ : expected); + } + const obj = this._obj; + const promise = utils.flag(this, "promise"); + const isNot = utils.flag(this, "negate"); + let thrown = null; + if (promise === "rejects") { + thrown = obj; + } else if (promise === "resolves" && typeof obj !== "function") { + if (!isNot) { + const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't"; + const error = { showDiff: false }; + throw new AssertionError(message, error, utils.flag(this, "ssfi")); + } else { + return; + } + } else { + let isThrow = false; + try { + obj(); + } catch (err) { + isThrow = true; + thrown = err; + } + if (!isThrow && !isNot) { + const message = utils.flag(this, "message") || "expected function to throw an error, but it didn't"; + const error = { showDiff: false }; + throw new AssertionError(message, error, utils.flag(this, "ssfi")); + } + } + if (typeof expected === "function") { + const name = expected.name || expected.prototype.constructor.name; + return this.assert(thrown && thrown instanceof expected, `expected error to be instance of ${name}`, `expected error not to be instance of ${name}`, expected, thrown); + } + if (expected instanceof Error) { + const equal = equals(thrown, expected, [...customTesters, iterableEquality]); + return this.assert(equal, "expected a thrown error to be #{exp}", "expected a thrown error not to be #{exp}", expected, thrown); + } + if (typeof expected === "object" && "asymmetricMatch" in expected && typeof expected.asymmetricMatch === "function") { + const matcher = expected; + return this.assert(thrown && matcher.asymmetricMatch(thrown), "expected error to match asymmetric matcher", "expected error not to match asymmetric matcher", matcher, thrown); + } + throw new Error(`"toThrow" expects string, RegExp, function, Error instance or asymmetric matcher, got "${typeof expected}"`); + }); + [{ + name: "toHaveResolved", + condition: (spy) => spy.mock.settledResults.length > 0 && spy.mock.settledResults.some(({ type }) => type === "fulfilled"), + action: "resolved" + }, { + name: ["toHaveReturned", "toReturn"], + condition: (spy) => spy.mock.calls.length > 0 && spy.mock.results.some(({ type }) => type !== "throw"), + action: "called" + }].forEach(({ name, condition, action }) => { + def(name, function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = condition(spy); + this.assert(pass, `expected "${spyName}" to be successfully ${action} at least once`, `expected "${spyName}" to not be successfully ${action}`, pass, !pass, false); + }); + }); + [{ + name: "toHaveResolvedTimes", + condition: (spy, times) => spy.mock.settledResults.reduce((s, { type }) => type === "fulfilled" ? ++s : s, 0) === times, + action: "resolved" + }, { + name: ["toHaveReturnedTimes", "toReturnTimes"], + condition: (spy, times) => spy.mock.results.reduce((s, { type }) => type === "throw" ? s : ++s, 0) === times, + action: "called" + }].forEach(({ name, condition, action }) => { + def(name, function(times) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = condition(spy, times); + this.assert(pass, `expected "${spyName}" to be successfully ${action} ${times} times`, `expected "${spyName}" to not be successfully ${action} ${times} times`, `expected resolved times: ${times}`, `received resolved times: ${pass}`, false); + }); + }); + [{ + name: "toHaveResolvedWith", + condition: (spy, value) => spy.mock.settledResults.some(({ type, value: result }) => type === "fulfilled" && equals(value, result)), + action: "resolve" + }, { + name: ["toHaveReturnedWith", "toReturnWith"], + condition: (spy, value) => spy.mock.results.some(({ type, value: result }) => type === "return" && equals(value, result)), + action: "return" + }].forEach(({ name, condition, action }) => { + def(name, function(value) { + const spy = getSpy(this); + const pass = condition(spy, value); + const isNot = utils.flag(this, "negate"); + if (pass && isNot || !pass && !isNot) { + const spyName = spy.getMockName(); + const msg = utils.getMessage(this, [ + pass, + `expected "${spyName}" to ${action} with: #{exp} at least once`, + `expected "${spyName}" to not ${action} with: #{exp}`, + value + ]); + const results = action === "return" ? spy.mock.results : spy.mock.settledResults; + throw new AssertionError(formatReturns(spy, results, msg, value)); + } + }); + }); + [{ + name: "toHaveLastResolvedWith", + condition: (spy, value) => { + const result = spy.mock.settledResults.at(-1); + return Boolean(result && result.type === "fulfilled" && equals(result.value, value)); + }, + action: "resolve" + }, { + name: ["toHaveLastReturnedWith", "lastReturnedWith"], + condition: (spy, value) => { + const result = spy.mock.results.at(-1); + return Boolean(result && result.type === "return" && equals(result.value, value)); + }, + action: "return" + }].forEach(({ name, condition, action }) => { + def(name, function(value) { + const spy = getSpy(this); + const results = action === "return" ? spy.mock.results : spy.mock.settledResults; + const result = results.at(-1); + const spyName = spy.getMockName(); + this.assert(condition(spy, value), `expected last "${spyName}" call to ${action} #{exp}`, `expected last "${spyName}" call to not ${action} #{exp}`, value, result === null || result === void 0 ? void 0 : result.value); + }); + }); + [{ + name: "toHaveNthResolvedWith", + condition: (spy, index, value) => { + const result = spy.mock.settledResults[index - 1]; + return result && result.type === "fulfilled" && equals(result.value, value); + }, + action: "resolve" + }, { + name: ["toHaveNthReturnedWith", "nthReturnedWith"], + condition: (spy, index, value) => { + const result = spy.mock.results[index - 1]; + return result && result.type === "return" && equals(result.value, value); + }, + action: "return" + }].forEach(({ name, condition, action }) => { + def(name, function(nthCall, value) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const results = action === "return" ? spy.mock.results : spy.mock.settledResults; + const result = results[nthCall - 1]; + const ordinalCall = `${ordinalOf(nthCall)} call`; + this.assert(condition(spy, nthCall, value), `expected ${ordinalCall} "${spyName}" call to ${action} #{exp}`, `expected ${ordinalCall} "${spyName}" call to not ${action} #{exp}`, value, result === null || result === void 0 ? void 0 : result.value); + }); + }); + // @ts-expect-error @internal + def("withContext", function(context) { + for (const key in context) { + utils.flag(this, key, context[key]); + } + return this; + }); + utils.addProperty(chai.Assertion.prototype, "resolves", function __VITEST_RESOLVES__() { + const error = new Error("resolves"); + utils.flag(this, "promise", "resolves"); + utils.flag(this, "error", error); + const test = utils.flag(this, "vitest-test"); + const obj = utils.flag(this, "object"); + if (utils.flag(this, "poll")) { + throw new SyntaxError(`expect.poll() is not supported in combination with .resolves`); + } + if (typeof (obj === null || obj === void 0 ? void 0 : obj.then) !== "function") { + throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`); + } + const proxy = new Proxy(this, { get: (target, key, receiver) => { + const result = Reflect.get(target, key, receiver); + if (typeof result !== "function") { + return result instanceof chai.Assertion ? proxy : result; + } + return (...args) => { + utils.flag(this, "_name", key); + const promise = obj.then((value) => { + utils.flag(this, "object", value); + return result.call(this, ...args); + }, (err) => { + const _error = new AssertionError(`promise rejected "${utils.inspect(err)}" instead of resolving`, { showDiff: false }); + _error.cause = err; + _error.stack = error.stack.replace(error.message, _error.message); + throw _error; + }); + return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error); + }; + } }); + return proxy; + }); + utils.addProperty(chai.Assertion.prototype, "rejects", function __VITEST_REJECTS__() { + const error = new Error("rejects"); + utils.flag(this, "promise", "rejects"); + utils.flag(this, "error", error); + const test = utils.flag(this, "vitest-test"); + const obj = utils.flag(this, "object"); + const wrapper = typeof obj === "function" ? obj() : obj; + if (utils.flag(this, "poll")) { + throw new SyntaxError(`expect.poll() is not supported in combination with .rejects`); + } + if (typeof (wrapper === null || wrapper === void 0 ? void 0 : wrapper.then) !== "function") { + throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`); + } + const proxy = new Proxy(this, { get: (target, key, receiver) => { + const result = Reflect.get(target, key, receiver); + if (typeof result !== "function") { + return result instanceof chai.Assertion ? proxy : result; + } + return (...args) => { + utils.flag(this, "_name", key); + const promise = wrapper.then((value) => { + const _error = new AssertionError(`promise resolved "${utils.inspect(value)}" instead of rejecting`, { + showDiff: true, + expected: new Error("rejected promise"), + actual: value + }); + _error.stack = error.stack.replace(error.message, _error.message); + throw _error; + }, (err) => { + utils.flag(this, "object", err); + return result.call(this, ...args); + }); + return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error); + }; + } }); + return proxy; + }); +}; +function ordinalOf(i) { + const j = i % 10; + const k = i % 100; + if (j === 1 && k !== 11) { + return `${i}st`; + } + if (j === 2 && k !== 12) { + return `${i}nd`; + } + if (j === 3 && k !== 13) { + return `${i}rd`; + } + return `${i}th`; +} +function formatCalls(spy, msg, showActualCall) { + if (spy.mock.calls.length) { + msg += c.gray(`\n\nReceived: \n\n${spy.mock.calls.map((callArg, i) => { + let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call:\n\n`); + if (showActualCall) { + methodCall += diff(showActualCall, callArg, { omitAnnotationLines: true }); + } else { + methodCall += stringify(callArg).split("\n").map((line) => ` ${line}`).join("\n"); + } + methodCall += "\n"; + return methodCall; + }).join("\n")}`); + } + msg += c.gray(`\n\nNumber of calls: ${c.bold(spy.mock.calls.length)}\n`); + return msg; +} +function formatReturns(spy, results, msg, showActualReturn) { + if (results.length) { + msg += c.gray(`\n\nReceived: \n\n${results.map((callReturn, i) => { + let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call return:\n\n`); + if (showActualReturn) { + methodCall += diff(showActualReturn, callReturn.value, { omitAnnotationLines: true }); + } else { + methodCall += stringify(callReturn).split("\n").map((line) => ` ${line}`).join("\n"); + } + methodCall += "\n"; + return methodCall; + }).join("\n")}`); + } + msg += c.gray(`\n\nNumber of calls: ${c.bold(spy.mock.calls.length)}\n`); + return msg; +} + +function getMatcherState(assertion, expect) { + const obj = assertion._obj; + const isNot = util.flag(assertion, "negate"); + const promise = util.flag(assertion, "promise") || ""; + const customMessage = util.flag(assertion, "message"); + const jestUtils = { + ...getMatcherUtils(), + diff, + stringify, + iterableEquality, + subsetEquality + }; + let task = util.flag(assertion, "vitest-test"); + const currentTestName = (task === null || task === void 0 ? void 0 : task.fullTestName) ?? ""; + if ((task === null || task === void 0 ? void 0 : task.type) !== "test") { + task = undefined; + } + const matcherState = { + ...getState(expect), + task, + currentTestName, + customTesters: getCustomEqualityTesters(), + isNot, + utils: jestUtils, + promise, + equals, + suppressedErrors: [], + soft: util.flag(assertion, "soft"), + poll: util.flag(assertion, "poll") + }; + return { + state: matcherState, + isNot, + obj, + customMessage + }; +} +class JestExtendError extends Error { + constructor(message, actual, expected) { + super(message); + this.actual = actual; + this.expected = expected; + } +} +function JestExtendPlugin(c, expect, matchers) { + return (_, utils) => { + Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => { + function expectWrapper(...args) { + const { state, isNot, obj, customMessage } = getMatcherState(this, expect); + const result = expectAssertion.call(state, obj, ...args); + if (result && typeof result === "object" && typeof result.then === "function") { + const thenable = result; + return thenable.then(({ pass, message, actual, expected }) => { + if (pass && isNot || !pass && !isNot) { + const errorMessage = customMessage != null ? customMessage : message(); + throw new JestExtendError(errorMessage, actual, expected); + } + }); + } + const { pass, message, actual, expected } = result; + if (pass && isNot || !pass && !isNot) { + const errorMessage = customMessage != null ? customMessage : message(); + throw new JestExtendError(errorMessage, actual, expected); + } + } + const softWrapper = wrapAssertion(utils, expectAssertionName, expectWrapper); + utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, softWrapper); + utils.addMethod(c.Assertion.prototype, expectAssertionName, softWrapper); + class CustomMatcher extends AsymmetricMatcher { + constructor(inverse = false, ...sample) { + super(sample, inverse); + } + asymmetricMatch(other) { + const { pass } = expectAssertion.call(this.getMatcherContext(expect), other, ...this.sample); + return this.inverse ? !pass : pass; + } + toString() { + return `${this.inverse ? "not." : ""}${expectAssertionName}`; + } + getExpectedType() { + return "any"; + } + toAsymmetricMatcher() { + return `${this.toString()}<${this.sample.map((item) => stringify(item)).join(", ")}>`; + } + } + const customMatcher = (...sample) => new CustomMatcher(false, ...sample); + Object.defineProperty(expect, expectAssertionName, { + configurable: true, + enumerable: true, + value: customMatcher, + writable: true + }); + Object.defineProperty(expect.not, expectAssertionName, { + configurable: true, + enumerable: true, + value: (...sample) => new CustomMatcher(true, ...sample), + writable: true + }); + // keep track of asymmetric matchers on global so that it can be copied over to local context's `expect`. + // note that the negated variant is automatically shared since it's assigned on the single `expect.not` object. + Object.defineProperty(globalThis[ASYMMETRIC_MATCHERS_OBJECT], expectAssertionName, { + configurable: true, + enumerable: true, + value: customMatcher, + writable: true + }); + }); + }; +} +const JestExtend = (chai, utils) => { + utils.addMethod(chai.expect, "extend", (expect, expects) => { + use(JestExtendPlugin(chai, expect, expects)); + }); +}; + +export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality }; diff --git a/vanilla/node_modules/@vitest/expect/package.json b/vanilla/node_modules/@vitest/expect/package.json new file mode 100644 index 0000000..14c0b9e --- /dev/null +++ b/vanilla/node_modules/@vitest/expect/package.json @@ -0,0 +1,46 @@ +{ + "name": "@vitest/expect", + "type": "module", + "version": "4.0.18", + "description": "Jest's expect matchers as a Chai plugin", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/expect#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/expect" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@types/chai": "^5.2.2", + "chai": "^6.2.1", + "tinyrainbow": "^3.0.3", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18" + }, + "devDependencies": { + "@vitest/runner": "4.0.18" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/@vitest/mocker/LICENSE b/vanilla/node_modules/@vitest/mocker/LICENSE new file mode 100644 index 0000000..0e5771d --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vanilla/node_modules/@vitest/mocker/README.md b/vanilla/node_modules/@vitest/mocker/README.md new file mode 100644 index 0000000..f23202d --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/README.md @@ -0,0 +1,5 @@ +# @vitest/mocker + +Vitest's module mocker implementation. + +[GitHub](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/EXPORTS.md) diff --git a/vanilla/node_modules/@vitest/mocker/dist/auto-register.d.ts b/vanilla/node_modules/@vitest/mocker/dist/auto-register.d.ts new file mode 100644 index 0000000..04fa25e --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/auto-register.d.ts @@ -0,0 +1,2 @@ + +export { }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/auto-register.js b/vanilla/node_modules/@vitest/mocker/dist/auto-register.js new file mode 100644 index 0000000..8da252b --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/auto-register.js @@ -0,0 +1,9 @@ +import { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js'; +import { registerModuleMocker } from './register.js'; +import './chunk-mocker.js'; +import './index.js'; +import './chunk-registry.js'; +import './chunk-pathe.M-eThtNZ.js'; +import '@vitest/spy'; + +registerModuleMocker(() => new ModuleMockerServerInterceptor()); diff --git a/vanilla/node_modules/@vitest/mocker/dist/automock.d.ts b/vanilla/node_modules/@vitest/mocker/dist/automock.d.ts new file mode 100644 index 0000000..e453d22 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/automock.d.ts @@ -0,0 +1,12 @@ +import MagicString from 'magic-string'; + +interface AutomockOptions { + /** + * @default "__vitest_mocker__" + */ + globalThisAccessor?: string; +} +declare function automockModule(code: string, mockType: "automock" | "autospy", parse: (code: string) => any, options?: AutomockOptions): MagicString; + +export { automockModule }; +export type { AutomockOptions }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/automock.js b/vanilla/node_modules/@vitest/mocker/dist/automock.js new file mode 100644 index 0000000..c2e2d96 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/automock.js @@ -0,0 +1,3 @@ +import 'magic-string'; +export { a as automockModule } from './chunk-automock.js'; +import 'estree-walker'; diff --git a/vanilla/node_modules/@vitest/mocker/dist/browser.d.ts b/vanilla/node_modules/@vitest/mocker/dist/browser.d.ts new file mode 100644 index 0000000..7048b29 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/browser.d.ts @@ -0,0 +1,53 @@ +import { M as ModuleMockerInterceptor } from './mocker.d-TnKRhz7N.js'; +export { C as CompilerHintsOptions, b as ModuleMocker, a as ModuleMockerCompilerHints, d as ModuleMockerConfig, e as ModuleMockerRPC, R as ResolveIdResult, f as ResolveMockResult, c as createCompilerHints } from './mocker.d-TnKRhz7N.js'; +import { StartOptions, SetupWorker } from 'msw/browser'; +import { M as MockerRegistry, a as MockedModule } from './types.d-B8CCKmHt.js'; +import '@vitest/spy'; +import './index.d-C-sLYZi-.js'; + +interface ModuleMockerMSWInterceptorOptions { + /** + * The identifier to access the globalThis object in the worker. + * This will be injected into the script as is, so make sure it's a valid JS expression. + * @example + * ```js + * // globalThisAccessor: '__my_variable__' produces: + * globalThis[__my_variable__] + * // globalThisAccessor: 'Symbol.for('secret:mocks')' produces: + * globalThis[Symbol.for('secret:mocks')] + * // globalThisAccessor: '"__vitest_mocker__"' (notice quotes) produces: + * globalThis["__vitest_mocker__"] + * ``` + * @default `"__vitest_mocker__"` + */ + globalThisAccessor?: string; + /** + * Options passed down to `msw.setupWorker().start(options)` + */ + mswOptions?: StartOptions; + /** + * A pre-configured `msw.setupWorker` instance. + */ + mswWorker?: SetupWorker; +} +declare class ModuleMockerMSWInterceptor implements ModuleMockerInterceptor { + private readonly options; + protected readonly mocks: MockerRegistry; + private startPromise; + private worker; + constructor(options?: ModuleMockerMSWInterceptorOptions); + register(module: MockedModule): Promise; + delete(url: string): Promise; + invalidate(): Promise; + private resolveManualMock; + protected init(): Promise; +} + +declare class ModuleMockerServerInterceptor implements ModuleMockerInterceptor { + register(module: MockedModule): Promise; + delete(id: string): Promise; + invalidate(): Promise; +} + +export { ModuleMockerInterceptor, ModuleMockerMSWInterceptor, ModuleMockerServerInterceptor }; +export type { ModuleMockerMSWInterceptorOptions }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/browser.js b/vanilla/node_modules/@vitest/mocker/dist/browser.js new file mode 100644 index 0000000..3e83247 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/browser.js @@ -0,0 +1,91 @@ +export { M as ModuleMocker, c as createCompilerHints } from './chunk-mocker.js'; +import { M as MockerRegistry } from './chunk-registry.js'; +import { c as createManualModuleSource, a as cleanUrl } from './chunk-utils.js'; +export { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js'; +import './index.js'; +import './chunk-pathe.M-eThtNZ.js'; + +class ModuleMockerMSWInterceptor { + mocks = new MockerRegistry(); + startPromise; + worker; + constructor(options = {}) { + this.options = options; + if (!options.globalThisAccessor) { + options.globalThisAccessor = "\"__vitest_mocker__\""; + } + } + async register(module) { + await this.init(); + this.mocks.add(module); + } + async delete(url) { + await this.init(); + this.mocks.delete(url); + } + async invalidate() { + this.mocks.clear(); + } + async resolveManualMock(mock) { + const exports$1 = Object.keys(await mock.resolve()); + const text = createManualModuleSource(mock.url, exports$1, this.options.globalThisAccessor); + return new Response(text, { headers: { "Content-Type": "application/javascript" } }); + } + async init() { + if (this.worker) { + return this.worker; + } + if (this.startPromise) { + return this.startPromise; + } + const worker = this.options.mswWorker; + this.startPromise = Promise.all([worker ? { setupWorker(handler) { + worker.use(handler); + return worker; + } } : import('msw/browser'), import('msw/core/http')]).then(([{ setupWorker }, { http }]) => { + const worker = setupWorker(http.get(/.+/, async ({ request }) => { + const path = cleanQuery(request.url.slice(location.origin.length)); + if (!this.mocks.has(path)) { + return passthrough(); + } + const mock = this.mocks.get(path); + switch (mock.type) { + case "manual": return this.resolveManualMock(mock); + case "automock": + case "autospy": return Response.redirect(injectQuery(path, `mock=${mock.type}`)); + case "redirect": return Response.redirect(mock.redirect); + default: throw new Error(`Unknown mock type: ${mock.type}`); + } + })); + return worker.start(this.options.mswOptions).then(() => worker); + }).finally(() => { + this.worker = worker; + this.startPromise = undefined; + }); + return await this.startPromise; + } +} +const trailingSeparatorRE = /[?&]$/; +const timestampRE = /\bt=\d{13}&?\b/; +const versionRE = /\bv=\w{8}&?\b/; +function cleanQuery(url) { + return url.replace(timestampRE, "").replace(versionRE, "").replace(trailingSeparatorRE, ""); +} +function passthrough() { + return new Response(null, { + status: 302, + statusText: "Passthrough", + headers: { "x-msw-intention": "passthrough" } + }); +} +const replacePercentageRE = /%/g; +function injectQuery(url, queryToInject) { + // encode percents for consistent behavior with pathToFileURL + // see #2614 for details + const resolvedUrl = new URL(url.replace(replacePercentageRE, "%25"), location.href); + const { search, hash } = resolvedUrl; + const pathname = cleanUrl(url); + return `${pathname}?${queryToInject}${search ? `&${search.slice(1)}` : ""}${hash ?? ""}`; +} + +export { ModuleMockerMSWInterceptor }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-automock.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-automock.js new file mode 100644 index 0000000..135ceaf --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/chunk-automock.js @@ -0,0 +1,354 @@ +import MagicString from 'magic-string'; +import { walk } from 'estree-walker'; + +const isNodeInPatternWeakSet = new WeakSet(); +function setIsNodeInPattern(node) { + return isNodeInPatternWeakSet.add(node); +} +function isNodeInPattern(node) { + return isNodeInPatternWeakSet.has(node); +} +/** +* Same logic from \@vue/compiler-core & \@vue/compiler-sfc +* Except this is using acorn AST +*/ +function esmWalker(root, { onIdentifier, onImportMeta, onDynamicImport, onCallExpression }) { + const parentStack = []; + const varKindStack = []; + const scopeMap = new WeakMap(); + const identifiers = []; + const setScope = (node, name) => { + let scopeIds = scopeMap.get(node); + if (scopeIds && scopeIds.has(name)) { + return; + } + if (!scopeIds) { + scopeIds = new Set(); + scopeMap.set(node, scopeIds); + } + scopeIds.add(name); + }; + function isInScope(name, parents) { + return parents.some((node) => { + var _scopeMap$get; + return node && ((_scopeMap$get = scopeMap.get(node)) === null || _scopeMap$get === void 0 ? void 0 : _scopeMap$get.has(name)); + }); + } + function handlePattern(p, parentScope) { + if (p.type === "Identifier") { + setScope(parentScope, p.name); + } else if (p.type === "RestElement") { + handlePattern(p.argument, parentScope); + } else if (p.type === "ObjectPattern") { + p.properties.forEach((property) => { + if (property.type === "RestElement") { + setScope(parentScope, property.argument.name); + } else { + handlePattern(property.value, parentScope); + } + }); + } else if (p.type === "ArrayPattern") { + p.elements.forEach((element) => { + if (element) { + handlePattern(element, parentScope); + } + }); + } else if (p.type === "AssignmentPattern") { + handlePattern(p.left, parentScope); + } else { + setScope(parentScope, p.name); + } + } + walk(root, { + enter(node, parent) { + if (node.type === "ImportDeclaration") { + return this.skip(); + } + // track parent stack, skip for "else-if"/"else" branches as acorn nests + // the ast within "if" nodes instead of flattening them + if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) { + parentStack.unshift(parent); + } + // track variable declaration kind stack used by VariableDeclarator + if (node.type === "VariableDeclaration") { + varKindStack.unshift(node.kind); + } + if (node.type === "CallExpression") { + onCallExpression === null || onCallExpression === void 0 ? void 0 : onCallExpression(node); + } + if (node.type === "MetaProperty" && node.meta.name === "import") { + onImportMeta === null || onImportMeta === void 0 ? void 0 : onImportMeta(node); + } else if (node.type === "ImportExpression") { + onDynamicImport === null || onDynamicImport === void 0 ? void 0 : onDynamicImport(node); + } + if (node.type === "Identifier") { + if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) { + // record the identifier, for DFS -> BFS + identifiers.push([node, parentStack.slice(0)]); + } + } else if (node.type === "ClassDeclaration" && node.id) { + // A class declaration name could shadow an import, so add its name to the parent scope + const parentScope = findParentScope(parentStack); + if (parentScope) { + setScope(parentScope, node.id.name); + } + } else if (node.type === "ClassExpression" && node.id) { + // A class expression name could shadow an import, so add its name to the scope + setScope(node, node.id.name); + } else if (isFunctionNode(node)) { + // If it is a function declaration, it could be shadowing an import + // Add its name to the scope so it won't get replaced + if (node.type === "FunctionDeclaration") { + const parentScope = findParentScope(parentStack); + if (parentScope) { + setScope(parentScope, node.id.name); + } + } + // walk function expressions and add its arguments to known identifiers + // so that we don't prefix them + node.params.forEach((p) => { + if (p.type === "ObjectPattern" || p.type === "ArrayPattern") { + handlePattern(p, node); + return; + } + walk(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent) { + // skip params default value of destructure + if ((parent === null || parent === void 0 ? void 0 : parent.type) === "AssignmentPattern" && (parent === null || parent === void 0 ? void 0 : parent.right) === child) { + return this.skip(); + } + if (child.type !== "Identifier") { + return; + } + // do not record as scope variable if is a destructuring keyword + if (isStaticPropertyKey(child, parent)) { + return; + } + // do not record if this is a default value + // assignment of a destructuring variable + if ((parent === null || parent === void 0 ? void 0 : parent.type) === "TemplateLiteral" && (parent === null || parent === void 0 ? void 0 : parent.expressions.includes(child)) || (parent === null || parent === void 0 ? void 0 : parent.type) === "CallExpression" && (parent === null || parent === void 0 ? void 0 : parent.callee) === child) { + return; + } + setScope(node, child.name); + } }); + }); + } else if (node.type === "Property" && parent.type === "ObjectPattern") { + // mark property in destructuring pattern + setIsNodeInPattern(node); + } else if (node.type === "VariableDeclarator") { + const parentFunction = findParentScope(parentStack, varKindStack[0] === "var"); + if (parentFunction) { + handlePattern(node.id, parentFunction); + } + } else if (node.type === "CatchClause" && node.param) { + handlePattern(node.param, node); + } + }, + leave(node, parent) { + // untrack parent stack from above + if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) { + parentStack.shift(); + } + if (node.type === "VariableDeclaration") { + varKindStack.shift(); + } + } + }); + // emit the identifier events in BFS so the hoisted declarations + // can be captured correctly + identifiers.forEach(([node, stack]) => { + if (!isInScope(node.name, stack)) { + const parent = stack[0]; + const grandparent = stack[1]; + const hasBindingShortcut = isStaticProperty(parent) && parent.shorthand && (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)); + const classDeclaration = parent.type === "PropertyDefinition" && (grandparent === null || grandparent === void 0 ? void 0 : grandparent.type) === "ClassBody" || parent.type === "ClassDeclaration" && node === parent.superClass; + const classExpression = parent.type === "ClassExpression" && node === parent.id; + onIdentifier === null || onIdentifier === void 0 ? void 0 : onIdentifier(node, { + hasBindingShortcut, + classDeclaration, + classExpression + }, stack); + } + }); +} +function isRefIdentifier(id, parent, parentStack) { + // declaration id + if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) { + return false; + } + if (isFunctionNode(parent)) { + // function declaration/expression id + if (parent.id === id) { + return false; + } + // params list + if (parent.params.includes(id)) { + return false; + } + } + // class method name + if (parent.type === "MethodDefinition" && !parent.computed) { + return false; + } + // property key + if (isStaticPropertyKey(id, parent)) { + return false; + } + // object destructuring pattern + if (isNodeInPattern(parent) && parent.value === id) { + return false; + } + // non-assignment array destructuring pattern + if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) { + return false; + } + // member expression property + if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) { + return false; + } + if (parent.type === "ExportSpecifier") { + return false; + } + // is a special keyword but parsed as identifier + if (id.name === "arguments") { + return false; + } + return true; +} +function isStaticProperty(node) { + return node && node.type === "Property" && !node.computed; +} +function isStaticPropertyKey(node, parent) { + return isStaticProperty(parent) && parent.key === node; +} +const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/; +function isFunctionNode(node) { + return functionNodeTypeRE.test(node.type); +} +const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/; +function isBlock(node) { + return blockNodeTypeRE.test(node.type); +} +function findParentScope(parentStack, isVar = false) { + return parentStack.find(isVar ? isFunctionNode : isBlock); +} +function isInDestructuringAssignment(parent, parentStack) { + if (parent && (parent.type === "Property" || parent.type === "ArrayPattern")) { + return parentStack.some((i) => i.type === "AssignmentExpression"); + } + return false; +} +function getArbitraryModuleIdentifier(node) { + return node.type === "Identifier" ? node.name : node.raw; +} + +// TODO: better source map replacement +function automockModule(code, mockType, parse, options = {}) { + const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\""; + const ast = parse(code); + const m = new MagicString(code); + const allSpecifiers = []; + let importIndex = 0; + for (const _node of ast.body) { + if (_node.type === "ExportAllDeclaration") { + throw new Error(`automocking files with \`export *\` is not supported in browser mode because it cannot be statically analysed`); + } + if (_node.type === "ExportNamedDeclaration") { + const node = _node; + const declaration = node.declaration; + function traversePattern(expression) { + // export const test = '1' + if (expression.type === "Identifier") { + allSpecifiers.push({ name: expression.name }); + } else if (expression.type === "ArrayPattern") { + expression.elements.forEach((element) => { + if (!element) { + return; + } + traversePattern(element); + }); + } else if (expression.type === "ObjectPattern") { + expression.properties.forEach((property) => { + // export const { ...rest } = {} + if (property.type === "RestElement") { + traversePattern(property); + } else if (property.type === "Property") { + traversePattern(property.value); + } else ; + }); + } else if (expression.type === "RestElement") { + traversePattern(expression.argument); + } else if (expression.type === "AssignmentPattern") { + throw new Error(`AssignmentPattern is not supported. Please open a new bug report.`); + } else if (expression.type === "MemberExpression") { + throw new Error(`MemberExpression is not supported. Please open a new bug report.`); + } else ; + } + if (declaration) { + if (declaration.type === "FunctionDeclaration") { + allSpecifiers.push({ name: declaration.id.name }); + } else if (declaration.type === "VariableDeclaration") { + declaration.declarations.forEach((declaration) => { + traversePattern(declaration.id); + }); + } else if (declaration.type === "ClassDeclaration") { + allSpecifiers.push({ name: declaration.id.name }); + } else ; + m.remove(node.start, declaration.start); + } + const specifiers = node.specifiers || []; + const source = node.source; + if (!source && specifiers.length) { + specifiers.forEach((specifier) => { + allSpecifiers.push({ + alias: getArbitraryModuleIdentifier(specifier.exported), + name: getArbitraryModuleIdentifier(specifier.local) + }); + }); + m.remove(node.start, node.end); + } else if (source && specifiers.length) { + const importNames = []; + specifiers.forEach((specifier) => { + const importedName = `__vitest_imported_${importIndex++}__`; + importNames.push([getArbitraryModuleIdentifier(specifier.local), importedName]); + allSpecifiers.push({ + name: importedName, + alias: getArbitraryModuleIdentifier(specifier.exported) + }); + }); + const importString = `import { ${importNames.map(([name, alias]) => `${name} as ${alias}`).join(", ")} } from '${source.value}'`; + m.overwrite(node.start, node.end, importString); + } + } + if (_node.type === "ExportDefaultDeclaration") { + const node = _node; + const declaration = node.declaration; + allSpecifiers.push({ + name: "__vitest_default", + alias: "default" + }); + m.overwrite(node.start, declaration.start, `const __vitest_default = `); + } + } + const moduleObject = ` +const __vitest_current_es_module__ = { + __esModule: true, + ${allSpecifiers.map(({ name }) => `["${name}"]: ${name},`).join("\n ")} +} +const __vitest_mocked_module__ = globalThis[${globalThisAccessor}].mockObject(__vitest_current_es_module__, "${mockType}") +`; + const assigning = allSpecifiers.map(({ name }, index) => { + return `const __vitest_mocked_${index}__ = __vitest_mocked_module__["${name}"]`; + }).join("\n"); + const redeclarations = allSpecifiers.map(({ name, alias }, index) => { + return ` __vitest_mocked_${index}__ as ${alias || name},`; + }).join("\n"); + const specifiersExports = ` +export { +${redeclarations} +} +`; + m.append(moduleObject + assigning + specifiersExports); + return m; +} + +export { automockModule as a, esmWalker as e }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js new file mode 100644 index 0000000..4b472cc --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js @@ -0,0 +1,15 @@ +import { r as rpc } from './chunk-mocker.js'; + +class ModuleMockerServerInterceptor { + async register(module) { + await rpc("vitest:interceptor:register", module.toJSON()); + } + async delete(id) { + await rpc("vitest:interceptor:delete", id); + } + async invalidate() { + await rpc("vitest:interceptor:invalidate"); + } +} + +export { ModuleMockerServerInterceptor as M }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-mocker.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-mocker.js new file mode 100644 index 0000000..d86b758 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/chunk-mocker.js @@ -0,0 +1,521 @@ +import { mockObject } from './index.js'; +import { M as MockerRegistry, R as RedirectedModule, A as AutomockedModule } from './chunk-registry.js'; +import { e as extname, j as join } from './chunk-pathe.M-eThtNZ.js'; + +/** +* Get original stacktrace without source map support the most performant way. +* - Create only 1 stack frame. +* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). +*/ +function createSimpleStackTrace(options) { + const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {}; + const limit = Error.stackTraceLimit; + const prepareStackTrace = Error.prepareStackTrace; + Error.stackTraceLimit = stackTraceLimit; + Error.prepareStackTrace = (e) => e.stack; + const err = new Error(message); + const stackTrace = err.stack || ""; + Error.prepareStackTrace = prepareStackTrace; + Error.stackTraceLimit = limit; + return stackTrace; +} + +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +function cwd() { + if (typeof process !== "undefined" && typeof process.cwd === "function") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 1 || dots === 1); + else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; + +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m; +const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/; +function extractLocation(urlLike) { + // Fail-fast but return locations like "(native)" + if (!urlLike.includes(":")) { + return [urlLike]; + } + const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; + const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); + if (!parts) { + return [urlLike]; + } + let url = parts[1]; + if (url.startsWith("async ")) { + url = url.slice(6); + } + if (url.startsWith("http:") || url.startsWith("https:")) { + const urlObj = new URL(url); + urlObj.searchParams.delete("import"); + urlObj.searchParams.delete("browserv"); + url = urlObj.pathname + urlObj.hash + urlObj.search; + } + if (url.startsWith("/@fs/")) { + const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url); + url = url.slice(isWindows ? 5 : 4); + } + return [ + url, + parts[2] || undefined, + parts[3] || undefined + ]; +} +function parseSingleFFOrSafariStack(raw) { + let line = raw.trim(); + if (SAFARI_NATIVE_CODE_REGEXP.test(line)) { + return null; + } + if (line.includes(" > eval")) { + line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); + } + // Early return for lines that don't look like Firefox/Safari stack traces + // Firefox/Safari stack traces must contain '@' and should have location info after it + if (!line.includes("@")) { + return null; + } + // Find the correct @ that separates function name from location + // For cases like '@https://@fs/path' or 'functionName@https://@fs/path' + // we need to find the first @ that precedes a valid location (containing :) + let atIndex = -1; + let locationPart = ""; + let functionName; + // Try each @ from left to right to find the one that gives us a valid location + for (let i = 0; i < line.length; i++) { + if (line[i] === "@") { + const candidateLocation = line.slice(i + 1); + // Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1") + if (candidateLocation.includes(":") && candidateLocation.length >= 3) { + atIndex = i; + locationPart = candidateLocation; + functionName = i > 0 ? line.slice(0, i) : undefined; + break; + } + } + } + // Validate we found a valid location with minimum length (filename:line format) + if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) { + return null; + } + const [url, lineNumber, columnNumber] = extractLocation(locationPart); + if (!url || !lineNumber || !columnNumber) { + return null; + } + return { + file: url, + method: functionName || "", + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function parseSingleStack(raw) { + const line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) { + return parseSingleFFOrSafariStack(line); + } + return parseSingleV8Stack(line); +} +// Based on https://github.com/stacktracejs/error-stack-parser +// Credit to stacktracejs +function parseSingleV8Stack(raw) { + let line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) { + return null; + } + if (line.includes("(eval ")) { + line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, ""); + } + let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, ""); + // capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in + // case it has spaces in it, as the string is split on \s+ later on + const location = sanitizedLine.match(/ (\(.+\)$)/); + // remove the parenthesized location from the line, if it was matched + sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; + // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine + // because this line doesn't have function name + const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); + let method = location && sanitizedLine || ""; + let file = url && ["eval", ""].includes(url) ? undefined : url; + if (!file || !lineNumber || !columnNumber) { + return null; + } + if (method.startsWith("async ")) { + method = method.slice(6); + } + if (file.startsWith("file://")) { + file = file.slice(7); + } + // normalize Windows path (\ -> /) + file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file); + if (method) { + method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, ""); + } + return { + method, + file, + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} + +function createCompilerHints(options) { + const globalThisAccessor = (options === null || options === void 0 ? void 0 : options.globalThisKey) || "__vitest_mocker__"; + function _mocker() { + // @ts-expect-error injected by the plugin + return typeof globalThis[globalThisAccessor] !== "undefined" ? globalThis[globalThisAccessor] : new Proxy({}, { get(_, name) { + throw new Error("Vitest mocker was not initialized in this environment. " + `vi.${String(name)}() is forbidden.`); + } }); + } + return { + hoisted(factory) { + if (typeof factory !== "function") { + throw new TypeError(`vi.hoisted() expects a function, but received a ${typeof factory}`); + } + return factory(); + }, + mock(path, factory) { + if (typeof path !== "string") { + throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`); + } + const importer = getImporter("mock"); + _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory); + }, + unmock(path) { + if (typeof path !== "string") { + throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`); + } + _mocker().queueUnmock(path, getImporter("unmock")); + }, + doMock(path, factory) { + if (typeof path !== "string") { + throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`); + } + const importer = getImporter("doMock"); + _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory); + }, + doUnmock(path) { + if (typeof path !== "string") { + throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`); + } + _mocker().queueUnmock(path, getImporter("doUnmock")); + }, + async importActual(path) { + return _mocker().importActual(path, getImporter("importActual")); + }, + async importMock(path) { + return _mocker().importMock(path, getImporter("importMock")); + } + }; +} +function getImporter(name) { + const stackTrace = /* @__PURE__ */ createSimpleStackTrace({ stackTraceLimit: 5 }); + const stackArray = stackTrace.split("\n"); + // if there is no message in a stack trace, use the item - 1 + const importerStackIndex = stackArray.findIndex((stack) => { + return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`); + }); + const stack = /* @__PURE__ */ parseSingleStack(stackArray[importerStackIndex + 1]); + return (stack === null || stack === void 0 ? void 0 : stack.file) || ""; +} + +const hot = import.meta.hot || { + on: warn, + off: warn, + send: warn +}; +function warn() { + console.warn("Vitest mocker cannot work if Vite didn't establish WS connection."); +} +function rpc(event, data) { + hot.send(event, data); + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + reject(new Error(`Failed to resolve ${event} in time`)); + }, 5e3); + hot.on(`${event}:result`, function r(data) { + resolve(data); + clearTimeout(timeout); + hot.off(`${event}:result`, r); + }); + }); +} + +const { now } = Date; +class ModuleMocker { + registry = new MockerRegistry(); + queue = new Set(); + mockedIds = new Set(); + constructor(interceptor, rpc, createMockInstance, config) { + this.interceptor = interceptor; + this.rpc = rpc; + this.createMockInstance = createMockInstance; + this.config = config; + } + async prepare() { + if (!this.queue.size) { + return; + } + await Promise.all([...this.queue.values()]); + } + async resolveFactoryModule(id) { + const mock = this.registry.get(id); + if (!mock || mock.type !== "manual") { + throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`); + } + const result = await mock.resolve(); + return result; + } + getFactoryModule(id) { + const mock = this.registry.get(id); + if (!mock || mock.type !== "manual") { + throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`); + } + if (!mock.cache) { + throw new Error(`Mock ${id} wasn't resolved. This is probably a Vitest error. Please, open a new issue with reproduction.`); + } + return mock.cache; + } + async invalidate() { + const ids = Array.from(this.mockedIds); + if (!ids.length) { + return; + } + await this.rpc.invalidate(ids); + await this.interceptor.invalidate(); + this.registry.clear(); + } + async importActual(id, importer) { + const resolved = await this.rpc.resolveId(id, importer); + if (resolved == null) { + throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`); + } + const ext = extname(resolved.id); + const url = new URL(resolved.url, location.href); + const query = `_vitest_original&ext${ext}`; + const actualUrl = `${url.pathname}${url.search ? `${url.search}&${query}` : `?${query}`}${url.hash}`; + return this.wrapDynamicImport(() => import( + /* @vite-ignore */ + actualUrl +)).then((mod) => { + if (!resolved.optimized || typeof mod.default === "undefined") { + return mod; + } + // vite injects this helper for optimized modules, so we try to follow the same behavior + const m = mod.default; + return (m === null || m === void 0 ? void 0 : m.__esModule) ? m : { + ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, + default: m + }; + }); + } + async importMock(rawId, importer) { + await this.prepare(); + const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" }); + const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl)); + let mock = this.registry.get(mockUrl); + if (!mock) { + if (redirectUrl) { + const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString(); + mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect); + } else { + mock = new AutomockedModule(rawId, resolvedId, mockUrl); + } + } + if (mock.type === "manual") { + return await mock.resolve(); + } + if (mock.type === "automock" || mock.type === "autospy") { + const url = new URL(`/@id/${resolvedId}`, location.href); + const query = url.search ? `${url.search}&t=${now()}` : `?t=${now()}`; + const moduleObject = await import( + /* @vite-ignore */ + `${url.pathname}${query}&mock=${mock.type}${url.hash}` +); + return this.mockObject(moduleObject, mock.type); + } + return import( + /* @vite-ignore */ + mock.redirect +); + } + mockObject(object, moduleType = "automock") { + return mockObject({ + globalConstructors: { + Object, + Function, + Array, + Map, + RegExp + }, + createMockInstance: this.createMockInstance, + type: moduleType + }, object); + } + queueMock(rawId, importer, factoryOrOptions) { + const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : (factoryOrOptions === null || factoryOrOptions === void 0 ? void 0 : factoryOrOptions.spy) ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => { + const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl)); + this.mockedIds.add(resolvedId); + const factory = typeof factoryOrOptions === "function" ? async () => { + const data = await factoryOrOptions(); + // vite wraps all external modules that have "needsInterop" in a function that + // merges all exports from default into the module object + return needsInterop ? { default: data } : data; + } : undefined; + const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString() : null; + let module; + if (mockType === "manual") { + module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory); + } else if (mockType === "autospy") { + module = this.registry.register("autospy", rawId, resolvedId, mockUrl); + } else if (mockType === "redirect") { + module = this.registry.register("redirect", rawId, resolvedId, mockUrl, mockRedirect); + } else { + module = this.registry.register("automock", rawId, resolvedId, mockUrl); + } + await this.interceptor.register(module); + }).finally(() => { + this.queue.delete(promise); + }); + this.queue.add(promise); + } + queueUnmock(id, importer) { + const promise = this.rpc.resolveId(id, importer).then(async (resolved) => { + if (!resolved) { + return; + } + const mockUrl = this.resolveMockPath(cleanVersion(resolved.url)); + this.mockedIds.add(resolved.id); + this.registry.delete(mockUrl); + await this.interceptor.delete(mockUrl); + }).finally(() => { + this.queue.delete(promise); + }); + this.queue.add(promise); + } + // We need to await mock registration before importing the actual module + // In case there is a mocked module in the import chain + wrapDynamicImport(moduleFactory) { + if (typeof moduleFactory === "function") { + const promise = new Promise((resolve, reject) => { + this.prepare().finally(() => { + moduleFactory().then(resolve, reject); + }); + }); + return promise; + } + return moduleFactory; + } + resolveMockPath(path) { + const config = this.config; + const fsRoot = join("/@fs/", config.root); + // URL can be /file/path.js, but path is resolved to /file/path + if (path.startsWith(config.root)) { + return path.slice(config.root.length); + } + if (path.startsWith(fsRoot)) { + return path.slice(fsRoot.length); + } + return path; + } +} +const versionRegexp = /(\?|&)v=\w{8}/; +function cleanVersion(url) { + return url.replace(versionRegexp, ""); +} + +export { ModuleMocker as M, createCompilerHints as c, hot as h, rpc as r }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js new file mode 100644 index 0000000..11a98f0 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js @@ -0,0 +1,174 @@ +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} + +const _UNC_REGEX = /^[/\\]{2}/; +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; +const _EXTNAME_RE = /.(\.[^./]+|\.)$/; +const normalize = function(path) { + if (path.length === 0) { + return "."; + } + path = normalizeWindowsPath(path); + const isUNCPath = path.match(_UNC_REGEX); + const isPathAbsolute = isAbsolute(path); + const trailingSeparator = path[path.length - 1] === "/"; + path = normalizeString(path, !isPathAbsolute); + if (path.length === 0) { + if (isPathAbsolute) { + return "/"; + } + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) { + path += "/"; + } + if (_DRIVE_LETTER_RE.test(path)) { + path += "/"; + } + if (isUNCPath) { + if (!isPathAbsolute) { + return `//./${path}`; + } + return `//${path}`; + } + return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; +}; +const join = function(...segments) { + let path = ""; + for (const seg of segments) { + if (!seg) { + continue; + } + if (path.length > 0) { + const pathTrailing = path[path.length - 1] === "/"; + const segLeading = seg[0] === "/"; + const both = pathTrailing && segLeading; + if (both) { + path += seg.slice(1); + } else { + path += pathTrailing || segLeading ? seg : `/${seg}`; + } + } else { + path += seg; + } + } + return normalize(path); +}; +function cwd() { + if (typeof process !== "undefined" && typeof process.cwd === "function") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; +const extname = function(p) { + if (p === "..") return ""; + const match = _EXTNAME_RE.exec(normalizeWindowsPath(p)); + return match && match[1] || ""; +}; +const dirname = function(p) { + const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); + if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { + segments[0] += "/"; + } + return segments.join("/") || (isAbsolute(p) ? "/" : "."); +}; +const basename = function(p, extension) { + const segments = normalizeWindowsPath(p).split("/"); + let lastSegment = ""; + for (let i = segments.length - 1; i >= 0; i--) { + const val = segments[i]; + if (val) { + lastSegment = val; + break; + } + } + return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment; +}; + +export { basename as b, dirname as d, extname as e, isAbsolute as i, join as j, resolve as r }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-registry.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-registry.js new file mode 100644 index 0000000..fe0e803 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/chunk-registry.js @@ -0,0 +1,185 @@ +class MockerRegistry { + registryByUrl = new Map(); + registryById = new Map(); + clear() { + this.registryByUrl.clear(); + this.registryById.clear(); + } + keys() { + return this.registryByUrl.keys(); + } + add(mock) { + this.registryByUrl.set(mock.url, mock); + this.registryById.set(mock.id, mock); + } + register(typeOrEvent, raw, id, url, factoryOrRedirect) { + const type = typeof typeOrEvent === "object" ? typeOrEvent.type : typeOrEvent; + if (typeof typeOrEvent === "object") { + const event = typeOrEvent; + if (event instanceof AutomockedModule || event instanceof AutospiedModule || event instanceof ManualMockedModule || event instanceof RedirectedModule) { + throw new TypeError(`[vitest] Cannot register a mock that is already defined. ` + `Expected a JSON representation from \`MockedModule.toJSON\`, instead got "${event.type}". ` + `Use "registry.add()" to update a mock instead.`); + } + if (event.type === "automock") { + const module = AutomockedModule.fromJSON(event); + this.add(module); + return module; + } else if (event.type === "autospy") { + const module = AutospiedModule.fromJSON(event); + this.add(module); + return module; + } else if (event.type === "redirect") { + const module = RedirectedModule.fromJSON(event); + this.add(module); + return module; + } else if (event.type === "manual") { + throw new Error(`Cannot set serialized manual mock. Define a factory function manually with \`ManualMockedModule.fromJSON()\`.`); + } else { + throw new Error(`Unknown mock type: ${event.type}`); + } + } + if (typeof raw !== "string") { + throw new TypeError("[vitest] Mocks require a raw string."); + } + if (typeof url !== "string") { + throw new TypeError("[vitest] Mocks require a url string."); + } + if (typeof id !== "string") { + throw new TypeError("[vitest] Mocks require an id string."); + } + if (type === "manual") { + if (typeof factoryOrRedirect !== "function") { + throw new TypeError("[vitest] Manual mocks require a factory function."); + } + const mock = new ManualMockedModule(raw, id, url, factoryOrRedirect); + this.add(mock); + return mock; + } else if (type === "automock" || type === "autospy") { + const mock = type === "automock" ? new AutomockedModule(raw, id, url) : new AutospiedModule(raw, id, url); + this.add(mock); + return mock; + } else if (type === "redirect") { + if (typeof factoryOrRedirect !== "string") { + throw new TypeError("[vitest] Redirect mocks require a redirect string."); + } + const mock = new RedirectedModule(raw, id, url, factoryOrRedirect); + this.add(mock); + return mock; + } else { + throw new Error(`[vitest] Unknown mock type: ${type}`); + } + } + delete(id) { + this.registryByUrl.delete(id); + } + deleteById(id) { + this.registryById.delete(id); + } + get(id) { + return this.registryByUrl.get(id); + } + getById(id) { + return this.registryById.get(id); + } + has(id) { + return this.registryByUrl.has(id); + } +} +class AutomockedModule { + type = "automock"; + constructor(raw, id, url) { + this.raw = raw; + this.id = id; + this.url = url; + } + static fromJSON(data) { + return new AutospiedModule(data.raw, data.id, data.url); + } + toJSON() { + return { + type: this.type, + url: this.url, + raw: this.raw, + id: this.id + }; + } +} +class AutospiedModule { + type = "autospy"; + constructor(raw, id, url) { + this.raw = raw; + this.id = id; + this.url = url; + } + static fromJSON(data) { + return new AutospiedModule(data.raw, data.id, data.url); + } + toJSON() { + return { + type: this.type, + url: this.url, + id: this.id, + raw: this.raw + }; + } +} +class RedirectedModule { + type = "redirect"; + constructor(raw, id, url, redirect) { + this.raw = raw; + this.id = id; + this.url = url; + this.redirect = redirect; + } + static fromJSON(data) { + return new RedirectedModule(data.raw, data.id, data.url, data.redirect); + } + toJSON() { + return { + type: this.type, + url: this.url, + raw: this.raw, + id: this.id, + redirect: this.redirect + }; + } +} +class ManualMockedModule { + cache; + type = "manual"; + constructor(raw, id, url, factory) { + this.raw = raw; + this.id = id; + this.url = url; + this.factory = factory; + } + async resolve() { + if (this.cache) { + return this.cache; + } + let exports$1; + try { + exports$1 = await this.factory(); + } catch (err) { + const vitestError = new Error("[vitest] There was an error when mocking a module. " + "If you are using \"vi.mock\" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. " + "Read more: https://vitest.dev/api/vi.html#vi-mock"); + vitestError.cause = err; + throw vitestError; + } + if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) { + throw new TypeError(`[vitest] vi.mock("${this.raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`); + } + return this.cache = exports$1; + } + static fromJSON(data, factory) { + return new ManualMockedModule(data.raw, data.id, data.url, factory); + } + toJSON() { + return { + type: this.type, + url: this.url, + id: this.id, + raw: this.raw + }; + } +} + +export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, ManualMockedModule as a, AutospiedModule as b }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-utils.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-utils.js new file mode 100644 index 0000000..de1b7e4 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/chunk-utils.js @@ -0,0 +1,16 @@ +const postfixRE = /[?#].*$/; +function cleanUrl(url) { + return url.replace(postfixRE, ""); +} +function createManualModuleSource(moduleUrl, exports$1, globalAccessor = "\"__vitest_mocker__\"") { + const source = `const module = globalThis[${globalAccessor}].getFactoryModule("${moduleUrl}");`; + const keys = exports$1.map((name) => { + if (name === "default") { + return `export default module["default"];`; + } + return `export const ${name} = module["${name}"];`; + }).join("\n"); + return `${source}\n${keys}`; +} + +export { cleanUrl as a, createManualModuleSource as c }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts b/vanilla/node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts new file mode 100644 index 0000000..cad0899 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts @@ -0,0 +1,25 @@ +import './types.d-B8CCKmHt.js'; + +type Key = string | symbol; +type CreateMockInstanceProcedure = (options?: { + prototypeMembers?: (string | symbol)[]; + name?: string | symbol; + originalImplementation?: (...args: any[]) => any; + keepMembersImplementation?: boolean; +}) => any; +interface MockObjectOptions { + type: "automock" | "autospy"; + globalConstructors: GlobalConstructors; + createMockInstance: CreateMockInstanceProcedure; +} +declare function mockObject(options: MockObjectOptions, object: Record, mockExports?: Record): Record; +interface GlobalConstructors { + Object: ObjectConstructor; + Function: FunctionConstructor; + RegExp: RegExpConstructor; + Array: ArrayConstructor; + Map: MapConstructor; +} + +export { mockObject as m }; +export type { CreateMockInstanceProcedure as C, GlobalConstructors as G, MockObjectOptions as M }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/index.d.ts b/vanilla/node_modules/@vitest/mocker/dist/index.d.ts new file mode 100644 index 0000000..107b5fb --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/index.d.ts @@ -0,0 +1,2 @@ +export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-C-sLYZi-.js'; +export { A as AutomockedModule, h as AutomockedModuleSerialized, f as AutospiedModule, i as AutospiedModuleSerialized, g as ManualMockedModule, j as ManualMockedModuleSerialized, a as MockedModule, k as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, l as RedirectedModuleSerialized, e as ServerIdResolution, S as ServerMockResolution } from './types.d-B8CCKmHt.js'; diff --git a/vanilla/node_modules/@vitest/mocker/dist/index.js b/vanilla/node_modules/@vitest/mocker/dist/index.js new file mode 100644 index 0000000..79c5c9a --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/index.js @@ -0,0 +1,185 @@ +export { A as AutomockedModule, b as AutospiedModule, a as ManualMockedModule, M as MockerRegistry, R as RedirectedModule } from './chunk-registry.js'; + +function mockObject(options, object, mockExports = {}) { + const finalizers = new Array(); + const refs = new RefTracker(); + const define = (container, key, value) => { + try { + container[key] = value; + return true; + } catch { + return false; + } + }; + const createMock = (currentValue) => { + if (!options.createMockInstance) { + throw new Error("[@vitest/mocker] `createMockInstance` is not defined. This is a Vitest error. Please open a new issue with reproduction."); + } + const createMockInstance = options.createMockInstance; + const prototypeMembers = currentValue.prototype ? collectFunctionProperties(currentValue.prototype) : []; + return createMockInstance({ + name: currentValue.name, + prototypeMembers, + originalImplementation: options.type === "autospy" ? currentValue : undefined, + keepMembersImplementation: options.type === "autospy" + }); + }; + const mockPropertiesOf = (container, newContainer) => { + const containerType = getType(container); + const isModule = containerType === "Module" || !!container.__esModule; + for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) { + // Modules define their exports as getters. We want to process those. + if (!isModule && descriptor.get) { + try { + if (options.type === "autospy") { + Object.defineProperty(newContainer, property, descriptor); + } else { + Object.defineProperty(newContainer, property, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + get: () => {}, + set: descriptor.set ? () => {} : undefined + }); + } + } catch {} + continue; + } + // Skip special read-only props, we don't want to mess with those. + if (isReadonlyProp(container[property], property)) { + continue; + } + const value = container[property]; + // Special handling of references we've seen before to prevent infinite + // recursion in circular objects. + const refId = refs.getId(value); + if (refId !== undefined) { + finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId))); + continue; + } + const type = getType(value); + if (Array.isArray(value)) { + if (options.type === "automock") { + define(newContainer, property, []); + } else { + const array = value.map((value) => { + if (value && typeof value === "object") { + const newObject = {}; + mockPropertiesOf(value, newObject); + return newObject; + } + if (typeof value === "function") { + return createMock(value); + } + return value; + }); + define(newContainer, property, array); + } + continue; + } + const isFunction = type.includes("Function") && typeof value === "function"; + if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") { + define(newContainer, property, value); + continue; + } + // Sometimes this assignment fails for some unknown reason. If it does, + // just move along. + if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) { + continue; + } + if (isFunction) { + const mock = createMock(newContainer[property]); + newContainer[property] = mock; + } + refs.track(value, newContainer[property]); + mockPropertiesOf(value, newContainer[property]); + } + }; + const mockedObject = mockExports; + mockPropertiesOf(object, mockedObject); + // Plug together refs + for (const finalizer of finalizers) { + finalizer(); + } + return mockedObject; +} +class RefTracker { + idMap = new Map(); + mockedValueMap = new Map(); + getId(value) { + return this.idMap.get(value); + } + getMockedValue(id) { + return this.mockedValueMap.get(id); + } + track(originalValue, mockedValue) { + const newId = this.idMap.size; + this.idMap.set(originalValue, newId); + this.mockedValueMap.set(newId, mockedValue); + return newId; + } +} +function getType(value) { + return Object.prototype.toString.apply(value).slice(8, -1); +} +function isReadonlyProp(object, prop) { + if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") { + const typeName = getType(object); + return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction" || typeName === "AsyncGeneratorFunction"; + } + if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") { + return getType(object) === "RegExp"; + } + return false; +} +function getAllMockableProperties(obj, isModule, constructors) { + const { Map, Object, Function, RegExp, Array } = constructors; + const allProps = new Map(); + let curr = obj; + do { + // we don't need properties from these + if (curr === Object.prototype || curr === Function.prototype || curr === RegExp.prototype) { + break; + } + collectOwnProperties(curr, (key) => { + const descriptor = Object.getOwnPropertyDescriptor(curr, key); + if (descriptor) { + allProps.set(key, { + key, + descriptor + }); + } + }); + } while (curr = Object.getPrototypeOf(curr)); + // default is not specified in ownKeys, if module is interoped + if (isModule && !allProps.has("default") && "default" in obj) { + const descriptor = Object.getOwnPropertyDescriptor(obj, "default"); + if (descriptor) { + allProps.set("default", { + key: "default", + descriptor + }); + } + } + return Array.from(allProps.values()); +} +function collectOwnProperties(obj, collector) { + const collect = typeof collector === "function" ? collector : (key) => collector.add(key); + Object.getOwnPropertyNames(obj).forEach(collect); + Object.getOwnPropertySymbols(obj).forEach(collect); +} +function collectFunctionProperties(prototype) { + const properties = new Set(); + collectOwnProperties(prototype, (prop) => { + const descriptor = Object.getOwnPropertyDescriptor(prototype, prop); + if (!descriptor || descriptor.get) { + return; + } + const type = getType(descriptor.value); + if (type.includes("Function") && !isReadonlyProp(descriptor.value, prop)) { + properties.add(prop); + } + }); + return Array.from(properties); +} + +export { mockObject }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts b/vanilla/node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts new file mode 100644 index 0000000..db47e96 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts @@ -0,0 +1,81 @@ +import { MaybeMockedDeep } from '@vitest/spy'; +import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, M as MockerRegistry, d as MockedModuleType } from './types.d-B8CCKmHt.js'; +import { C as CreateMockInstanceProcedure } from './index.d-C-sLYZi-.js'; + +interface CompilerHintsOptions { + /** + * This is the key used to access the globalThis object in the worker. + * Unlike `globalThisAccessor` in other APIs, this is not injected into the script. + * ```ts + * // globalThisKey: '__my_variable__' produces: + * globalThis['__my_variable__'] + * // globalThisKey: '"__my_variable__"' produces: + * globalThis['"__my_variable__"'] // notice double quotes + * ``` + * @default '__vitest_mocker__' + */ + globalThisKey?: string; +} +interface ModuleMockerCompilerHints { + hoisted: (factory: () => T) => T; + mock: (path: string | Promise, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void; + unmock: (path: string | Promise) => void; + doMock: (path: string | Promise, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void; + doUnmock: (path: string | Promise) => void; + importActual: (path: string) => Promise; + importMock: (path: string) => Promise>; +} +declare function createCompilerHints(options?: CompilerHintsOptions): ModuleMockerCompilerHints; + +interface ModuleMockerInterceptor { + register: (module: MockedModule) => Promise; + delete: (url: string) => Promise; + invalidate: () => Promise; +} + +declare class ModuleMocker { + private interceptor; + private rpc; + private createMockInstance; + private config; + protected registry: MockerRegistry; + private queue; + private mockedIds; + constructor(interceptor: ModuleMockerInterceptor, rpc: ModuleMockerRPC, createMockInstance: CreateMockInstanceProcedure, config: ModuleMockerConfig); + prepare(): Promise; + resolveFactoryModule(id: string): Promise>; + getFactoryModule(id: string): any; + invalidate(): Promise; + importActual(id: string, importer: string): Promise; + importMock(rawId: string, importer: string): Promise; + mockObject(object: Record, moduleType?: "automock" | "autospy"): Record; + queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void; + queueUnmock(id: string, importer: string): void; + wrapDynamicImport(moduleFactory: () => Promise): Promise; + private resolveMockPath; +} +interface ResolveIdResult { + id: string; + url: string; + optimized: boolean; +} +interface ResolveMockResult { + mockType: MockedModuleType; + resolvedId: string; + resolvedUrl: string; + redirectUrl?: string | null; + needsInterop?: boolean; +} +interface ModuleMockerRPC { + invalidate: (ids: string[]) => Promise; + resolveId: (id: string, importer: string) => Promise; + resolveMock: (id: string, importer: string, options: { + mock: "spy" | "factory" | "auto"; + }) => Promise; +} +interface ModuleMockerConfig { + root: string; +} + +export { ModuleMocker as b, createCompilerHints as c }; +export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as d, ModuleMockerRPC as e, ResolveMockResult as f }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/node.d.ts b/vanilla/node_modules/@vitest/mocker/dist/node.d.ts new file mode 100644 index 0000000..2f9b27c --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/node.d.ts @@ -0,0 +1,800 @@ +import { AutomockOptions } from './automock.js'; +export { automockModule } from './automock.js'; +import { Plugin, Rollup, ViteDevServer } from 'vite'; +import { SourceMap } from 'magic-string'; +import { M as MockerRegistry, S as ServerMockResolution, e as ServerIdResolution } from './types.d-B8CCKmHt.js'; +export { findMockRedirect } from './redirect.js'; + +declare function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor?: string): string; + +declare function automockPlugin(options?: AutomockOptions): Plugin; + +interface DynamicImportPluginOptions { + /** + * @default `"__vitest_mocker__"` + */ + globalThisAccessor?: string; + filter?: (id: string) => boolean; +} +declare function dynamicImportPlugin(options?: DynamicImportPluginOptions): Plugin; + +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; +} + +interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Comment[] | undefined; + trailingComments?: Comment[] | undefined; +} + +interface NodeMap { + AssignmentProperty: AssignmentProperty; + CatchClause: CatchClause; + Class: Class; + ClassBody: ClassBody; + Expression: Expression; + Function: Function; + Identifier: Identifier; + Literal: Literal; + MethodDefinition: MethodDefinition; + ModuleDeclaration: ModuleDeclaration; + ModuleSpecifier: ModuleSpecifier; + Pattern: Pattern; + PrivateIdentifier: PrivateIdentifier; + Program: Program; + Property: Property; + PropertyDefinition: PropertyDefinition; + SpreadElement: SpreadElement; + Statement: Statement; + Super: Super; + SwitchCase: SwitchCase; + TemplateElement: TemplateElement; + VariableDeclarator: VariableDeclarator; +} + +type Node$1 = NodeMap[keyof NodeMap]; + +interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +interface SourceLocation { + source?: string | null | undefined; + start: Position; + end: Position; +} + +interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Comment[] | undefined; +} + +interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +interface BaseFunction extends BaseNode { + params: Pattern[]; + generator?: boolean | undefined; + async?: boolean | undefined; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +type Statement = + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | Declaration; + +interface BaseStatement extends BaseNode {} + +interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Statement[]; + innerComments?: Comment[] | undefined; +} + +interface StaticBlock extends Omit { + type: "StaticBlock"; +} + +interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null | undefined; +} + +interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null | undefined; +} + +interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null | undefined; +} + +interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null | undefined; +} + +interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null | undefined; + finalizer?: BlockStatement | null | undefined; +} + +interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null | undefined; + test?: Expression | null | undefined; + update?: Expression | null | undefined; + body: Statement; +} + +interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +interface BaseDeclaration extends BaseStatement {} + +interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { + id: Identifier; +} + +interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const" | "using" | "await using"; +} + +interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null | undefined; +} + +interface ExpressionMap { + ArrayExpression: ArrayExpression; + ArrowFunctionExpression: ArrowFunctionExpression; + AssignmentExpression: AssignmentExpression; + AwaitExpression: AwaitExpression; + BinaryExpression: BinaryExpression; + CallExpression: CallExpression; + ChainExpression: ChainExpression; + ClassExpression: ClassExpression; + ConditionalExpression: ConditionalExpression; + FunctionExpression: FunctionExpression; + Identifier: Identifier; + ImportExpression: ImportExpression; + Literal: Literal; + LogicalExpression: LogicalExpression; + MemberExpression: MemberExpression; + MetaProperty: MetaProperty; + NewExpression: NewExpression; + ObjectExpression: ObjectExpression; + SequenceExpression: SequenceExpression; + TaggedTemplateExpression: TaggedTemplateExpression; + TemplateLiteral: TemplateLiteral; + ThisExpression: ThisExpression; + UnaryExpression: UnaryExpression; + UpdateExpression: UpdateExpression; + YieldExpression: YieldExpression; +} + +type Expression = ExpressionMap[keyof ExpressionMap]; + +interface BaseExpression extends BaseNode {} + +type ChainElement = SimpleCallExpression | MemberExpression; + +interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +interface Property extends BaseNode { + type: "Property"; + key: Expression | PrivateIdentifier; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null | undefined; + computed: boolean; + static: boolean; +} + +interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null | undefined; + type: "FunctionExpression"; + body: BlockStatement; +} + +interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Expression[]; +} + +interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression | PrivateIdentifier; + right: Expression; +} + +interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +type CallExpression = SimpleCallExpression | NewExpression; + +interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; + +interface BasePattern extends BaseNode {} + +interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null | undefined; + consequent: Statement[]; +} + +interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string | undefined; +} + +interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null | undefined; + regex: { + pattern: string; + flags: string; + }; + raw?: string | undefined; +} + +interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null | undefined; + bigint: string; + raw?: string | undefined; +} + +type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +type BinaryOperator = + | "==" + | "!=" + | "===" + | "!==" + | "<" + | "<=" + | ">" + | ">=" + | "<<" + | ">>" + | ">>>" + | "+" + | "-" + | "*" + | "/" + | "%" + | "**" + | "|" + | "^" + | "&" + | "in" + | "instanceof"; + +type LogicalOperator = "||" | "&&" | "??"; + +type AssignmentOperator = + | "=" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "**=" + | "<<=" + | ">>=" + | ">>>=" + | "|=" + | "^=" + | "&=" + | "||=" + | "&&=" + | "??="; + +type UpdateOperator = "++" | "--"; + +interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +interface Super extends BaseNode { + type: "Super"; +} + +interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null | undefined; + delegate: boolean; +} + +interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null | undefined; + raw: string; + }; +} + +interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +type Class = ClassDeclaration | ClassExpression; +interface BaseClass extends BaseNode { + superClass?: Expression | null | undefined; + body: ClassBody; +} + +interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +interface ClassDeclaration extends MaybeNamedClassDeclaration { + id: Identifier; +} + +interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null | undefined; +} + +interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +type ModuleDeclaration = + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration; +interface BaseModuleDeclaration extends BaseNode {} + +type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; +interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + attributes: ImportAttribute[]; + source: Literal; +} + +interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier | Literal; +} + +interface ImportAttribute extends BaseNode { + type: "ImportAttribute"; + key: Identifier | Literal; + value: Literal; +} + +interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; + options?: Expression | null | undefined; +} + +interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null | undefined; + specifiers: ExportSpecifier[]; + attributes: ImportAttribute[]; + source?: Literal | null | undefined; +} + +interface ExportSpecifier extends Omit { + type: "ExportSpecifier"; + local: Identifier | Literal; + exported: Identifier | Literal; +} + +interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; +} + +interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + exported: Identifier | Literal | null; + attributes: ImportAttribute[]; + source: Literal; +} + +interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} + +type Positioned = T & { + start: number; + end: number; +}; +type Node = Positioned; + +interface HoistMocksOptions { + /** + * List of modules that should always be imported before compiler hints. + * @default 'vitest' + */ + hoistedModule?: string; + /** + * @default ["vi", "vitest"] + */ + utilsObjectNames?: string[]; + /** + * @default ["mock", "unmock"] + */ + hoistableMockMethodNames?: string[]; + /** + * @default ["mock", "unmock", "doMock", "doUnmock"] + */ + dynamicImportMockMethodNames?: string[]; + /** + * @default ["hoisted"] + */ + hoistedMethodNames?: string[]; + regexpHoistable?: RegExp; + codeFrameGenerator?: CodeFrameGenerator; +} +interface HoistMocksPluginOptions extends Omit { + include?: string | RegExp | (string | RegExp)[]; + exclude?: string | RegExp | (string | RegExp)[]; + /** + * overrides include/exclude options + */ + filter?: (id: string) => boolean; +} +declare function hoistMocksPlugin(options?: HoistMocksPluginOptions): Plugin; +interface HoistMocksResult { + code: string; + map: SourceMap; +} +interface CodeFrameGenerator { + (node: Positioned, id: string, code: string): string; +} +declare function hoistMocks(code: string, id: string, parse: Rollup.PluginContext["parse"], options?: HoistMocksOptions): HoistMocksResult | undefined; + +interface InterceptorPluginOptions { + /** + * @default "__vitest_mocker__" + */ + globalThisAccessor?: string; + registry?: MockerRegistry; +} +declare function interceptorPlugin(options?: InterceptorPluginOptions): Plugin; + +interface MockerPluginOptions extends AutomockOptions { + hoistMocks?: HoistMocksPluginOptions; +} +declare function mockerPlugin(options?: MockerPluginOptions): Plugin[]; + +interface ServerResolverOptions { + /** + * @default ['/node_modules/'] + */ + moduleDirectories?: string[]; +} +declare class ServerMockResolver { + private server; + private options; + constructor(server: ViteDevServer, options?: ServerResolverOptions); + resolveMock(rawId: string, importer: string, options: { + mock: "spy" | "factory" | "auto"; + }): Promise; + invalidate(ids: string[]): void; + resolveId(id: string, importer?: string): Promise; + private normalizeResolveIdToUrl; + private resolveMockId; + private resolveModule; +} + +export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, createManualModuleSource, dynamicImportPlugin, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin }; +export type { HoistMocksPluginOptions, HoistMocksResult, InterceptorPluginOptions, ServerResolverOptions }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/node.js b/vanilla/node_modules/@vitest/mocker/dist/node.js new file mode 100644 index 0000000..f2ca242 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/node.js @@ -0,0 +1,967 @@ +import { a as cleanUrl, c as createManualModuleSource } from './chunk-utils.js'; +import { a as automockModule, e as esmWalker } from './chunk-automock.js'; +import MagicString from 'magic-string'; +import { createFilter } from 'vite'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path/posix'; +import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js'; +import { fileURLToPath } from 'node:url'; +import { existsSync, readFileSync } from 'node:fs'; +import { findMockRedirect } from './redirect.js'; +import { i as isAbsolute, j as join$1, r as resolve } from './chunk-pathe.M-eThtNZ.js'; +import 'estree-walker'; +import 'node:module'; + +function automockPlugin(options = {}) { + return { + name: "vitest:automock", + enforce: "post", + transform(code, id) { + if (id.includes("mock=automock") || id.includes("mock=autospy")) { + const mockType = id.includes("mock=automock") ? "automock" : "autospy"; + const ms = automockModule(code, mockType, this.parse, options); + return { + code: ms.toString(), + map: ms.generateMap({ + hires: "boundary", + source: cleanUrl(id) + }) + }; + } + } + }; +} + +const regexDynamicImport = /import\s*\(/; +function dynamicImportPlugin(options = {}) { + return { + name: "vitest:browser:esm-injector", + enforce: "post", + transform(source, id) { + // TODO: test is not called for static imports + if (!regexDynamicImport.test(source)) { + return; + } + if (options.filter && !options.filter(id)) { + return; + } + return injectDynamicImport(source, id, this.parse, options); + } + }; +} +function injectDynamicImport(code, id, parse, options = {}) { + const s = new MagicString(code); + let ast; + try { + ast = parse(code); + } catch (err) { + console.error(`Cannot parse ${id}:\n${err.message}`); + return; + } + // 3. convert references to import bindings & import.meta references + esmWalker(ast, { + onImportMeta() { + // s.update(node.start, node.end, viImportMetaKey) + }, + onDynamicImport(node) { + const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\""; + const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`; + const importSubstring = code.substring(node.start, node.end); + const hasIgnore = importSubstring.includes("/* @vite-ignore */"); + s.overwrite(node.start, node.source.start, replaceString + (hasIgnore ? "/* @vite-ignore */ " : "")); + s.overwrite(node.end - 1, node.end, "))"); + } + }); + return { + code: s.toString(), + map: s.generateMap({ + hires: "boundary", + source: id + }) + }; +} + +// AST walker module for ESTree compatible trees + + +function makeTest(test) { + if (typeof test === "string") + { return function (type) { return type === test; } } + else if (!test) + { return function () { return true; } } + else + { return test } +} + +var Found = function Found(node, state) { this.node = node; this.state = state; }; + +// Find the innermost node of a given type that contains the given +// position. Interface similar to findNodeAt. +function findNodeAround(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + var type = override || node.type; + if (node.start > pos || node.end < pos) { return } + baseVisitor[type](node, st, c); + if (test(type, node)) { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } +} + +function skipThrough(node, st, c) { c(node, st); } +function ignore(_node, _st, _c) {} + +// Node walkers. + +var base = {}; + +base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var stmt = list[i]; + + c(stmt, st, "Statement"); + } +}; +base.Statement = skipThrough; +base.EmptyStatement = ignore; +base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = + function (node, st, c) { return c(node.expression, st, "Expression"); }; +base.IfStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Statement"); + if (node.alternate) { c(node.alternate, st, "Statement"); } +}; +base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; +base.BreakStatement = base.ContinueStatement = ignore; +base.WithStatement = function (node, st, c) { + c(node.object, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.SwitchStatement = function (node, st, c) { + c(node.discriminant, st, "Expression"); + for (var i = 0, list = node.cases; i < list.length; i += 1) { + var cs = list[i]; + + c(cs, st); + } +}; +base.SwitchCase = function (node, st, c) { + if (node.test) { c(node.test, st, "Expression"); } + for (var i = 0, list = node.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } +}; +base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { + if (node.argument) { c(node.argument, st, "Expression"); } +}; +base.ThrowStatement = base.SpreadElement = + function (node, st, c) { return c(node.argument, st, "Expression"); }; +base.TryStatement = function (node, st, c) { + c(node.block, st, "Statement"); + if (node.handler) { c(node.handler, st); } + if (node.finalizer) { c(node.finalizer, st, "Statement"); } +}; +base.CatchClause = function (node, st, c) { + if (node.param) { c(node.param, st, "Pattern"); } + c(node.body, st, "Statement"); +}; +base.WhileStatement = base.DoWhileStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.ForStatement = function (node, st, c) { + if (node.init) { c(node.init, st, "ForInit"); } + if (node.test) { c(node.test, st, "Expression"); } + if (node.update) { c(node.update, st, "Expression"); } + c(node.body, st, "Statement"); +}; +base.ForInStatement = base.ForOfStatement = function (node, st, c) { + c(node.left, st, "ForInit"); + c(node.right, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.ForInit = function (node, st, c) { + if (node.type === "VariableDeclaration") { c(node, st); } + else { c(node, st, "Expression"); } +}; +base.DebuggerStatement = ignore; + +base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; +base.VariableDeclaration = function (node, st, c) { + for (var i = 0, list = node.declarations; i < list.length; i += 1) + { + var decl = list[i]; + + c(decl, st); + } +}; +base.VariableDeclarator = function (node, st, c) { + c(node.id, st, "Pattern"); + if (node.init) { c(node.init, st, "Expression"); } +}; + +base.Function = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + c(param, st, "Pattern"); + } + c(node.body, st, node.expression ? "Expression" : "Statement"); +}; + +base.Pattern = function (node, st, c) { + if (node.type === "Identifier") + { c(node, st, "VariablePattern"); } + else if (node.type === "MemberExpression") + { c(node, st, "MemberPattern"); } + else + { c(node, st); } +}; +base.VariablePattern = ignore; +base.MemberPattern = skipThrough; +base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; +base.ArrayPattern = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Pattern"); } + } +}; +base.ObjectPattern = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + if (prop.type === "Property") { + if (prop.computed) { c(prop.key, st, "Expression"); } + c(prop.value, st, "Pattern"); + } else if (prop.type === "RestElement") { + c(prop.argument, st, "Pattern"); + } + } +}; + +base.Expression = skipThrough; +base.ThisExpression = base.Super = base.MetaProperty = ignore; +base.ArrayExpression = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Expression"); } + } +}; +base.ObjectExpression = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) + { + var prop = list[i]; + + c(prop, st); + } +}; +base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; +base.SequenceExpression = function (node, st, c) { + for (var i = 0, list = node.expressions; i < list.length; i += 1) + { + var expr = list[i]; + + c(expr, st, "Expression"); + } +}; +base.TemplateLiteral = function (node, st, c) { + for (var i = 0, list = node.quasis; i < list.length; i += 1) + { + var quasi = list[i]; + + c(quasi, st); + } + + for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) + { + var expr = list$1[i$1]; + + c(expr, st, "Expression"); + } +}; +base.TemplateElement = ignore; +base.UnaryExpression = base.UpdateExpression = function (node, st, c) { + c(node.argument, st, "Expression"); +}; +base.BinaryExpression = base.LogicalExpression = function (node, st, c) { + c(node.left, st, "Expression"); + c(node.right, st, "Expression"); +}; +base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { + c(node.left, st, "Pattern"); + c(node.right, st, "Expression"); +}; +base.ConditionalExpression = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Expression"); + c(node.alternate, st, "Expression"); +}; +base.NewExpression = base.CallExpression = function (node, st, c) { + c(node.callee, st, "Expression"); + if (node.arguments) + { for (var i = 0, list = node.arguments; i < list.length; i += 1) + { + var arg = list[i]; + + c(arg, st, "Expression"); + } } +}; +base.MemberExpression = function (node, st, c) { + c(node.object, st, "Expression"); + if (node.computed) { c(node.property, st, "Expression"); } +}; +base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { + if (node.declaration) + { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } + if (node.source) { c(node.source, st, "Expression"); } +}; +base.ExportAllDeclaration = function (node, st, c) { + if (node.exported) + { c(node.exported, st); } + c(node.source, st, "Expression"); +}; +base.ImportDeclaration = function (node, st, c) { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) + { + var spec = list[i]; + + c(spec, st); + } + c(node.source, st, "Expression"); +}; +base.ImportExpression = function (node, st, c) { + c(node.source, st, "Expression"); +}; +base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; + +base.TaggedTemplateExpression = function (node, st, c) { + c(node.tag, st, "Expression"); + c(node.quasi, st, "Expression"); +}; +base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; +base.Class = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + if (node.superClass) { c(node.superClass, st, "Expression"); } + c(node.body, st); +}; +base.ClassBody = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var elt = list[i]; + + c(elt, st); + } +}; +base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) { + if (node.computed) { c(node.key, st, "Expression"); } + if (node.value) { c(node.value, st, "Expression"); } +}; + +function hoistMocksPlugin(options = {}) { + const filter = options.filter || createFilter(options.include, options.exclude); + const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [ + "mock", + "unmock", + "doMock", + "doUnmock" + ], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"] } = options; + const methods = new Set([ + ...hoistableMockMethodNames, + ...hoistedMethodNames, + ...dynamicImportMockMethodNames + ]); + const regexpHoistable = new RegExp(`\\b(?:${utilsObjectNames.join("|")})\\s*\.\\s*(?:${Array.from(methods).join("|")})\\s*\\(`); + return { + name: "vitest:mocks", + enforce: "post", + transform(code, id) { + if (!filter(id)) { + return; + } + return hoistMocks(code, id, this.parse, { + regexpHoistable, + hoistableMockMethodNames, + hoistedMethodNames, + utilsObjectNames, + dynamicImportMockMethodNames, + ...options + }); + } + }; +} +const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API. +You may encounter this issue when importing the mocks API from another module other than 'vitest'. +To fix this issue you can either: +- import the mocks API directly from 'vitest' +- enable the 'globals' options`; +function API_NOT_FOUND_CHECK(names) { + return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`; +} +function isIdentifier(node) { + return node.type === "Identifier"; +} +function getNodeTail(code, node) { + let end = node.end; + if (code[node.end] === ";") { + end += 1; + } + if (code[node.end] === "\n") { + return end + 1; + } + if (code[node.end + 1] === "\n") { + end += 1; + } + return end; +} +const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/; +const hashbangRE = /^#!.*\n/; +// this is a fork of Vite SSR transform +function hoistMocks(code, id, parse, options = {}) { + var _hashbangRE$exec; + const needHoisting = (options.regexpHoistable || regexpHoistable).test(code); + if (!needHoisting) { + return; + } + const s = new MagicString(code); + let ast; + try { + ast = parse(code); + } catch (err) { + console.error(`Cannot parse ${id}:\n${err.message}.`); + return; + } + const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [ + "mock", + "unmock", + "doMock", + "doUnmock" + ], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options; + // hoist at the start of the file, after the hashbang + let hoistIndex = ((_hashbangRE$exec = hashbangRE.exec(code)) === null || _hashbangRE$exec === void 0 ? void 0 : _hashbangRE$exec[0].length) ?? 0; + let hoistedModuleImported = false; + let uid = 0; + const idToImportMap = new Map(); + const imports = []; + // this will transform import statements into dynamic ones, if there are imports + // it will keep the import as is, if we don't need to mock anything + // in browser environment it will wrap the module value with "vitest_wrap_module" function + // that returns a proxy to the module so that named exports can be mocked + function defineImport(importNode) { + const source = importNode.source.value; + // always hoist vitest import to top of the file, so + // "vi" helpers can access it + if (hoistedModule === source) { + hoistedModuleImported = true; + return; + } + const importId = `__vi_import_${uid++}__`; + imports.push({ + id: importId, + node: importNode + }); + return importId; + } + // 1. check all import statements and record id -> importName map + for (const node of ast.body) { + // import foo from 'foo' --> foo -> __import_foo__.default + // import { baz } from 'foo' --> baz -> __import_foo__.baz + // import * as ok from 'foo' --> ok -> __import_foo__ + if (node.type === "ImportDeclaration") { + const importId = defineImport(node); + if (!importId) { + continue; + } + for (const spec of node.specifiers) { + if (spec.type === "ImportSpecifier") { + if (spec.imported.type === "Identifier") { + idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`); + } else { + idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`); + } + } else if (spec.type === "ImportDefaultSpecifier") { + idToImportMap.set(spec.local.name, `${importId}.default`); + } else { + // namespace specifier + idToImportMap.set(spec.local.name, importId); + } + } + } + } + const declaredConst = new Set(); + const hoistedNodes = []; + function createSyntaxError(node, message) { + const _error = new SyntaxError(message); + Error.captureStackTrace(_error, createSyntaxError); + const serializedError = { + name: "SyntaxError", + message: _error.message, + stack: _error.stack + }; + if (options.codeFrameGenerator) { + serializedError.frame = options.codeFrameGenerator(node, id, code); + } + return serializedError; + } + function assertNotDefaultExport(node, error) { + var _findNodeAround; + const defaultExport = (_findNodeAround = findNodeAround(ast, node.start, "ExportDefaultDeclaration")) === null || _findNodeAround === void 0 ? void 0 : _findNodeAround.node; + if ((defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration) === node || (defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration.type) === "AwaitExpression" && defaultExport.declaration.argument === node) { + throw createSyntaxError(defaultExport, error); + } + } + function assertNotNamedExport(node, error) { + var _findNodeAround2; + const nodeExported = (_findNodeAround2 = findNodeAround(ast, node.start, "ExportNamedDeclaration")) === null || _findNodeAround2 === void 0 ? void 0 : _findNodeAround2.node; + if ((nodeExported === null || nodeExported === void 0 ? void 0 : nodeExported.declaration) === node) { + throw createSyntaxError(nodeExported, error); + } + } + function getVariableDeclaration(node) { + var _findNodeAround3, _declarationNode$decl; + const declarationNode = (_findNodeAround3 = findNodeAround(ast, node.start, "VariableDeclaration")) === null || _findNodeAround3 === void 0 ? void 0 : _findNodeAround3.node; + const init = declarationNode === null || declarationNode === void 0 || (_declarationNode$decl = declarationNode.declarations[0]) === null || _declarationNode$decl === void 0 ? void 0 : _declarationNode$decl.init; + if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) { + return declarationNode; + } + } + const usedUtilityExports = new Set(); + esmWalker(ast, { + onIdentifier(id, info, parentStack) { + const binding = idToImportMap.get(id.name); + if (!binding) { + return; + } + if (info.hasBindingShortcut) { + s.appendLeft(id.end, `: ${binding}`); + } else if (info.classDeclaration) { + if (!declaredConst.has(id.name)) { + declaredConst.add(id.name); + // locate the top-most node containing the class declaration + const topNode = parentStack[parentStack.length - 2]; + s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`); + } + } else if (!info.classExpression) { + s.update(id.start, id.end, binding); + } + }, + onCallExpression(node) { + if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) { + const methodName = node.callee.property.name; + usedUtilityExports.add(node.callee.object.name); + if (hoistableMockMethodNames.includes(methodName)) { + const method = `${node.callee.object.name}.${methodName}`; + assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`); + const declarationNode = getVariableDeclaration(node); + if (declarationNode) { + assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`); + } + // rewrite vi.mock(import('..')) into vi.mock('..') + if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) { + const moduleInfo = node.arguments[0]; + // vi.mock(import('./path')) -> vi.mock('./path') + if (moduleInfo.type === "ImportExpression") { + const source = moduleInfo.source; + s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end)); + } + // vi.mock(await import('./path')) -> vi.mock('./path') + if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") { + const source = moduleInfo.argument.source; + s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end)); + } + } + hoistedNodes.push(node); + } else if (dynamicImportMockMethodNames.includes(methodName)) { + const moduleInfo = node.arguments[0]; + let source = null; + if (moduleInfo.type === "ImportExpression") { + source = moduleInfo.source; + } + if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") { + source = moduleInfo.argument.source; + } + if (source) { + s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end)); + } + } + if (hoistedMethodNames.includes(methodName)) { + assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first."); + const declarationNode = getVariableDeclaration(node); + if (declarationNode) { + assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first."); + // hoist "const variable = vi.hoisted(() => {})" + hoistedNodes.push(declarationNode); + } else { + var _findNodeAround4; + const awaitedExpression = (_findNodeAround4 = findNodeAround(ast, node.start, "AwaitExpression")) === null || _findNodeAround4 === void 0 ? void 0 : _findNodeAround4.node; + // hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})" + const moveNode = (awaitedExpression === null || awaitedExpression === void 0 ? void 0 : awaitedExpression.argument) === node ? awaitedExpression : node; + hoistedNodes.push(moveNode); + } + } + } + } + }); + function getNodeName(node) { + const callee = node.callee || {}; + if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) { + return `${callee.object.name}.${callee.property.name}()`; + } + return "\"hoisted method\""; + } + function getNodeCall(node) { + if (node.type === "CallExpression") { + return node; + } + if (node.type === "VariableDeclaration") { + const { declarations } = node; + const init = declarations[0].init; + if (init) { + return getNodeCall(init); + } + } + if (node.type === "AwaitExpression") { + const { argument } = node; + if (argument.type === "CallExpression") { + return getNodeCall(argument); + } + } + return node; + } + function createError(outsideNode, insideNode) { + const outsideCall = getNodeCall(outsideNode); + const insideCall = getNodeCall(insideNode); + throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`); + } + // validate hoistedNodes doesn't have nodes inside other nodes + for (let i = 0; i < hoistedNodes.length; i++) { + const node = hoistedNodes[i]; + for (let j = i + 1; j < hoistedNodes.length; j++) { + const otherNode = hoistedNodes[j]; + if (node.start >= otherNode.start && node.end <= otherNode.end) { + throw createError(otherNode, node); + } + if (otherNode.start >= node.start && otherNode.end <= node.end) { + throw createError(node, otherNode); + } + } + } + // hoist vi.mock/vi.hoisted + for (const node of hoistedNodes) { + const end = getNodeTail(code, node); + // don't hoist into itself if it's already at the top + if (hoistIndex === end || hoistIndex === node.start) { + hoistIndex = end; + } else { + s.move(node.start, end, hoistIndex); + } + } + // hoist actual dynamic imports last so they are inserted after all hoisted mocks + for (const { node: importNode, id: importId } of imports) { + const source = importNode.source.value; + s.update(importNode.start, importNode.end, `const ${importId} = await import(${JSON.stringify(source)});\n`); + if (importNode.start === hoistIndex) { + // no need to hoist, but update hoistIndex to keep the order + hoistIndex = importNode.end; + } else { + // There will be an error if the module is called before it is imported, + // so the module import statement is hoisted to the top + s.move(importNode.start, importNode.end, hoistIndex); + } + } + if (!hoistedModuleImported && hoistedNodes.length) { + const utilityImports = [...usedUtilityExports]; + // "vi" or "vitest" is imported from a module other than "vitest" + if (utilityImports.some((name) => idToImportMap.has(name))) { + s.prepend(API_NOT_FOUND_CHECK(utilityImports)); + } else if (utilityImports.length) { + s.prepend(`import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`); + } + } + return { + code: s.toString(), + map: s.generateMap({ + hires: "boundary", + source: id + }) + }; +} + +function interceptorPlugin(options = {}) { + const registry = options.registry || new MockerRegistry(); + return { + name: "vitest:mocks:interceptor", + enforce: "pre", + load: { + order: "pre", + async handler(id) { + const mock = registry.getById(id); + if (!mock) { + return; + } + if (mock.type === "manual") { + const exports$1 = Object.keys(await mock.resolve()); + const accessor = options.globalThisAccessor || "\"__vitest_mocker__\""; + return createManualModuleSource(mock.url, exports$1, accessor); + } + if (mock.type === "redirect") { + return readFile(mock.redirect, "utf-8"); + } + } + }, + transform: { + order: "post", + handler(code, id) { + const mock = registry.getById(id); + if (!mock) { + return; + } + if (mock.type === "automock" || mock.type === "autospy") { + const m = automockModule(code, mock.type, this.parse, { globalThisAccessor: options.globalThisAccessor }); + return { + code: m.toString(), + map: m.generateMap({ + hires: "boundary", + source: cleanUrl(id) + }) + }; + } + } + }, + configureServer(server) { + server.ws.on("vitest:interceptor:register", (event) => { + if (event.type === "manual") { + const module = ManualMockedModule.fromJSON(event, async () => { + const keys = await getFactoryExports(event.url); + return Object.fromEntries(keys.map((key) => [key, null])); + }); + registry.add(module); + } else { + if (event.type === "redirect") { + const redirectUrl = new URL(event.redirect); + event.redirect = join(server.config.root, redirectUrl.pathname); + } + registry.register(event); + } + server.ws.send("vitest:interceptor:register:result"); + }); + server.ws.on("vitest:interceptor:delete", (id) => { + registry.delete(id); + server.ws.send("vitest:interceptor:delete:result"); + }); + server.ws.on("vitest:interceptor:invalidate", () => { + registry.clear(); + server.ws.send("vitest:interceptor:invalidate:result"); + }); + function getFactoryExports(url) { + server.ws.send("vitest:interceptor:resolve", url); + let timeout; + return new Promise((resolve, reject) => { + timeout = setTimeout(() => { + reject(new Error(`Timeout while waiting for factory exports of ${url}`)); + }, 1e4); + server.ws.on("vitest:interceptor:resolved", ({ url: resolvedUrl, keys }) => { + if (resolvedUrl === url) { + clearTimeout(timeout); + resolve(keys); + } + }); + }); + } + } + }; +} + +const VALID_ID_PREFIX = "/@id/"; +class ServerMockResolver { + constructor(server, options = {}) { + this.server = server; + this.options = options; + } + async resolveMock(rawId, importer, options) { + const { id, fsPath, external } = await this.resolveMockId(rawId, importer); + const resolvedUrl = this.normalizeResolveIdToUrl({ id }).url; + if (options.mock === "factory") { + var _manifest$fsPath; + const manifest = getViteDepsManifest(this.server.config); + const needsInterop = (manifest === null || manifest === void 0 || (_manifest$fsPath = manifest[fsPath]) === null || _manifest$fsPath === void 0 ? void 0 : _manifest$fsPath.needsInterop) ?? false; + return { + mockType: "manual", + resolvedId: id, + resolvedUrl, + needsInterop + }; + } + if (options.mock === "spy") { + return { + mockType: "autospy", + resolvedId: id, + resolvedUrl + }; + } + const redirectUrl = findMockRedirect(this.server.config.root, fsPath, external); + return { + mockType: redirectUrl === null ? "automock" : "redirect", + redirectUrl, + resolvedId: id, + resolvedUrl + }; + } + invalidate(ids) { + ids.forEach((id) => { + const moduleGraph = this.server.moduleGraph; + const module = moduleGraph.getModuleById(id); + if (module) { + module.transformResult = null; + } + }); + } + async resolveId(id, importer) { + const resolved = await this.server.pluginContainer.resolveId(id, importer, { ssr: false }); + if (!resolved) { + return null; + } + return this.normalizeResolveIdToUrl(resolved); + } + normalizeResolveIdToUrl(resolved) { + const isOptimized = resolved.id.startsWith(withTrailingSlash(this.server.config.cacheDir)); + let url; + // normalise the URL to be acceptable by the browser + // https://github.com/vitejs/vite/blob/14027b0f2a9b01c14815c38aab22baf5b29594bb/packages/vite/src/node/plugins/importAnalysis.ts#L103 + const root = this.server.config.root; + if (resolved.id.startsWith(withTrailingSlash(root))) { + url = resolved.id.slice(root.length); + } else if (resolved.id !== "/@react-refresh" && isAbsolute(resolved.id) && existsSync(cleanUrl(resolved.id))) { + url = join$1("/@fs/", resolved.id); + } else { + url = resolved.id; + } + if (url[0] !== "." && url[0] !== "/") { + url = resolved.id.startsWith(VALID_ID_PREFIX) ? resolved.id : VALID_ID_PREFIX + resolved.id.replace("\0", "__x00__"); + } + return { + id: resolved.id, + url, + optimized: isOptimized + }; + } + async resolveMockId(rawId, importer) { + if (!this.server.moduleGraph.getModuleById(importer) && !importer.startsWith(this.server.config.root)) { + importer = join$1(this.server.config.root, importer); + } + const resolved = await this.server.pluginContainer.resolveId(rawId, importer, { ssr: false }); + return this.resolveModule(rawId, resolved); + } + resolveModule(rawId, resolved) { + const id = (resolved === null || resolved === void 0 ? void 0 : resolved.id) || rawId; + const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null; + return { + id, + fsPath: cleanUrl(id), + external + }; + } +} +function isModuleDirectory(config, path) { + const moduleDirectories = config.moduleDirectories || ["/node_modules/"]; + return moduleDirectories.some((dir) => path.includes(dir)); +} +const metadata = new WeakMap(); +function getViteDepsManifest(config) { + if (metadata.has(config)) { + return metadata.get(config); + } + const cacheDirPath = getDepsCacheDir(config); + const metadataPath = resolve(cacheDirPath, "_metadata.json"); + if (!existsSync(metadataPath)) { + return null; + } + const { optimized } = JSON.parse(readFileSync(metadataPath, "utf-8")); + const newManifest = {}; + for (const name in optimized) { + const dep = optimized[name]; + const file = resolve(cacheDirPath, dep.file); + newManifest[file] = { + hash: dep.fileHash, + needsInterop: dep.needsInterop + }; + } + metadata.set(config, newManifest); + return newManifest; +} +function getDepsCacheDir(config) { + return resolve(config.cacheDir, "deps"); +} +function withTrailingSlash(path) { + if (path.at(-1) !== "/") { + return `${path}/`; + } + return path; +} + +// this is an implementation for public usage +// vitest doesn't use this plugin directly +function mockerPlugin(options = {}) { + let server; + const registerPath = resolve(fileURLToPath(new URL("./register.js", import.meta.url))); + return [ + { + name: "vitest:mocker:ws-rpc", + config(_, { command }) { + if (command !== "serve") { + return; + } + return { + server: { preTransformRequests: false }, + optimizeDeps: { exclude: ["@vitest/mocker/register", "@vitest/mocker/browser"] } + }; + }, + configureServer(server_) { + server = server_; + const mockResolver = new ServerMockResolver(server); + server.ws.on("vitest:mocks:resolveId", async ({ id, importer }) => { + const resolved = await mockResolver.resolveId(id, importer); + server.ws.send("vitest:mocks:resolvedId:result", resolved); + }); + server.ws.on("vitest:mocks:resolveMock", async ({ id, importer, options }) => { + const resolved = await mockResolver.resolveMock(id, importer, options); + server.ws.send("vitest:mocks:resolveMock:result", resolved); + }); + server.ws.on("vitest:mocks:invalidate", async ({ ids }) => { + mockResolver.invalidate(ids); + server.ws.send("vitest:mocks:invalidate:result"); + }); + }, + async load(id) { + if (id !== registerPath) { + return; + } + if (!server) { + // mocker doesn't work during build + return "export {}"; + } + const content = await readFile(registerPath, "utf-8"); + const result = content.replace(/__VITEST_GLOBAL_THIS_ACCESSOR__/g, options.globalThisAccessor ?? "\"__vitest_mocker__\"").replace("__VITEST_MOCKER_ROOT__", JSON.stringify(server.config.root)); + return result; + } + }, + hoistMocksPlugin(options.hoistMocks), + interceptorPlugin(options), + automockPlugin(options), + dynamicImportPlugin(options) + ]; +} + +export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/redirect.d.ts b/vanilla/node_modules/@vitest/mocker/dist/redirect.d.ts new file mode 100644 index 0000000..1f8256b --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/redirect.d.ts @@ -0,0 +1,3 @@ +declare function findMockRedirect(root: string, mockPath: string, external: string | null): string | null; + +export { findMockRedirect }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/redirect.js b/vanilla/node_modules/@vitest/mocker/dist/redirect.js new file mode 100644 index 0000000..0071819 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/redirect.js @@ -0,0 +1,79 @@ +import fs from 'node:fs'; +import nodeModule from 'node:module'; +import { d as dirname, j as join, b as basename, r as resolve, e as extname } from './chunk-pathe.M-eThtNZ.js'; + +const { existsSync, readdirSync, statSync } = fs; +function findMockRedirect(root, mockPath, external) { + const path = external || mockPath; + // it's a node_module alias + // all mocks should be inside /__mocks__ + if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) { + const mockDirname = dirname(path); + const mockFolder = join(root, "__mocks__", mockDirname); + if (!existsSync(mockFolder)) { + return null; + } + const baseOriginal = basename(path); + function findFile(mockFolder, baseOriginal) { + const files = readdirSync(mockFolder); + for (const file of files) { + const baseFile = basename(file, extname(file)); + if (baseFile === baseOriginal) { + const path = resolve(mockFolder, file); + // if the same name, return the file + if (statSync(path).isFile()) { + return path; + } else { + // find folder/index.{js,ts} + const indexFile = findFile(path, "index"); + if (indexFile) { + return indexFile; + } + } + } + } + return null; + } + return findFile(mockFolder, baseOriginal); + } + const dir = dirname(path); + const baseId = basename(path); + const fullPath = resolve(dir, "__mocks__", baseId); + return existsSync(fullPath) ? fullPath : null; +} +const builtins = new Set([ + ...nodeModule.builtinModules, + "assert/strict", + "diagnostics_channel", + "dns/promises", + "fs/promises", + "path/posix", + "path/win32", + "readline/promises", + "stream/consumers", + "stream/promises", + "stream/web", + "timers/promises", + "util/types", + "wasi" +]); +// https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix +const prefixedBuiltins = new Set([ + "node:sea", + "node:sqlite", + "node:test", + "node:test/reporters" +]); +const NODE_BUILTIN_NAMESPACE = "node:"; +function isNodeBuiltin(id) { + // Added in v18.6.0 + if (nodeModule.isBuiltin) { + return nodeModule.isBuiltin(id); + } + if (prefixedBuiltins.has(id)) { + return true; + } + return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(NODE_BUILTIN_NAMESPACE.length) : id); +} + +export { findMockRedirect }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/register.d.ts b/vanilla/node_modules/@vitest/mocker/dist/register.d.ts new file mode 100644 index 0000000..73e6207 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/register.d.ts @@ -0,0 +1,9 @@ +import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-TnKRhz7N.js'; +import '@vitest/spy'; +import './types.d-B8CCKmHt.js'; +import './index.d-C-sLYZi-.js'; + +declare function registerModuleMocker(interceptor: (accessor: string) => ModuleMockerInterceptor): ModuleMockerCompilerHints; +declare function registerNativeFactoryResolver(mocker: ModuleMocker): void; + +export { registerModuleMocker, registerNativeFactoryResolver }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/register.js b/vanilla/node_modules/@vitest/mocker/dist/register.js new file mode 100644 index 0000000..841b687 --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/register.js @@ -0,0 +1,41 @@ +import { createMockInstance } from '@vitest/spy'; +import { M as ModuleMocker, r as rpc, c as createCompilerHints, h as hot } from './chunk-mocker.js'; +import './index.js'; +import './chunk-registry.js'; +import './chunk-pathe.M-eThtNZ.js'; + +function registerModuleMocker(interceptor) { + const mocker = new ModuleMocker(interceptor(__VITEST_GLOBAL_THIS_ACCESSOR__), { + resolveId(id, importer) { + return rpc("vitest:mocks:resolveId", { + id, + importer + }); + }, + resolveMock(id, importer, options) { + return rpc("vitest:mocks:resolveMock", { + id, + importer, + options + }); + }, + async invalidate(ids) { + return rpc("vitest:mocks:invalidate", { ids }); + } + }, createMockInstance, { root: __VITEST_MOCKER_ROOT__ }); + globalThis[__VITEST_GLOBAL_THIS_ACCESSOR__] = mocker; + registerNativeFactoryResolver(mocker); + return createCompilerHints({ globalThisKey: __VITEST_GLOBAL_THIS_ACCESSOR__ }); +} +function registerNativeFactoryResolver(mocker) { + hot.on("vitest:interceptor:resolve", async (url) => { + const exports$1 = await mocker.resolveFactoryModule(url); + const keys = Object.keys(exports$1); + hot.send("vitest:interceptor:resolved", { + url, + keys + }); + }); +} + +export { registerModuleMocker, registerNativeFactoryResolver }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts b/vanilla/node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts new file mode 100644 index 0000000..a99816f --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts @@ -0,0 +1,107 @@ +declare class MockerRegistry { + private readonly registryByUrl; + private readonly registryById; + clear(): void; + keys(): IterableIterator; + add(mock: MockedModule): void; + register(json: MockedModuleSerialized): MockedModule; + register(type: "redirect", raw: string, id: string, url: string, redirect: string): RedirectedModule; + register(type: "manual", raw: string, id: string, url: string, factory: () => any): ManualMockedModule; + register(type: "automock", raw: string, id: string, url: string): AutomockedModule; + register(type: "autospy", id: string, raw: string, url: string): AutospiedModule; + delete(id: string): void; + deleteById(id: string): void; + get(id: string): MockedModule | undefined; + getById(id: string): MockedModule | undefined; + has(id: string): boolean; +} +type MockedModule = AutomockedModule | AutospiedModule | ManualMockedModule | RedirectedModule; +type MockedModuleType = "automock" | "autospy" | "manual" | "redirect"; +type MockedModuleSerialized = AutomockedModuleSerialized | AutospiedModuleSerialized | ManualMockedModuleSerialized | RedirectedModuleSerialized; +declare class AutomockedModule { + raw: string; + id: string; + url: string; + readonly type = "automock"; + constructor(raw: string, id: string, url: string); + static fromJSON(data: AutomockedModuleSerialized): AutospiedModule; + toJSON(): AutomockedModuleSerialized; +} +interface AutomockedModuleSerialized { + type: "automock"; + url: string; + raw: string; + id: string; +} +declare class AutospiedModule { + raw: string; + id: string; + url: string; + readonly type = "autospy"; + constructor(raw: string, id: string, url: string); + static fromJSON(data: AutospiedModuleSerialized): AutospiedModule; + toJSON(): AutospiedModuleSerialized; +} +interface AutospiedModuleSerialized { + type: "autospy"; + url: string; + raw: string; + id: string; +} +declare class RedirectedModule { + raw: string; + id: string; + url: string; + redirect: string; + readonly type = "redirect"; + constructor(raw: string, id: string, url: string, redirect: string); + static fromJSON(data: RedirectedModuleSerialized): RedirectedModule; + toJSON(): RedirectedModuleSerialized; +} +interface RedirectedModuleSerialized { + type: "redirect"; + url: string; + id: string; + raw: string; + redirect: string; +} +declare class ManualMockedModule { + raw: string; + id: string; + url: string; + factory: () => any; + cache: Record | undefined; + readonly type = "manual"; + constructor(raw: string, id: string, url: string, factory: () => any); + resolve(): Promise>; + static fromJSON(data: ManualMockedModuleSerialized, factory: () => any): ManualMockedModule; + toJSON(): ManualMockedModuleSerialized; +} +interface ManualMockedModuleSerialized { + type: "manual"; + url: string; + id: string; + raw: string; +} + +type Awaitable = T | PromiseLike; +type ModuleMockFactoryWithHelper = (importOriginal: () => Promise) => Awaitable>; +type ModuleMockFactory = () => any; +interface ModuleMockOptions { + spy?: boolean; +} +interface ServerMockResolution { + mockType: "manual" | "redirect" | "automock" | "autospy"; + resolvedId: string; + resolvedUrl: string; + needsInterop?: boolean; + redirectUrl?: string | null; +} +interface ServerIdResolution { + id: string; + url: string; + optimized: boolean; +} + +export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, AutospiedModule as f, ManualMockedModule as g }; +export type { ServerMockResolution as S, MockedModule as a, ModuleMockOptions as b, ModuleMockFactoryWithHelper as c, MockedModuleType as d, ServerIdResolution as e, AutomockedModuleSerialized as h, AutospiedModuleSerialized as i, ManualMockedModuleSerialized as j, MockedModuleSerialized as k, RedirectedModuleSerialized as l, ModuleMockFactory as m }; diff --git a/vanilla/node_modules/@vitest/mocker/package.json b/vanilla/node_modules/@vitest/mocker/package.json new file mode 100644 index 0000000..1bd814c --- /dev/null +++ b/vanilla/node_modules/@vitest/mocker/package.json @@ -0,0 +1,86 @@ +{ + "name": "@vitest/mocker", + "type": "module", + "version": "4.0.18", + "description": "Vitest module mocker implementation", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/mocker" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./node": { + "types": "./dist/node.d.ts", + "default": "./dist/node.js" + }, + "./browser": { + "types": "./dist/browser.d.ts", + "default": "./dist/browser.js" + }, + "./redirect": { + "types": "./dist/redirect.d.ts", + "default": "./dist/redirect.js" + }, + "./automock": { + "types": "./dist/automock.d.ts", + "default": "./dist/automock.js" + }, + "./register": { + "types": "./dist/register.d.ts", + "default": "./dist/register.js" + }, + "./auto-register": { + "types": "./dist/register.d.ts", + "default": "./dist/register.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + }, + "dependencies": { + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21", + "@vitest/spy": "4.0.18" + }, + "devDependencies": { + "@types/estree": "^1.0.8", + "acorn-walk": "^8.3.4", + "msw": "^2.12.3", + "pathe": "^2.0.3", + "vite": "^6.3.5", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/@vitest/pretty-format/LICENSE b/vanilla/node_modules/@vitest/pretty-format/LICENSE new file mode 100644 index 0000000..0e5771d --- /dev/null +++ b/vanilla/node_modules/@vitest/pretty-format/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vanilla/node_modules/@vitest/pretty-format/dist/index.d.ts b/vanilla/node_modules/@vitest/pretty-format/dist/index.d.ts new file mode 100644 index 0000000..a229bcf --- /dev/null +++ b/vanilla/node_modules/@vitest/pretty-format/dist/index.d.ts @@ -0,0 +1,124 @@ +/** +* 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. +*/ +interface Colors { + comment: { + close: string; + open: string; + }; + content: { + close: string; + open: string; + }; + prop: { + close: string; + open: string; + }; + tag: { + close: string; + open: string; + }; + value: { + close: string; + open: string; + }; +} +type Indent = (arg0: string) => string; +type Refs = Array; +type Print = (arg0: unknown) => string; +type Theme = Required<{ + comment?: string; + content?: string; + prop?: string; + tag?: string; + value?: string; +}>; +/** +* compare function used when sorting object keys, `null` can be used to skip over sorting. +*/ +type CompareKeys = ((a: string, b: string) => number) | null | undefined; +type RequiredOptions = Required; +interface Options extends Omit { + compareKeys: CompareKeys; + theme: Theme; +} +interface PrettyFormatOptions { + callToJSON?: boolean; + escapeRegex?: boolean; + escapeString?: boolean; + highlight?: boolean; + indent?: number; + maxDepth?: number; + maxWidth?: number; + min?: boolean; + printBasicPrototype?: boolean; + printFunctionName?: boolean; + printShadowRoot?: boolean; + compareKeys?: CompareKeys; + plugins?: Plugins; +} +type OptionsReceived = PrettyFormatOptions; +interface Config { + callToJSON: boolean; + compareKeys: CompareKeys; + colors: Colors; + escapeRegex: boolean; + escapeString: boolean; + indent: string; + maxDepth: number; + maxWidth: number; + min: boolean; + plugins: Plugins; + printBasicPrototype: boolean; + printFunctionName: boolean; + printShadowRoot: boolean; + spacingInner: string; + spacingOuter: string; +} +type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string; +type Test = (arg0: any) => boolean; +interface NewPlugin { + serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string; + test: Test; +} +interface PluginOptions { + edgeSpacing: string; + min: boolean; + spacing: string; +} +interface OldPlugin { + print: (val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string; + test: Test; +} +type Plugin = NewPlugin | OldPlugin; +type Plugins = Array; + +/** +* 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. +*/ + +declare const DEFAULT_OPTIONS: Options; +/** +* Returns a presentation string of your `val` object +* @param val any potential JavaScript object +* @param options Custom settings +*/ +declare function format(val: unknown, options?: OptionsReceived): string; +declare const plugins: { + AsymmetricMatcher: NewPlugin; + DOMCollection: NewPlugin; + DOMElement: NewPlugin; + Immutable: NewPlugin; + ReactElement: NewPlugin; + ReactTestComponent: NewPlugin; + Error: NewPlugin; +}; + +export { DEFAULT_OPTIONS, format, plugins }; +export type { Colors, CompareKeys, Config, NewPlugin, OldPlugin, Options, OptionsReceived, Plugin, Plugins, PrettyFormatOptions, Printer, Refs, Theme }; diff --git a/vanilla/node_modules/@vitest/pretty-format/dist/index.js b/vanilla/node_modules/@vitest/pretty-format/dist/index.js new file mode 100644 index 0000000..f134477 --- /dev/null +++ b/vanilla/node_modules/@vitest/pretty-format/dist/index.js @@ -0,0 +1,1022 @@ +import styles from 'tinyrainbow'; + +function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); +} + +function getKeysOfEnumerableProperties(object, compareKeys) { + const rawKeys = Object.keys(object); + const keys = compareKeys === null ? rawKeys : rawKeys.sort(compareKeys); + if (Object.getOwnPropertySymbols) { + for (const symbol of Object.getOwnPropertySymbols(object)) { + if (Object.getOwnPropertyDescriptor(object, symbol).enumerable) { + keys.push(symbol); + } + } + } + return keys; +} +/** +* Return entries (for example, of a map) +* with spacing, indentation, and comma +* without surrounding punctuation (for example, braces) +*/ +function printIteratorEntries(iterator, config, indentation, depth, refs, printer, separator = ": ") { + let result = ""; + let width = 0; + let current = iterator.next(); + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + while (!current.done) { + result += indentationNext; + if (width++ === config.maxWidth) { + result += "…"; + break; + } + const name = printer(current.value[0], config, indentationNext, depth, refs); + const value = printer(current.value[1], config, indentationNext, depth, refs); + result += name + separator + value; + current = iterator.next(); + if (!current.done) { + result += `,${config.spacingInner}`; + } else if (!config.min) { + result += ","; + } + } + result += config.spacingOuter + indentation; + } + return result; +} +/** +* Return values (for example, of a set) +* with spacing, indentation, and comma +* without surrounding punctuation (braces or brackets) +*/ +function printIteratorValues(iterator, config, indentation, depth, refs, printer) { + let result = ""; + let width = 0; + let current = iterator.next(); + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + while (!current.done) { + result += indentationNext; + if (width++ === config.maxWidth) { + result += "…"; + break; + } + result += printer(current.value, config, indentationNext, depth, refs); + current = iterator.next(); + if (!current.done) { + result += `,${config.spacingInner}`; + } else if (!config.min) { + result += ","; + } + } + result += config.spacingOuter + indentation; + } + return result; +} +/** +* Return items (for example, of an array) +* with spacing, indentation, and comma +* without surrounding punctuation (for example, brackets) +*/ +function printListItems(list, config, indentation, depth, refs, printer) { + let result = ""; + list = list instanceof ArrayBuffer ? new DataView(list) : list; + const isDataView = (l) => l instanceof DataView; + const length = isDataView(list) ? list.byteLength : list.length; + if (length > 0) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + for (let i = 0; i < length; i++) { + result += indentationNext; + if (i === config.maxWidth) { + result += "…"; + break; + } + if (isDataView(list) || i in list) { + result += printer(isDataView(list) ? list.getInt8(i) : list[i], config, indentationNext, depth, refs); + } + if (i < length - 1) { + result += `,${config.spacingInner}`; + } else if (!config.min) { + result += ","; + } + } + result += config.spacingOuter + indentation; + } + return result; +} +/** +* Return properties of an object +* with spacing, indentation, and comma +* without surrounding punctuation (for example, braces) +*/ +function printObjectProperties(val, config, indentation, depth, refs, printer) { + let result = ""; + const keys = getKeysOfEnumerableProperties(val, config.compareKeys); + if (keys.length > 0) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const name = printer(key, config, indentationNext, depth, refs); + const value = printer(val[key], config, indentationNext, depth, refs); + result += `${indentationNext + name}: ${value}`; + if (i < keys.length - 1) { + result += `,${config.spacingInner}`; + } else if (!config.min) { + result += ","; + } + } + result += config.spacingOuter + indentation; + } + return result; +} + +const asymmetricMatcher = typeof Symbol === "function" && Symbol.for ? Symbol.for("jest.asymmetricMatcher") : 1267621; +const SPACE$2 = " "; +const serialize$5 = (val, config, indentation, depth, refs, printer) => { + const stringedValue = val.toString(); + if (stringedValue === "ArrayContaining" || stringedValue === "ArrayNotContaining") { + if (++depth > config.maxDepth) { + return `[${stringedValue}]`; + } + return `${stringedValue + SPACE$2}[${printListItems(val.sample, config, indentation, depth, refs, printer)}]`; + } + if (stringedValue === "ObjectContaining" || stringedValue === "ObjectNotContaining") { + if (++depth > config.maxDepth) { + return `[${stringedValue}]`; + } + return `${stringedValue + SPACE$2}{${printObjectProperties(val.sample, config, indentation, depth, refs, printer)}}`; + } + if (stringedValue === "StringMatching" || stringedValue === "StringNotMatching") { + return stringedValue + SPACE$2 + printer(val.sample, config, indentation, depth, refs); + } + if (stringedValue === "StringContaining" || stringedValue === "StringNotContaining") { + return stringedValue + SPACE$2 + printer(val.sample, config, indentation, depth, refs); + } + if (typeof val.toAsymmetricMatcher !== "function") { + throw new TypeError(`Asymmetric matcher ${val.constructor.name} does not implement toAsymmetricMatcher()`); + } + return val.toAsymmetricMatcher(); +}; +const test$5 = (val) => val && val.$$typeof === asymmetricMatcher; +const plugin$5 = { + serialize: serialize$5, + test: test$5 +}; + +const SPACE$1 = " "; +const OBJECT_NAMES = new Set(["DOMStringMap", "NamedNodeMap"]); +const ARRAY_REGEXP = /^(?:HTML\w*Collection|NodeList)$/; +function testName(name) { + return OBJECT_NAMES.has(name) || ARRAY_REGEXP.test(name); +} +const test$4 = (val) => val && val.constructor && !!val.constructor.name && testName(val.constructor.name); +function isNamedNodeMap(collection) { + return collection.constructor.name === "NamedNodeMap"; +} +const serialize$4 = (collection, config, indentation, depth, refs, printer) => { + const name = collection.constructor.name; + if (++depth > config.maxDepth) { + return `[${name}]`; + } + return (config.min ? "" : name + SPACE$1) + (OBJECT_NAMES.has(name) ? `{${printObjectProperties(isNamedNodeMap(collection) ? [...collection].reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}) : { ...collection }, config, indentation, depth, refs, printer)}}` : `[${printListItems([...collection], config, indentation, depth, refs, printer)}]`); +}; +const plugin$4 = { + serialize: serialize$4, + test: test$4 +}; + +/** +* 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. +*/ +function escapeHTML(str) { + return str.replaceAll("<", "<").replaceAll(">", ">"); +} + +// Return empty string if keys is empty. +function printProps(keys, props, config, indentation, depth, refs, printer) { + const indentationNext = indentation + config.indent; + const colors = config.colors; + return keys.map((key) => { + const value = props[key]; + // hidden injected value that should not be printed + if (typeof value === "string" && value[0] === "_" && value.startsWith("__vitest_") && value.match(/__vitest_\d+__/)) { + return ""; + } + let printed = printer(value, config, indentationNext, depth, refs); + if (typeof value !== "string") { + if (printed.includes("\n")) { + printed = config.spacingOuter + indentationNext + printed + config.spacingOuter + indentation; + } + printed = `{${printed}}`; + } + return `${config.spacingInner + indentation + colors.prop.open + key + colors.prop.close}=${colors.value.open}${printed}${colors.value.close}`; + }).join(""); +} +// Return empty string if children is empty. +function printChildren(children, config, indentation, depth, refs, printer) { + return children.map((child) => config.spacingOuter + indentation + (typeof child === "string" ? printText(child, config) : printer(child, config, indentation, depth, refs))).join(""); +} +function printShadowRoot(children, config, indentation, depth, refs, printer) { + if (config.printShadowRoot === false) { + return ""; + } + return [`${config.spacingOuter + indentation}#shadow-root`, printChildren(children, config, indentation + config.indent, depth, refs, printer)].join(""); +} +function printText(text, config) { + const contentColor = config.colors.content; + return contentColor.open + escapeHTML(text) + contentColor.close; +} +function printComment(comment, config) { + const commentColor = config.colors.comment; + return `${commentColor.open}${commentColor.close}`; +} +// Separate the functions to format props, children, and element, +// so a plugin could override a particular function, if needed. +// Too bad, so sad: the traditional (but unnecessary) space +// in a self-closing tagColor requires a second test of printedProps. +function printElement(type, printedProps, printedChildren, config, indentation) { + const tagColor = config.colors.tag; + return `${tagColor.open}<${type}${printedProps && tagColor.close + printedProps + config.spacingOuter + indentation + tagColor.open}${printedChildren ? `>${tagColor.close}${printedChildren}${config.spacingOuter}${indentation}${tagColor.open}${tagColor.close}`; +} +function printElementAsLeaf(type, config) { + const tagColor = config.colors.tag; + return `${tagColor.open}<${type}${tagColor.close} …${tagColor.open} />${tagColor.close}`; +} + +const ELEMENT_NODE = 1; +const TEXT_NODE = 3; +const COMMENT_NODE = 8; +const FRAGMENT_NODE = 11; +const ELEMENT_REGEXP = /^(?:(?:HTML|SVG)\w*)?Element$/; +function testHasAttribute(val) { + try { + return typeof val.hasAttribute === "function" && val.hasAttribute("is"); + } catch { + return false; + } +} +function testNode(val) { + const constructorName = val.constructor.name; + const { nodeType, tagName } = val; + const isCustomElement = typeof tagName === "string" && tagName.includes("-") || testHasAttribute(val); + return nodeType === ELEMENT_NODE && (ELEMENT_REGEXP.test(constructorName) || isCustomElement) || nodeType === TEXT_NODE && constructorName === "Text" || nodeType === COMMENT_NODE && constructorName === "Comment" || nodeType === FRAGMENT_NODE && constructorName === "DocumentFragment"; +} +const test$3 = (val) => val?.constructor?.name && testNode(val); +function nodeIsText(node) { + return node.nodeType === TEXT_NODE; +} +function nodeIsComment(node) { + return node.nodeType === COMMENT_NODE; +} +function nodeIsFragment(node) { + return node.nodeType === FRAGMENT_NODE; +} +const serialize$3 = (node, config, indentation, depth, refs, printer) => { + if (nodeIsText(node)) { + return printText(node.data, config); + } + if (nodeIsComment(node)) { + return printComment(node.data, config); + } + const type = nodeIsFragment(node) ? "DocumentFragment" : node.tagName.toLowerCase(); + if (++depth > config.maxDepth) { + return printElementAsLeaf(type, config); + } + return printElement(type, printProps(nodeIsFragment(node) ? [] : Array.from(node.attributes, (attr) => attr.name).sort(), nodeIsFragment(node) ? {} : [...node.attributes].reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}), config, indentation + config.indent, depth, refs, printer), (nodeIsFragment(node) || !node.shadowRoot ? "" : printShadowRoot(Array.prototype.slice.call(node.shadowRoot.children), config, indentation + config.indent, depth, refs, printer)) + printChildren(Array.prototype.slice.call(node.childNodes || node.children), config, indentation + config.indent, depth, refs, printer), config, indentation); +}; +const plugin$3 = { + serialize: serialize$3, + test: test$3 +}; + +// SENTINEL constants are from https://github.com/facebook/immutable-js +const IS_ITERABLE_SENTINEL = "@@__IMMUTABLE_ITERABLE__@@"; +const IS_LIST_SENTINEL = "@@__IMMUTABLE_LIST__@@"; +const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@"; +const IS_MAP_SENTINEL = "@@__IMMUTABLE_MAP__@@"; +const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@"; +const IS_RECORD_SENTINEL = "@@__IMMUTABLE_RECORD__@@"; +const IS_SEQ_SENTINEL = "@@__IMMUTABLE_SEQ__@@"; +const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@"; +const IS_STACK_SENTINEL = "@@__IMMUTABLE_STACK__@@"; +const getImmutableName = (name) => `Immutable.${name}`; +const printAsLeaf = (name) => `[${name}]`; +const SPACE = " "; +const LAZY = "…"; +function printImmutableEntries(val, config, indentation, depth, refs, printer, type) { + return ++depth > config.maxDepth ? printAsLeaf(getImmutableName(type)) : `${getImmutableName(type) + SPACE}{${printIteratorEntries(val.entries(), config, indentation, depth, refs, printer)}}`; +} +// Record has an entries method because it is a collection in immutable v3. +// Return an iterator for Immutable Record from version v3 or v4. +function getRecordEntries(val) { + let i = 0; + return { next() { + if (i < val._keys.length) { + const key = val._keys[i++]; + return { + done: false, + value: [key, val.get(key)] + }; + } + return { + done: true, + value: undefined + }; + } }; +} +function printImmutableRecord(val, config, indentation, depth, refs, printer) { + // _name property is defined only for an Immutable Record instance + // which was constructed with a second optional descriptive name arg + const name = getImmutableName(val._name || "Record"); + return ++depth > config.maxDepth ? printAsLeaf(name) : `${name + SPACE}{${printIteratorEntries(getRecordEntries(val), config, indentation, depth, refs, printer)}}`; +} +function printImmutableSeq(val, config, indentation, depth, refs, printer) { + const name = getImmutableName("Seq"); + if (++depth > config.maxDepth) { + return printAsLeaf(name); + } + if (val[IS_KEYED_SENTINEL]) { + return `${name + SPACE}{${val._iter || val._object ? printIteratorEntries(val.entries(), config, indentation, depth, refs, printer) : LAZY}}`; + } + return `${name + SPACE}[${val._iter || val._array || val._collection || val._iterable ? printIteratorValues(val.values(), config, indentation, depth, refs, printer) : LAZY}]`; +} +function printImmutableValues(val, config, indentation, depth, refs, printer, type) { + return ++depth > config.maxDepth ? printAsLeaf(getImmutableName(type)) : `${getImmutableName(type) + SPACE}[${printIteratorValues(val.values(), config, indentation, depth, refs, printer)}]`; +} +const serialize$2 = (val, config, indentation, depth, refs, printer) => { + if (val[IS_MAP_SENTINEL]) { + return printImmutableEntries(val, config, indentation, depth, refs, printer, val[IS_ORDERED_SENTINEL] ? "OrderedMap" : "Map"); + } + if (val[IS_LIST_SENTINEL]) { + return printImmutableValues(val, config, indentation, depth, refs, printer, "List"); + } + if (val[IS_SET_SENTINEL]) { + return printImmutableValues(val, config, indentation, depth, refs, printer, val[IS_ORDERED_SENTINEL] ? "OrderedSet" : "Set"); + } + if (val[IS_STACK_SENTINEL]) { + return printImmutableValues(val, config, indentation, depth, refs, printer, "Stack"); + } + if (val[IS_SEQ_SENTINEL]) { + return printImmutableSeq(val, config, indentation, depth, refs, printer); + } + // For compatibility with immutable v3 and v4, let record be the default. + return printImmutableRecord(val, config, indentation, depth, refs, printer); +}; +// Explicitly comparing sentinel properties to true avoids false positive +// when mock identity-obj-proxy returns the key as the value for any key. +const test$2 = (val) => val && (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); +const plugin$2 = { + serialize: serialize$2, + test: test$2 +}; + +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} + +var reactIs$1 = {exports: {}}; + +var reactIs_production = {}; + +/** + * @license React + * react-is.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. + */ + +var hasRequiredReactIs_production; + +function requireReactIs_production () { + if (hasRequiredReactIs_production) return reactIs_production; + hasRequiredReactIs_production = 1; + var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), + REACT_PROFILER_TYPE = Symbol.for("react.profiler"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"); + function typeOf(object) { + if ("object" === typeof object && null !== object) { + var $$typeof = object.$$typeof; + switch ($$typeof) { + case REACT_ELEMENT_TYPE: + switch (((object = object.type), object)) { + case REACT_FRAGMENT_TYPE: + case REACT_PROFILER_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_SUSPENSE_TYPE: + case REACT_SUSPENSE_LIST_TYPE: + case REACT_VIEW_TRANSITION_TYPE: + return object; + default: + switch (((object = object && object.$$typeof), object)) { + case REACT_CONTEXT_TYPE: + case REACT_FORWARD_REF_TYPE: + case REACT_LAZY_TYPE: + case REACT_MEMO_TYPE: + return object; + case REACT_CONSUMER_TYPE: + return object; + default: + return $$typeof; + } + } + case REACT_PORTAL_TYPE: + return $$typeof; + } + } + } + reactIs_production.ContextConsumer = REACT_CONSUMER_TYPE; + reactIs_production.ContextProvider = REACT_CONTEXT_TYPE; + reactIs_production.Element = REACT_ELEMENT_TYPE; + reactIs_production.ForwardRef = REACT_FORWARD_REF_TYPE; + reactIs_production.Fragment = REACT_FRAGMENT_TYPE; + reactIs_production.Lazy = REACT_LAZY_TYPE; + reactIs_production.Memo = REACT_MEMO_TYPE; + reactIs_production.Portal = REACT_PORTAL_TYPE; + reactIs_production.Profiler = REACT_PROFILER_TYPE; + reactIs_production.StrictMode = REACT_STRICT_MODE_TYPE; + reactIs_production.Suspense = REACT_SUSPENSE_TYPE; + reactIs_production.SuspenseList = REACT_SUSPENSE_LIST_TYPE; + reactIs_production.isContextConsumer = function (object) { + return typeOf(object) === REACT_CONSUMER_TYPE; + }; + reactIs_production.isContextProvider = function (object) { + return typeOf(object) === REACT_CONTEXT_TYPE; + }; + reactIs_production.isElement = function (object) { + return ( + "object" === typeof object && + null !== object && + object.$$typeof === REACT_ELEMENT_TYPE + ); + }; + reactIs_production.isForwardRef = function (object) { + return typeOf(object) === REACT_FORWARD_REF_TYPE; + }; + reactIs_production.isFragment = function (object) { + return typeOf(object) === REACT_FRAGMENT_TYPE; + }; + reactIs_production.isLazy = function (object) { + return typeOf(object) === REACT_LAZY_TYPE; + }; + reactIs_production.isMemo = function (object) { + return typeOf(object) === REACT_MEMO_TYPE; + }; + reactIs_production.isPortal = function (object) { + return typeOf(object) === REACT_PORTAL_TYPE; + }; + reactIs_production.isProfiler = function (object) { + return typeOf(object) === REACT_PROFILER_TYPE; + }; + reactIs_production.isStrictMode = function (object) { + return typeOf(object) === REACT_STRICT_MODE_TYPE; + }; + reactIs_production.isSuspense = function (object) { + return typeOf(object) === REACT_SUSPENSE_TYPE; + }; + reactIs_production.isSuspenseList = function (object) { + return typeOf(object) === REACT_SUSPENSE_LIST_TYPE; + }; + reactIs_production.isValidElementType = function (type) { + return "string" === typeof type || + "function" === typeof type || + type === REACT_FRAGMENT_TYPE || + type === REACT_PROFILER_TYPE || + type === REACT_STRICT_MODE_TYPE || + type === REACT_SUSPENSE_TYPE || + type === REACT_SUSPENSE_LIST_TYPE || + ("object" === typeof type && + null !== type && + (type.$$typeof === REACT_LAZY_TYPE || + type.$$typeof === REACT_MEMO_TYPE || + type.$$typeof === REACT_CONTEXT_TYPE || + type.$$typeof === REACT_CONSUMER_TYPE || + type.$$typeof === REACT_FORWARD_REF_TYPE || + type.$$typeof === REACT_CLIENT_REFERENCE || + void 0 !== type.getModuleId)) + ? true + : false; + }; + reactIs_production.typeOf = typeOf; + return reactIs_production; +} + +var hasRequiredReactIs$1; + +function requireReactIs$1 () { + if (hasRequiredReactIs$1) return reactIs$1.exports; + hasRequiredReactIs$1 = 1; + + { + reactIs$1.exports = requireReactIs_production(); + } + return reactIs$1.exports; +} + +var reactIsExports$1 = requireReactIs$1(); +var index$1 = /*@__PURE__*/getDefaultExportFromCjs(reactIsExports$1); + +var ReactIs19 = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + default: index$1 +}, [reactIsExports$1]); + +var reactIs = {exports: {}}; + +var reactIs_production_min = {}; + +/** + * @license React + * react-is.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +var hasRequiredReactIs_production_min; + +function requireReactIs_production_min () { + if (hasRequiredReactIs_production_min) return reactIs_production_min; + hasRequiredReactIs_production_min = 1; +var b=Symbol.for("react.element"),c=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),e=Symbol.for("react.strict_mode"),f=Symbol.for("react.profiler"),g=Symbol.for("react.provider"),h=Symbol.for("react.context"),k=Symbol.for("react.server_context"),l=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),n=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),t=Symbol.for("react.offscreen"),u;u=Symbol.for("react.module.reference"); + function v(a){if("object"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}reactIs_production_min.ContextConsumer=h;reactIs_production_min.ContextProvider=g;reactIs_production_min.Element=b;reactIs_production_min.ForwardRef=l;reactIs_production_min.Fragment=d;reactIs_production_min.Lazy=q;reactIs_production_min.Memo=p;reactIs_production_min.Portal=c;reactIs_production_min.Profiler=f;reactIs_production_min.StrictMode=e;reactIs_production_min.Suspense=m; + reactIs_production_min.SuspenseList=n;reactIs_production_min.isAsyncMode=function(){return false};reactIs_production_min.isConcurrentMode=function(){return false};reactIs_production_min.isContextConsumer=function(a){return v(a)===h};reactIs_production_min.isContextProvider=function(a){return v(a)===g};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===b};reactIs_production_min.isForwardRef=function(a){return v(a)===l};reactIs_production_min.isFragment=function(a){return v(a)===d};reactIs_production_min.isLazy=function(a){return v(a)===q};reactIs_production_min.isMemo=function(a){return v(a)===p}; + reactIs_production_min.isPortal=function(a){return v(a)===c};reactIs_production_min.isProfiler=function(a){return v(a)===f};reactIs_production_min.isStrictMode=function(a){return v(a)===e};reactIs_production_min.isSuspense=function(a){return v(a)===m};reactIs_production_min.isSuspenseList=function(a){return v(a)===n}; + reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===d||a===f||a===e||a===m||a===n||a===t||"object"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?true:false};reactIs_production_min.typeOf=v; + return reactIs_production_min; +} + +var hasRequiredReactIs; + +function requireReactIs () { + if (hasRequiredReactIs) return reactIs.exports; + hasRequiredReactIs = 1; + + { + reactIs.exports = requireReactIs_production_min(); + } + return reactIs.exports; +} + +var reactIsExports = requireReactIs(); +var index = /*@__PURE__*/getDefaultExportFromCjs(reactIsExports); + +var ReactIs18 = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + default: index +}, [reactIsExports]); + +const reactIsMethods = [ + "isAsyncMode", + "isConcurrentMode", + "isContextConsumer", + "isContextProvider", + "isElement", + "isForwardRef", + "isFragment", + "isLazy", + "isMemo", + "isPortal", + "isProfiler", + "isStrictMode", + "isSuspense", + "isSuspenseList", + "isValidElementType" +]; +const ReactIs = Object.fromEntries(reactIsMethods.map((m) => [m, (v) => ReactIs18[m](v) || ReactIs19[m](v)])); +// Given element.props.children, or subtree during recursive traversal, +// return flattened array of children. +function getChildren(arg, children = []) { + if (Array.isArray(arg)) { + for (const item of arg) { + getChildren(item, children); + } + } else if (arg != null && arg !== false && arg !== "") { + children.push(arg); + } + return children; +} +function getType(element) { + const type = element.type; + if (typeof type === "string") { + return type; + } + if (typeof type === "function") { + return type.displayName || type.name || "Unknown"; + } + if (ReactIs.isFragment(element)) { + return "React.Fragment"; + } + if (ReactIs.isSuspense(element)) { + return "React.Suspense"; + } + if (typeof type === "object" && type !== null) { + if (ReactIs.isContextProvider(element)) { + return "Context.Provider"; + } + if (ReactIs.isContextConsumer(element)) { + return "Context.Consumer"; + } + if (ReactIs.isForwardRef(element)) { + if (type.displayName) { + return type.displayName; + } + const functionName = type.render.displayName || type.render.name || ""; + return functionName === "" ? "ForwardRef" : `ForwardRef(${functionName})`; + } + if (ReactIs.isMemo(element)) { + const functionName = type.displayName || type.type.displayName || type.type.name || ""; + return functionName === "" ? "Memo" : `Memo(${functionName})`; + } + } + return "UNDEFINED"; +} +function getPropKeys$1(element) { + const { props } = element; + return Object.keys(props).filter((key) => key !== "children" && props[key] !== undefined).sort(); +} +const serialize$1 = (element, config, indentation, depth, refs, printer) => ++depth > config.maxDepth ? printElementAsLeaf(getType(element), config) : printElement(getType(element), printProps(getPropKeys$1(element), element.props, config, indentation + config.indent, depth, refs, printer), printChildren(getChildren(element.props.children), config, indentation + config.indent, depth, refs, printer), config, indentation); +const test$1 = (val) => val != null && ReactIs.isElement(val); +const plugin$1 = { + serialize: serialize$1, + test: test$1 +}; + +const testSymbol = typeof Symbol === "function" && Symbol.for ? Symbol.for("react.test.json") : 245830487; +function getPropKeys(object) { + const { props } = object; + return props ? Object.keys(props).filter((key) => props[key] !== undefined).sort() : []; +} +const serialize = (object, config, indentation, depth, refs, printer) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement(object.type, object.props ? printProps(getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer) : "", object.children ? printChildren(object.children, config, indentation + config.indent, depth, refs, printer) : "", config, indentation); +const test = (val) => val && val.$$typeof === testSymbol; +const plugin = { + serialize, + test +}; + +const toString = Object.prototype.toString; +const toISOString = Date.prototype.toISOString; +const errorToString = Error.prototype.toString; +const regExpToString = RegExp.prototype.toString; +/** +* Explicitly comparing typeof constructor to function avoids undefined as name +* when mock identity-obj-proxy returns the key as the value for any key. +*/ +function getConstructorName(val) { + return typeof val.constructor === "function" && val.constructor.name || "Object"; +} +/** Is val is equal to global window object? Works even if it does not exist :) */ +function isWindow(val) { + return typeof window !== "undefined" && val === window; +} +// eslint-disable-next-line regexp/no-super-linear-backtracking +const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; +const NEWLINE_REGEXP = /\n/g; +class PrettyFormatPluginError extends Error { + constructor(message, stack) { + super(message); + this.stack = stack; + this.name = this.constructor.name; + } +} +function isToStringedArrayType(toStringed) { + return toStringed === "[object Array]" || toStringed === "[object ArrayBuffer]" || toStringed === "[object DataView]" || toStringed === "[object Float32Array]" || toStringed === "[object Float64Array]" || toStringed === "[object Int8Array]" || toStringed === "[object Int16Array]" || toStringed === "[object Int32Array]" || toStringed === "[object Uint8Array]" || toStringed === "[object Uint8ClampedArray]" || toStringed === "[object Uint16Array]" || toStringed === "[object Uint32Array]"; +} +function printNumber(val) { + return Object.is(val, -0) ? "-0" : String(val); +} +function printBigInt(val) { + return String(`${val}n`); +} +function printFunction(val, printFunctionName) { + if (!printFunctionName) { + return "[Function]"; + } + return `[Function ${val.name || "anonymous"}]`; +} +function printSymbol(val) { + return String(val).replace(SYMBOL_REGEXP, "Symbol($1)"); +} +function printError(val) { + return `[${errorToString.call(val)}]`; +} +/** +* The first port of call for printing an object, handles most of the +* data-types in JS. +*/ +function printBasicValue(val, printFunctionName, escapeRegex, escapeString) { + if (val === true || val === false) { + return `${val}`; + } + if (val === undefined) { + return "undefined"; + } + if (val === null) { + return "null"; + } + const typeOf = typeof val; + if (typeOf === "number") { + return printNumber(val); + } + if (typeOf === "bigint") { + return printBigInt(val); + } + if (typeOf === "string") { + if (escapeString) { + return `"${val.replaceAll(/"|\\/g, "\\$&")}"`; + } + return `"${val}"`; + } + if (typeOf === "function") { + return printFunction(val, printFunctionName); + } + if (typeOf === "symbol") { + return printSymbol(val); + } + const toStringed = toString.call(val); + if (toStringed === "[object WeakMap]") { + return "WeakMap {}"; + } + if (toStringed === "[object WeakSet]") { + return "WeakSet {}"; + } + if (toStringed === "[object Function]" || toStringed === "[object GeneratorFunction]") { + return printFunction(val, printFunctionName); + } + if (toStringed === "[object Symbol]") { + return printSymbol(val); + } + if (toStringed === "[object Date]") { + return Number.isNaN(+val) ? "Date { NaN }" : toISOString.call(val); + } + if (toStringed === "[object Error]") { + return printError(val); + } + if (toStringed === "[object RegExp]") { + if (escapeRegex) { + // https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js + return regExpToString.call(val).replaceAll(/[$()*+.?[\\\]^{|}]/g, "\\$&"); + } + return regExpToString.call(val); + } + if (val instanceof Error) { + return printError(val); + } + return null; +} +/** +* Handles more complex objects ( such as objects with circular references. +* maps and sets etc ) +*/ +function printComplexValue(val, config, indentation, depth, refs, hasCalledToJSON) { + if (refs.includes(val)) { + return "[Circular]"; + } + refs = [...refs]; + refs.push(val); + const hitMaxDepth = ++depth > config.maxDepth; + const min = config.min; + if (config.callToJSON && !hitMaxDepth && val.toJSON && typeof val.toJSON === "function" && !hasCalledToJSON) { + return printer(val.toJSON(), config, indentation, depth, refs, true); + } + const toStringed = toString.call(val); + if (toStringed === "[object Arguments]") { + return hitMaxDepth ? "[Arguments]" : `${min ? "" : "Arguments "}[${printListItems(val, config, indentation, depth, refs, printer)}]`; + } + if (isToStringedArrayType(toStringed)) { + return hitMaxDepth ? `[${val.constructor.name}]` : `${min ? "" : !config.printBasicPrototype && val.constructor.name === "Array" ? "" : `${val.constructor.name} `}[${printListItems(val, config, indentation, depth, refs, printer)}]`; + } + if (toStringed === "[object Map]") { + return hitMaxDepth ? "[Map]" : `Map {${printIteratorEntries(val.entries(), config, indentation, depth, refs, printer, " => ")}}`; + } + if (toStringed === "[object Set]") { + return hitMaxDepth ? "[Set]" : `Set {${printIteratorValues(val.values(), config, indentation, depth, refs, printer)}}`; + } + // Avoid failure to serialize global window object in jsdom test environment. + // For example, not even relevant if window is prop of React element. + return hitMaxDepth || isWindow(val) ? `[${getConstructorName(val)}]` : `${min ? "" : !config.printBasicPrototype && getConstructorName(val) === "Object" ? "" : `${getConstructorName(val)} `}{${printObjectProperties(val, config, indentation, depth, refs, printer)}}`; +} +const ErrorPlugin = { + test: (val) => val && val instanceof Error, + serialize(val, config, indentation, depth, refs, printer) { + if (refs.includes(val)) { + return "[Circular]"; + } + refs = [...refs, val]; + const hitMaxDepth = ++depth > config.maxDepth; + const { message, cause, ...rest } = val; + const entries = { + message, + ...typeof cause !== "undefined" ? { cause } : {}, + ...val instanceof AggregateError ? { errors: val.errors } : {}, + ...rest + }; + const name = val.name !== "Error" ? val.name : getConstructorName(val); + return hitMaxDepth ? `[${name}]` : `${name} {${printIteratorEntries(Object.entries(entries).values(), config, indentation, depth, refs, printer)}}`; + } +}; +function isNewPlugin(plugin) { + return plugin.serialize != null; +} +function printPlugin(plugin, val, config, indentation, depth, refs) { + let printed; + try { + printed = isNewPlugin(plugin) ? plugin.serialize(val, config, indentation, depth, refs, printer) : plugin.print(val, (valChild) => printer(valChild, config, indentation, depth, refs), (str) => { + const indentationNext = indentation + config.indent; + return indentationNext + str.replaceAll(NEWLINE_REGEXP, `\n${indentationNext}`); + }, { + edgeSpacing: config.spacingOuter, + min: config.min, + spacing: config.spacingInner + }, config.colors); + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + if (typeof printed !== "string") { + throw new TypeError(`pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`); + } + return printed; +} +function findPlugin(plugins, val) { + for (const plugin of plugins) { + try { + if (plugin.test(val)) { + return plugin; + } + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + } + return null; +} +function printer(val, config, indentation, depth, refs, hasCalledToJSON) { + const plugin = findPlugin(config.plugins, val); + if (plugin !== null) { + return printPlugin(plugin, val, config, indentation, depth, refs); + } + const basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString); + if (basicResult !== null) { + return basicResult; + } + return printComplexValue(val, config, indentation, depth, refs, hasCalledToJSON); +} +const DEFAULT_THEME = { + comment: "gray", + content: "reset", + prop: "yellow", + tag: "cyan", + value: "green" +}; +const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); +const DEFAULT_OPTIONS = { + callToJSON: true, + compareKeys: undefined, + escapeRegex: false, + escapeString: true, + highlight: false, + indent: 2, + maxDepth: Number.POSITIVE_INFINITY, + maxWidth: Number.POSITIVE_INFINITY, + min: false, + plugins: [], + printBasicPrototype: true, + printFunctionName: true, + printShadowRoot: true, + theme: DEFAULT_THEME +}; +function validateOptions(options) { + for (const key of Object.keys(options)) { + if (!Object.hasOwn(DEFAULT_OPTIONS, key)) { + throw new Error(`pretty-format: Unknown option "${key}".`); + } + } + if (options.min && options.indent !== undefined && options.indent !== 0) { + throw new Error("pretty-format: Options \"min\" and \"indent\" cannot be used together."); + } +} +function getColorsHighlight() { + return DEFAULT_THEME_KEYS.reduce((colors, key) => { + const value = DEFAULT_THEME[key]; + const color = value && styles[value]; + if (color && typeof color.close === "string" && typeof color.open === "string") { + colors[key] = color; + } else { + throw new Error(`pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`); + } + return colors; + }, Object.create(null)); +} +function getColorsEmpty() { + return DEFAULT_THEME_KEYS.reduce((colors, key) => { + colors[key] = { + close: "", + open: "" + }; + return colors; + }, Object.create(null)); +} +function getPrintFunctionName(options) { + return options?.printFunctionName ?? DEFAULT_OPTIONS.printFunctionName; +} +function getEscapeRegex(options) { + return options?.escapeRegex ?? DEFAULT_OPTIONS.escapeRegex; +} +function getEscapeString(options) { + return options?.escapeString ?? DEFAULT_OPTIONS.escapeString; +} +function getConfig(options) { + return { + callToJSON: options?.callToJSON ?? DEFAULT_OPTIONS.callToJSON, + colors: options?.highlight ? getColorsHighlight() : getColorsEmpty(), + compareKeys: typeof options?.compareKeys === "function" || options?.compareKeys === null ? options.compareKeys : DEFAULT_OPTIONS.compareKeys, + escapeRegex: getEscapeRegex(options), + escapeString: getEscapeString(options), + indent: options?.min ? "" : createIndent(options?.indent ?? DEFAULT_OPTIONS.indent), + maxDepth: options?.maxDepth ?? DEFAULT_OPTIONS.maxDepth, + maxWidth: options?.maxWidth ?? DEFAULT_OPTIONS.maxWidth, + min: options?.min ?? DEFAULT_OPTIONS.min, + plugins: options?.plugins ?? DEFAULT_OPTIONS.plugins, + printBasicPrototype: options?.printBasicPrototype ?? true, + printFunctionName: getPrintFunctionName(options), + printShadowRoot: options?.printShadowRoot ?? true, + spacingInner: options?.min ? " " : "\n", + spacingOuter: options?.min ? "" : "\n" + }; +} +function createIndent(indent) { + return Array.from({ length: indent + 1 }).join(" "); +} +/** +* Returns a presentation string of your `val` object +* @param val any potential JavaScript object +* @param options Custom settings +*/ +function format(val, options) { + if (options) { + validateOptions(options); + if (options.plugins) { + const plugin = findPlugin(options.plugins, val); + if (plugin !== null) { + return printPlugin(plugin, val, getConfig(options), "", 0, []); + } + } + } + const basicResult = printBasicValue(val, getPrintFunctionName(options), getEscapeRegex(options), getEscapeString(options)); + if (basicResult !== null) { + return basicResult; + } + return printComplexValue(val, getConfig(options), "", 0, []); +} +const plugins = { + AsymmetricMatcher: plugin$5, + DOMCollection: plugin$4, + DOMElement: plugin$3, + Immutable: plugin$2, + ReactElement: plugin$1, + ReactTestComponent: plugin, + Error: ErrorPlugin +}; + +export { DEFAULT_OPTIONS, format, plugins }; diff --git a/vanilla/node_modules/@vitest/pretty-format/package.json b/vanilla/node_modules/@vitest/pretty-format/package.json new file mode 100644 index 0000000..44a0098 --- /dev/null +++ b/vanilla/node_modules/@vitest/pretty-format/package.json @@ -0,0 +1,44 @@ +{ + "name": "@vitest/pretty-format", + "type": "module", + "version": "4.0.18", + "description": "Fork of pretty-format with support for ESM", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/pretty-format" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "tinyrainbow": "^3.0.3" + }, + "devDependencies": { + "@types/react-is": "^19.2.0", + "react-is": "^19.2.0", + "react-is-18": "npm:react-is@18.3.1" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/@vitest/runner/LICENSE b/vanilla/node_modules/@vitest/runner/LICENSE new file mode 100644 index 0000000..0e5771d --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vanilla/node_modules/@vitest/runner/README.md b/vanilla/node_modules/@vitest/runner/README.md new file mode 100644 index 0000000..2796b6a --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/README.md @@ -0,0 +1,5 @@ +# @vitest/runner + +Vitest mechanism to collect and run tasks. + +[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/advanced/runner) diff --git a/vanilla/node_modules/@vitest/runner/dist/chunk-tasks.js b/vanilla/node_modules/@vitest/runner/dist/chunk-tasks.js new file mode 100644 index 0000000..a66af35 --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/dist/chunk-tasks.js @@ -0,0 +1,340 @@ +import { processError } from '@vitest/utils/error'; +import { parseSingleStack } from '@vitest/utils/source-map'; +import { relative } from 'pathe'; +import { toArray } from '@vitest/utils/helpers'; + +function createChainable(keys, fn) { + function create(context) { + const chain = function(...args) { + return fn.apply(context, args); + }; + Object.assign(chain, fn); + chain.withContext = () => chain.bind(context); + chain.setContext = (key, value) => { + context[key] = value; + }; + chain.mergeContext = (ctx) => { + Object.assign(context, ctx); + }; + for (const key of keys) { + Object.defineProperty(chain, key, { get() { + return create({ + ...context, + [key]: true + }); + } }); + } + return chain; + } + const chain = create({}); + chain.fn = fn; + return chain; +} + +/** +* If any tasks been marked as `only`, mark all other tasks as `skip`. +*/ +function interpretTaskModes(file, namePattern, testLocations, onlyMode, parentIsOnly, allowOnly) { + const matchedLocations = []; + const traverseSuite = (suite, parentIsOnly, parentMatchedWithLocation) => { + const suiteIsOnly = parentIsOnly || suite.mode === "only"; + // Check if any tasks in this suite have `.only` - if so, only those should run + const hasSomeTasksOnly = onlyMode && suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t)); + suite.tasks.forEach((t) => { + // Check if either the parent suite or the task itself are marked as included + // If there are tasks with `.only` in this suite, only include those (not all tasks from describe.only) + const includeTask = hasSomeTasksOnly ? t.mode === "only" || t.type === "suite" && someTasksAreOnly(t) : suiteIsOnly || t.mode === "only"; + if (onlyMode) { + if (t.type === "suite" && (includeTask || someTasksAreOnly(t))) { + // Don't skip this suite + if (t.mode === "only") { + checkAllowOnly(t, allowOnly); + t.mode = "run"; + } + } else if (t.mode === "run" && !includeTask) { + t.mode = "skip"; + } else if (t.mode === "only") { + checkAllowOnly(t, allowOnly); + t.mode = "run"; + } + } + let hasLocationMatch = parentMatchedWithLocation; + // Match test location against provided locations, only run if present + // in `testLocations`. Note: if `includeTaskLocations` is not enabled, + // all test will be skipped. + if (testLocations !== undefined && testLocations.length !== 0) { + if (t.location && (testLocations === null || testLocations === void 0 ? void 0 : testLocations.includes(t.location.line))) { + t.mode = "run"; + matchedLocations.push(t.location.line); + hasLocationMatch = true; + } else if (parentMatchedWithLocation) { + t.mode = "run"; + } else if (t.type === "test") { + t.mode = "skip"; + } + } + if (t.type === "test") { + if (namePattern && !getTaskFullName(t).match(namePattern)) { + t.mode = "skip"; + } + } else if (t.type === "suite") { + if (t.mode === "skip") { + skipAllTasks(t); + } else if (t.mode === "todo") { + todoAllTasks(t); + } else { + traverseSuite(t, includeTask, hasLocationMatch); + } + } + }); + // if all subtasks are skipped, mark as skip + if (suite.mode === "run" || suite.mode === "queued") { + if (suite.tasks.length && suite.tasks.every((i) => i.mode !== "run" && i.mode !== "queued")) { + suite.mode = "skip"; + } + } + }; + traverseSuite(file, parentIsOnly, false); + const nonMatching = testLocations === null || testLocations === void 0 ? void 0 : testLocations.filter((loc) => !matchedLocations.includes(loc)); + if (nonMatching && nonMatching.length !== 0) { + const message = nonMatching.length === 1 ? `line ${nonMatching[0]}` : `lines ${nonMatching.join(", ")}`; + if (file.result === undefined) { + file.result = { + state: "fail", + errors: [] + }; + } + if (file.result.errors === undefined) { + file.result.errors = []; + } + file.result.errors.push(processError(new Error(`No test found in ${file.name} in ${message}`))); + } +} +function getTaskFullName(task) { + return `${task.suite ? `${getTaskFullName(task.suite)} ` : ""}${task.name}`; +} +function someTasksAreOnly(suite) { + return suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t)); +} +function skipAllTasks(suite) { + suite.tasks.forEach((t) => { + if (t.mode === "run" || t.mode === "queued") { + t.mode = "skip"; + if (t.type === "suite") { + skipAllTasks(t); + } + } + }); +} +function todoAllTasks(suite) { + suite.tasks.forEach((t) => { + if (t.mode === "run" || t.mode === "queued") { + t.mode = "todo"; + if (t.type === "suite") { + todoAllTasks(t); + } + } + }); +} +function checkAllowOnly(task, allowOnly) { + if (allowOnly) { + return; + } + const error = processError(new Error("[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error")); + task.result = { + state: "fail", + errors: [error] + }; +} +/* @__NO_SIDE_EFFECTS__ */ +function generateHash(str) { + let hash = 0; + if (str.length === 0) { + return `${hash}`; + } + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash = hash & hash; + } + return `${hash}`; +} +function calculateSuiteHash(parent) { + parent.tasks.forEach((t, idx) => { + t.id = `${parent.id}_${idx}`; + if (t.type === "suite") { + calculateSuiteHash(t); + } + }); +} +function createFileTask(filepath, root, projectName, pool, viteEnvironment) { + const path = relative(root, filepath); + const file = { + id: generateFileHash(path, projectName), + name: path, + fullName: path, + type: "suite", + mode: "queued", + filepath, + tasks: [], + meta: Object.create(null), + projectName, + file: undefined, + pool, + viteEnvironment + }; + file.file = file; + return file; +} +/** +* Generate a unique ID for a file based on its path and project name +* @param file File relative to the root of the project to keep ID the same between different machines +* @param projectName The name of the test project +*/ +/* @__NO_SIDE_EFFECTS__ */ +function generateFileHash(file, projectName) { + return /* @__PURE__ */ generateHash(`${file}${projectName || ""}`); +} +function findTestFileStackTrace(testFilePath, error) { + // first line is the error message + const lines = error.split("\n").slice(1); + for (const line of lines) { + const stack = parseSingleStack(line); + if (stack && stack.file === testFilePath) { + return stack; + } + } +} + +/** +* Return a function for running multiple async operations with limited concurrency. +*/ +function limitConcurrency(concurrency = Infinity) { + // The number of currently active + pending tasks. + let count = 0; + // The head and tail of the pending task queue, built using a singly linked list. + // Both head and tail are initially undefined, signifying an empty queue. + // They both become undefined again whenever there are no pending tasks. + let head; + let tail; + // A bookkeeping function executed whenever a task has been run to completion. + const finish = () => { + count--; + // Check if there are further pending tasks in the queue. + if (head) { + // Allow the next pending task to run and pop it from the queue. + head[0](); + head = head[1]; + // The head may now be undefined if there are no further pending tasks. + // In that case, set tail to undefined as well. + tail = head && tail; + } + }; + return (func, ...args) => { + // Create a promise chain that: + // 1. Waits for its turn in the task queue (if necessary). + // 2. Runs the task. + // 3. Allows the next pending task (if any) to run. + return new Promise((resolve) => { + if (count++ < concurrency) { + // No need to queue if fewer than maxConcurrency tasks are running. + resolve(); + } else if (tail) { + // There are pending tasks, so append to the queue. + tail = tail[1] = [resolve]; + } else { + // No other pending tasks, initialize the queue with a new tail and head. + head = tail = [resolve]; + } + }).then(() => { + // Running func here ensures that even a non-thenable result or an + // immediately thrown error gets wrapped into a Promise. + return func(...args); + }).finally(finish); + }; +} + +/** +* Partition in tasks groups by consecutive concurrent +*/ +function partitionSuiteChildren(suite) { + let tasksGroup = []; + const tasksGroups = []; + for (const c of suite.tasks) { + if (tasksGroup.length === 0 || c.concurrent === tasksGroup[0].concurrent) { + tasksGroup.push(c); + } else { + tasksGroups.push(tasksGroup); + tasksGroup = [c]; + } + } + if (tasksGroup.length > 0) { + tasksGroups.push(tasksGroup); + } + return tasksGroups; +} + +function isTestCase(s) { + return s.type === "test"; +} +function getTests(suite) { + const tests = []; + const arraySuites = toArray(suite); + for (const s of arraySuites) { + if (isTestCase(s)) { + tests.push(s); + } else { + for (const task of s.tasks) { + if (isTestCase(task)) { + tests.push(task); + } else { + const taskTests = getTests(task); + for (const test of taskTests) { + tests.push(test); + } + } + } + } + } + return tests; +} +function getTasks(tasks = []) { + return toArray(tasks).flatMap((s) => isTestCase(s) ? [s] : [s, ...getTasks(s.tasks)]); +} +function getSuites(suite) { + return toArray(suite).flatMap((s) => s.type === "suite" ? [s, ...getSuites(s.tasks)] : []); +} +function hasTests(suite) { + return toArray(suite).some((s) => s.tasks.some((c) => isTestCase(c) || hasTests(c))); +} +function hasFailed(suite) { + return toArray(suite).some((s) => { + var _s$result; + return ((_s$result = s.result) === null || _s$result === void 0 ? void 0 : _s$result.state) === "fail" || s.type === "suite" && hasFailed(s.tasks); + }); +} +function getNames(task) { + const names = [task.name]; + let current = task; + while (current === null || current === void 0 ? void 0 : current.suite) { + current = current.suite; + if (current === null || current === void 0 ? void 0 : current.name) { + names.unshift(current.name); + } + } + if (current !== task.file) { + names.unshift(task.file.name); + } + return names; +} +function getFullName(task, separator = " > ") { + return getNames(task).join(separator); +} +function getTestName(task, separator = " > ") { + return getNames(task).slice(1).join(separator); +} +function createTaskName(names, separator = " > ") { + return names.filter((name) => name !== undefined).join(separator); +} + +export { calculateSuiteHash as a, createFileTask as b, createChainable as c, generateHash as d, createTaskName as e, findTestFileStackTrace as f, generateFileHash as g, getFullName as h, interpretTaskModes as i, getNames as j, getSuites as k, limitConcurrency as l, getTasks as m, getTestName as n, getTests as o, partitionSuiteChildren as p, hasFailed as q, hasTests as r, someTasksAreOnly as s, isTestCase as t }; diff --git a/vanilla/node_modules/@vitest/runner/dist/index.d.ts b/vanilla/node_modules/@vitest/runner/dist/index.d.ts new file mode 100644 index 0000000..2038f8f --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/dist/index.d.ts @@ -0,0 +1,180 @@ +import { b as TestArtifact, a as Test, S as Suite, d as SuiteHooks, F as File, e as TaskUpdateEvent, T as Task, f as TestAPI, g as SuiteAPI, h as SuiteCollector } from './tasks.d-C7UxawJ9.js'; +export { A as AfterAllListener, n as AfterEachListener, B as BeforeAllListener, p as BeforeEachListener, q as Fixture, r as FixtureFn, s as FixtureOptions, t as Fixtures, I as ImportDuration, u as InferFixturesTypes, O as OnTestFailedHandler, v as OnTestFinishedHandler, R as RunMode, w as RuntimeContext, x as SequenceHooks, y as SequenceSetupFiles, z as SuiteFactory, D as TaskBase, E as TaskCustomOptions, G as TaskEventPack, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, M as TaskResultPack, N as TaskState, P as TestAnnotation, Q as TestAnnotationArtifact, U as TestAnnotationLocation, V as TestArtifactBase, W as TestArtifactLocation, X as TestArtifactRegistry, Y as TestAttachment, Z as TestContext, _ as TestFunction, $ as TestOptions, a0 as Use, a1 as VisualRegressionArtifact, i as afterAll, j as afterEach, k as beforeAll, l as beforeEach, o as onTestFailed, m as onTestFinished } from './tasks.d-C7UxawJ9.js'; +import { Awaitable } from '@vitest/utils'; +import { FileSpecification, VitestRunner } from './types.js'; +export { CancelReason, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource } from './types.js'; +import '@vitest/utils/diff'; + +/** +* @experimental +* @advanced +* +* Records a custom test artifact during test execution. +* +* This function allows you to attach structured data, files, or metadata to a test. +* +* Vitest automatically injects the source location where the artifact was created and manages any attachments you include. +* +* @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests +* @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase} +* +* @returns A promise that resolves to the recorded artifact with location injected +* +* @throws {Error} If called after the test has finished running +* @throws {Error} If the test runner doesn't support artifacts +* +* @example +* ```ts +* // In a custom assertion +* async function toHaveValidSchema(this: MatcherState, actual: unknown) { +* const validation = validateSchema(actual) +* +* await recordArtifact(this.task, { +* type: 'my-plugin:schema-validation', +* passed: validation.valid, +* errors: validation.errors, +* }) +* +* return { pass: validation.valid, message: () => '...' } +* } +* ``` +*/ +declare function recordArtifact(task: Test, artifact: Artifact): Promise; + +declare function setFn(key: Test, fn: () => Awaitable): void; +declare function getFn(key: Task): () => Awaitable; +declare function setHooks(key: Suite, hooks: SuiteHooks): void; +declare function getHooks(key: Suite): SuiteHooks; + +declare function updateTask(event: TaskUpdateEvent, task: Task, runner: VitestRunner): void; +declare function startTests(specs: string[] | FileSpecification[], runner: VitestRunner): Promise; +declare function publicCollect(specs: string[] | FileSpecification[], runner: VitestRunner): Promise; + +/** +* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. +* Suites can contain both tests and other suites, enabling complex test structures. +* +* @param {string} name - The name of the suite, used for identification and reporting. +* @param {Function} fn - A function that defines the tests and suites within this suite. +* @example +* ```ts +* // Define a suite with two tests +* suite('Math operations', () => { +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* +* test('should subtract two numbers', () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* }); +* ``` +* @example +* ```ts +* // Define nested suites +* suite('String operations', () => { +* suite('Trimming', () => { +* test('should trim whitespace from start and end', () => { +* expect(' hello '.trim()).toBe('hello'); +* }); +* }); +* +* suite('Concatenation', () => { +* test('should concatenate two strings', () => { +* expect('hello' + ' ' + 'world').toBe('hello world'); +* }); +* }); +* }); +* ``` +*/ +declare const suite: SuiteAPI; +/** +* Defines a test case with a given name and test function. The test function can optionally be configured with test options. +* +* @param {string | Function} name - The name of the test or a function that will be used as a test name. +* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. +* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. +* @throws {Error} If called inside another test function. +* @example +* ```ts +* // Define a simple test +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* ``` +* @example +* ```ts +* // Define a test with options +* test('should subtract two numbers', { retry: 3 }, () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* ``` +*/ +declare const test: TestAPI; +/** +* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. +* Suites can contain both tests and other suites, enabling complex test structures. +* +* @param {string} name - The name of the suite, used for identification and reporting. +* @param {Function} fn - A function that defines the tests and suites within this suite. +* @example +* ```ts +* // Define a suite with two tests +* describe('Math operations', () => { +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* +* test('should subtract two numbers', () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* }); +* ``` +* @example +* ```ts +* // Define nested suites +* describe('String operations', () => { +* describe('Trimming', () => { +* test('should trim whitespace from start and end', () => { +* expect(' hello '.trim()).toBe('hello'); +* }); +* }); +* +* describe('Concatenation', () => { +* test('should concatenate two strings', () => { +* expect('hello' + ' ' + 'world').toBe('hello world'); +* }); +* }); +* }); +* ``` +*/ +declare const describe: SuiteAPI; +/** +* Defines a test case with a given name and test function. The test function can optionally be configured with test options. +* +* @param {string | Function} name - The name of the test or a function that will be used as a test name. +* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. +* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. +* @throws {Error} If called inside another test function. +* @example +* ```ts +* // Define a simple test +* it('adds two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* ``` +* @example +* ```ts +* // Define a test with options +* it('subtracts two numbers', { retry: 3 }, () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* ``` +*/ +declare const it: TestAPI; +declare function getCurrentSuite(): SuiteCollector; +declare function createTaskCollector(fn: (...args: any[]) => any, context?: Record): TestAPI; + +declare function getCurrentTest(): T; + +export { File, FileSpecification, Suite, SuiteAPI, SuiteCollector, SuiteHooks, Task, TaskUpdateEvent, Test, TestAPI, TestArtifact, VitestRunner, publicCollect as collectTests, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, recordArtifact, setFn, setHooks, startTests, suite, test, updateTask }; diff --git a/vanilla/node_modules/@vitest/runner/dist/index.js b/vanilla/node_modules/@vitest/runner/dist/index.js new file mode 100644 index 0000000..c6403f4 --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/dist/index.js @@ -0,0 +1,2114 @@ +import { processError } from '@vitest/utils/error'; +import { isObject, createDefer, assertTypes, toArray, isNegativeNaN, objectAttr, shuffle } from '@vitest/utils/helpers'; +import { getSafeTimers } from '@vitest/utils/timers'; +import { format, formatRegExp, objDisplay } from '@vitest/utils/display'; +import { c as createChainable, e as createTaskName, f as findTestFileStackTrace, b as createFileTask, a as calculateSuiteHash, s as someTasksAreOnly, i as interpretTaskModes, l as limitConcurrency, p as partitionSuiteChildren, r as hasTests, q as hasFailed } from './chunk-tasks.js'; +import '@vitest/utils/source-map'; +import 'pathe'; + +class PendingError extends Error { + code = "VITEST_PENDING"; + taskId; + constructor(message, task, note) { + super(message); + this.message = message; + this.note = note; + this.taskId = task.id; + } +} +class TestRunAbortError extends Error { + name = "TestRunAbortError"; + reason; + constructor(message, reason) { + super(message); + this.reason = reason; + } +} + +// use WeakMap here to make the Test and Suite object serializable +const fnMap = new WeakMap(); +const testFixtureMap = new WeakMap(); +const hooksMap = new WeakMap(); +function setFn(key, fn) { + fnMap.set(key, fn); +} +function getFn(key) { + return fnMap.get(key); +} +function setTestFixture(key, fixture) { + testFixtureMap.set(key, fixture); +} +function getTestFixture(key) { + return testFixtureMap.get(key); +} +function setHooks(key, hooks) { + hooksMap.set(key, hooks); +} +function getHooks(key) { + return hooksMap.get(key); +} + +function mergeScopedFixtures(testFixtures, scopedFixtures) { + const scopedFixturesMap = scopedFixtures.reduce((map, fixture) => { + map[fixture.prop] = fixture; + return map; + }, {}); + const newFixtures = {}; + testFixtures.forEach((fixture) => { + const useFixture = scopedFixturesMap[fixture.prop] || { ...fixture }; + newFixtures[useFixture.prop] = useFixture; + }); + for (const fixtureKep in newFixtures) { + var _fixture$deps; + const fixture = newFixtures[fixtureKep]; + // if the fixture was define before the scope, then its dep + // will reference the original fixture instead of the scope + fixture.deps = (_fixture$deps = fixture.deps) === null || _fixture$deps === void 0 ? void 0 : _fixture$deps.map((dep) => newFixtures[dep.prop]); + } + return Object.values(newFixtures); +} +function mergeContextFixtures(fixtures, context, runner) { + const fixtureOptionKeys = [ + "auto", + "injected", + "scope" + ]; + const fixtureArray = Object.entries(fixtures).map(([prop, value]) => { + const fixtureItem = { value }; + if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) { + var _runner$injectValue; + // fixture with options + Object.assign(fixtureItem, value[1]); + const userValue = value[0]; + fixtureItem.value = fixtureItem.injected ? ((_runner$injectValue = runner.injectValue) === null || _runner$injectValue === void 0 ? void 0 : _runner$injectValue.call(runner, prop)) ?? userValue : userValue; + } + fixtureItem.scope = fixtureItem.scope || "test"; + if (fixtureItem.scope === "worker" && !runner.getWorkerContext) { + fixtureItem.scope = "file"; + } + fixtureItem.prop = prop; + fixtureItem.isFn = typeof fixtureItem.value === "function"; + return fixtureItem; + }); + if (Array.isArray(context.fixtures)) { + context.fixtures = context.fixtures.concat(fixtureArray); + } else { + context.fixtures = fixtureArray; + } + // Update dependencies of fixture functions + fixtureArray.forEach((fixture) => { + if (fixture.isFn) { + const usedProps = getUsedProps(fixture.value); + if (usedProps.length) { + fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop)); + } + // test can access anything, so we ignore it + if (fixture.scope !== "test") { + var _fixture$deps2; + (_fixture$deps2 = fixture.deps) === null || _fixture$deps2 === void 0 ? void 0 : _fixture$deps2.forEach((dep) => { + if (!dep.isFn) { + // non fn fixtures are always resolved and available to anyone + return; + } + // worker scope can only import from worker scope + if (fixture.scope === "worker" && dep.scope === "worker") { + return; + } + // file scope an import from file and worker scopes + if (fixture.scope === "file" && dep.scope !== "test") { + return; + } + throw new SyntaxError(`cannot use the ${dep.scope} fixture "${dep.prop}" inside the ${fixture.scope} fixture "${fixture.prop}"`); + }); + } + } + }); + return context; +} +const fixtureValueMaps = new Map(); +const cleanupFnArrayMap = new Map(); +async function callFixtureCleanup(context) { + const cleanupFnArray = cleanupFnArrayMap.get(context) ?? []; + for (const cleanup of cleanupFnArray.reverse()) { + await cleanup(); + } + cleanupFnArrayMap.delete(context); +} +function withFixtures(runner, fn, testContext) { + return (hookContext) => { + const context = hookContext || testContext; + if (!context) { + return fn({}); + } + const fixtures = getTestFixture(context); + if (!(fixtures === null || fixtures === void 0 ? void 0 : fixtures.length)) { + return fn(context); + } + const usedProps = getUsedProps(fn); + const hasAutoFixture = fixtures.some(({ auto }) => auto); + if (!usedProps.length && !hasAutoFixture) { + return fn(context); + } + if (!fixtureValueMaps.get(context)) { + fixtureValueMaps.set(context, new Map()); + } + const fixtureValueMap = fixtureValueMaps.get(context); + if (!cleanupFnArrayMap.has(context)) { + cleanupFnArrayMap.set(context, []); + } + const cleanupFnArray = cleanupFnArrayMap.get(context); + const usedFixtures = fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop)); + const pendingFixtures = resolveDeps(usedFixtures); + if (!pendingFixtures.length) { + return fn(context); + } + async function resolveFixtures() { + for (const fixture of pendingFixtures) { + // fixture could be already initialized during "before" hook + if (fixtureValueMap.has(fixture)) { + continue; + } + const resolvedValue = await resolveFixtureValue(runner, fixture, context, cleanupFnArray); + context[fixture.prop] = resolvedValue; + fixtureValueMap.set(fixture, resolvedValue); + if (fixture.scope === "test") { + cleanupFnArray.unshift(() => { + fixtureValueMap.delete(fixture); + }); + } + } + } + return resolveFixtures().then(() => fn(context)); + }; +} +const globalFixturePromise = new WeakMap(); +function resolveFixtureValue(runner, fixture, context, cleanupFnArray) { + var _runner$getWorkerCont; + const fileContext = getFileContext(context.task.file); + const workerContext = (_runner$getWorkerCont = runner.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner); + if (!fixture.isFn) { + var _fixture$prop; + fileContext[_fixture$prop = fixture.prop] ?? (fileContext[_fixture$prop] = fixture.value); + if (workerContext) { + var _fixture$prop2; + workerContext[_fixture$prop2 = fixture.prop] ?? (workerContext[_fixture$prop2] = fixture.value); + } + return fixture.value; + } + if (fixture.scope === "test") { + return resolveFixtureFunction(fixture.value, context, cleanupFnArray); + } + // in case the test runs in parallel + if (globalFixturePromise.has(fixture)) { + return globalFixturePromise.get(fixture); + } + let fixtureContext; + if (fixture.scope === "worker") { + if (!workerContext) { + throw new TypeError("[@vitest/runner] The worker context is not available in the current test runner. Please, provide the `getWorkerContext` method when initiating the runner."); + } + fixtureContext = workerContext; + } else { + fixtureContext = fileContext; + } + if (fixture.prop in fixtureContext) { + return fixtureContext[fixture.prop]; + } + if (!cleanupFnArrayMap.has(fixtureContext)) { + cleanupFnArrayMap.set(fixtureContext, []); + } + const cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext); + const promise = resolveFixtureFunction(fixture.value, fixtureContext, cleanupFnFileArray).then((value) => { + fixtureContext[fixture.prop] = value; + globalFixturePromise.delete(fixture); + return value; + }); + globalFixturePromise.set(fixture, promise); + return promise; +} +async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) { + // wait for `use` call to extract fixture value + const useFnArgPromise = createDefer(); + let isUseFnArgResolved = false; + const fixtureReturn = fixtureFn(context, async (useFnArg) => { + // extract `use` argument + isUseFnArgResolved = true; + useFnArgPromise.resolve(useFnArg); + // suspend fixture teardown by holding off `useReturnPromise` resolution until cleanup + const useReturnPromise = createDefer(); + cleanupFnArray.push(async () => { + // start teardown by resolving `use` Promise + useReturnPromise.resolve(); + // wait for finishing teardown + await fixtureReturn; + }); + await useReturnPromise; + }).catch((e) => { + // treat fixture setup error as test failure + if (!isUseFnArgResolved) { + useFnArgPromise.reject(e); + return; + } + // otherwise re-throw to avoid silencing error during cleanup + throw e; + }); + return useFnArgPromise; +} +function resolveDeps(fixtures, depSet = new Set(), pendingFixtures = []) { + fixtures.forEach((fixture) => { + if (pendingFixtures.includes(fixture)) { + return; + } + if (!fixture.isFn || !fixture.deps) { + pendingFixtures.push(fixture); + return; + } + if (depSet.has(fixture)) { + throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`); + } + depSet.add(fixture); + resolveDeps(fixture.deps, depSet, pendingFixtures); + pendingFixtures.push(fixture); + depSet.clear(); + }); + return pendingFixtures; +} +function getUsedProps(fn) { + let fnString = filterOutComments(fn.toString()); + // match lowered async function and strip it off + // example code on esbuild-try https://esbuild.github.io/try/#YgAwLjI0LjAALS1zdXBwb3J0ZWQ6YXN5bmMtYXdhaXQ9ZmFsc2UAZQBlbnRyeS50cwBjb25zdCBvID0gewogIGYxOiBhc3luYyAoKSA9PiB7fSwKICBmMjogYXN5bmMgKGEpID0+IHt9LAogIGYzOiBhc3luYyAoYSwgYikgPT4ge30sCiAgZjQ6IGFzeW5jIGZ1bmN0aW9uKGEpIHt9LAogIGY1OiBhc3luYyBmdW5jdGlvbiBmZihhKSB7fSwKICBhc3luYyBmNihhKSB7fSwKCiAgZzE6IGFzeW5jICgpID0+IHt9LAogIGcyOiBhc3luYyAoeyBhIH0pID0+IHt9LAogIGczOiBhc3luYyAoeyBhIH0sIGIpID0+IHt9LAogIGc0OiBhc3luYyBmdW5jdGlvbiAoeyBhIH0pIHt9LAogIGc1OiBhc3luYyBmdW5jdGlvbiBnZyh7IGEgfSkge30sCiAgYXN5bmMgZzYoeyBhIH0pIHt9LAoKICBoMTogYXN5bmMgKCkgPT4ge30sCiAgLy8gY29tbWVudCBiZXR3ZWVuCiAgaDI6IGFzeW5jIChhKSA9PiB7fSwKfQ + // __async(this, null, function* + // __async(this, arguments, function* + // __async(this, [_0, _1], function* + if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) { + fnString = fnString.split(/__async\((?:this|null),/)[1]; + } + const match = fnString.match(/[^(]*\(([^)]*)/); + if (!match) { + return []; + } + const args = splitByComma(match[1]); + if (!args.length) { + return []; + } + let first = args[0]; + if ("__VITEST_FIXTURE_INDEX__" in fn) { + first = args[fn.__VITEST_FIXTURE_INDEX__]; + if (!first) { + return []; + } + } + if (!(first[0] === "{" && first.endsWith("}"))) { + throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`); + } + const _first = first.slice(1, -1).replace(/\s/g, ""); + const props = splitByComma(_first).map((prop) => { + return prop.replace(/:.*|=.*/g, ""); + }); + const last = props.at(-1); + if (last && last.startsWith("...")) { + throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`); + } + return props; +} +function filterOutComments(s) { + const result = []; + let commentState = "none"; + for (let i = 0; i < s.length; ++i) { + if (commentState === "singleline") { + if (s[i] === "\n") { + commentState = "none"; + } + } else if (commentState === "multiline") { + if (s[i - 1] === "*" && s[i] === "/") { + commentState = "none"; + } + } else if (commentState === "none") { + if (s[i] === "/" && s[i + 1] === "/") { + commentState = "singleline"; + } else if (s[i] === "/" && s[i + 1] === "*") { + commentState = "multiline"; + i += 2; + } else { + result.push(s[i]); + } + } + } + return result.join(""); +} +function splitByComma(s) { + const result = []; + const stack = []; + let start = 0; + for (let i = 0; i < s.length; i++) { + if (s[i] === "{" || s[i] === "[") { + stack.push(s[i] === "{" ? "}" : "]"); + } else if (s[i] === stack.at(-1)) { + stack.pop(); + } else if (!stack.length && s[i] === ",") { + const token = s.substring(start, i).trim(); + if (token) { + result.push(token); + } + start = i + 1; + } + } + const lastToken = s.substring(start).trim(); + if (lastToken) { + result.push(lastToken); + } + return result; +} + +let _test; +function setCurrentTest(test) { + _test = test; +} +function getCurrentTest() { + return _test; +} +const tests = []; +function addRunningTest(test) { + tests.push(test); + return () => { + tests.splice(tests.indexOf(test)); + }; +} +function getRunningTests() { + return tests; +} + +function getDefaultHookTimeout() { + return getRunner().config.hookTimeout; +} +const CLEANUP_TIMEOUT_KEY = Symbol.for("VITEST_CLEANUP_TIMEOUT"); +const CLEANUP_STACK_TRACE_KEY = Symbol.for("VITEST_CLEANUP_STACK_TRACE"); +function getBeforeHookCleanupCallback(hook, result, context) { + if (typeof result === "function") { + const timeout = CLEANUP_TIMEOUT_KEY in hook && typeof hook[CLEANUP_TIMEOUT_KEY] === "number" ? hook[CLEANUP_TIMEOUT_KEY] : getDefaultHookTimeout(); + const stackTraceError = CLEANUP_STACK_TRACE_KEY in hook && hook[CLEANUP_STACK_TRACE_KEY] instanceof Error ? hook[CLEANUP_STACK_TRACE_KEY] : undefined; + return withTimeout(result, timeout, true, stackTraceError, (_, error) => { + if (context) { + abortContextSignal(context, error); + } + }); + } +} +/** +* Registers a callback function to be executed once before all tests within the current suite. +* This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment. +* +* **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed before all tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using beforeAll to set up a database connection +* beforeAll(async () => { +* await database.connect(); +* }); +* ``` +*/ +function beforeAll(fn, timeout = getDefaultHookTimeout()) { + assertTypes(fn, "\"beforeAll\" callback", ["function"]); + const stackTraceError = new Error("STACK_TRACE_ERROR"); + return getCurrentSuite().on("beforeAll", Object.assign(withTimeout(fn, timeout, true, stackTraceError), { + [CLEANUP_TIMEOUT_KEY]: timeout, + [CLEANUP_STACK_TRACE_KEY]: stackTraceError + })); +} +/** +* Registers a callback function to be executed once after all tests within the current suite have completed. +* This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files. +* +* **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed after all tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using afterAll to close a database connection +* afterAll(async () => { +* await database.disconnect(); +* }); +* ``` +*/ +function afterAll(fn, timeout) { + assertTypes(fn, "\"afterAll\" callback", ["function"]); + return getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"))); +} +/** +* Registers a callback function to be executed before each test within the current suite. +* This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. +* +* **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using beforeEach to reset a database state +* beforeEach(async () => { +* await database.reset(); +* }); +* ``` +*/ +function beforeEach(fn, timeout = getDefaultHookTimeout()) { + assertTypes(fn, "\"beforeEach\" callback", ["function"]); + const stackTraceError = new Error("STACK_TRACE_ERROR"); + const runner = getRunner(); + return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, stackTraceError, abortIfTimeout), { + [CLEANUP_TIMEOUT_KEY]: timeout, + [CLEANUP_STACK_TRACE_KEY]: stackTraceError + })); +} +/** +* Registers a callback function to be executed after each test within the current suite has completed. +* This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. +* +* **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using afterEach to delete temporary files created during a test +* afterEach(async () => { +* await fileSystem.deleteTempFiles(); +* }); +* ``` +*/ +function afterEach(fn, timeout) { + assertTypes(fn, "\"afterEach\" callback", ["function"]); + const runner = getRunner(); + return getCurrentSuite().on("afterEach", withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout)); +} +/** +* Registers a callback function to be executed when a test fails within the current suite. +* This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics. +* +* **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors). +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @throws {Error} Throws an error if the function is not called within a test. +* @returns {void} +* @example +* ```ts +* // Example of using onTestFailed to log failure details +* onTestFailed(({ errors }) => { +* console.log(`Test failed: ${test.name}`, errors); +* }); +* ``` +*/ +const onTestFailed = createTestHook("onTestFailed", (test, handler, timeout) => { + test.onFailed || (test.onFailed = []); + test.onFailed.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout)); +}); +/** +* Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail). +* This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources. +* +* This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`. +* +* **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call. +* +* @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @throws {Error} Throws an error if the function is not called within a test. +* @returns {void} +* @example +* ```ts +* // Example of using onTestFinished for cleanup +* const db = await connectToDatabase(); +* onTestFinished(async () => { +* await db.disconnect(); +* }); +* ``` +*/ +const onTestFinished = createTestHook("onTestFinished", (test, handler, timeout) => { + test.onFinished || (test.onFinished = []); + test.onFinished.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout)); +}); +function createTestHook(name, handler) { + return (fn, timeout) => { + assertTypes(fn, `"${name}" callback`, ["function"]); + const current = getCurrentTest(); + if (!current) { + throw new Error(`Hook ${name}() can only be called inside a test`); + } + return handler(current, fn, timeout); + }; +} + +/** +* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. +* Suites can contain both tests and other suites, enabling complex test structures. +* +* @param {string} name - The name of the suite, used for identification and reporting. +* @param {Function} fn - A function that defines the tests and suites within this suite. +* @example +* ```ts +* // Define a suite with two tests +* suite('Math operations', () => { +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* +* test('should subtract two numbers', () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* }); +* ``` +* @example +* ```ts +* // Define nested suites +* suite('String operations', () => { +* suite('Trimming', () => { +* test('should trim whitespace from start and end', () => { +* expect(' hello '.trim()).toBe('hello'); +* }); +* }); +* +* suite('Concatenation', () => { +* test('should concatenate two strings', () => { +* expect('hello' + ' ' + 'world').toBe('hello world'); +* }); +* }); +* }); +* ``` +*/ +const suite = createSuite(); +/** +* Defines a test case with a given name and test function. The test function can optionally be configured with test options. +* +* @param {string | Function} name - The name of the test or a function that will be used as a test name. +* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. +* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. +* @throws {Error} If called inside another test function. +* @example +* ```ts +* // Define a simple test +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* ``` +* @example +* ```ts +* // Define a test with options +* test('should subtract two numbers', { retry: 3 }, () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* ``` +*/ +const test = createTest(function(name, optionsOrFn, optionsOrTest) { + if (getCurrentTest()) { + throw new Error("Calling the test function inside another test function is not allowed. Please put it inside \"describe\" or \"suite\" so it can be properly collected."); + } + getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest); +}); +/** +* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. +* Suites can contain both tests and other suites, enabling complex test structures. +* +* @param {string} name - The name of the suite, used for identification and reporting. +* @param {Function} fn - A function that defines the tests and suites within this suite. +* @example +* ```ts +* // Define a suite with two tests +* describe('Math operations', () => { +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* +* test('should subtract two numbers', () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* }); +* ``` +* @example +* ```ts +* // Define nested suites +* describe('String operations', () => { +* describe('Trimming', () => { +* test('should trim whitespace from start and end', () => { +* expect(' hello '.trim()).toBe('hello'); +* }); +* }); +* +* describe('Concatenation', () => { +* test('should concatenate two strings', () => { +* expect('hello' + ' ' + 'world').toBe('hello world'); +* }); +* }); +* }); +* ``` +*/ +const describe = suite; +/** +* Defines a test case with a given name and test function. The test function can optionally be configured with test options. +* +* @param {string | Function} name - The name of the test or a function that will be used as a test name. +* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. +* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. +* @throws {Error} If called inside another test function. +* @example +* ```ts +* // Define a simple test +* it('adds two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* ``` +* @example +* ```ts +* // Define a test with options +* it('subtracts two numbers', { retry: 3 }, () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* ``` +*/ +const it = test; +let runner; +let defaultSuite; +let currentTestFilepath; +function assert(condition, message) { + if (!condition) { + throw new Error(`Vitest failed to find ${message}. One of the following is possible:` + "\n- \"vitest\" is imported directly without running \"vitest\" command" + "\n- \"vitest\" is imported inside \"globalSetup\" (to fix this, use \"setupFiles\" instead, because \"globalSetup\" runs in a different context)" + "\n- \"vitest\" is imported inside Vite / Vitest config file" + "\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n"); + } +} +function getDefaultSuite() { + assert(defaultSuite, "the default suite"); + return defaultSuite; +} +function getRunner() { + assert(runner, "the runner"); + return runner; +} +function createDefaultSuite(runner) { + const config = runner.config.sequence; + const collector = suite("", { concurrent: config.concurrent }, () => {}); + // no parent suite for top-level tests + delete collector.suite; + return collector; +} +function clearCollectorContext(file, currentRunner) { + if (!defaultSuite) { + defaultSuite = createDefaultSuite(currentRunner); + } + defaultSuite.file = file; + runner = currentRunner; + currentTestFilepath = file.filepath; + collectorContext.tasks.length = 0; + defaultSuite.clear(); + collectorContext.currentSuite = defaultSuite; +} +function getCurrentSuite() { + const currentSuite = collectorContext.currentSuite || defaultSuite; + assert(currentSuite, "the current suite"); + return currentSuite; +} +function createSuiteHooks() { + return { + beforeAll: [], + afterAll: [], + beforeEach: [], + afterEach: [] + }; +} +function parseArguments(optionsOrFn, timeoutOrTest) { + if (timeoutOrTest != null && typeof timeoutOrTest === "object") { + throw new TypeError(`Signature "test(name, fn, { ... })" was deprecated in Vitest 3 and removed in Vitest 4. Please, provide options as a second argument instead.`); + } + let options = {}; + let fn; + // it('', () => {}, 1000) + if (typeof timeoutOrTest === "number") { + options = { timeout: timeoutOrTest }; + } else if (typeof optionsOrFn === "object") { + options = optionsOrFn; + } + if (typeof optionsOrFn === "function") { + if (typeof timeoutOrTest === "function") { + throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options."); + } + fn = optionsOrFn; + } else if (typeof timeoutOrTest === "function") { + fn = timeoutOrTest; + } + return { + options, + handler: fn + }; +} +// implementations +function createSuiteCollector(name, factory = () => {}, mode, each, suiteOptions, parentCollectorFixtures) { + const tasks = []; + let suite; + initSuite(true); + const task = function(name = "", options = {}) { + var _collectorContext$cur, _collectorContext$cur2, _collectorContext$cur3; + const timeout = (options === null || options === void 0 ? void 0 : options.timeout) ?? runner.config.testTimeout; + const currentSuite = (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.suite; + const task = { + id: "", + name, + fullName: createTaskName([(currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullName) ?? ((_collectorContext$cur2 = collectorContext.currentSuite) === null || _collectorContext$cur2 === void 0 || (_collectorContext$cur2 = _collectorContext$cur2.file) === null || _collectorContext$cur2 === void 0 ? void 0 : _collectorContext$cur2.fullName), name]), + fullTestName: createTaskName([currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullTestName, name]), + suite: currentSuite, + each: options.each, + fails: options.fails, + context: undefined, + type: "test", + file: (currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.file) ?? ((_collectorContext$cur3 = collectorContext.currentSuite) === null || _collectorContext$cur3 === void 0 ? void 0 : _collectorContext$cur3.file), + timeout, + retry: options.retry ?? runner.config.retry, + repeats: options.repeats, + mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run", + meta: options.meta ?? Object.create(null), + annotations: [], + artifacts: [] + }; + const handler = options.handler; + if (task.mode === "run" && !handler) { + task.mode = "todo"; + } + if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) { + task.concurrent = true; + } + task.shuffle = suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle; + const context = createTestContext(task, runner); + // create test context + Object.defineProperty(task, "context", { + value: context, + enumerable: false + }); + setTestFixture(context, options.fixtures); + // custom can be called from any place, let's assume the limit is 15 stacks + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 15; + const stackTraceError = new Error("STACK_TRACE_ERROR"); + Error.stackTraceLimit = limit; + if (handler) { + setFn(task, withTimeout(withAwaitAsyncAssertions(withFixtures(runner, handler, context), task), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error))); + } + if (runner.config.includeTaskLocation) { + const error = stackTraceError.stack; + const stack = findTestFileStackTrace(currentTestFilepath, error); + if (stack) { + task.location = { + line: stack.line, + column: stack.column + }; + } + } + tasks.push(task); + return task; + }; + const test = createTest(function(name, optionsOrFn, timeoutOrTest) { + let { options, handler } = parseArguments(optionsOrFn, timeoutOrTest); + // inherit repeats, retry, timeout from suite + if (typeof suiteOptions === "object") { + options = Object.assign({}, suiteOptions, options); + } + // inherit concurrent / sequential from suite + options.concurrent = this.concurrent || !this.sequential && (options === null || options === void 0 ? void 0 : options.concurrent); + options.sequential = this.sequential || !this.concurrent && (options === null || options === void 0 ? void 0 : options.sequential); + const test = task(formatName(name), { + ...this, + ...options, + handler + }); + test.type = "test"; + }); + let collectorFixtures = parentCollectorFixtures; + const collector = { + type: "collector", + name, + mode, + suite, + options: suiteOptions, + test, + tasks, + collect, + task, + clear, + on: addHook, + fixtures() { + return collectorFixtures; + }, + scoped(fixtures) { + const parsed = mergeContextFixtures(fixtures, { fixtures: collectorFixtures }, runner); + if (parsed.fixtures) { + collectorFixtures = parsed.fixtures; + } + } + }; + function addHook(name, ...fn) { + getHooks(suite)[name].push(...fn); + } + function initSuite(includeLocation) { + var _collectorContext$cur4, _collectorContext$cur5, _collectorContext$cur6; + if (typeof suiteOptions === "number") { + suiteOptions = { timeout: suiteOptions }; + } + const currentSuite = (_collectorContext$cur4 = collectorContext.currentSuite) === null || _collectorContext$cur4 === void 0 ? void 0 : _collectorContext$cur4.suite; + suite = { + id: "", + type: "suite", + name, + fullName: createTaskName([(currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullName) ?? ((_collectorContext$cur5 = collectorContext.currentSuite) === null || _collectorContext$cur5 === void 0 || (_collectorContext$cur5 = _collectorContext$cur5.file) === null || _collectorContext$cur5 === void 0 ? void 0 : _collectorContext$cur5.fullName), name]), + fullTestName: createTaskName([currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullTestName, name]), + suite: currentSuite, + mode, + each, + file: (currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.file) ?? ((_collectorContext$cur6 = collectorContext.currentSuite) === null || _collectorContext$cur6 === void 0 ? void 0 : _collectorContext$cur6.file), + shuffle: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle, + tasks: [], + meta: Object.create(null), + concurrent: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.concurrent + }; + if (runner && includeLocation && runner.config.includeTaskLocation) { + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 15; + const error = new Error("stacktrace").stack; + Error.stackTraceLimit = limit; + const stack = findTestFileStackTrace(currentTestFilepath, error); + if (stack) { + suite.location = { + line: stack.line, + column: stack.column + }; + } + } + setHooks(suite, createSuiteHooks()); + } + function clear() { + tasks.length = 0; + initSuite(false); + } + async function collect(file) { + if (!file) { + throw new TypeError("File is required to collect tasks."); + } + if (factory) { + await runWithSuite(collector, () => factory(test)); + } + const allChildren = []; + for (const i of tasks) { + allChildren.push(i.type === "collector" ? await i.collect(file) : i); + } + suite.tasks = allChildren; + return suite; + } + collectTask(collector); + return collector; +} +function withAwaitAsyncAssertions(fn, task) { + return (async (...args) => { + const fnResult = await fn(...args); + // some async expect will be added to this array, in case user forget to await them + if (task.promises) { + const result = await Promise.allSettled(task.promises); + const errors = result.map((r) => r.status === "rejected" ? r.reason : undefined).filter(Boolean); + if (errors.length) { + throw errors; + } + } + return fnResult; + }); +} +function createSuite() { + function suiteFn(name, factoryOrOptions, optionsOrFactory) { + var _currentSuite$options; + if (getCurrentTest()) { + throw new Error("Calling the suite function inside test function is not allowed. It can be only called at the top level or inside another suite function."); + } + let mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run"; + const currentSuite = collectorContext.currentSuite || defaultSuite; + let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory); + if (mode === "run" && !factory) { + mode = "todo"; + } + const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false; + const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false; + // inherit options from current suite + options = { + ...currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.options, + ...options, + shuffle: this.shuffle ?? options.shuffle ?? (currentSuite === null || currentSuite === void 0 || (_currentSuite$options = currentSuite.options) === null || _currentSuite$options === void 0 ? void 0 : _currentSuite$options.shuffle) ?? (runner === null || runner === void 0 ? void 0 : runner.config.sequence.shuffle) + }; + // inherit concurrent / sequential from suite + const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified; + const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified; + options.concurrent = isConcurrent && !isSequential; + options.sequential = isSequential && !isConcurrent; + return createSuiteCollector(formatName(name), factory, mode, this.each, options, currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fixtures()); + } + suiteFn.each = function(cases, ...args) { + const suite = this.withContext(); + this.setContext("each", true); + if (Array.isArray(cases) && args.length) { + cases = formatTemplateString(cases, args); + } + return (name, optionsOrFn, fnOrOptions) => { + const _name = formatName(name); + const arrayOnlyCases = cases.every(Array.isArray); + const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); + const fnFirst = typeof optionsOrFn === "function"; + cases.forEach((i, idx) => { + const items = Array.isArray(i) ? i : [i]; + if (fnFirst) { + if (arrayOnlyCases) { + suite(formatTitle(_name, items, idx), handler ? () => handler(...items) : undefined, options.timeout); + } else { + suite(formatTitle(_name, items, idx), handler ? () => handler(i) : undefined, options.timeout); + } + } else { + if (arrayOnlyCases) { + suite(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : undefined); + } else { + suite(formatTitle(_name, items, idx), options, handler ? () => handler(i) : undefined); + } + } + }); + this.setContext("each", undefined); + }; + }; + suiteFn.for = function(cases, ...args) { + if (Array.isArray(cases) && args.length) { + cases = formatTemplateString(cases, args); + } + return (name, optionsOrFn, fnOrOptions) => { + const name_ = formatName(name); + const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); + cases.forEach((item, idx) => { + suite(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : undefined); + }); + }; + }; + suiteFn.skipIf = (condition) => condition ? suite.skip : suite; + suiteFn.runIf = (condition) => condition ? suite : suite.skip; + return createChainable([ + "concurrent", + "sequential", + "shuffle", + "skip", + "only", + "todo" + ], suiteFn); +} +function createTaskCollector(fn, context) { + const taskFn = fn; + taskFn.each = function(cases, ...args) { + const test = this.withContext(); + this.setContext("each", true); + if (Array.isArray(cases) && args.length) { + cases = formatTemplateString(cases, args); + } + return (name, optionsOrFn, fnOrOptions) => { + const _name = formatName(name); + const arrayOnlyCases = cases.every(Array.isArray); + const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); + const fnFirst = typeof optionsOrFn === "function"; + cases.forEach((i, idx) => { + const items = Array.isArray(i) ? i : [i]; + if (fnFirst) { + if (arrayOnlyCases) { + test(formatTitle(_name, items, idx), handler ? () => handler(...items) : undefined, options.timeout); + } else { + test(formatTitle(_name, items, idx), handler ? () => handler(i) : undefined, options.timeout); + } + } else { + if (arrayOnlyCases) { + test(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : undefined); + } else { + test(formatTitle(_name, items, idx), options, handler ? () => handler(i) : undefined); + } + } + }); + this.setContext("each", undefined); + }; + }; + taskFn.for = function(cases, ...args) { + const test = this.withContext(); + if (Array.isArray(cases) && args.length) { + cases = formatTemplateString(cases, args); + } + return (name, optionsOrFn, fnOrOptions) => { + const _name = formatName(name); + const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); + cases.forEach((item, idx) => { + // monkey-patch handler to allow parsing fixture + const handlerWrapper = handler ? (ctx) => handler(item, ctx) : undefined; + if (handlerWrapper) { + handlerWrapper.__VITEST_FIXTURE_INDEX__ = 1; + handlerWrapper.toString = () => handler.toString(); + } + test(formatTitle(_name, toArray(item), idx), options, handlerWrapper); + }); + }; + }; + taskFn.skipIf = function(condition) { + return condition ? this.skip : this; + }; + taskFn.runIf = function(condition) { + return condition ? this : this.skip; + }; + taskFn.scoped = function(fixtures) { + const collector = getCurrentSuite(); + collector.scoped(fixtures); + }; + taskFn.extend = function(fixtures) { + const _context = mergeContextFixtures(fixtures, context || {}, runner); + const originalWrapper = fn; + return createTest(function(name, optionsOrFn, optionsOrTest) { + const collector = getCurrentSuite(); + const scopedFixtures = collector.fixtures(); + const context = { ...this }; + if (scopedFixtures) { + context.fixtures = mergeScopedFixtures(context.fixtures || [], scopedFixtures); + } + originalWrapper.call(context, formatName(name), optionsOrFn, optionsOrTest); + }, _context); + }; + taskFn.beforeEach = beforeEach; + taskFn.afterEach = afterEach; + taskFn.beforeAll = beforeAll; + taskFn.afterAll = afterAll; + const _test = createChainable([ + "concurrent", + "sequential", + "skip", + "only", + "todo", + "fails" + ], taskFn); + if (context) { + _test.mergeContext(context); + } + return _test; +} +function createTest(fn, context) { + return createTaskCollector(fn, context); +} +function formatName(name) { + return typeof name === "string" ? name : typeof name === "function" ? name.name || "" : String(name); +} +function formatTitle(template, items, idx) { + if (template.includes("%#") || template.includes("%$")) { + // '%#' match index of the test case + template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%"); + } + const count = template.split("%").length - 1; + if (template.includes("%f")) { + const placeholders = template.match(/%f/g) || []; + placeholders.forEach((_, i) => { + if (isNegativeNaN(items[i]) || Object.is(items[i], -0)) { + // Replace the i-th occurrence of '%f' with '-%f' + let occurrence = 0; + template = template.replace(/%f/g, (match) => { + occurrence++; + return occurrence === i + 1 ? "-%f" : match; + }); + } + }); + } + const isObjectItem = isObject(items[0]); + function formatAttribute(s) { + return s.replace(/\$([$\w.]+)/g, (_, key) => { + var _runner$config; + const isArrayKey = /^\d+$/.test(key); + if (!isObjectItem && !isArrayKey) { + return `$${key}`; + } + const arrayElement = isArrayKey ? objectAttr(items, key) : undefined; + const value = isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement; + return objDisplay(value, { truncate: runner === null || runner === void 0 || (_runner$config = runner.config) === null || _runner$config === void 0 || (_runner$config = _runner$config.chaiConfig) === null || _runner$config === void 0 ? void 0 : _runner$config.truncateThreshold }); + }); + } + let output = ""; + let i = 0; + handleRegexMatch( + template, + formatRegExp, + // format "%" + (match) => { + if (i < count) { + output += format(match[0], items[i++]); + } else { + output += match[0]; + } + }, + // format "$" + (nonMatch) => { + output += formatAttribute(nonMatch); + } + ); + return output; +} +// based on https://github.com/unocss/unocss/blob/2e74b31625bbe3b9c8351570749aa2d3f799d919/packages/autocomplete/src/parse.ts#L11 +function handleRegexMatch(input, regex, onMatch, onNonMatch) { + let lastIndex = 0; + for (const m of input.matchAll(regex)) { + if (lastIndex < m.index) { + onNonMatch(input.slice(lastIndex, m.index)); + } + onMatch(m); + lastIndex = m.index + m[0].length; + } + if (lastIndex < input.length) { + onNonMatch(input.slice(lastIndex)); + } +} +function formatTemplateString(cases, args) { + const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0]; + const res = []; + for (let i = 0; i < Math.floor(args.length / header.length); i++) { + const oneCase = {}; + for (let j = 0; j < header.length; j++) { + oneCase[header[j]] = args[i * header.length + j]; + } + res.push(oneCase); + } + return res; +} + +const now$2 = Date.now; +const collectorContext = { + tasks: [], + currentSuite: null +}; +function collectTask(task) { + var _collectorContext$cur; + (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.tasks.push(task); +} +async function runWithSuite(suite, fn) { + const prev = collectorContext.currentSuite; + collectorContext.currentSuite = suite; + await fn(); + collectorContext.currentSuite = prev; +} +function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) { + if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) { + return fn; + } + const { setTimeout, clearTimeout } = getSafeTimers(); + // this function name is used to filter error in test/cli/test/fails.test.ts + return (function runWithTimeout(...args) { + const startTime = now$2(); + const runner = getRunner(); + runner._currentTaskStartTime = startTime; + runner._currentTaskTimeout = timeout; + return new Promise((resolve_, reject_) => { + var _timer$unref; + const timer = setTimeout(() => { + clearTimeout(timer); + rejectTimeoutError(); + }, timeout); + // `unref` might not exist in browser + (_timer$unref = timer.unref) === null || _timer$unref === void 0 ? void 0 : _timer$unref.call(timer); + function rejectTimeoutError() { + const error = makeTimeoutError(isHook, timeout, stackTraceError); + onTimeout === null || onTimeout === void 0 ? void 0 : onTimeout(args, error); + reject_(error); + } + function resolve(result) { + runner._currentTaskStartTime = undefined; + runner._currentTaskTimeout = undefined; + clearTimeout(timer); + // if test/hook took too long in microtask, setTimeout won't be triggered, + // but we still need to fail the test, see + // https://github.com/vitest-dev/vitest/issues/2920 + if (now$2() - startTime >= timeout) { + rejectTimeoutError(); + return; + } + resolve_(result); + } + function reject(error) { + runner._currentTaskStartTime = undefined; + runner._currentTaskTimeout = undefined; + clearTimeout(timer); + reject_(error); + } + // sync test/hook will be caught by try/catch + try { + const result = fn(...args); + // the result is a thenable, we don't wrap this in Promise.resolve + // to avoid creating new promises + if (typeof result === "object" && result != null && typeof result.then === "function") { + result.then(resolve, reject); + } else { + resolve(result); + } + } + // user sync test/hook throws an error +catch (error) { + reject(error); + } + }); + }); +} +const abortControllers = new WeakMap(); +function abortIfTimeout([context], error) { + if (context) { + abortContextSignal(context, error); + } +} +function abortContextSignal(context, error) { + const abortController = abortControllers.get(context); + abortController === null || abortController === void 0 ? void 0 : abortController.abort(error); +} +function createTestContext(test, runner) { + var _runner$extendTaskCon; + const context = function() { + throw new Error("done() callback is deprecated, use promise instead"); + }; + let abortController = abortControllers.get(context); + if (!abortController) { + abortController = new AbortController(); + abortControllers.set(context, abortController); + } + context.signal = abortController.signal; + context.task = test; + context.skip = (condition, note) => { + if (condition === false) { + // do nothing + return undefined; + } + test.result ?? (test.result = { state: "skip" }); + test.result.pending = true; + throw new PendingError("test is skipped; abort execution", test, typeof condition === "string" ? condition : note); + }; + context.annotate = ((message, type, attachment) => { + if (test.result && test.result.state !== "run") { + throw new Error(`Cannot annotate tests outside of the test run. The test "${test.name}" finished running with the "${test.result.state}" state already.`); + } + const annotation = { + message, + type: typeof type === "object" || type === undefined ? "notice" : type + }; + const annotationAttachment = typeof type === "object" ? type : attachment; + if (annotationAttachment) { + annotation.attachment = annotationAttachment; + manageArtifactAttachment(annotation.attachment); + } + return recordAsyncOperation(test, recordArtifact(test, { + type: "internal:annotation", + annotation + }).then(async ({ annotation }) => { + if (!runner.onTestAnnotate) { + throw new Error(`Test runner doesn't support test annotations.`); + } + await finishSendTasksUpdate(runner); + const resolvedAnnotation = await runner.onTestAnnotate(test, annotation); + test.annotations.push(resolvedAnnotation); + return resolvedAnnotation; + })); + }); + context.onTestFailed = (handler, timeout) => { + test.onFailed || (test.onFailed = []); + test.onFailed.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error))); + }; + context.onTestFinished = (handler, timeout) => { + test.onFinished || (test.onFinished = []); + test.onFinished.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error))); + }; + return ((_runner$extendTaskCon = runner.extendTaskContext) === null || _runner$extendTaskCon === void 0 ? void 0 : _runner$extendTaskCon.call(runner, context)) || context; +} +function makeTimeoutError(isHook, timeout, stackTraceError) { + const message = `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.\nIf this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`; + const error = new Error(message); + if (stackTraceError === null || stackTraceError === void 0 ? void 0 : stackTraceError.stack) { + error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message); + } + return error; +} +const fileContexts = new WeakMap(); +function getFileContext(file) { + const context = fileContexts.get(file); + if (!context) { + throw new Error(`Cannot find file context for ${file.name}`); + } + return context; +} +function setFileContext(file, context) { + fileContexts.set(file, context); +} + +async function runSetupFiles(config, files, runner) { + if (config.sequence.setupFiles === "parallel") { + await Promise.all(files.map(async (fsPath) => { + await runner.importFile(fsPath, "setup"); + })); + } else { + for (const fsPath of files) { + await runner.importFile(fsPath, "setup"); + } + } +} + +const now$1 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now; +async function collectTests(specs, runner) { + const files = []; + const config = runner.config; + const $ = runner.trace; + for (const spec of specs) { + const filepath = typeof spec === "string" ? spec : spec.filepath; + await $("collect_spec", { "code.file.path": filepath }, async () => { + var _runner$onCollectStar; + const testLocations = typeof spec === "string" ? undefined : spec.testLocations; + const file = createFileTask(filepath, config.root, config.name, runner.pool, runner.viteEnvironment); + setFileContext(file, Object.create(null)); + file.shuffle = config.sequence.shuffle; + (_runner$onCollectStar = runner.onCollectStart) === null || _runner$onCollectStar === void 0 ? void 0 : _runner$onCollectStar.call(runner, file); + clearCollectorContext(file, runner); + try { + var _runner$getImportDura; + const setupFiles = toArray(config.setupFiles); + if (setupFiles.length) { + const setupStart = now$1(); + await runSetupFiles(config, setupFiles, runner); + const setupEnd = now$1(); + file.setupDuration = setupEnd - setupStart; + } else { + file.setupDuration = 0; + } + const collectStart = now$1(); + await runner.importFile(filepath, "collect"); + const durations = (_runner$getImportDura = runner.getImportDurations) === null || _runner$getImportDura === void 0 ? void 0 : _runner$getImportDura.call(runner); + if (durations) { + file.importDurations = durations; + } + const defaultTasks = await getDefaultSuite().collect(file); + const fileHooks = createSuiteHooks(); + mergeHooks(fileHooks, getHooks(defaultTasks)); + for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) { + if (c.type === "test" || c.type === "suite") { + file.tasks.push(c); + } else if (c.type === "collector") { + const suite = await c.collect(file); + if (suite.name || suite.tasks.length) { + mergeHooks(fileHooks, getHooks(suite)); + file.tasks.push(suite); + } + } else { + // check that types are exhausted + c; + } + } + setHooks(file, fileHooks); + file.collectDuration = now$1() - collectStart; + } catch (e) { + var _runner$getImportDura2; + const error = processError(e); + file.result = { + state: "fail", + errors: [error] + }; + const durations = (_runner$getImportDura2 = runner.getImportDurations) === null || _runner$getImportDura2 === void 0 ? void 0 : _runner$getImportDura2.call(runner); + if (durations) { + file.importDurations = durations; + } + } + calculateSuiteHash(file); + const hasOnlyTasks = someTasksAreOnly(file); + interpretTaskModes(file, config.testNamePattern, testLocations, hasOnlyTasks, false, config.allowOnly); + if (file.mode === "queued") { + file.mode = "run"; + } + files.push(file); + }); + } + return files; +} +function mergeHooks(baseHooks, hooks) { + for (const _key in hooks) { + const key = _key; + baseHooks[key].push(...hooks[key]); + } + return baseHooks; +} + +const now = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now; +const unixNow = Date.now; +const { clearTimeout, setTimeout } = getSafeTimers(); +function updateSuiteHookState(task, name, state, runner) { + if (!task.result) { + task.result = { state: "run" }; + } + if (!task.result.hooks) { + task.result.hooks = {}; + } + const suiteHooks = task.result.hooks; + if (suiteHooks) { + suiteHooks[name] = state; + let event = state === "run" ? "before-hook-start" : "before-hook-end"; + if (name === "afterAll" || name === "afterEach") { + event = state === "run" ? "after-hook-start" : "after-hook-end"; + } + updateTask(event, task, runner); + } +} +function getSuiteHooks(suite, name, sequence) { + const hooks = getHooks(suite)[name]; + if (sequence === "stack" && (name === "afterAll" || name === "afterEach")) { + return hooks.slice().reverse(); + } + return hooks; +} +async function callTestHooks(runner, test, hooks, sequence) { + if (sequence === "stack") { + hooks = hooks.slice().reverse(); + } + if (!hooks.length) { + return; + } + const context = test.context; + const onTestFailed = test.context.onTestFailed; + const onTestFinished = test.context.onTestFinished; + context.onTestFailed = () => { + throw new Error(`Cannot call "onTestFailed" inside a test hook.`); + }; + context.onTestFinished = () => { + throw new Error(`Cannot call "onTestFinished" inside a test hook.`); + }; + if (sequence === "parallel") { + try { + await Promise.all(hooks.map((fn) => fn(test.context))); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + } else { + for (const fn of hooks) { + try { + await fn(test.context); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + } + } + context.onTestFailed = onTestFailed; + context.onTestFinished = onTestFinished; +} +async function callSuiteHook(suite, currentTask, name, runner, args) { + const sequence = runner.config.sequence.hooks; + const callbacks = []; + // stop at file level + const parentSuite = "filepath" in suite ? null : suite.suite || suite.file; + if (name === "beforeEach" && parentSuite) { + callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args)); + } + const hooks = getSuiteHooks(suite, name, sequence); + if (hooks.length > 0) { + updateSuiteHookState(currentTask, name, "run", runner); + } + async function runHook(hook) { + return getBeforeHookCleanupCallback(hook, await hook(...args), name === "beforeEach" ? args[0] : undefined); + } + if (sequence === "parallel") { + callbacks.push(...await Promise.all(hooks.map((hook) => runHook(hook)))); + } else { + for (const hook of hooks) { + callbacks.push(await runHook(hook)); + } + } + if (hooks.length > 0) { + updateSuiteHookState(currentTask, name, "pass", runner); + } + if (name === "afterEach" && parentSuite) { + callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args)); + } + return callbacks; +} +const packs = new Map(); +const eventsPacks = []; +const pendingTasksUpdates = []; +function sendTasksUpdate(runner) { + if (packs.size) { + var _runner$onTaskUpdate; + const taskPacks = Array.from(packs).map(([id, task]) => { + return [ + id, + task[0], + task[1] + ]; + }); + const p = (_runner$onTaskUpdate = runner.onTaskUpdate) === null || _runner$onTaskUpdate === void 0 ? void 0 : _runner$onTaskUpdate.call(runner, taskPacks, eventsPacks); + if (p) { + pendingTasksUpdates.push(p); + // remove successful promise to not grow array indefnitely, + // but keep rejections so finishSendTasksUpdate can handle them + p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {}); + } + eventsPacks.length = 0; + packs.clear(); + } +} +async function finishSendTasksUpdate(runner) { + sendTasksUpdate(runner); + await Promise.all(pendingTasksUpdates); +} +function throttle(fn, ms) { + let last = 0; + let pendingCall; + return function call(...args) { + const now = unixNow(); + if (now - last > ms) { + last = now; + clearTimeout(pendingCall); + pendingCall = undefined; + return fn.apply(this, args); + } + // Make sure fn is still called even if there are no further calls + pendingCall ?? (pendingCall = setTimeout(() => call.bind(this)(...args), ms)); + }; +} +// throttle based on summary reporter's DURATION_UPDATE_INTERVAL_MS +const sendTasksUpdateThrottled = throttle(sendTasksUpdate, 100); +function updateTask(event, task, runner) { + eventsPacks.push([ + task.id, + event, + undefined + ]); + packs.set(task.id, [task.result, task.meta]); + sendTasksUpdateThrottled(runner); +} +async function callCleanupHooks(runner, cleanups) { + const sequence = runner.config.sequence.hooks; + if (sequence === "stack") { + cleanups = cleanups.slice().reverse(); + } + if (sequence === "parallel") { + await Promise.all(cleanups.map(async (fn) => { + if (typeof fn !== "function") { + return; + } + await fn(); + })); + } else { + for (const fn of cleanups) { + if (typeof fn !== "function") { + continue; + } + await fn(); + } + } +} +async function runTest(test, runner) { + var _runner$onBeforeRunTa, _test$result, _runner$onAfterRunTas; + await ((_runner$onBeforeRunTa = runner.onBeforeRunTask) === null || _runner$onBeforeRunTa === void 0 ? void 0 : _runner$onBeforeRunTa.call(runner, test)); + if (test.mode !== "run" && test.mode !== "queued") { + updateTask("test-prepare", test, runner); + updateTask("test-finished", test, runner); + return; + } + if (((_test$result = test.result) === null || _test$result === void 0 ? void 0 : _test$result.state) === "fail") { + // should not be possible to get here, I think this is just copy pasted from suite + // TODO: maybe someone fails tests in `beforeAll` hooks? + // https://github.com/vitest-dev/vitest/pull/7069 + updateTask("test-failed-early", test, runner); + return; + } + const start = now(); + test.result = { + state: "run", + startTime: unixNow(), + retryCount: 0 + }; + updateTask("test-prepare", test, runner); + const cleanupRunningTest = addRunningTest(test); + setCurrentTest(test); + const suite = test.suite || test.file; + const $ = runner.trace; + const repeats = test.repeats ?? 0; + for (let repeatCount = 0; repeatCount <= repeats; repeatCount++) { + const retry = test.retry ?? 0; + for (let retryCount = 0; retryCount <= retry; retryCount++) { + var _test$onFinished, _test$onFailed, _runner$onAfterRetryT, _test$result2, _test$result3; + let beforeEachCleanups = []; + try { + var _runner$onBeforeTryTa, _runner$onAfterTryTas; + await ((_runner$onBeforeTryTa = runner.onBeforeTryTask) === null || _runner$onBeforeTryTa === void 0 ? void 0 : _runner$onBeforeTryTa.call(runner, test, { + retry: retryCount, + repeats: repeatCount + })); + test.result.repeatCount = repeatCount; + beforeEachCleanups = await $("test.beforeEach", () => callSuiteHook(suite, test, "beforeEach", runner, [test.context, suite])); + if (runner.runTask) { + await $("test.callback", () => runner.runTask(test)); + } else { + const fn = getFn(test); + if (!fn) { + throw new Error("Test function is not found. Did you add it using `setFn`?"); + } + await $("test.callback", () => fn()); + } + await ((_runner$onAfterTryTas = runner.onAfterTryTask) === null || _runner$onAfterTryTas === void 0 ? void 0 : _runner$onAfterTryTas.call(runner, test, { + retry: retryCount, + repeats: repeatCount + })); + if (test.result.state !== "fail") { + if (!test.repeats) { + test.result.state = "pass"; + } else if (test.repeats && retry === retryCount) { + test.result.state = "pass"; + } + } + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + try { + var _runner$onTaskFinishe; + await ((_runner$onTaskFinishe = runner.onTaskFinished) === null || _runner$onTaskFinishe === void 0 ? void 0 : _runner$onTaskFinishe.call(runner, test)); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + try { + await $("test.afterEach", () => callSuiteHook(suite, test, "afterEach", runner, [test.context, suite])); + if (beforeEachCleanups.length) { + await $("test.cleanup", () => callCleanupHooks(runner, beforeEachCleanups)); + } + await callFixtureCleanup(test.context); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + if ((_test$onFinished = test.onFinished) === null || _test$onFinished === void 0 ? void 0 : _test$onFinished.length) { + await $("test.onFinished", () => callTestHooks(runner, test, test.onFinished, "stack")); + } + if (test.result.state === "fail" && ((_test$onFailed = test.onFailed) === null || _test$onFailed === void 0 ? void 0 : _test$onFailed.length)) { + await $("test.onFailed", () => callTestHooks(runner, test, test.onFailed, runner.config.sequence.hooks)); + } + test.onFailed = undefined; + test.onFinished = undefined; + await ((_runner$onAfterRetryT = runner.onAfterRetryTask) === null || _runner$onAfterRetryT === void 0 ? void 0 : _runner$onAfterRetryT.call(runner, test, { + retry: retryCount, + repeats: repeatCount + })); + // skipped with new PendingError + if (((_test$result2 = test.result) === null || _test$result2 === void 0 ? void 0 : _test$result2.pending) || ((_test$result3 = test.result) === null || _test$result3 === void 0 ? void 0 : _test$result3.state) === "skip") { + var _test$result4; + test.mode = "skip"; + test.result = { + state: "skip", + note: (_test$result4 = test.result) === null || _test$result4 === void 0 ? void 0 : _test$result4.note, + pending: true, + duration: now() - start + }; + updateTask("test-finished", test, runner); + setCurrentTest(undefined); + cleanupRunningTest(); + return; + } + if (test.result.state === "pass") { + break; + } + if (retryCount < retry) { + // reset state when retry test + test.result.state = "run"; + test.result.retryCount = (test.result.retryCount ?? 0) + 1; + } + // update retry info + updateTask("test-retried", test, runner); + } + } + // if test is marked to be failed, flip the result + if (test.fails) { + if (test.result.state === "pass") { + const error = processError(new Error("Expect test to fail")); + test.result.state = "fail"; + test.result.errors = [error]; + } else { + test.result.state = "pass"; + test.result.errors = undefined; + } + } + cleanupRunningTest(); + setCurrentTest(undefined); + test.result.duration = now() - start; + await ((_runner$onAfterRunTas = runner.onAfterRunTask) === null || _runner$onAfterRunTas === void 0 ? void 0 : _runner$onAfterRunTas.call(runner, test)); + updateTask("test-finished", test, runner); +} +function failTask(result, err, diffOptions) { + if (err instanceof PendingError) { + result.state = "skip"; + result.note = err.note; + result.pending = true; + return; + } + result.state = "fail"; + const errors = Array.isArray(err) ? err : [err]; + for (const e of errors) { + const error = processError(e, diffOptions); + result.errors ?? (result.errors = []); + result.errors.push(error); + } +} +function markTasksAsSkipped(suite, runner) { + suite.tasks.forEach((t) => { + t.mode = "skip"; + t.result = { + ...t.result, + state: "skip" + }; + updateTask("test-finished", t, runner); + if (t.type === "suite") { + markTasksAsSkipped(t, runner); + } + }); +} +async function runSuite(suite, runner) { + var _runner$onBeforeRunSu, _suite$result; + await ((_runner$onBeforeRunSu = runner.onBeforeRunSuite) === null || _runner$onBeforeRunSu === void 0 ? void 0 : _runner$onBeforeRunSu.call(runner, suite)); + if (((_suite$result = suite.result) === null || _suite$result === void 0 ? void 0 : _suite$result.state) === "fail") { + markTasksAsSkipped(suite, runner); + // failed during collection + updateTask("suite-failed-early", suite, runner); + return; + } + const start = now(); + const mode = suite.mode; + suite.result = { + state: mode === "skip" || mode === "todo" ? mode : "run", + startTime: unixNow() + }; + const $ = runner.trace; + updateTask("suite-prepare", suite, runner); + let beforeAllCleanups = []; + if (suite.mode === "skip") { + suite.result.state = "skip"; + updateTask("suite-finished", suite, runner); + } else if (suite.mode === "todo") { + suite.result.state = "todo"; + updateTask("suite-finished", suite, runner); + } else { + var _runner$onAfterRunSui; + try { + try { + beforeAllCleanups = await $("suite.beforeAll", () => callSuiteHook(suite, suite, "beforeAll", runner, [suite])); + } catch (e) { + markTasksAsSkipped(suite, runner); + throw e; + } + if (runner.runSuite) { + await runner.runSuite(suite); + } else { + for (let tasksGroup of partitionSuiteChildren(suite)) { + if (tasksGroup[0].concurrent === true) { + await Promise.all(tasksGroup.map((c) => runSuiteChild(c, runner))); + } else { + const { sequence } = runner.config; + if (suite.shuffle) { + // run describe block independently from tests + const suites = tasksGroup.filter((group) => group.type === "suite"); + const tests = tasksGroup.filter((group) => group.type === "test"); + const groups = shuffle([suites, tests], sequence.seed); + tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed)); + } + for (const c of tasksGroup) { + await runSuiteChild(c, runner); + } + } + } + } + } catch (e) { + failTask(suite.result, e, runner.config.diffOptions); + } + try { + await $("suite.afterAll", () => callSuiteHook(suite, suite, "afterAll", runner, [suite])); + if (beforeAllCleanups.length) { + await $("suite.cleanup", () => callCleanupHooks(runner, beforeAllCleanups)); + } + if (suite.file === suite) { + const context = getFileContext(suite); + await callFixtureCleanup(context); + } + } catch (e) { + failTask(suite.result, e, runner.config.diffOptions); + } + if (suite.mode === "run" || suite.mode === "queued") { + if (!runner.config.passWithNoTests && !hasTests(suite)) { + var _suite$result$errors; + suite.result.state = "fail"; + if (!((_suite$result$errors = suite.result.errors) === null || _suite$result$errors === void 0 ? void 0 : _suite$result$errors.length)) { + const error = processError(new Error(`No test found in suite ${suite.name}`)); + suite.result.errors = [error]; + } + } else if (hasFailed(suite)) { + suite.result.state = "fail"; + } else { + suite.result.state = "pass"; + } + } + suite.result.duration = now() - start; + await ((_runner$onAfterRunSui = runner.onAfterRunSuite) === null || _runner$onAfterRunSui === void 0 ? void 0 : _runner$onAfterRunSui.call(runner, suite)); + updateTask("suite-finished", suite, runner); + } +} +let limitMaxConcurrency; +async function runSuiteChild(c, runner) { + const $ = runner.trace; + if (c.type === "test") { + return limitMaxConcurrency(() => { + var _c$location, _c$location2; + return $("run.test", { + "vitest.test.id": c.id, + "vitest.test.name": c.name, + "vitest.test.mode": c.mode, + "vitest.test.timeout": c.timeout, + "code.file.path": c.file.filepath, + "code.line.number": (_c$location = c.location) === null || _c$location === void 0 ? void 0 : _c$location.line, + "code.column.number": (_c$location2 = c.location) === null || _c$location2 === void 0 ? void 0 : _c$location2.column + }, () => runTest(c, runner)); + }); + } else if (c.type === "suite") { + var _c$location3, _c$location4; + return $("run.suite", { + "vitest.suite.id": c.id, + "vitest.suite.name": c.name, + "vitest.suite.mode": c.mode, + "code.file.path": c.file.filepath, + "code.line.number": (_c$location3 = c.location) === null || _c$location3 === void 0 ? void 0 : _c$location3.line, + "code.column.number": (_c$location4 = c.location) === null || _c$location4 === void 0 ? void 0 : _c$location4.column + }, () => runSuite(c, runner)); + } +} +async function runFiles(files, runner) { + limitMaxConcurrency ?? (limitMaxConcurrency = limitConcurrency(runner.config.maxConcurrency)); + for (const file of files) { + if (!file.tasks.length && !runner.config.passWithNoTests) { + var _file$result; + if (!((_file$result = file.result) === null || _file$result === void 0 || (_file$result = _file$result.errors) === null || _file$result === void 0 ? void 0 : _file$result.length)) { + const error = processError(new Error(`No test suite found in file ${file.filepath}`)); + file.result = { + state: "fail", + errors: [error] + }; + } + } + await runner.trace("run.spec", { + "code.file.path": file.filepath, + "vitest.suite.tasks.length": file.tasks.length + }, () => runSuite(file, runner)); + } +} +const workerRunners = new WeakSet(); +function defaultTrace(_, attributes, cb) { + if (typeof attributes === "function") { + return attributes(); + } + return cb(); +} +async function startTests(specs, runner) { + var _runner$cancel; + runner.trace ?? (runner.trace = defaultTrace); + const cancel = (_runner$cancel = runner.cancel) === null || _runner$cancel === void 0 ? void 0 : _runner$cancel.bind(runner); + // Ideally, we need to have an event listener for this, but only have a runner here. + // Adding another onCancel felt wrong (maybe it needs to be refactored) + runner.cancel = (reason) => { + // We intentionally create only one error since there is only one test run that can be cancelled + const error = new TestRunAbortError("The test run was aborted by the user.", reason); + getRunningTests().forEach((test) => abortContextSignal(test.context, error)); + return cancel === null || cancel === void 0 ? void 0 : cancel(reason); + }; + if (!workerRunners.has(runner)) { + var _runner$onCleanupWork; + (_runner$onCleanupWork = runner.onCleanupWorkerContext) === null || _runner$onCleanupWork === void 0 ? void 0 : _runner$onCleanupWork.call(runner, async () => { + var _runner$getWorkerCont; + const context = (_runner$getWorkerCont = runner.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner); + if (context) { + await callFixtureCleanup(context); + } + }); + workerRunners.add(runner); + } + try { + var _runner$onBeforeColle, _runner$onCollected, _runner$onBeforeRunFi, _runner$onAfterRunFil; + const paths = specs.map((f) => typeof f === "string" ? f : f.filepath); + await ((_runner$onBeforeColle = runner.onBeforeCollect) === null || _runner$onBeforeColle === void 0 ? void 0 : _runner$onBeforeColle.call(runner, paths)); + const files = await collectTests(specs, runner); + await ((_runner$onCollected = runner.onCollected) === null || _runner$onCollected === void 0 ? void 0 : _runner$onCollected.call(runner, files)); + await ((_runner$onBeforeRunFi = runner.onBeforeRunFiles) === null || _runner$onBeforeRunFi === void 0 ? void 0 : _runner$onBeforeRunFi.call(runner, files)); + await runFiles(files, runner); + await ((_runner$onAfterRunFil = runner.onAfterRunFiles) === null || _runner$onAfterRunFil === void 0 ? void 0 : _runner$onAfterRunFil.call(runner, files)); + await finishSendTasksUpdate(runner); + return files; + } finally { + runner.cancel = cancel; + } +} +async function publicCollect(specs, runner) { + var _runner$onBeforeColle2, _runner$onCollected2; + runner.trace ?? (runner.trace = defaultTrace); + const paths = specs.map((f) => typeof f === "string" ? f : f.filepath); + await ((_runner$onBeforeColle2 = runner.onBeforeCollect) === null || _runner$onBeforeColle2 === void 0 ? void 0 : _runner$onBeforeColle2.call(runner, paths)); + const files = await collectTests(specs, runner); + await ((_runner$onCollected2 = runner.onCollected) === null || _runner$onCollected2 === void 0 ? void 0 : _runner$onCollected2.call(runner, files)); + return files; +} + +/** +* @experimental +* @advanced +* +* Records a custom test artifact during test execution. +* +* This function allows you to attach structured data, files, or metadata to a test. +* +* Vitest automatically injects the source location where the artifact was created and manages any attachments you include. +* +* @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests +* @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase} +* +* @returns A promise that resolves to the recorded artifact with location injected +* +* @throws {Error} If called after the test has finished running +* @throws {Error} If the test runner doesn't support artifacts +* +* @example +* ```ts +* // In a custom assertion +* async function toHaveValidSchema(this: MatcherState, actual: unknown) { +* const validation = validateSchema(actual) +* +* await recordArtifact(this.task, { +* type: 'my-plugin:schema-validation', +* passed: validation.valid, +* errors: validation.errors, +* }) +* +* return { pass: validation.valid, message: () => '...' } +* } +* ``` +*/ +async function recordArtifact(task, artifact) { + const runner = getRunner(); + if (task.result && task.result.state !== "run") { + throw new Error(`Cannot record a test artifact outside of the test run. The test "${task.name}" finished running with the "${task.result.state}" state already.`); + } + const stack = findTestFileStackTrace(task.file.filepath, new Error("STACK_TRACE").stack); + if (stack) { + artifact.location = { + file: stack.file, + line: stack.line, + column: stack.column + }; + if (artifact.type === "internal:annotation") { + artifact.annotation.location = artifact.location; + } + } + if (Array.isArray(artifact.attachments)) { + for (const attachment of artifact.attachments) { + manageArtifactAttachment(attachment); + } + } + // annotations won't resolve as artifacts for backwards compatibility until next major + if (artifact.type === "internal:annotation") { + return artifact; + } + if (!runner.onTestArtifactRecord) { + throw new Error(`Test runner doesn't support test artifacts.`); + } + await finishSendTasksUpdate(runner); + const resolvedArtifact = await runner.onTestArtifactRecord(task, artifact); + task.artifacts.push(resolvedArtifact); + return resolvedArtifact; +} +const table = []; +for (let i = 65; i < 91; i++) { + table.push(String.fromCharCode(i)); +} +for (let i = 97; i < 123; i++) { + table.push(String.fromCharCode(i)); +} +for (let i = 0; i < 10; i++) { + table.push(i.toString(10)); +} +table.push("+", "/"); +function encodeUint8Array(bytes) { + let base64 = ""; + const len = bytes.byteLength; + for (let i = 0; i < len; i += 3) { + if (len === i + 1) { + const a = (bytes[i] & 252) >> 2; + const b = (bytes[i] & 3) << 4; + base64 += table[a]; + base64 += table[b]; + base64 += "=="; + } else if (len === i + 2) { + const a = (bytes[i] & 252) >> 2; + const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4; + const c = (bytes[i + 1] & 15) << 2; + base64 += table[a]; + base64 += table[b]; + base64 += table[c]; + base64 += "="; + } else { + const a = (bytes[i] & 252) >> 2; + const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4; + const c = (bytes[i + 1] & 15) << 2 | (bytes[i + 2] & 192) >> 6; + const d = bytes[i + 2] & 63; + base64 += table[a]; + base64 += table[b]; + base64 += table[c]; + base64 += table[d]; + } + } + return base64; +} +/** +* Records an async operation associated with a test task. +* +* This function tracks promises that should be awaited before a test completes. +* The promise is automatically removed from the test's promise list once it settles. +*/ +function recordAsyncOperation(test, promise) { + // if promise is explicitly awaited, remove it from the list + promise = promise.finally(() => { + if (!test.promises) { + return; + } + const index = test.promises.indexOf(promise); + if (index !== -1) { + test.promises.splice(index, 1); + } + }); + // record promise + if (!test.promises) { + test.promises = []; + } + test.promises.push(promise); + return promise; +} +/** +* Validates and prepares a test attachment for serialization. +* +* This function ensures attachments have either `body` or `path` set (but not both), and converts `Uint8Array` bodies to base64-encoded strings for easier serialization. +* +* @param attachment - The attachment to validate and prepare +* +* @throws {TypeError} If neither `body` nor `path` is provided +* @throws {TypeError} If both `body` and `path` are provided +*/ +function manageArtifactAttachment(attachment) { + if (attachment.body == null && !attachment.path) { + throw new TypeError(`Test attachment requires "body" or "path" to be set. Both are missing.`); + } + if (attachment.body && attachment.path) { + throw new TypeError(`Test attachment requires only one of "body" or "path" to be set. Both are specified.`); + } + // convert to a string so it's easier to serialise + if (attachment.body instanceof Uint8Array) { + attachment.body = encodeUint8Array(attachment.body); + } +} + +export { afterAll, afterEach, beforeAll, beforeEach, publicCollect as collectTests, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, onTestFailed, onTestFinished, recordArtifact, setFn, setHooks, startTests, suite, test, updateTask }; diff --git a/vanilla/node_modules/@vitest/runner/dist/tasks.d-C7UxawJ9.d.ts b/vanilla/node_modules/@vitest/runner/dist/tasks.d-C7UxawJ9.d.ts new file mode 100644 index 0000000..a0b07a1 --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/dist/tasks.d-C7UxawJ9.d.ts @@ -0,0 +1,834 @@ +import { TestError, Awaitable } from '@vitest/utils'; + +interface FixtureItem extends FixtureOptions { + prop: string; + value: any; + scope: "test" | "file" | "worker"; + /** + * Indicates whether the fixture is a function + */ + isFn: boolean; + /** + * The dependencies(fixtures) of current fixture function. + */ + deps?: FixtureItem[]; +} + +/** +* Registers a callback function to be executed once before all tests within the current suite. +* This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment. +* +* **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed before all tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using beforeAll to set up a database connection +* beforeAll(async () => { +* await database.connect(); +* }); +* ``` +*/ +declare function beforeAll(fn: BeforeAllListener, timeout?: number): void; +/** +* Registers a callback function to be executed once after all tests within the current suite have completed. +* This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files. +* +* **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed after all tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using afterAll to close a database connection +* afterAll(async () => { +* await database.disconnect(); +* }); +* ``` +*/ +declare function afterAll(fn: AfterAllListener, timeout?: number): void; +/** +* Registers a callback function to be executed before each test within the current suite. +* This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. +* +* **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using beforeEach to reset a database state +* beforeEach(async () => { +* await database.reset(); +* }); +* ``` +*/ +declare function beforeEach(fn: BeforeEachListener, timeout?: number): void; +/** +* Registers a callback function to be executed after each test within the current suite has completed. +* This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. +* +* **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using afterEach to delete temporary files created during a test +* afterEach(async () => { +* await fileSystem.deleteTempFiles(); +* }); +* ``` +*/ +declare function afterEach(fn: AfterEachListener, timeout?: number): void; +/** +* Registers a callback function to be executed when a test fails within the current suite. +* This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics. +* +* **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors). +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @throws {Error} Throws an error if the function is not called within a test. +* @returns {void} +* @example +* ```ts +* // Example of using onTestFailed to log failure details +* onTestFailed(({ errors }) => { +* console.log(`Test failed: ${test.name}`, errors); +* }); +* ``` +*/ +declare const onTestFailed: TaskHook; +/** +* Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail). +* This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources. +* +* This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`. +* +* **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call. +* +* @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @throws {Error} Throws an error if the function is not called within a test. +* @returns {void} +* @example +* ```ts +* // Example of using onTestFinished for cleanup +* const db = await connectToDatabase(); +* onTestFinished(async () => { +* await db.disconnect(); +* }); +* ``` +*/ +declare const onTestFinished: TaskHook; + +type ChainableFunction< + T extends string, + F extends (...args: any) => any, + C = object +> = F & { [x in T] : ChainableFunction } & { + fn: (this: Record, ...args: Parameters) => ReturnType; +} & C; +declare function createChainable< + T extends string, + Args extends any[], + R = any +>(keys: T[], fn: (this: Record, ...args: Args) => R): ChainableFunction R>; + +type RunMode = "run" | "skip" | "only" | "todo" | "queued"; +type TaskState = RunMode | "pass" | "fail"; +interface TaskBase { + /** + * Unique task identifier. Based on the file id and the position of the task. + * The id of the file task is based on the file path relative to root and project name. + * It will not change between runs. + * @example `1201091390`, `1201091390_0`, `1201091390_0_1` + */ + id: string; + /** + * Task name provided by the user. If no name was provided, it will be an empty string. + */ + name: string; + /** + * Full name including the file path, any parent suites, and this task's name. + * + * Uses ` > ` as the separator between levels. + * + * @example + * // file + * 'test/task-names.test.ts' + * @example + * // suite + * 'test/task-names.test.ts > meal planning' + * 'test/task-names.test.ts > meal planning > grocery lists' + * @example + * // test + * 'test/task-names.test.ts > meal planning > grocery lists > calculates ingredients' + */ + fullName: string; + /** + * Full name excluding the file path, including any parent suites and this task's name. `undefined` for file tasks. + * + * Uses ` > ` as the separator between levels. + * + * @example + * // file + * undefined + * @example + * // suite + * 'meal planning' + * 'meal planning > grocery lists' + * @example + * // test + * 'meal planning > grocery lists > calculates ingredients' + */ + fullTestName?: string; + /** + * Task mode. + * - **skip**: task is skipped + * - **only**: only this task and other tasks with `only` mode will run + * - **todo**: task is marked as a todo, alias for `skip` + * - **run**: task will run or already ran + * - **queued**: task will start running next. It can only exist on the File + */ + mode: RunMode; + /** + * Custom metadata for the task. JSON reporter will save this data. + */ + meta: TaskMeta; + /** + * Whether the task was produced with `.each()` method. + */ + each?: boolean; + /** + * Whether the task should run concurrently with other tasks. + */ + concurrent?: boolean; + /** + * Whether the tasks of the suite run in a random order. + */ + shuffle?: boolean; + /** + * Suite that this task is part of. File task or the global suite will have no parent. + */ + suite?: Suite; + /** + * Result of the task. Suite and file tasks will only have the result if there + * was an error during collection or inside `afterAll`/`beforeAll`. + */ + result?: TaskResult; + /** + * The amount of times the task should be retried if it fails. + * @default 0 + */ + retry?: number; + /** + * The amount of times the task should be repeated after the successful run. + * If the task fails, it will not be retried unless `retry` is specified. + * @default 0 + */ + repeats?: number; + /** + * Location of the task in the file. This field is populated only if + * `includeTaskLocation` option is set. It is generated by calling `new Error` + * and parsing the stack trace, so the location might differ depending on the runtime. + */ + location?: { + line: number; + column: number; + }; + /** + * If the test was collected by parsing the file AST, and the name + * is not a static string, this property will be set to `true`. + * @experimental + */ + dynamic?: boolean; +} +interface TaskPopulated extends TaskBase { + /** + * File task. It's the root task of the file. + */ + file: File; + /** + * Whether the task should succeed if it fails. If the task fails, it will be marked as passed. + */ + fails?: boolean; + /** + * Store promises (from async expects) to wait for them before finishing the test + */ + promises?: Promise[]; +} +/** +* Custom metadata that can be used in reporters. +*/ +interface TaskMeta {} +/** +* The result of calling a task. +*/ +interface TaskResult { + /** + * State of the task. Inherits the `task.mode` during collection. + * When the task has finished, it will be changed to `pass` or `fail`. + * - **pass**: task ran successfully + * - **fail**: task failed + */ + state: TaskState; + /** + * Errors that occurred during the task execution. It is possible to have several errors + * if `expect.soft()` failed multiple times or `retry` was triggered. + */ + errors?: TestError[]; + /** + * How long in milliseconds the task took to run. + */ + duration?: number; + /** + * Time in milliseconds when the task started running. + */ + startTime?: number; + /** + * Heap size in bytes after the task finished. + * Only available if `logHeapUsage` option is set and `process.memoryUsage` is defined. + */ + heap?: number; + /** + * State of related to this task hooks. Useful during reporting. + */ + hooks?: Partial>; + /** + * The amount of times the task was retried. The task is retried only if it + * failed and `retry` option is set. + */ + retryCount?: number; + /** + * The amount of times the task was repeated. The task is repeated only if + * `repeats` option is set. This number also contains `retryCount`. + */ + repeatCount?: number; +} +/** The time spent importing & executing a non-externalized file. */ +interface ImportDuration { + /** The time spent importing & executing the file itself, not counting all non-externalized imports that the file does. */ + selfTime: number; + /** The time spent importing & executing the file and all its imports. */ + totalTime: number; + /** Will be set to `true`, if the module was externalized. In this case totalTime and selfTime are identical. */ + external?: boolean; + /** Which module imported this module first. All subsequent imports are cached. */ + importer?: string; +} +/** +* The tuple representing a single task update. +* Usually reported after the task finishes. +*/ +type TaskResultPack = [id: string, result: TaskResult | undefined, meta: TaskMeta]; +interface TaskEventData { + annotation?: TestAnnotation | undefined; + artifact?: TestArtifact | undefined; +} +type TaskEventPack = [id: string, event: TaskUpdateEvent, data: TaskEventData | undefined]; +type TaskUpdateEvent = "test-failed-early" | "suite-failed-early" | "test-prepare" | "test-finished" | "test-retried" | "suite-prepare" | "suite-finished" | "before-hook-start" | "before-hook-end" | "after-hook-start" | "after-hook-end" | "test-annotation" | "test-artifact"; +interface Suite extends TaskBase { + type: "suite"; + /** + * File task. It's the root task of the file. + */ + file: File; + /** + * An array of tasks that are part of the suite. + */ + tasks: Task[]; +} +interface File extends Suite { + /** + * The name of the pool that the file belongs to. + * @default 'forks' + */ + pool?: string; + /** + * The environment that processes the file on the server. + */ + viteEnvironment?: string; + /** + * The path to the file in UNIX format. + */ + filepath: string; + /** + * The name of the workspace project the file belongs to. + */ + projectName: string | undefined; + /** + * The time it took to collect all tests in the file. + * This time also includes importing all the file dependencies. + */ + collectDuration?: number; + /** + * The time it took to import the setup file. + */ + setupDuration?: number; + /** The time spent importing every non-externalized dependency that Vitest has processed. */ + importDurations?: Record; +} +interface Test extends TaskPopulated { + type: "test"; + /** + * Test context that will be passed to the test function. + */ + context: TestContext & ExtraContext; + /** + * The test timeout in milliseconds. + */ + timeout: number; + /** + * An array of custom annotations. + */ + annotations: TestAnnotation[]; + /** + * An array of artifacts produced by the test. + * + * @experimental + */ + artifacts: TestArtifact[]; + fullTestName: string; +} +type Task = Test | Suite | File; +type TestFunction = (context: TestContext & ExtraContext) => Awaitable | void; +type ExtractEachCallbackArgs> = { + 1: [T[0]]; + 2: [T[0], T[1]]; + 3: [T[0], T[1], T[2]]; + 4: [T[0], T[1], T[2], T[3]]; + 5: [T[0], T[1], T[2], T[3], T[4]]; + 6: [T[0], T[1], T[2], T[3], T[4], T[5]]; + 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]]; + 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]]; + 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]]; + 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]]; + fallback: Array ? U : any>; +}[T extends Readonly<[any]> ? 1 : T extends Readonly<[any, any]> ? 2 : T extends Readonly<[any, any, any]> ? 3 : T extends Readonly<[any, any, any, any]> ? 4 : T extends Readonly<[any, any, any, any, any]> ? 5 : T extends Readonly<[any, any, any, any, any, any]> ? 6 : T extends Readonly<[any, any, any, any, any, any, any]> ? 7 : T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8 : T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10 : "fallback"]; +interface EachFunctionReturn { + (name: string | Function, fn: (...args: T) => Awaitable, options?: number): void; + (name: string | Function, options: TestCollectorOptions, fn: (...args: T) => Awaitable): void; +} +interface TestEachFunction { + (cases: ReadonlyArray): EachFunctionReturn; + >(cases: ReadonlyArray): EachFunctionReturn>; + (cases: ReadonlyArray): EachFunctionReturn; + (...args: [TemplateStringsArray, ...any]): EachFunctionReturn; +} +interface TestForFunctionReturn< + Arg, + Context +> { + (name: string | Function, fn: (arg: Arg, context: Context) => Awaitable): void; + (name: string | Function, options: TestCollectorOptions, fn: (args: Arg, context: Context) => Awaitable): void; +} +interface TestForFunction { + (cases: ReadonlyArray): TestForFunctionReturn; + (strings: TemplateStringsArray, ...values: any[]): TestForFunctionReturn; +} +interface SuiteForFunction { + (cases: ReadonlyArray): EachFunctionReturn<[T]>; + (...args: [TemplateStringsArray, ...any]): EachFunctionReturn; +} +interface TestCollectorCallable { + (name: string | Function, fn?: TestFunction, options?: number): void; + (name: string | Function, options?: TestCollectorOptions, fn?: TestFunction): void; +} +type ChainableTestAPI = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "fails", TestCollectorCallable, { + each: TestEachFunction; + for: TestForFunction; +}>; +type TestCollectorOptions = Omit; +interface TestOptions { + /** + * Test timeout. + */ + timeout?: number; + /** + * Times to retry the test if fails. Useful for making flaky tests more stable. + * When retries is up, the last test error will be thrown. + * + * @default 0 + */ + retry?: number; + /** + * How many times the test will run again. + * Only inner tests will repeat if set on `describe()`, nested `describe()` will inherit parent's repeat by default. + * + * @default 0 + */ + repeats?: number; + /** + * Whether suites and tests run concurrently. + * Tests inherit `concurrent` from `describe()` and nested `describe()` will inherit from parent's `concurrent`. + */ + concurrent?: boolean; + /** + * Whether tests run sequentially. + * Tests inherit `sequential` from `describe()` and nested `describe()` will inherit from parent's `sequential`. + */ + sequential?: boolean; + /** + * Whether the tasks of the suite run in a random order. + */ + shuffle?: boolean; + /** + * Whether the test should be skipped. + */ + skip?: boolean; + /** + * Should this test be the only one running in a suite. + */ + only?: boolean; + /** + * Whether the test should be skipped and marked as a todo. + */ + todo?: boolean; + /** + * Whether the test is expected to fail. If it does, the test will pass, otherwise it will fail. + */ + fails?: boolean; +} +interface ExtendedAPI { + skipIf: (condition: any) => ChainableTestAPI; + runIf: (condition: any) => ChainableTestAPI; +} +interface Hooks { + beforeAll: typeof beforeAll; + afterAll: typeof afterAll; + beforeEach: typeof beforeEach; + afterEach: typeof afterEach; +} +type TestAPI = ChainableTestAPI & ExtendedAPI & Hooks & { + extend: = object>(fixtures: Fixtures) => TestAPI<{ [K in keyof T | keyof ExtraContext] : K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never }>; + scoped: (fixtures: Partial>) => void; +}; +interface FixtureOptions { + /** + * Whether to automatically set up current fixture, even though it's not being used in tests. + * @default false + */ + auto?: boolean; + /** + * Indicated if the injected value from the config should be preferred over the fixture value + */ + injected?: boolean; + /** + * When should the fixture be set up. + * - **test**: fixture will be set up before every test + * - **worker**: fixture will be set up once per worker + * - **file**: fixture will be set up once per file + * + * **Warning:** The `vmThreads` and `vmForks` pools initiate worker fixtures once per test file. + * @default 'test' + */ + scope?: "test" | "worker" | "file"; +} +type Use = (value: T) => Promise; +type FixtureFn< + T, + K extends keyof T, + ExtraContext +> = (context: Omit & ExtraContext, use: Use) => Promise; +type Fixture< + T, + K extends keyof T, + ExtraContext = object +> = ((...args: any) => any) extends T[K] ? T[K] extends any ? FixtureFn>> : never : T[K] | (T[K] extends any ? FixtureFn>> : never); +type Fixtures< + T, + ExtraContext = object +> = { [K in keyof T] : Fixture | [Fixture, FixtureOptions?] }; +type InferFixturesTypes = T extends TestAPI ? C : T; +interface SuiteCollectorCallable { + (name: string | Function, fn?: SuiteFactory, options?: number): SuiteCollector; + (name: string | Function, options: TestOptions, fn?: SuiteFactory): SuiteCollector; +} +type ChainableSuiteAPI = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "shuffle", SuiteCollectorCallable, { + each: TestEachFunction; + for: SuiteForFunction; +}>; +type SuiteAPI = ChainableSuiteAPI & { + skipIf: (condition: any) => ChainableSuiteAPI; + runIf: (condition: any) => ChainableSuiteAPI; +}; +interface BeforeAllListener { + (suite: Readonly): Awaitable; +} +interface AfterAllListener { + (suite: Readonly): Awaitable; +} +interface BeforeEachListener { + (context: TestContext & ExtraContext, suite: Readonly): Awaitable; +} +interface AfterEachListener { + (context: TestContext & ExtraContext, suite: Readonly): Awaitable; +} +interface SuiteHooks { + beforeAll: BeforeAllListener[]; + afterAll: AfterAllListener[]; + beforeEach: BeforeEachListener[]; + afterEach: AfterEachListener[]; +} +interface TaskCustomOptions extends TestOptions { + /** + * Whether the task was produced with `.each()` method. + */ + each?: boolean; + /** + * Custom metadata for the task that will be assigned to `task.meta`. + */ + meta?: Record; + /** + * Task fixtures. + */ + fixtures?: FixtureItem[]; + /** + * Function that will be called when the task is executed. + * If nothing is provided, the runner will try to get the function using `getFn(task)`. + * If the runner cannot find the function, the task will be marked as failed. + */ + handler?: (context: TestContext) => Awaitable; +} +interface SuiteCollector { + readonly name: string; + readonly mode: RunMode; + options?: TestOptions; + type: "collector"; + test: TestAPI; + tasks: (Suite | Test | SuiteCollector)[]; + scoped: (fixtures: Fixtures) => void; + fixtures: () => FixtureItem[] | undefined; + file?: File; + suite?: Suite; + task: (name: string, options?: TaskCustomOptions) => Test; + collect: (file: File) => Promise; + clear: () => void; + on: >(name: T, ...fn: SuiteHooks[T]) => void; +} +type SuiteFactory = (test: TestAPI) => Awaitable; +interface RuntimeContext { + tasks: (SuiteCollector | Test)[]; + currentSuite: SuiteCollector | null; +} +/** +* User's custom test context. +*/ +interface TestContext { + /** + * Metadata of the current test + */ + readonly task: Readonly; + /** + * An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that will be aborted if the test times out or + * the test run was cancelled. + * @see {@link https://vitest.dev/guide/test-context#signal} + */ + readonly signal: AbortSignal; + /** + * Register a callback to run when this specific test fails. + * Useful when tests run concurrently. + * @see {@link https://vitest.dev/guide/test-context#ontestfailed} + */ + readonly onTestFailed: (fn: OnTestFailedHandler, timeout?: number) => void; + /** + * Register a callback to run when this specific test finishes. + * Useful when tests run concurrently. + * @see {@link https://vitest.dev/guide/test-context#ontestfinished} + */ + readonly onTestFinished: (fn: OnTestFinishedHandler, timeout?: number) => void; + /** + * Mark tests as skipped. All execution after this call will be skipped. + * This function throws an error, so make sure you are not catching it accidentally. + * @see {@link https://vitest.dev/guide/test-context#skip} + */ + readonly skip: { + (note?: string): never; + (condition: boolean, note?: string): void; + }; + /** + * Add a test annotation that will be displayed by your reporter. + * @see {@link https://vitest.dev/guide/test-context#annotate} + */ + readonly annotate: { + (message: string, type?: string, attachment?: TestAttachment): Promise; + (message: string, attachment?: TestAttachment): Promise; + }; +} +type OnTestFailedHandler = (context: TestContext) => Awaitable; +type OnTestFinishedHandler = (context: TestContext) => Awaitable; +interface TaskHook { + (fn: HookListener, timeout?: number): void; +} +type SequenceHooks = "stack" | "list" | "parallel"; +type SequenceSetupFiles = "list" | "parallel"; +/** +* Represents a file or data attachment associated with a test artifact. +* +* Attachments can be either file-based (via `path`) or inline content (via `body`). +* The `contentType` helps consumers understand how to interpret the attachment data. +*/ +interface TestAttachment { + /** MIME type of the attachment (e.g., 'image/png', 'text/plain') */ + contentType?: string; + /** File system path to the attachment */ + path?: string; + /** Inline attachment content as a string or raw binary data */ + body?: string | Uint8Array; +} +/** +* Source code location information for a test artifact. +* +* Indicates where in the source code the artifact originated from. +*/ +interface TestArtifactLocation { + /** Line number in the source file (1-indexed) */ + line: number; + /** Column number in the line (1-indexed) */ + column: number; + /** Path to the source file */ + file: string; +} +/** +* @experimental +* +* Base interface for all test artifacts. +* +* Extend this interface when creating custom test artifacts. Vitest automatically manages the `attachments` array and injects the `location` property to indicate where the artifact was created in your test code. +*/ +interface TestArtifactBase { + /** File or data attachments associated with this artifact */ + attachments?: TestAttachment[]; + /** Source location where this artifact was created */ + location?: TestArtifactLocation; +} +/** +* @deprecated Use {@linkcode TestArtifactLocation} instead. +* +* Kept for backwards compatibility. +*/ +type TestAnnotationLocation = TestArtifactLocation; +interface TestAnnotation { + message: string; + type: string; + location?: TestArtifactLocation; + attachment?: TestAttachment; +} +/** +* @experimental +* +* Artifact type for test annotations. +*/ +interface TestAnnotationArtifact extends TestArtifactBase { + type: "internal:annotation"; + annotation: TestAnnotation; +} +interface VisualRegressionArtifactAttachment extends TestAttachment { + name: "reference" | "actual" | "diff"; + width: number; + height: number; +} +/** +* @experimental +* +* Artifact type for visual regressions. +*/ +interface VisualRegressionArtifact extends TestArtifactBase { + type: "internal:toMatchScreenshot"; + kind: "visual-regression"; + message: string; + attachments: VisualRegressionArtifactAttachment[]; +} +/** +* @experimental +* @advanced +* +* Registry for custom test artifact types. +* +* Augment this interface to register custom artifact types that your tests can produce. +* +* Each custom artifact should extend {@linkcode TestArtifactBase} and include a unique `type` discriminator property. +* +* @remarks +* - Use a `Symbol` as the **registry key** to guarantee uniqueness +* - The `type` property should follow the pattern `'package-name:artifact-name'`, `'internal:'` is a reserved prefix +* - Use `attachments` to include files or data; extend {@linkcode TestAttachment} for custom metadata +* - `location` property is automatically injected to indicate where the artifact was created +* +* @example +* ```ts +* // Define custom attachment type for generated PDF +* interface PDFAttachment extends TestAttachment { +* contentType: 'application/pdf' +* body: Uint8Array +* pageCount: number +* fileSize: number +* } +* +* interface PDFGenerationArtifact extends TestArtifactBase { +* type: 'my-plugin:pdf-generation' +* templateName: string +* isValid: boolean +* attachments: [PDFAttachment] +* } +* +* // Use a symbol to guarantee key uniqueness +* const pdfKey = Symbol('pdf-generation') +* +* declare module 'vitest' { +* interface TestArtifactRegistry { +* [pdfKey]: PDFGenerationArtifact +* } +* } +* +* // Custom assertion for PDF generation +* async function toGenerateValidPDF( +* this: MatcherState, +* actual: PDFTemplate, +* data: Record +* ): AsyncExpectationResult { +* const pdfBuffer = await actual.render(data) +* const validation = await validatePDF(pdfBuffer) +* +* await recordArtifact(this.task, { +* type: 'my-plugin:pdf-generation', +* templateName: actual.name, +* isValid: validation.success, +* attachments: [{ +* contentType: 'application/pdf', +* body: pdfBuffer, +* pageCount: validation.pageCount, +* fileSize: pdfBuffer.byteLength +* }] +* }) +* +* return { +* pass: validation.success, +* message: () => validation.success +* ? `Generated valid PDF with ${validation.pageCount} pages` +* : `Invalid PDF: ${validation.error}` +* } +* } +* ``` +*/ +interface TestArtifactRegistry {} +/** +* @experimental +* +* Union type of all test artifacts, including built-in and custom registered artifacts. +* +* This type automatically includes all artifacts registered via {@link TestArtifactRegistry}. +*/ +type TestArtifact = TestAnnotationArtifact | VisualRegressionArtifact | TestArtifactRegistry[keyof TestArtifactRegistry]; + +export { createChainable as c, afterAll as i, afterEach as j, beforeAll as k, beforeEach as l, onTestFinished as m, onTestFailed as o }; +export type { TestOptions as $, AfterAllListener as A, BeforeAllListener as B, ChainableFunction as C, TaskBase as D, TaskCustomOptions as E, File as F, TaskEventPack as G, TaskHook as H, ImportDuration as I, TaskMeta as J, TaskPopulated as K, TaskResult as L, TaskResultPack as M, TaskState as N, OnTestFailedHandler as O, TestAnnotation as P, TestAnnotationArtifact as Q, RunMode as R, Suite as S, Task as T, TestAnnotationLocation as U, TestArtifactBase as V, TestArtifactLocation as W, TestArtifactRegistry as X, TestAttachment as Y, TestContext as Z, TestFunction as _, Test as a, Use as a0, VisualRegressionArtifact as a1, TestArtifact as b, SuiteHooks as d, TaskUpdateEvent as e, TestAPI as f, SuiteAPI as g, SuiteCollector as h, AfterEachListener as n, BeforeEachListener as p, Fixture as q, FixtureFn as r, FixtureOptions as s, Fixtures as t, InferFixturesTypes as u, OnTestFinishedHandler as v, RuntimeContext as w, SequenceHooks as x, SequenceSetupFiles as y, SuiteFactory as z }; diff --git a/vanilla/node_modules/@vitest/runner/dist/types.d.ts b/vanilla/node_modules/@vitest/runner/dist/types.d.ts new file mode 100644 index 0000000..aefc0b8 --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/dist/types.d.ts @@ -0,0 +1,183 @@ +import { DiffOptions } from '@vitest/utils/diff'; +import { F as File, a as Test, S as Suite, M as TaskResultPack, G as TaskEventPack, P as TestAnnotation, b as TestArtifact, Z as TestContext, I as ImportDuration, x as SequenceHooks, y as SequenceSetupFiles } from './tasks.d-C7UxawJ9.js'; +export { A as AfterAllListener, n as AfterEachListener, B as BeforeAllListener, p as BeforeEachListener, q as Fixture, r as FixtureFn, s as FixtureOptions, t as Fixtures, u as InferFixturesTypes, O as OnTestFailedHandler, v as OnTestFinishedHandler, R as RunMode, w as RuntimeContext, g as SuiteAPI, h as SuiteCollector, z as SuiteFactory, d as SuiteHooks, T as Task, D as TaskBase, E as TaskCustomOptions, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, N as TaskState, e as TaskUpdateEvent, f as TestAPI, Q as TestAnnotationArtifact, U as TestAnnotationLocation, V as TestArtifactBase, W as TestArtifactLocation, X as TestArtifactRegistry, Y as TestAttachment, _ as TestFunction, $ as TestOptions, a0 as Use, a1 as VisualRegressionArtifact } from './tasks.d-C7UxawJ9.js'; +import '@vitest/utils'; + +/** +* This is a subset of Vitest config that's required for the runner to work. +*/ +interface VitestRunnerConfig { + root: string; + setupFiles: string[]; + name?: string; + passWithNoTests: boolean; + testNamePattern?: RegExp; + allowOnly?: boolean; + sequence: { + shuffle?: boolean; + concurrent?: boolean; + seed: number; + hooks: SequenceHooks; + setupFiles: SequenceSetupFiles; + }; + chaiConfig?: { + truncateThreshold?: number; + }; + maxConcurrency: number; + testTimeout: number; + hookTimeout: number; + retry: number; + includeTaskLocation?: boolean; + diffOptions?: DiffOptions; +} +/** +* Possible options to run a single file in a test. +*/ +interface FileSpecification { + filepath: string; + testLocations: number[] | undefined; +} +type VitestRunnerImportSource = "collect" | "setup"; +interface VitestRunnerConstructor { + new (config: VitestRunnerConfig): VitestRunner; +} +type CancelReason = "keyboard-input" | "test-failure" | (string & Record); +interface VitestRunner { + /** + * First thing that's getting called before actually collecting and running tests. + */ + onBeforeCollect?: (paths: string[]) => unknown; + /** + * Called after the file task was created but not collected yet. + */ + onCollectStart?: (file: File) => unknown; + /** + * Called after collecting tests and before "onBeforeRun". + */ + onCollected?: (files: File[]) => unknown; + /** + * Called when test runner should cancel next test runs. + * Runner should listen for this method and mark tests and suites as skipped in + * "onBeforeRunSuite" and "onBeforeRunTask" when called. + */ + cancel?: (reason: CancelReason) => unknown; + /** + * Called before running a single test. Doesn't have "result" yet. + */ + onBeforeRunTask?: (test: Test) => unknown; + /** + * Called before actually running the test function. Already has "result" with "state" and "startTime". + */ + onBeforeTryTask?: (test: Test, options: { + retry: number; + repeats: number; + }) => unknown; + /** + * When the task has finished running, but before cleanup hooks are called + */ + onTaskFinished?: (test: Test) => unknown; + /** + * Called after result and state are set. + */ + onAfterRunTask?: (test: Test) => unknown; + /** + * Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws. + */ + onAfterTryTask?: (test: Test, options: { + retry: number; + repeats: number; + }) => unknown; + /** + * Called after the retry resolution happend. Unlike `onAfterTryTask`, the test now has a new state. + * All `after` hooks were also called by this point. + */ + onAfterRetryTask?: (test: Test, options: { + retry: number; + repeats: number; + }) => unknown; + /** + * Called before running a single suite. Doesn't have "result" yet. + */ + onBeforeRunSuite?: (suite: Suite) => unknown; + /** + * Called after running a single suite. Has state and result. + */ + onAfterRunSuite?: (suite: Suite) => unknown; + /** + * If defined, will be called instead of usual Vitest suite partition and handling. + * "before" and "after" hooks will not be ignored. + */ + runSuite?: (suite: Suite) => Promise; + /** + * If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function. + * "before" and "after" hooks will not be ignored. + */ + runTask?: (test: Test) => Promise; + /** + * Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests. + */ + onTaskUpdate?: (task: TaskResultPack[], events: TaskEventPack[]) => Promise; + /** + * Called when annotation is added via the `context.annotate` method. + */ + onTestAnnotate?: (test: Test, annotation: TestAnnotation) => Promise; + /** + * @experimental + * + * Called when artifacts are recorded on tests via the `recordArtifact` utility. + */ + onTestArtifactRecord?: (test: Test, artifact: Artifact) => Promise; + /** + * Called before running all tests in collected paths. + */ + onBeforeRunFiles?: (files: File[]) => unknown; + /** + * Called right after running all tests in collected paths. + */ + onAfterRunFiles?: (files: File[]) => unknown; + /** + * Called when new context for a test is defined. Useful if you want to add custom properties to the context. + * If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead. + * + * @see https://vitest.dev/advanced/runner#your-task-function + */ + extendTaskContext?: (context: TestContext) => TestContext; + /** + * Called when test and setup files are imported. Can be called in two situations: when collecting tests and when importing setup files. + */ + importFile: (filepath: string, source: VitestRunnerImportSource) => unknown; + /** + * Function that is called when the runner attempts to get the value when `test.extend` is used with `{ injected: true }` + */ + injectValue?: (key: string) => unknown; + /** + * Gets the time spent importing each individual non-externalized file that Vitest collected. + */ + getImportDurations?: () => Record; + /** + * Publicly available configuration. + */ + config: VitestRunnerConfig; + /** + * The name of the current pool. Can affect how stack trace is inferred on the server side. + */ + pool?: string; + /** + * The current Vite environment that processes the files on the server. + */ + viteEnvironment?: string; + /** + * Return the worker context for fixtures specified with `scope: 'worker'` + */ + getWorkerContext?: () => Record; + onCleanupWorkerContext?: (cleanup: () => unknown) => void; + trace?(name: string, cb: () => T): T; + trace?(name: string, attributes: Record, cb: () => T): T; + /** @private */ + _currentTaskStartTime?: number; + /** @private */ + _currentTaskTimeout?: number; +} + +export { File, ImportDuration, SequenceHooks, SequenceSetupFiles, Suite, TaskEventPack, TaskResultPack, Test, TestAnnotation, TestArtifact, TestContext }; +export type { CancelReason, FileSpecification, VitestRunner, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource }; diff --git a/vanilla/node_modules/@vitest/runner/dist/types.js b/vanilla/node_modules/@vitest/runner/dist/types.js new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/dist/types.js @@ -0,0 +1 @@ + diff --git a/vanilla/node_modules/@vitest/runner/dist/utils.d.ts b/vanilla/node_modules/@vitest/runner/dist/utils.d.ts new file mode 100644 index 0000000..8d3757d --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/dist/utils.d.ts @@ -0,0 +1,45 @@ +import { S as Suite, F as File, T as Task, a as Test } from './tasks.d-C7UxawJ9.js'; +export { C as ChainableFunction, c as createChainable } from './tasks.d-C7UxawJ9.js'; +import { ParsedStack, Arrayable } from '@vitest/utils'; + +/** +* If any tasks been marked as `only`, mark all other tasks as `skip`. +*/ +declare function interpretTaskModes(file: Suite, namePattern?: string | RegExp, testLocations?: number[] | undefined, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean): void; +declare function someTasksAreOnly(suite: Suite): boolean; +declare function generateHash(str: string): string; +declare function calculateSuiteHash(parent: Suite): void; +declare function createFileTask(filepath: string, root: string, projectName: string | undefined, pool?: string, viteEnvironment?: string): File; +/** +* Generate a unique ID for a file based on its path and project name +* @param file File relative to the root of the project to keep ID the same between different machines +* @param projectName The name of the test project +*/ +declare function generateFileHash(file: string, projectName: string | undefined): string; +declare function findTestFileStackTrace(testFilePath: string, error: string): ParsedStack | undefined; + +/** +* Return a function for running multiple async operations with limited concurrency. +*/ +declare function limitConcurrency(concurrency?: number): < + Args extends unknown[], + T +>(func: (...args: Args) => PromiseLike | T, ...args: Args) => Promise; + +/** +* Partition in tasks groups by consecutive concurrent +*/ +declare function partitionSuiteChildren(suite: Suite): Task[][]; + +declare function isTestCase(s: Task): s is Test; +declare function getTests(suite: Arrayable): Test[]; +declare function getTasks(tasks?: Arrayable): Task[]; +declare function getSuites(suite: Arrayable): Suite[]; +declare function hasTests(suite: Arrayable): boolean; +declare function hasFailed(suite: Arrayable): boolean; +declare function getNames(task: Task): string[]; +declare function getFullName(task: Task, separator?: string): string; +declare function getTestName(task: Task, separator?: string): string; +declare function createTaskName(names: readonly (string | undefined)[], separator?: string): string; + +export { calculateSuiteHash, createFileTask, createTaskName, findTestFileStackTrace, generateFileHash, generateHash, getFullName, getNames, getSuites, getTasks, getTestName, getTests, hasFailed, hasTests, interpretTaskModes, isTestCase, limitConcurrency, partitionSuiteChildren, someTasksAreOnly }; diff --git a/vanilla/node_modules/@vitest/runner/dist/utils.js b/vanilla/node_modules/@vitest/runner/dist/utils.js new file mode 100644 index 0000000..24362a4 --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/dist/utils.js @@ -0,0 +1,5 @@ +export { a as calculateSuiteHash, c as createChainable, b as createFileTask, e as createTaskName, f as findTestFileStackTrace, g as generateFileHash, d as generateHash, h as getFullName, j as getNames, k as getSuites, m as getTasks, n as getTestName, o as getTests, q as hasFailed, r as hasTests, i as interpretTaskModes, t as isTestCase, l as limitConcurrency, p as partitionSuiteChildren, s as someTasksAreOnly } from './chunk-tasks.js'; +import '@vitest/utils/error'; +import '@vitest/utils/source-map'; +import 'pathe'; +import '@vitest/utils/helpers'; diff --git a/vanilla/node_modules/@vitest/runner/package.json b/vanilla/node_modules/@vitest/runner/package.json new file mode 100644 index 0000000..0cc2165 --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/package.json @@ -0,0 +1,48 @@ +{ + "name": "@vitest/runner", + "type": "module", + "version": "4.0.18", + "description": "Vitest test runner", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/runner#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/runner" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": true, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./utils": { + "types": "./dist/utils.d.ts", + "default": "./dist/utils.js" + }, + "./types": { + "types": "./dist/types.d.ts", + "default": "./dist/types.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "pathe": "^2.0.3", + "@vitest/utils": "4.0.18" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/@vitest/runner/types.d.ts b/vanilla/node_modules/@vitest/runner/types.d.ts new file mode 100644 index 0000000..26a1254 --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/types.d.ts @@ -0,0 +1 @@ +export * from './dist/types.js' diff --git a/vanilla/node_modules/@vitest/runner/utils.d.ts b/vanilla/node_modules/@vitest/runner/utils.d.ts new file mode 100644 index 0000000..e3f344e --- /dev/null +++ b/vanilla/node_modules/@vitest/runner/utils.d.ts @@ -0,0 +1 @@ +export * from './dist/utils.js' diff --git a/vanilla/node_modules/@vitest/snapshot/LICENSE b/vanilla/node_modules/@vitest/snapshot/LICENSE new file mode 100644 index 0000000..0e5771d --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vanilla/node_modules/@vitest/snapshot/README.md b/vanilla/node_modules/@vitest/snapshot/README.md new file mode 100644 index 0000000..edf0817 --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/README.md @@ -0,0 +1,84 @@ +# @vitest/snapshot + +Lightweight implementation of Jest's snapshots. + +## Usage + +```js +import { SnapshotClient } from '@vitest/snapshot' +import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment' +import { SnapshotManager } from '@vitest/snapshot/manager' + +const client = new SnapshotClient({ + // you need to provide your own equality check implementation if you use it + // this function is called when `.toMatchSnapshot({ property: 1 })` is called + isEqual: (received, expected) => + equals(received, expected, [iterableEquality, subsetEquality]), +}) + +// class that implements snapshot saving and reading +// by default uses fs module, but you can provide your own implementation depending on the environment +const environment = new NodeSnapshotEnvironment() + +// you need to implement this yourselves, +// this depends on your runner +function getCurrentFilepath() { + return '/file.spec.js' +} +function getCurrentTestName() { + return 'test1' +} + +// example for inline snapshots, nothing is required to support regular snapshots, +// just call `assert` with `isInline: false` +function wrapper(received) { + function __INLINE_SNAPSHOT__(inlineSnapshot, message) { + client.assert({ + received, + message, + isInline: true, + inlineSnapshot, + filepath: getCurrentFilepath(), + name: getCurrentTestName(), + }) + } + return { + // the name is hard-coded, it should be inside another function, so Vitest can find the actual test file where it was called (parses call stack trace + 2) + // you can override this behaviour in SnapshotState's `_inferInlineSnapshotStack` method by providing your own SnapshotState to SnapshotClient constructor + toMatchInlineSnapshot: (...args) => __INLINE_SNAPSHOT__(...args), + } +} + +const options = { + updateSnapshot: 'new', + snapshotEnvironment: environment, +} + +await client.startCurrentRun( + getCurrentFilepath(), + getCurrentTestName(), + options +) + +// this will save snapshot to a file which is returned by "snapshotEnvironment.resolvePath" +client.assert({ + received: 'some text', + isInline: false, +}) + +// uses "pretty-format", so it requires quotes +// also naming is hard-coded when parsing test files +wrapper('text 1').toMatchInlineSnapshot() +wrapper('text 2').toMatchInlineSnapshot('"text 2"') + +const result = await client.finishCurrentRun() // this saves files and returns SnapshotResult + +// you can use manager to manage several clients +const manager = new SnapshotManager(options) +manager.add(result) + +// do something +// and then read the summary + +console.log(manager.summary) +``` diff --git a/vanilla/node_modules/@vitest/snapshot/dist/environment.d-DHdQ1Csl.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/environment.d-DHdQ1Csl.d.ts new file mode 100644 index 0000000..435ae4f --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/dist/environment.d-DHdQ1Csl.d.ts @@ -0,0 +1,22 @@ +interface ParsedStack { + method: string; + file: string; + line: number; + column: number; +} + +interface SnapshotEnvironment { + getVersion: () => string; + getHeader: () => string; + resolvePath: (filepath: string) => Promise; + resolveRawPath: (testPath: string, rawPath: string) => Promise; + saveSnapshotFile: (filepath: string, snapshot: string) => Promise; + readSnapshotFile: (filepath: string) => Promise; + removeSnapshotFile: (filepath: string) => Promise; + processStackTrace?: (stack: ParsedStack) => ParsedStack; +} +interface SnapshotEnvironmentOptions { + snapshotsDirName?: string; +} + +export type { ParsedStack as P, SnapshotEnvironment as S, SnapshotEnvironmentOptions as a }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/environment.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/environment.d.ts new file mode 100644 index 0000000..efa86bc --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/dist/environment.d.ts @@ -0,0 +1,16 @@ +import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment.d-DHdQ1Csl.js'; + +declare class NodeSnapshotEnvironment implements SnapshotEnvironment { + private options; + constructor(options?: SnapshotEnvironmentOptions); + getVersion(): string; + getHeader(): string; + resolveRawPath(testPath: string, rawPath: string): Promise; + resolvePath(filepath: string): Promise; + prepareDirectory(dirPath: string): Promise; + saveSnapshotFile(filepath: string, snapshot: string): Promise; + readSnapshotFile(filepath: string): Promise; + removeSnapshotFile(filepath: string): Promise; +} + +export { NodeSnapshotEnvironment, SnapshotEnvironment }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/environment.js b/vanilla/node_modules/@vitest/snapshot/dist/environment.js new file mode 100644 index 0000000..079b478 --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/dist/environment.js @@ -0,0 +1,40 @@ +import { promises, existsSync } from 'node:fs'; +import { resolve, isAbsolute, dirname, join, basename } from 'pathe'; + +class NodeSnapshotEnvironment { + constructor(options = {}) { + this.options = options; + } + getVersion() { + return "1"; + } + getHeader() { + return `// Snapshot v${this.getVersion()}`; + } + async resolveRawPath(testPath, rawPath) { + return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath); + } + async resolvePath(filepath) { + return join(join(dirname(filepath), this.options.snapshotsDirName ?? "__snapshots__"), `${basename(filepath)}.snap`); + } + async prepareDirectory(dirPath) { + await promises.mkdir(dirPath, { recursive: true }); + } + async saveSnapshotFile(filepath, snapshot) { + await promises.mkdir(dirname(filepath), { recursive: true }); + await promises.writeFile(filepath, snapshot, "utf-8"); + } + async readSnapshotFile(filepath) { + if (!existsSync(filepath)) { + return null; + } + return promises.readFile(filepath, "utf-8"); + } + async removeSnapshotFile(filepath) { + if (existsSync(filepath)) { + await promises.unlink(filepath); + } + } +} + +export { NodeSnapshotEnvironment }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/index.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/index.d.ts new file mode 100644 index 0000000..260d8ed --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/dist/index.d.ts @@ -0,0 +1,130 @@ +import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './rawSnapshot.d-lFsMJFUd.js'; +export { c as SnapshotData, d as SnapshotSerializer, e as SnapshotSummary, f as SnapshotUpdateState, U as UncheckedSnapshot } from './rawSnapshot.d-lFsMJFUd.js'; +import { S as SnapshotEnvironment, P as ParsedStack } from './environment.d-DHdQ1Csl.js'; +import { Plugin, Plugins } from '@vitest/pretty-format'; + +/** +* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +declare class DefaultMap< + K, + V +> extends Map { + private defaultFn; + constructor(defaultFn: (key: K) => V, entries?: Iterable); + get(key: K): V; +} +declare class CounterMap extends DefaultMap { + constructor(); + _total: number | undefined; + valueOf(): number; + increment(key: K): void; + total(): number; +} + +interface SnapshotReturnOptions { + actual: string; + count: number; + expected?: string; + key: string; + pass: boolean; +} +interface SaveStatus { + deleted: boolean; + saved: boolean; +} +declare class SnapshotState { + testFilePath: string; + snapshotPath: string; + private _counters; + private _dirty; + private _updateSnapshot; + private _snapshotData; + private _initialData; + private _inlineSnapshots; + private _inlineSnapshotStacks; + private _testIdToKeys; + private _rawSnapshots; + private _uncheckedKeys; + private _snapshotFormat; + private _environment; + private _fileExists; + expand: boolean; + private _added; + private _matched; + private _unmatched; + private _updated; + get added(): CounterMap; + set added(value: number); + get matched(): CounterMap; + set matched(value: number); + get unmatched(): CounterMap; + set unmatched(value: number); + get updated(): CounterMap; + set updated(value: number); + private constructor(); + static create(testFilePath: string, options: SnapshotStateOptions): Promise; + get environment(): SnapshotEnvironment; + markSnapshotsAsCheckedForTest(testName: string): void; + clearTest(testId: string): void; + protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null; + private _addSnapshot; + save(): Promise; + getUncheckedCount(): number; + getUncheckedKeys(): Array; + removeUncheckedKeys(): void; + match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot }: SnapshotMatchOptions): SnapshotReturnOptions; + pack(): Promise; +} + +interface AssertOptions { + received: unknown; + filepath: string; + name: string; + /** + * Not required but needed for `SnapshotClient.clearTest` to implement test-retry behavior. + * @default name + */ + testId?: string; + message?: string; + isInline?: boolean; + properties?: object; + inlineSnapshot?: string; + error?: Error; + errorMessage?: string; + rawSnapshot?: RawSnapshotInfo; +} +interface SnapshotClientOptions { + isEqual?: (received: unknown, expected: unknown) => boolean; +} +declare class SnapshotClient { + private options; + snapshotStateMap: Map; + constructor(options?: SnapshotClientOptions); + setup(filepath: string, options: SnapshotStateOptions): Promise; + finish(filepath: string): Promise; + skipTest(filepath: string, testName: string): void; + clearTest(filepath: string, testId: string): void; + getSnapshotState(filepath: string): SnapshotState; + assert(options: AssertOptions): void; + assertRaw(options: AssertOptions): Promise; + clear(): void; +} + +declare function stripSnapshotIndentation(inlineSnapshot: string): string; + +/** +* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +declare function addSerializer(plugin: Plugin): void; +declare function getSerializers(): Plugins; + +export { SnapshotClient, SnapshotEnvironment, SnapshotMatchOptions, SnapshotResult, SnapshotState, SnapshotStateOptions, addSerializer, getSerializers, stripSnapshotIndentation }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/index.js b/vanilla/node_modules/@vitest/snapshot/dist/index.js new file mode 100644 index 0000000..40d564e --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/dist/index.js @@ -0,0 +1,1437 @@ +import { resolve } from 'pathe'; +import { plugins, format } from '@vitest/pretty-format'; + +// src/vlq.ts +var comma = ",".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} + +// src/trace-mapping.ts + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; + +// src/binary-search.ts +var found = false; +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + (high - low >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return state.lastIndex = binarySearch(haystack, needle, low, high); +} + +// src/trace-mapping.ts +var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; +var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; +var LEAST_UPPER_BOUND = -1; +var GREATEST_LOWER_BOUND = 1; +function cast(map) { + return map; +} +function decodedMappings(map) { + var _a; + return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded)); +} +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + if (line >= decoded.length) return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND + ); + if (index === -1) return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null + ); +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + if (index === -1 || index === segments.length) return -1; + return index; +} + +function notNullish(v) { + return v != null; +} +function isPrimitive(value) { + return value === null || typeof value !== "function" && typeof value !== "object"; +} +function isObject(item) { + return item != null && typeof item === "object" && !Array.isArray(item); +} +/** +* If code starts with a function call, will return its last index, respecting arguments. +* This will return 25 - last ending character of toMatch ")" +* Also works with callbacks +* ``` +* toMatch({ test: '123' }); +* toBeAliased('123') +* ``` +*/ +function getCallLastIndex(code) { + let charIndex = -1; + let inString = null; + let startedBracers = 0; + let endedBracers = 0; + let beforeChar = null; + while (charIndex <= code.length) { + beforeChar = code[charIndex]; + charIndex++; + const char = code[charIndex]; + const isCharString = char === "\"" || char === "'" || char === "`"; + if (isCharString && beforeChar !== "\\") { + if (inString === char) { + inString = null; + } else if (!inString) { + inString = char; + } + } + if (!inString) { + if (char === "(") { + startedBracers++; + } + if (char === ")") { + endedBracers++; + } + } + if (startedBracers && endedBracers && startedBracers === endedBracers) { + return charIndex; + } + } + return null; +} + +const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m; +const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/; +const stackIgnorePatterns = [ + "node:internal", + /\/packages\/\w+\/dist\//, + /\/@vitest\/\w+\/dist\//, + "/vitest/dist/", + "/vitest/src/", + "/node_modules/chai/", + "/node_modules/tinyspy/", + "/vite/dist/node/module-runner", + "/rolldown-vite/dist/node/module-runner", + "/deps/chunk-", + "/deps/@vitest", + "/deps/loupe", + "/deps/chai", + "/browser-playwright/dist/locators.js", + "/browser-webdriverio/dist/locators.js", + "/browser-preview/dist/locators.js", + /node:\w+/, + /__vitest_test__/, + /__vitest_browser__/, + /\/deps\/vitest_/ +]; +function extractLocation(urlLike) { + // Fail-fast but return locations like "(native)" + if (!urlLike.includes(":")) { + return [urlLike]; + } + const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; + const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); + if (!parts) { + return [urlLike]; + } + let url = parts[1]; + if (url.startsWith("async ")) { + url = url.slice(6); + } + if (url.startsWith("http:") || url.startsWith("https:")) { + const urlObj = new URL(url); + urlObj.searchParams.delete("import"); + urlObj.searchParams.delete("browserv"); + url = urlObj.pathname + urlObj.hash + urlObj.search; + } + if (url.startsWith("/@fs/")) { + const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url); + url = url.slice(isWindows ? 5 : 4); + } + return [ + url, + parts[2] || undefined, + parts[3] || undefined + ]; +} +function parseSingleFFOrSafariStack(raw) { + let line = raw.trim(); + if (SAFARI_NATIVE_CODE_REGEXP.test(line)) { + return null; + } + if (line.includes(" > eval")) { + line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); + } + // Early return for lines that don't look like Firefox/Safari stack traces + // Firefox/Safari stack traces must contain '@' and should have location info after it + if (!line.includes("@")) { + return null; + } + // Find the correct @ that separates function name from location + // For cases like '@https://@fs/path' or 'functionName@https://@fs/path' + // we need to find the first @ that precedes a valid location (containing :) + let atIndex = -1; + let locationPart = ""; + let functionName; + // Try each @ from left to right to find the one that gives us a valid location + for (let i = 0; i < line.length; i++) { + if (line[i] === "@") { + const candidateLocation = line.slice(i + 1); + // Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1") + if (candidateLocation.includes(":") && candidateLocation.length >= 3) { + atIndex = i; + locationPart = candidateLocation; + functionName = i > 0 ? line.slice(0, i) : undefined; + break; + } + } + } + // Validate we found a valid location with minimum length (filename:line format) + if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) { + return null; + } + const [url, lineNumber, columnNumber] = extractLocation(locationPart); + if (!url || !lineNumber || !columnNumber) { + return null; + } + return { + file: url, + method: functionName || "", + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +// Based on https://github.com/stacktracejs/error-stack-parser +// Credit to stacktracejs +function parseSingleV8Stack(raw) { + let line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) { + return null; + } + if (line.includes("(eval ")) { + line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, ""); + } + let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, ""); + // capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in + // case it has spaces in it, as the string is split on \s+ later on + const location = sanitizedLine.match(/ (\(.+\)$)/); + // remove the parenthesized location from the line, if it was matched + sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; + // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine + // because this line doesn't have function name + const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); + let method = location && sanitizedLine || ""; + let file = url && ["eval", ""].includes(url) ? undefined : url; + if (!file || !lineNumber || !columnNumber) { + return null; + } + if (method.startsWith("async ")) { + method = method.slice(6); + } + if (file.startsWith("file://")) { + file = file.slice(7); + } + // normalize Windows path (\ -> /) + file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file); + if (method) { + method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, ""); + } + return { + method, + file, + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function parseStacktrace(stack, options = {}) { + const { ignoreStackEntries = stackIgnorePatterns } = options; + const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack); + return stacks.map((stack) => { + var _options$getSourceMap; + if (options.getUrlId) { + stack.file = options.getUrlId(stack.file); + } + const map = (_options$getSourceMap = options.getSourceMap) === null || _options$getSourceMap === void 0 ? void 0 : _options$getSourceMap.call(options, stack.file); + if (!map || typeof map !== "object" || !map.version) { + return shouldFilter(ignoreStackEntries, stack.file) ? null : stack; + } + const traceMap = new DecodedMap(map, stack.file); + const position = getOriginalPosition(traceMap, stack); + if (!position) { + return stack; + } + const { line, column, source, name } = position; + let file = source || stack.file; + if (file.match(/\/\w:\//)) { + file = file.slice(1); + } + if (shouldFilter(ignoreStackEntries, file)) { + return null; + } + if (line != null && column != null) { + return { + line, + column, + file, + method: name || stack.method + }; + } + return stack; + }).filter((s) => s != null); +} +function shouldFilter(ignoreStackEntries, file) { + return ignoreStackEntries.some((p) => file.match(p)); +} +function parseFFOrSafariStackTrace(stack) { + return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish); +} +function parseV8Stacktrace(stack) { + return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish); +} +function parseErrorStacktrace(e, options = {}) { + if (!e || isPrimitive(e)) { + return []; + } + if ("stacks" in e && e.stacks) { + return e.stacks; + } + const stackStr = e.stack || ""; + // if "stack" property was overwritten at runtime to be something else, + // ignore the value because we don't know how to process it + let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : []; + if (!stackFrames.length) { + const e_ = e; + if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) { + stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options); + } + if (e_.sourceURL != null && e_.line != null && e_._column != null) { + stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options); + } + } + if (options.frameFilter) { + stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false); + } + e.stacks = stackFrames; + return stackFrames; +} +class DecodedMap { + _encoded; + _decoded; + _decodedMemo; + url; + version; + names = []; + resolvedSources; + constructor(map, from) { + this.map = map; + const { mappings, names, sources } = map; + this.version = map.version; + this.names = names || []; + this._encoded = mappings || ""; + this._decodedMemo = memoizedState(); + this.url = from; + this.resolvedSources = (sources || []).map((s) => resolve(s || "", from)); + } +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1 + }; +} +function getOriginalPosition(map, needle) { + const result = originalPositionFor(map, needle); + if (result.column == null) { + return null; + } + return result; +} + +const lineSplitRE = /\r?\n/; +function positionToOffset(source, lineNumber, columnNumber) { + const lines = source.split(lineSplitRE); + const nl = /\r\n/.test(source) ? 2 : 1; + let start = 0; + if (lineNumber > lines.length) { + return source.length; + } + for (let i = 0; i < lineNumber - 1; i++) { + start += lines[i].length + nl; + } + return start + columnNumber; +} +function offsetToLineNumber(source, offset) { + if (offset > source.length) { + throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`); + } + const lines = source.split(lineSplitRE); + const nl = /\r\n/.test(source) ? 2 : 1; + let counted = 0; + let line = 0; + for (; line < lines.length; line++) { + const lineLength = lines[line].length + nl; + if (counted + lineLength >= offset) { + break; + } + counted += lineLength; + } + return line + 1; +} + +async function saveInlineSnapshots(environment, snapshots) { + const MagicString = (await import('magic-string')).default; + const files = new Set(snapshots.map((i) => i.file)); + await Promise.all(Array.from(files).map(async (file) => { + const snaps = snapshots.filter((i) => i.file === file); + const code = await environment.readSnapshotFile(file); + const s = new MagicString(code); + for (const snap of snaps) { + const index = positionToOffset(code, snap.line, snap.column); + replaceInlineSnap(code, s, index, snap.snapshot); + } + const transformed = s.toString(); + if (transformed !== code) { + await environment.saveSnapshotFile(file, transformed); + } + })); +} +const startObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*\{/; +function replaceObjectSnap(code, s, index, newSnap) { + let _code = code.slice(index); + const startMatch = startObjectRegex.exec(_code); + if (!startMatch) { + return false; + } + _code = _code.slice(startMatch.index); + let callEnd = getCallLastIndex(_code); + if (callEnd === null) { + return false; + } + callEnd += index + startMatch.index; + const shapeStart = index + startMatch.index + startMatch[0].length; + const shapeEnd = getObjectShapeEndIndex(code, shapeStart); + const snap = `, ${prepareSnapString(newSnap, code, index)}`; + if (shapeEnd === callEnd) { + // toMatchInlineSnapshot({ foo: expect.any(String) }) + s.appendLeft(callEnd, snap); + } else { + // toMatchInlineSnapshot({ foo: expect.any(String) }, ``) + s.overwrite(shapeEnd, callEnd, snap); + } + return true; +} +function getObjectShapeEndIndex(code, index) { + let startBraces = 1; + let endBraces = 0; + while (startBraces !== endBraces && index < code.length) { + const s = code[index++]; + if (s === "{") { + startBraces++; + } else if (s === "}") { + endBraces++; + } + } + return index; +} +function prepareSnapString(snap, source, index) { + const lineNumber = offsetToLineNumber(source, index); + const line = source.split(lineSplitRE)[lineNumber - 1]; + const indent = line.match(/^\s*/)[0] || ""; + const indentNext = indent.includes(" ") ? `${indent}\t` : `${indent} `; + const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g); + const isOneline = lines.length <= 1; + const quote = "`"; + if (isOneline) { + return `${quote}${lines.join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}${quote}`; + } + return `${quote}\n${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}\n${indent}${quote}`; +} +const toMatchInlineName = "toMatchInlineSnapshot"; +const toThrowErrorMatchingInlineName = "toThrowErrorMatchingInlineSnapshot"; +// on webkit, the line number is at the end of the method, not at the start +function getCodeStartingAtIndex(code, index) { + const indexInline = index - toMatchInlineName.length; + if (code.slice(indexInline, index) === toMatchInlineName) { + return { + code: code.slice(indexInline), + index: indexInline + }; + } + const indexThrowInline = index - toThrowErrorMatchingInlineName.length; + if (code.slice(index - indexThrowInline, index) === toThrowErrorMatchingInlineName) { + return { + code: code.slice(index - indexThrowInline), + index: index - indexThrowInline + }; + } + return { + code: code.slice(index), + index + }; +} +const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*[\w$]*(['"`)])/; +function replaceInlineSnap(code, s, currentIndex, newSnap) { + const { code: codeStartingAtIndex, index } = getCodeStartingAtIndex(code, currentIndex); + const startMatch = startRegex.exec(codeStartingAtIndex); + const firstKeywordMatch = /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/.exec(codeStartingAtIndex); + if (!startMatch || startMatch.index !== (firstKeywordMatch === null || firstKeywordMatch === void 0 ? void 0 : firstKeywordMatch.index)) { + return replaceObjectSnap(code, s, index, newSnap); + } + const quote = startMatch[1]; + const startIndex = index + startMatch.index + startMatch[0].length; + const snapString = prepareSnapString(newSnap, code, index); + if (quote === ")") { + s.appendRight(startIndex - 1, snapString); + return true; + } + const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`); + const endMatch = quoteEndRE.exec(code.slice(startIndex)); + if (!endMatch) { + return false; + } + const endIndex = startIndex + endMatch.index + endMatch[0].length; + s.overwrite(startIndex - 1, endIndex, snapString); + return true; +} +const INDENTATION_REGEX = /^([^\S\n]*)\S/m; +function stripSnapshotIndentation(inlineSnapshot) { + var _lines$at; + // Find indentation if exists. + const match = inlineSnapshot.match(INDENTATION_REGEX); + if (!match || !match[1]) { + // No indentation. + return inlineSnapshot; + } + const indentation = match[1]; + const lines = inlineSnapshot.split(/\n/g); + if (lines.length <= 2) { + // Must be at least 3 lines. + return inlineSnapshot; + } + if (lines[0].trim() !== "" || ((_lines$at = lines.at(-1)) === null || _lines$at === void 0 ? void 0 : _lines$at.trim()) !== "") { + // If not blank first and last lines, abort. + return inlineSnapshot; + } + for (let i = 1; i < lines.length - 1; i++) { + if (lines[i] !== "") { + if (lines[i].indexOf(indentation) !== 0) { + // All lines except first and last should either be blank or have the same + // indent as the first line (or more). If this isn't the case we don't + // want to touch the snapshot at all. + return inlineSnapshot; + } + lines[i] = lines[i].substring(indentation.length); + } + } + // Last line is a special case because it won't have the same indent as others + // but may still have been given some indent to line up. + lines[lines.length - 1] = ""; + // Return inline snapshot, now at indent 0. + inlineSnapshot = lines.join("\n"); + return inlineSnapshot; +} + +async function saveRawSnapshots(environment, snapshots) { + await Promise.all(snapshots.map(async (snap) => { + if (!snap.readonly) { + await environment.saveSnapshotFile(snap.file, snap.snapshot); + } + })); +} + +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} + +var naturalCompare$1 = {exports: {}}; + +var hasRequiredNaturalCompare; + +function requireNaturalCompare () { + if (hasRequiredNaturalCompare) return naturalCompare$1.exports; + hasRequiredNaturalCompare = 1; + /* + * @version 1.4.0 + * @date 2015-10-26 + * @stability 3 - Stable + * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite) + * @license MIT License + */ + + + var naturalCompare = function(a, b) { + var i, codeA + , codeB = 1 + , posA = 0 + , posB = 0 + , alphabet = String.alphabet; + + function getCode(str, pos, code) { + if (code) { + for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i; + return +str.slice(pos - 1, i) + } + code = alphabet && alphabet.indexOf(str.charAt(pos)); + return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code + : code < 46 ? 65 // - + : code < 48 ? code - 1 + : code < 58 ? code + 18 // 0-9 + : code < 65 ? code - 11 + : code < 91 ? code + 11 // A-Z + : code < 97 ? code - 37 + : code < 123 ? code + 5 // a-z + : code - 63 + } + + + if ((a+="") != (b+="")) for (;codeB;) { + codeA = getCode(a, posA++); + codeB = getCode(b, posB++); + + if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) { + codeA = getCode(a, posA, posA); + codeB = getCode(b, posB, posA = i); + posB = i; + } + + if (codeA != codeB) return (codeA < codeB) ? -1 : 1 + } + return 0 + }; + + try { + naturalCompare$1.exports = naturalCompare; + } catch (e) { + String.naturalCompare = naturalCompare; + } + return naturalCompare$1.exports; +} + +var naturalCompareExports = requireNaturalCompare(); +var naturalCompare = /*@__PURE__*/getDefaultExportFromCjs(naturalCompareExports); + +const serialize$1 = (val, config, indentation, depth, refs, printer) => { + // Serialize a non-default name, even if config.printFunctionName is false. + const name = val.getMockName(); + const nameString = name === "vi.fn()" ? "" : ` ${name}`; + let callsString = ""; + if (val.mock.calls.length !== 0) { + const indentationNext = indentation + config.indent; + callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer(val.mock.calls, config, indentationNext, depth, refs)}${config.min ? ", " : ","}${config.spacingOuter}${indentationNext}"results": ${printer(val.mock.results, config, indentationNext, depth, refs)}${config.min ? "" : ","}${config.spacingOuter}${indentation}}`; + } + return `[MockFunction${nameString}]${callsString}`; +}; +const test = (val) => val && !!val._isMockFunction; +const plugin = { + serialize: serialize$1, + test +}; + +const { DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent, AsymmetricMatcher } = plugins; +let PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher, + plugin +]; +function addSerializer(plugin) { + PLUGINS = [plugin].concat(PLUGINS); +} +function getSerializers() { + return PLUGINS; +} + +// TODO: rewrite and clean up +function testNameToKey(testName, count) { + return `${testName} ${count}`; +} +function keyToTestName(key) { + if (!/ \d+$/.test(key)) { + throw new Error("Snapshot keys must end with a number."); + } + return key.replace(/ \d+$/, ""); +} +function getSnapshotData(content, options) { + const update = options.updateSnapshot; + const data = Object.create(null); + let snapshotContents = ""; + let dirty = false; + if (content != null) { + try { + snapshotContents = content; + // eslint-disable-next-line no-new-func + const populate = new Function("exports", snapshotContents); + populate(data); + } catch {} + } + // const validationResult = validateSnapshotVersion(snapshotContents) + const isInvalid = snapshotContents; + // if (update === 'none' && isInvalid) + // throw validationResult + if ((update === "all" || update === "new") && isInvalid) { + dirty = true; + } + return { + data, + dirty + }; +} +// Add extra line breaks at beginning and end of multiline snapshot +// to make the content easier to read. +function addExtraLineBreaks(string) { + return string.includes("\n") ? `\n${string}\n` : string; +} +// Remove extra line breaks at beginning and end of multiline snapshot. +// Instead of trim, which can remove additional newlines or spaces +// at beginning or end of the content from a custom serializer. +function removeExtraLineBreaks(string) { + return string.length > 2 && string[0] === "\n" && string.endsWith("\n") ? string.slice(1, -1) : string; +} +// export const removeLinesBeforeExternalMatcherTrap = (stack: string): string => { +// const lines = stack.split('\n') +// for (let i = 0; i < lines.length; i += 1) { +// // It's a function name specified in `packages/expect/src/index.ts` +// // for external custom matchers. +// if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__')) +// return lines.slice(i + 1).join('\n') +// } +// return stack +// } +const escapeRegex = true; +const printFunctionName = false; +function serialize(val, indent = 2, formatOverrides = {}) { + return normalizeNewlines(format(val, { + escapeRegex, + indent, + plugins: getSerializers(), + printFunctionName, + ...formatOverrides + })); +} +function escapeBacktickString(str) { + return str.replace(/`|\\|\$\{/g, "\\$&"); +} +function printBacktickString(str) { + return `\`${escapeBacktickString(str)}\``; +} +function normalizeNewlines(string) { + return string.replace(/\r\n|\r/g, "\n"); +} +async function saveSnapshotFile(environment, snapshotData, snapshotPath) { + const snapshots = Object.keys(snapshotData).sort(naturalCompare).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`); + const content = `${environment.getHeader()}\n\n${snapshots.join("\n\n")}\n`; + const oldContent = await environment.readSnapshotFile(snapshotPath); + const skipWriting = oldContent != null && oldContent === content; + if (skipWriting) { + return; + } + await environment.saveSnapshotFile(snapshotPath, content); +} +function deepMergeArray(target = [], source = []) { + const mergedOutput = Array.from(target); + source.forEach((sourceElement, index) => { + const targetElement = mergedOutput[index]; + if (Array.isArray(target[index])) { + mergedOutput[index] = deepMergeArray(target[index], sourceElement); + } else if (isObject(targetElement)) { + mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement); + } else { + // Source does not exist in target or target is primitive and cannot be deep merged + mergedOutput[index] = sourceElement; + } + }); + return mergedOutput; +} +/** +* Deep merge, but considers asymmetric matchers. Unlike base util's deep merge, +* will merge any object-like instance. +* Compatible with Jest's snapshot matcher. Should not be used outside of snapshot. +* +* @example +* ```ts +* toMatchSnapshot({ +* name: expect.stringContaining('text') +* }) +* ``` +*/ +function deepMergeSnapshot(target, source) { + if (isObject(target) && isObject(source)) { + const mergedOutput = { ...target }; + Object.keys(source).forEach((key) => { + if (isObject(source[key]) && !source[key].$$typeof) { + if (!(key in target)) { + Object.assign(mergedOutput, { [key]: source[key] }); + } else { + mergedOutput[key] = deepMergeSnapshot(target[key], source[key]); + } + } else if (Array.isArray(source[key])) { + mergedOutput[key] = deepMergeArray(target[key], source[key]); + } else { + Object.assign(mergedOutput, { [key]: source[key] }); + } + }); + return mergedOutput; + } else if (Array.isArray(target) && Array.isArray(source)) { + return deepMergeArray(target, source); + } + return target; +} +class DefaultMap extends Map { + constructor(defaultFn, entries) { + super(entries); + this.defaultFn = defaultFn; + } + get(key) { + if (!this.has(key)) { + this.set(key, this.defaultFn(key)); + } + return super.get(key); + } +} +class CounterMap extends DefaultMap { + constructor() { + super(() => 0); + } + // compat for jest-image-snapshot https://github.com/vitest-dev/vitest/issues/7322 + // `valueOf` and `Snapshot.added` setter allows + // snapshotState.added = snapshotState.added + 1 + // to function as + // snapshotState.added.total_ = snapshotState.added.total() + 1 + _total; + valueOf() { + return this._total = this.total(); + } + increment(key) { + if (typeof this._total !== "undefined") { + this._total++; + } + this.set(key, this.get(key) + 1); + } + total() { + if (typeof this._total !== "undefined") { + return this._total; + } + let total = 0; + for (const x of this.values()) { + total += x; + } + return total; + } +} + +function isSameStackPosition(x, y) { + return x.file === y.file && x.column === y.column && x.line === y.line; +} +class SnapshotState { + _counters = new CounterMap(); + _dirty; + _updateSnapshot; + _snapshotData; + _initialData; + _inlineSnapshots; + _inlineSnapshotStacks; + _testIdToKeys = new DefaultMap(() => []); + _rawSnapshots; + _uncheckedKeys; + _snapshotFormat; + _environment; + _fileExists; + expand; + // getter/setter for jest-image-snapshot compat + // https://github.com/vitest-dev/vitest/issues/7322 + _added = new CounterMap(); + _matched = new CounterMap(); + _unmatched = new CounterMap(); + _updated = new CounterMap(); + get added() { + return this._added; + } + set added(value) { + this._added._total = value; + } + get matched() { + return this._matched; + } + set matched(value) { + this._matched._total = value; + } + get unmatched() { + return this._unmatched; + } + set unmatched(value) { + this._unmatched._total = value; + } + get updated() { + return this._updated; + } + set updated(value) { + this._updated._total = value; + } + constructor(testFilePath, snapshotPath, snapshotContent, options) { + this.testFilePath = testFilePath; + this.snapshotPath = snapshotPath; + const { data, dirty } = getSnapshotData(snapshotContent, options); + this._fileExists = snapshotContent != null; + this._initialData = { ...data }; + this._snapshotData = { ...data }; + this._dirty = dirty; + this._inlineSnapshots = []; + this._inlineSnapshotStacks = []; + this._rawSnapshots = []; + this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); + this.expand = options.expand || false; + this._updateSnapshot = options.updateSnapshot; + this._snapshotFormat = { + printBasicPrototype: false, + escapeString: false, + ...options.snapshotFormat + }; + this._environment = options.snapshotEnvironment; + } + static async create(testFilePath, options) { + const snapshotPath = await options.snapshotEnvironment.resolvePath(testFilePath); + const content = await options.snapshotEnvironment.readSnapshotFile(snapshotPath); + return new SnapshotState(testFilePath, snapshotPath, content, options); + } + get environment() { + return this._environment; + } + markSnapshotsAsCheckedForTest(testName) { + this._uncheckedKeys.forEach((uncheckedKey) => { + // skip snapshots with following keys + // testName n + // testName > xxx n (this is for toMatchSnapshot("xxx") API) + if (/ \d+$| > /.test(uncheckedKey.slice(testName.length))) { + this._uncheckedKeys.delete(uncheckedKey); + } + }); + } + clearTest(testId) { + // clear inline + this._inlineSnapshots = this._inlineSnapshots.filter((s) => s.testId !== testId); + this._inlineSnapshotStacks = this._inlineSnapshotStacks.filter((s) => s.testId !== testId); + // clear file + for (const key of this._testIdToKeys.get(testId)) { + const name = keyToTestName(key); + const count = this._counters.get(name); + if (count > 0) { + if (key in this._snapshotData || key in this._initialData) { + this._snapshotData[key] = this._initialData[key]; + } + this._counters.set(name, count - 1); + } + } + this._testIdToKeys.delete(testId); + // clear stats + this.added.delete(testId); + this.updated.delete(testId); + this.matched.delete(testId); + this.unmatched.delete(testId); + } + _inferInlineSnapshotStack(stacks) { + // if called inside resolves/rejects, stacktrace is different + const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/)); + if (promiseIndex !== -1) { + return stacks[promiseIndex + 3]; + } + // inline snapshot function is called __INLINE_SNAPSHOT__ + // in integrations/snapshot/chai.ts + const stackIndex = stacks.findIndex((i) => i.method.includes("__INLINE_SNAPSHOT__")); + return stackIndex !== -1 ? stacks[stackIndex + 2] : null; + } + _addSnapshot(key, receivedSerialized, options) { + this._dirty = true; + if (options.stack) { + this._inlineSnapshots.push({ + snapshot: receivedSerialized, + testId: options.testId, + ...options.stack + }); + } else if (options.rawSnapshot) { + this._rawSnapshots.push({ + ...options.rawSnapshot, + snapshot: receivedSerialized + }); + } else { + this._snapshotData[key] = receivedSerialized; + } + } + async save() { + const hasExternalSnapshots = Object.keys(this._snapshotData).length; + const hasInlineSnapshots = this._inlineSnapshots.length; + const hasRawSnapshots = this._rawSnapshots.length; + const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots && !hasRawSnapshots; + const status = { + deleted: false, + saved: false + }; + if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) { + if (hasExternalSnapshots) { + await saveSnapshotFile(this._environment, this._snapshotData, this.snapshotPath); + this._fileExists = true; + } + if (hasInlineSnapshots) { + await saveInlineSnapshots(this._environment, this._inlineSnapshots); + } + if (hasRawSnapshots) { + await saveRawSnapshots(this._environment, this._rawSnapshots); + } + status.saved = true; + } else if (!hasExternalSnapshots && this._fileExists) { + if (this._updateSnapshot === "all") { + await this._environment.removeSnapshotFile(this.snapshotPath); + this._fileExists = false; + } + status.deleted = true; + } + return status; + } + getUncheckedCount() { + return this._uncheckedKeys.size || 0; + } + getUncheckedKeys() { + return Array.from(this._uncheckedKeys); + } + removeUncheckedKeys() { + if (this._updateSnapshot === "all" && this._uncheckedKeys.size) { + this._dirty = true; + this._uncheckedKeys.forEach((key) => delete this._snapshotData[key]); + this._uncheckedKeys.clear(); + } + } + match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot }) { + // this also increments counter for inline snapshots. maybe we shouldn't? + this._counters.increment(testName); + const count = this._counters.get(testName); + if (!key) { + key = testNameToKey(testName, count); + } + this._testIdToKeys.get(testId).push(key); + // Do not mark the snapshot as "checked" if the snapshot is inline and + // there's an external snapshot. This way the external snapshot can be + // removed with `--updateSnapshot`. + if (!(isInline && this._snapshotData[key] !== undefined)) { + this._uncheckedKeys.delete(key); + } + let receivedSerialized = rawSnapshot && typeof received === "string" ? received : serialize(received, undefined, this._snapshotFormat); + if (!rawSnapshot) { + receivedSerialized = addExtraLineBreaks(receivedSerialized); + } + if (rawSnapshot) { + // normalize EOL when snapshot contains CRLF but received is LF + if (rawSnapshot.content && rawSnapshot.content.match(/\r\n/) && !receivedSerialized.match(/\r\n/)) { + rawSnapshot.content = normalizeNewlines(rawSnapshot.content); + } + } + const expected = isInline ? inlineSnapshot : rawSnapshot ? rawSnapshot.content : this._snapshotData[key]; + const expectedTrimmed = rawSnapshot ? expected : expected === null || expected === void 0 ? void 0 : expected.trim(); + const pass = expectedTrimmed === (rawSnapshot ? receivedSerialized : receivedSerialized.trim()); + const hasSnapshot = expected !== undefined; + const snapshotIsPersisted = isInline || this._fileExists || rawSnapshot && rawSnapshot.content != null; + if (pass && !isInline && !rawSnapshot) { + // Executing a snapshot file as JavaScript and writing the strings back + // when other snapshots have changed loses the proper escaping for some + // characters. Since we check every snapshot in every test, use the newly + // generated formatted string. + // Note that this is only relevant when a snapshot is added and the dirty + // flag is set. + this._snapshotData[key] = receivedSerialized; + } + // find call site of toMatchInlineSnapshot + let stack; + if (isInline) { + var _this$environment$pro, _this$environment; + const stacks = parseErrorStacktrace(error || new Error("snapshot"), { ignoreStackEntries: [] }); + const _stack = this._inferInlineSnapshotStack(stacks); + if (!_stack) { + throw new Error(`@vitest/snapshot: Couldn't infer stack frame for inline snapshot.\n${JSON.stringify(stacks)}`); + } + stack = ((_this$environment$pro = (_this$environment = this.environment).processStackTrace) === null || _this$environment$pro === void 0 ? void 0 : _this$environment$pro.call(_this$environment, _stack)) || _stack; + // removing 1 column, because source map points to the wrong + // location for js files, but `column-1` points to the same in both js/ts + // https://github.com/vitejs/vite/issues/8657 + stack.column--; + // reject multiple inline snapshots at the same location if snapshot is different + const snapshotsWithSameStack = this._inlineSnapshotStacks.filter((s) => isSameStackPosition(s, stack)); + if (snapshotsWithSameStack.length > 0) { + // ensure only one snapshot will be written at the same location + this._inlineSnapshots = this._inlineSnapshots.filter((s) => !isSameStackPosition(s, stack)); + const differentSnapshot = snapshotsWithSameStack.find((s) => s.snapshot !== receivedSerialized); + if (differentSnapshot) { + throw Object.assign(new Error("toMatchInlineSnapshot with different snapshots cannot be called at the same location"), { + actual: receivedSerialized, + expected: differentSnapshot.snapshot + }); + } + } + this._inlineSnapshotStacks.push({ + ...stack, + testId, + snapshot: receivedSerialized + }); + } + // These are the conditions on when to write snapshots: + // * There's no snapshot file in a non-CI environment. + // * There is a snapshot file and we decided to update the snapshot. + // * There is a snapshot file, but it doesn't have this snapshot. + // These are the conditions on when not to write snapshots: + // * The update flag is set to 'none'. + // * There's no snapshot file or a file without this snapshot on a CI environment. + if (hasSnapshot && this._updateSnapshot === "all" || (!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) { + if (this._updateSnapshot === "all") { + if (!pass) { + if (hasSnapshot) { + this.updated.increment(testId); + } else { + this.added.increment(testId); + } + this._addSnapshot(key, receivedSerialized, { + stack, + testId, + rawSnapshot + }); + } else { + this.matched.increment(testId); + } + } else { + this._addSnapshot(key, receivedSerialized, { + stack, + testId, + rawSnapshot + }); + this.added.increment(testId); + } + return { + actual: "", + count, + expected: "", + key, + pass: true + }; + } else { + if (!pass) { + this.unmatched.increment(testId); + return { + actual: rawSnapshot ? receivedSerialized : removeExtraLineBreaks(receivedSerialized), + count, + expected: expectedTrimmed !== undefined ? rawSnapshot ? expectedTrimmed : removeExtraLineBreaks(expectedTrimmed) : undefined, + key, + pass: false + }; + } else { + this.matched.increment(testId); + return { + actual: "", + count, + expected: "", + key, + pass: true + }; + } + } + } + async pack() { + const snapshot = { + filepath: this.testFilePath, + added: 0, + fileDeleted: false, + matched: 0, + unchecked: 0, + uncheckedKeys: [], + unmatched: 0, + updated: 0 + }; + const uncheckedCount = this.getUncheckedCount(); + const uncheckedKeys = this.getUncheckedKeys(); + if (uncheckedCount) { + this.removeUncheckedKeys(); + } + const status = await this.save(); + snapshot.fileDeleted = status.deleted; + snapshot.added = this.added.total(); + snapshot.matched = this.matched.total(); + snapshot.unmatched = this.unmatched.total(); + snapshot.updated = this.updated.total(); + snapshot.unchecked = !status.deleted ? uncheckedCount : 0; + snapshot.uncheckedKeys = Array.from(uncheckedKeys); + return snapshot; + } +} + +function createMismatchError(message, expand, actual, expected) { + const error = new Error(message); + Object.defineProperty(error, "actual", { + value: actual, + enumerable: true, + configurable: true, + writable: true + }); + Object.defineProperty(error, "expected", { + value: expected, + enumerable: true, + configurable: true, + writable: true + }); + Object.defineProperty(error, "diffOptions", { value: { expand } }); + return error; +} +class SnapshotClient { + snapshotStateMap = new Map(); + constructor(options = {}) { + this.options = options; + } + async setup(filepath, options) { + if (this.snapshotStateMap.has(filepath)) { + return; + } + this.snapshotStateMap.set(filepath, await SnapshotState.create(filepath, options)); + } + async finish(filepath) { + const state = this.getSnapshotState(filepath); + const result = await state.pack(); + this.snapshotStateMap.delete(filepath); + return result; + } + skipTest(filepath, testName) { + const state = this.getSnapshotState(filepath); + state.markSnapshotsAsCheckedForTest(testName); + } + clearTest(filepath, testId) { + const state = this.getSnapshotState(filepath); + state.clearTest(testId); + } + getSnapshotState(filepath) { + const state = this.snapshotStateMap.get(filepath); + if (!state) { + throw new Error(`The snapshot state for '${filepath}' is not found. Did you call 'SnapshotClient.setup()'?`); + } + return state; + } + assert(options) { + const { filepath, name, testId = name, message, isInline = false, properties, inlineSnapshot, error, errorMessage, rawSnapshot } = options; + let { received } = options; + if (!filepath) { + throw new Error("Snapshot cannot be used outside of test"); + } + const snapshotState = this.getSnapshotState(filepath); + if (typeof properties === "object") { + if (typeof received !== "object" || !received) { + throw new Error("Received value must be an object when the matcher has properties"); + } + try { + var _this$options$isEqual, _this$options; + const pass = ((_this$options$isEqual = (_this$options = this.options).isEqual) === null || _this$options$isEqual === void 0 ? void 0 : _this$options$isEqual.call(_this$options, received, properties)) ?? false; + // const pass = equals(received, properties, [iterableEquality, subsetEquality]) + if (!pass) { + throw createMismatchError("Snapshot properties mismatched", snapshotState.expand, received, properties); + } else { + received = deepMergeSnapshot(received, properties); + } + } catch (err) { + err.message = errorMessage || "Snapshot mismatched"; + throw err; + } + } + const testName = [name, ...message ? [message] : []].join(" > "); + const { actual, expected, key, pass } = snapshotState.match({ + testId, + testName, + received, + isInline, + error, + inlineSnapshot, + rawSnapshot + }); + if (!pass) { + throw createMismatchError(`Snapshot \`${key || "unknown"}\` mismatched`, snapshotState.expand, rawSnapshot ? actual : actual === null || actual === void 0 ? void 0 : actual.trim(), rawSnapshot ? expected : expected === null || expected === void 0 ? void 0 : expected.trim()); + } + } + async assertRaw(options) { + if (!options.rawSnapshot) { + throw new Error("Raw snapshot is required"); + } + const { filepath, rawSnapshot } = options; + if (rawSnapshot.content == null) { + if (!filepath) { + throw new Error("Snapshot cannot be used outside of test"); + } + const snapshotState = this.getSnapshotState(filepath); + // save the filepath, so it don't lose even if the await make it out-of-context + options.filepath || (options.filepath = filepath); + // resolve and read the raw snapshot file + rawSnapshot.file = await snapshotState.environment.resolveRawPath(filepath, rawSnapshot.file); + rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) ?? undefined; + } + return this.assert(options); + } + clear() { + this.snapshotStateMap.clear(); + } +} + +export { SnapshotClient, SnapshotState, addSerializer, getSerializers, stripSnapshotIndentation }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/manager.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/manager.d.ts new file mode 100644 index 0000000..a782935 --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/dist/manager.d.ts @@ -0,0 +1,18 @@ +import { S as SnapshotStateOptions, e as SnapshotSummary, b as SnapshotResult } from './rawSnapshot.d-lFsMJFUd.js'; +import '@vitest/pretty-format'; +import './environment.d-DHdQ1Csl.js'; + +declare class SnapshotManager { + options: Omit; + summary: SnapshotSummary; + extension: string; + constructor(options: Omit); + clear(): void; + add(result: SnapshotResult): void; + resolvePath(testPath: string, context?: T): string; + resolveRawPath(testPath: string, rawPath: string): string; +} +declare function emptySummary(options: Omit): SnapshotSummary; +declare function addSnapshotResult(summary: SnapshotSummary, result: SnapshotResult): void; + +export { SnapshotManager, addSnapshotResult, emptySummary }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/manager.js b/vanilla/node_modules/@vitest/snapshot/dist/manager.js new file mode 100644 index 0000000..90a36a3 --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/dist/manager.js @@ -0,0 +1,73 @@ +import { join, dirname, basename, resolve, isAbsolute } from 'pathe'; + +class SnapshotManager { + summary; + extension = ".snap"; + constructor(options) { + this.options = options; + this.clear(); + } + clear() { + this.summary = emptySummary(this.options); + } + add(result) { + addSnapshotResult(this.summary, result); + } + resolvePath(testPath, context) { + const resolver = this.options.resolveSnapshotPath || (() => { + return join(join(dirname(testPath), "__snapshots__"), `${basename(testPath)}${this.extension}`); + }); + const path = resolver(testPath, this.extension, context); + return path; + } + resolveRawPath(testPath, rawPath) { + return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath); + } +} +function emptySummary(options) { + const summary = { + added: 0, + failure: false, + filesAdded: 0, + filesRemoved: 0, + filesRemovedList: [], + filesUnmatched: 0, + filesUpdated: 0, + matched: 0, + total: 0, + unchecked: 0, + uncheckedKeysByFile: [], + unmatched: 0, + updated: 0, + didUpdate: options.updateSnapshot === "all" + }; + return summary; +} +function addSnapshotResult(summary, result) { + if (result.added) { + summary.filesAdded++; + } + if (result.fileDeleted) { + summary.filesRemoved++; + } + if (result.unmatched) { + summary.filesUnmatched++; + } + if (result.updated) { + summary.filesUpdated++; + } + summary.added += result.added; + summary.matched += result.matched; + summary.unchecked += result.unchecked; + if (result.uncheckedKeys && result.uncheckedKeys.length > 0) { + summary.uncheckedKeysByFile.push({ + filePath: result.filepath, + keys: result.uncheckedKeys + }); + } + summary.unmatched += result.unmatched; + summary.updated += result.updated; + summary.total += result.added + result.matched + result.unmatched + result.updated; +} + +export { SnapshotManager, addSnapshotResult, emptySummary }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts new file mode 100644 index 0000000..96fa2dd --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts @@ -0,0 +1,61 @@ +import { OptionsReceived, Plugin } from '@vitest/pretty-format'; +import { S as SnapshotEnvironment } from './environment.d-DHdQ1Csl.js'; + +type SnapshotData = Record; +type SnapshotUpdateState = "all" | "new" | "none"; +type SnapshotSerializer = Plugin; +interface SnapshotStateOptions { + updateSnapshot: SnapshotUpdateState; + snapshotEnvironment: SnapshotEnvironment; + expand?: boolean; + snapshotFormat?: OptionsReceived; + resolveSnapshotPath?: (path: string, extension: string, context?: any) => string; +} +interface SnapshotMatchOptions { + testId: string; + testName: string; + received: unknown; + key?: string; + inlineSnapshot?: string; + isInline: boolean; + error?: Error; + rawSnapshot?: RawSnapshotInfo; +} +interface SnapshotResult { + filepath: string; + added: number; + fileDeleted: boolean; + matched: number; + unchecked: number; + uncheckedKeys: Array; + unmatched: number; + updated: number; +} +interface UncheckedSnapshot { + filePath: string; + keys: Array; +} +interface SnapshotSummary { + added: number; + didUpdate: boolean; + failure: boolean; + filesAdded: number; + filesRemoved: number; + filesRemovedList: Array; + filesUnmatched: number; + filesUpdated: number; + matched: number; + total: number; + unchecked: number; + uncheckedKeysByFile: Array; + unmatched: number; + updated: number; +} + +interface RawSnapshotInfo { + file: string; + readonly?: boolean; + content?: string; +} + +export type { RawSnapshotInfo as R, SnapshotStateOptions as S, UncheckedSnapshot as U, SnapshotMatchOptions as a, SnapshotResult as b, SnapshotData as c, SnapshotSerializer as d, SnapshotSummary as e, SnapshotUpdateState as f }; diff --git a/vanilla/node_modules/@vitest/snapshot/environment.d.ts b/vanilla/node_modules/@vitest/snapshot/environment.d.ts new file mode 100644 index 0000000..855f0d1 --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/environment.d.ts @@ -0,0 +1 @@ +export * from './dist/environment.js' diff --git a/vanilla/node_modules/@vitest/snapshot/manager.d.ts b/vanilla/node_modules/@vitest/snapshot/manager.d.ts new file mode 100644 index 0000000..f3e8077 --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/manager.d.ts @@ -0,0 +1 @@ +export * from './dist/manager.js' diff --git a/vanilla/node_modules/@vitest/snapshot/package.json b/vanilla/node_modules/@vitest/snapshot/package.json new file mode 100644 index 0000000..41c347e --- /dev/null +++ b/vanilla/node_modules/@vitest/snapshot/package.json @@ -0,0 +1,54 @@ +{ + "name": "@vitest/snapshot", + "type": "module", + "version": "4.0.18", + "description": "Vitest snapshot manager", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/snapshot#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/snapshot" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./environment": { + "types": "./dist/environment.d.ts", + "default": "./dist/environment.js" + }, + "./manager": { + "types": "./dist/manager.d.ts", + "default": "./dist/manager.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "magic-string": "^0.30.21", + "pathe": "^2.0.3", + "@vitest/pretty-format": "4.0.18" + }, + "devDependencies": { + "@types/natural-compare": "^1.4.3", + "natural-compare": "^1.4.0", + "@vitest/utils": "4.0.18" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/@vitest/spy/LICENSE b/vanilla/node_modules/@vitest/spy/LICENSE new file mode 100644 index 0000000..0e5771d --- /dev/null +++ b/vanilla/node_modules/@vitest/spy/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vanilla/node_modules/@vitest/spy/README.md b/vanilla/node_modules/@vitest/spy/README.md new file mode 100644 index 0000000..5d23c87 --- /dev/null +++ b/vanilla/node_modules/@vitest/spy/README.md @@ -0,0 +1,3 @@ +# @vitest/spy + +Lightweight Jest compatible spy implementation. diff --git a/vanilla/node_modules/@vitest/spy/dist/index.d.ts b/vanilla/node_modules/@vitest/spy/dist/index.d.ts new file mode 100644 index 0000000..408aeca --- /dev/null +++ b/vanilla/node_modules/@vitest/spy/dist/index.d.ts @@ -0,0 +1,384 @@ +interface MockResultReturn { + type: "return"; + /** + * The value that was returned from the function. If function returned a Promise, then this will be a resolved value. + */ + value: T; +} +interface MockResultIncomplete { + type: "incomplete"; + value: undefined; +} +interface MockResultThrow { + type: "throw"; + /** + * An error that was thrown during function execution. + */ + value: any; +} +interface MockSettledResultIncomplete { + type: "incomplete"; + value: undefined; +} +interface MockSettledResultFulfilled { + type: "fulfilled"; + value: T; +} +interface MockSettledResultRejected { + type: "rejected"; + value: any; +} +type MockResult = MockResultReturn | MockResultThrow | MockResultIncomplete; +type MockSettledResult = MockSettledResultFulfilled | MockSettledResultRejected | MockSettledResultIncomplete; +type MockParameters = T extends Constructable ? ConstructorParameters : T extends Procedure ? Parameters : never; +type MockReturnType = T extends Constructable ? void : T extends Procedure ? ReturnType : never; +type MockProcedureContext = T extends Constructable ? InstanceType : ThisParameterType; +interface MockContext { + /** + * This is an array containing all arguments for each call. One item of the array is the arguments of that call. + * + * @see https://vitest.dev/api/mock#mock-calls + * @example + * const fn = vi.fn() + * + * fn('arg1', 'arg2') + * fn('arg3') + * + * fn.mock.calls === [ + * ['arg1', 'arg2'], // first call + * ['arg3'], // second call + * ] + */ + calls: MockParameters[]; + /** + * This is an array containing all instances that were instantiated when mock was called with a `new` keyword. Note that this is an actual context (`this`) of the function, not a return value. + * @see https://vitest.dev/api/mock#mock-instances + */ + instances: MockProcedureContext[]; + /** + * An array of `this` values that were used during each call to the mock function. + * @see https://vitest.dev/api/mock#mock-contexts + */ + contexts: MockProcedureContext[]; + /** + * The order of mock's execution. This returns an array of numbers which are shared between all defined mocks. + * + * @see https://vitest.dev/api/mock#mock-invocationcallorder + * @example + * const fn1 = vi.fn() + * const fn2 = vi.fn() + * + * fn1() + * fn2() + * fn1() + * + * fn1.mock.invocationCallOrder === [1, 3] + * fn2.mock.invocationCallOrder === [2] + */ + invocationCallOrder: number[]; + /** + * This is an array containing all values that were `returned` from the function. + * + * The `value` property contains the returned value or thrown error. If the function returned a `Promise`, then `result` will always be `'return'` even if the promise was rejected. + * + * @see https://vitest.dev/api/mock#mock-results + * @example + * const fn = vi.fn() + * .mockReturnValueOnce('result') + * .mockImplementationOnce(() => { throw new Error('thrown error') }) + * + * const result = fn() + * + * try { + * fn() + * } + * catch {} + * + * fn.mock.results === [ + * { + * type: 'return', + * value: 'result', + * }, + * { + * type: 'throw', + * value: Error, + * }, + * ] + */ + results: MockResult>[]; + /** + * An array containing all values that were `resolved` or `rejected` from the function. + * + * This array will be empty if the function was never resolved or rejected. + * + * @see https://vitest.dev/api/mock#mock-settledresults + * @example + * const fn = vi.fn().mockResolvedValueOnce('result') + * + * const result = fn() + * + * fn.mock.settledResults === [ + * { + * type: 'incomplete', + * value: undefined, + * } + * ] + * fn.mock.results === [ + * { + * type: 'return', + * value: Promise<'result'>, + * }, + * ] + * + * await result + * + * fn.mock.settledResults === [ + * { + * type: 'fulfilled', + * value: 'result', + * }, + * ] + */ + settledResults: MockSettledResult>>[]; + /** + * This contains the arguments of the last call. If spy wasn't called, will return `undefined`. + * @see https://vitest.dev/api/mock#mock-lastcall + */ + lastCall: MockParameters | undefined; +} +type Procedure = (...args: any[]) => any; +type NormalizedProcedure = T extends Constructable ? ({ + new (...args: ConstructorParameters): InstanceType; +}) | ({ + (this: InstanceType, ...args: ConstructorParameters): void; +}) : T extends Procedure ? (...args: Parameters) => ReturnType : never; +type Methods = keyof { [K in keyof T as T[K] extends Procedure ? K : never] : T[K] }; +type Properties = { [K in keyof T] : T[K] extends Procedure ? never : K }[keyof T] & (string | symbol); +type Classes = { [K in keyof T] : T[K] extends new (...args: any[]) => any ? K : never }[keyof T] & (string | symbol); +interface MockInstance extends Disposable { + /** + * Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`. + * @see https://vitest.dev/api/mock#getmockname + */ + getMockName(): string; + /** + * Sets the internal mock name. This is useful for identifying the mock when an assertion fails. + * @see https://vitest.dev/api/mock#mockname + */ + mockName(name: string): this; + /** + * Current context of the mock. It stores information about all invocation calls, instances, and results. + */ + mock: MockContext; + /** + * Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions. + * + * To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/#clearmocks) setting in the configuration. + * @see https://vitest.dev/api/mock#mockclear + */ + mockClear(): this; + /** + * Does what `mockClear` does and resets inner implementation to the original function. This also resets all "once" implementations. + * + * Note that resetting a mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. + * Resetting a mock from `vi.fn(impl)` will set implementation to `impl`. It is useful for completely resetting a mock to its default state. + * + * To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/#mockreset) setting in the configuration. + * @see https://vitest.dev/api/mock#mockreset + */ + mockReset(): this; + /** + * Does what `mockReset` does and restores original descriptors of spied-on objects. + * @see https://vitest.dev/api/mock#mockrestore + */ + mockRestore(): void; + /** + * Returns current permanent mock implementation if there is one. + * + * If mock was created with `vi.fn`, it will consider passed down method as a mock implementation. + * + * If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided. + */ + getMockImplementation(): NormalizedProcedure | undefined; + /** + * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. + * @see https://vitest.dev/api/mock#mockimplementation + * @example + * const increment = vi.fn().mockImplementation(count => count + 1); + * expect(increment(3)).toBe(4); + */ + mockImplementation(fn: NormalizedProcedure): this; + /** + * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls. + * + * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called. + * @see https://vitest.dev/api/mock#mockimplementationonce + * @example + * const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1); + * expect(fn(3)).toBe(4); + * expect(fn(3)).toBe(3); + */ + mockImplementationOnce(fn: NormalizedProcedure): this; + /** + * Overrides the original mock implementation temporarily while the callback is being executed. + * + * Note that this method takes precedence over the [`mockImplementationOnce`](https://vitest.dev/api/mock#mockimplementationonce). + * @see https://vitest.dev/api/mock#withimplementation + * @example + * const myMockFn = vi.fn(() => 'original') + * + * myMockFn.withImplementation(() => 'temp', () => { + * myMockFn() // 'temp' + * }) + * + * myMockFn() // 'original' + */ + withImplementation(fn: NormalizedProcedure, cb: () => Promise): Promise; + withImplementation(fn: NormalizedProcedure, cb: () => unknown): this; + /** + * Use this if you need to return the `this` context from the method without invoking the actual implementation. + * @see https://vitest.dev/api/mock#mockreturnthis + */ + mockReturnThis(): this; + /** + * Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function. + * @see https://vitest.dev/api/mock#mockreturnvalue + * @example + * const mock = vi.fn() + * mock.mockReturnValue(42) + * mock() // 42 + * mock.mockReturnValue(43) + * mock() // 43 + */ + mockReturnValue(value: MockReturnType): this; + /** + * Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function. + * + * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called. + * @example + * const myMockFn = vi + * .fn() + * .mockReturnValue('default') + * .mockReturnValueOnce('first call') + * .mockReturnValueOnce('second call') + * + * // 'first call', 'second call', 'default' + * console.log(myMockFn(), myMockFn(), myMockFn()) + */ + mockReturnValueOnce(value: MockReturnType): this; + /** + * Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function. + * @example + * const asyncMock = vi.fn().mockResolvedValue(42) + * asyncMock() // Promise<42> + */ + mockResolvedValue(value: Awaited>): this; + /** + * Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value. + * @example + * const myMockFn = vi + * .fn() + * .mockResolvedValue('default') + * .mockResolvedValueOnce('first call') + * .mockResolvedValueOnce('second call') + * + * // Promise<'first call'>, Promise<'second call'>, Promise<'default'> + * console.log(myMockFn(), myMockFn(), myMockFn()) + */ + mockResolvedValueOnce(value: Awaited>): this; + /** + * Accepts an error that will be rejected when async function is called. + * @example + * const asyncMock = vi.fn().mockRejectedValue(new Error('Async error')) + * await asyncMock() // throws Error<'Async error'> + */ + mockRejectedValue(error: unknown): this; + /** + * Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value. + * @example + * const asyncMock = vi + * .fn() + * .mockResolvedValueOnce('first call') + * .mockRejectedValueOnce(new Error('Async error')) + * + * await asyncMock() // first call + * await asyncMock() // throws Error<'Async error'> + */ + mockRejectedValueOnce(error: unknown): this; +} +type Mock = MockInstance & (T extends Constructable ? (T extends Procedure ? { + new (...args: ConstructorParameters): InstanceType; + (...args: Parameters): ReturnType; +} : { + new (...args: ConstructorParameters): InstanceType; +}) : { + new (...args: MockParameters): MockReturnType; + (...args: MockParameters): MockReturnType; +}) & { [P in keyof T] : T[P] }; +type PartialMaybePromise = T extends Promise> ? Promise>> : Partial; +type PartialResultFunction = T extends Constructable ? ({ + new (...args: ConstructorParameters): InstanceType; +}) | ({ + (this: InstanceType, ...args: ConstructorParameters): void; +}) : T extends Procedure ? (...args: Parameters) => PartialMaybePromise> : T; +type PartialMock = Mock> : T>>; +type MaybeMockedConstructor = T extends Constructable ? Mock : T; +type MockedFunction = Mock & { [K in keyof T] : T[K] }; +type PartiallyMockedFunction = PartialMock & { [K in keyof T] : T[K] }; +type MockedFunctionDeep = Mock & MockedObjectDeep; +type PartiallyMockedFunctionDeep = PartialMock & MockedObjectDeep; +type MockedObject = MaybeMockedConstructor & { [K in Methods] : T[K] extends Procedure ? MockedFunction : T[K] } & { [K in Properties] : T[K] }; +type MockedObjectDeep = MaybeMockedConstructor & { [K in Methods] : T[K] extends Procedure ? MockedFunctionDeep : T[K] } & { [K in Properties] : MaybeMockedDeep }; +type MaybeMockedDeep = T extends Procedure | Constructable ? MockedFunctionDeep : T extends object ? MockedObjectDeep : T; +type MaybePartiallyMockedDeep = T extends Procedure | Constructable ? PartiallyMockedFunctionDeep : T extends object ? MockedObjectDeep : T; +type MaybeMocked = T extends Procedure | Constructable ? MockedFunction : T extends object ? MockedObject : T; +type MaybePartiallyMocked = T extends Procedure | Constructable ? PartiallyMockedFunction : T extends object ? MockedObject : T; +interface Constructable { + new (...args: any[]): any; +} +type MockedClass = MockInstance & { + prototype: T extends { + prototype: any; + } ? Mocked : never; +} & T; +type Mocked = { [P in keyof T] : T[P] extends Procedure ? MockInstance : T[P] extends Constructable ? MockedClass : T[P] } & T; +interface MockConfig { + mockImplementation: Procedure | Constructable | undefined; + mockOriginal: Procedure | Constructable | undefined; + mockName: string; + onceMockImplementations: Array; +} +interface MockInstanceOption { + originalImplementation?: Procedure | Constructable; + mockImplementation?: Procedure | Constructable; + resetToMockImplementation?: boolean; + restore?: () => void; + prototypeMembers?: (string | symbol)[]; + keepMembersImplementation?: boolean; + prototypeState?: MockContext; + prototypeConfig?: MockConfig; + resetToMockName?: boolean; + name?: string | symbol; +} + +declare function isMockFunction(fn: any): fn is Mock; +declare function createMockInstance(options?: MockInstanceOption): Mock; +declare function fn(originalImplementation?: T): Mock; +declare function spyOn< + T extends object, + S extends Properties> +>(object: T, key: S, accessor: "get"): Mock<() => T[S]>; +declare function spyOn< + T extends object, + G extends Properties> +>(object: T, key: G, accessor: "set"): Mock<(arg: T[G]) => void>; +declare function spyOn< + T extends object, + M extends Classes> | Methods> +>(object: T, key: M): Required[M] extends Constructable | Procedure ? Mock[M]> : never; +declare function restoreAllMocks(): void; +declare function clearAllMocks(): void; +declare function resetAllMocks(): void; + +export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn }; +export type { Constructable, MaybeMocked, MaybeMockedConstructor, MaybeMockedDeep, MaybePartiallyMocked, MaybePartiallyMockedDeep, Mock, MockContext, MockInstance, MockInstanceOption, MockParameters, MockProcedureContext, MockResult, MockResultIncomplete, MockResultReturn, MockResultThrow, MockReturnType, MockSettledResult, MockSettledResultFulfilled, MockSettledResultIncomplete, MockSettledResultRejected, Mocked, MockedClass, MockedFunction, MockedFunctionDeep, MockedObject, MockedObjectDeep, PartialMock, PartiallyMockedFunction, PartiallyMockedFunctionDeep, Procedure }; diff --git a/vanilla/node_modules/@vitest/spy/dist/index.js b/vanilla/node_modules/@vitest/spy/dist/index.js new file mode 100644 index 0000000..96f9784 --- /dev/null +++ b/vanilla/node_modules/@vitest/spy/dist/index.js @@ -0,0 +1,433 @@ +function isMockFunction(fn) { + return typeof fn === "function" && "_isMockFunction" in fn && fn._isMockFunction === true; +} +const MOCK_RESTORE = new Set(); +// Jest keeps the state in a separate WeakMap which is good for memory, +// but it makes the state slower to access and return different values +// if you stored it before calling `mockClear` where it will be recreated +const REGISTERED_MOCKS = new Set(); +const MOCK_CONFIGS = new WeakMap(); +function createMockInstance(options = {}) { + var _ref; + const { originalImplementation, restore, mockImplementation, resetToMockImplementation, resetToMockName } = options; + if (restore) { + MOCK_RESTORE.add(restore); + } + const config = getDefaultConfig(originalImplementation); + const state = getDefaultState(); + const mock = createMock({ + config, + state, + ...options + }); + const mockLength = ((_ref = mockImplementation || originalImplementation) === null || _ref === void 0 ? void 0 : _ref.length) ?? 0; + Object.defineProperty(mock, "length", { + writable: true, + enumerable: false, + value: mockLength, + configurable: true + }); + // inherit the default name so it appears in snapshots and logs + // this is used by `vi.spyOn()` for better debugging. + // when `vi.fn()` is called, we just use the default string + if (resetToMockName) { + config.mockName = mock.name || "vi.fn()"; + } + MOCK_CONFIGS.set(mock, config); + REGISTERED_MOCKS.add(mock); + mock._isMockFunction = true; + mock.getMockImplementation = () => { + // Jest only returns `config.mockImplementation` here, + // but we think it makes sense to return what the next function will be called + return config.onceMockImplementations[0] || config.mockImplementation; + }; + Object.defineProperty(mock, "mock", { + configurable: false, + enumerable: true, + writable: false, + value: state + }); + mock.mockImplementation = function mockImplementation(implementation) { + config.mockImplementation = implementation; + return mock; + }; + mock.mockImplementationOnce = function mockImplementationOnce(implementation) { + config.onceMockImplementations.push(implementation); + return mock; + }; + mock.withImplementation = function withImplementation(implementation, callback) { + const previousImplementation = config.mockImplementation; + const previousOnceImplementations = config.onceMockImplementations; + const reset = () => { + config.mockImplementation = previousImplementation; + config.onceMockImplementations = previousOnceImplementations; + }; + config.mockImplementation = implementation; + config.onceMockImplementations = []; + const returnValue = callback(); + if (typeof returnValue === "object" && typeof (returnValue === null || returnValue === void 0 ? void 0 : returnValue.then) === "function") { + return returnValue.then(() => { + reset(); + return mock; + }); + } else { + reset(); + } + return mock; + }; + mock.mockReturnThis = function mockReturnThis() { + return mock.mockImplementation(function() { + return this; + }); + }; + mock.mockReturnValue = function mockReturnValue(value) { + return mock.mockImplementation(() => value); + }; + mock.mockReturnValueOnce = function mockReturnValueOnce(value) { + return mock.mockImplementationOnce(() => value); + }; + mock.mockResolvedValue = function mockResolvedValue(value) { + return mock.mockImplementation(() => Promise.resolve(value)); + }; + mock.mockResolvedValueOnce = function mockResolvedValueOnce(value) { + return mock.mockImplementationOnce(() => Promise.resolve(value)); + }; + mock.mockRejectedValue = function mockRejectedValue(value) { + return mock.mockImplementation(() => Promise.reject(value)); + }; + mock.mockRejectedValueOnce = function mockRejectedValueOnce(value) { + return mock.mockImplementationOnce(() => Promise.reject(value)); + }; + mock.mockClear = function mockClear() { + state.calls = []; + state.contexts = []; + state.instances = []; + state.invocationCallOrder = []; + state.results = []; + state.settledResults = []; + return mock; + }; + mock.mockReset = function mockReset() { + mock.mockClear(); + config.mockImplementation = resetToMockImplementation ? mockImplementation : undefined; + config.mockName = resetToMockName ? mock.name || "vi.fn()" : "vi.fn()"; + config.onceMockImplementations = []; + return mock; + }; + mock.mockRestore = function mockRestore() { + mock.mockReset(); + return restore === null || restore === void 0 ? void 0 : restore(); + }; + mock.mockName = function mockName(name) { + if (typeof name === "string") { + config.mockName = name; + } + return mock; + }; + mock.getMockName = function getMockName() { + return config.mockName || "vi.fn()"; + }; + if (Symbol.dispose) { + mock[Symbol.dispose] = () => mock.mockRestore(); + } + if (mockImplementation) { + mock.mockImplementation(mockImplementation); + } + return mock; +} +function fn(originalImplementation) { + // if the function is already a mock, just return the same function, + // simillarly to how vi.spyOn() works + if (originalImplementation != null && isMockFunction(originalImplementation)) { + return originalImplementation; + } + return createMockInstance({ + mockImplementation: originalImplementation, + resetToMockImplementation: true + }); +} +function spyOn(object, key, accessor) { + assert(object != null, "The vi.spyOn() function could not find an object to spy upon. The first argument must be defined."); + assert(typeof object === "object" || typeof object === "function", "Vitest cannot spy on a primitive value."); + const [originalDescriptorObject, originalDescriptor] = getDescriptor(object, key) || []; + assert(originalDescriptor || key in object, `The property "${String(key)}" is not defined on the ${typeof object}.`); + let accessType = accessor || "value"; + let ssr = false; + // vite ssr support - actual function is stored inside a getter + if (accessType === "value" && originalDescriptor && originalDescriptor.value == null && originalDescriptor.get) { + accessType = "get"; + ssr = true; + } + let original; + if (originalDescriptor) { + original = originalDescriptor[accessType]; + } else if (accessType !== "value") { + original = () => object[key]; + } else { + original = object[key]; + } + const originalImplementation = ssr && original ? original() : original; + const originalType = typeof originalImplementation; + assert( + // allow only functions + originalType === "function" || accessType !== "value" && original == null, + `vi.spyOn() can only spy on a function. Received ${originalType}.` + ); + if (isMockFunction(originalImplementation)) { + return originalImplementation; + } + const reassign = (cb) => { + const { value, ...desc } = originalDescriptor || { + configurable: true, + writable: true + }; + if (accessType !== "value") { + delete desc.writable; + } + desc[accessType] = cb; + Object.defineProperty(object, key, desc); + }; + const restore = () => { + // if method is defined on the prototype, we can just remove it from + // the current object instead of redefining a copy of it + if (originalDescriptorObject !== object) { + Reflect.deleteProperty(object, key); + } else if (originalDescriptor && !original) { + Object.defineProperty(object, key, originalDescriptor); + } else { + reassign(original); + } + }; + const mock = createMockInstance({ + restore, + originalImplementation, + resetToMockName: true + }); + try { + reassign(ssr ? () => mock : mock); + } catch (error) { + if (error instanceof TypeError && Symbol.toStringTag && object[Symbol.toStringTag] === "Module" && (error.message.includes("Cannot redefine property") || error.message.includes("Cannot replace module namespace") || error.message.includes("can't redefine non-configurable property"))) { + throw new TypeError(`Cannot spy on export "${String(key)}". Module namespace is not configurable in ESM. See: https://vitest.dev/guide/browser/#limitations`, { cause: error }); + } + throw error; + } + return mock; +} +function getDescriptor(obj, method) { + const objDescriptor = Object.getOwnPropertyDescriptor(obj, method); + if (objDescriptor) { + return [obj, objDescriptor]; + } + let currentProto = Object.getPrototypeOf(obj); + while (currentProto !== null) { + const descriptor = Object.getOwnPropertyDescriptor(currentProto, method); + if (descriptor) { + return [currentProto, descriptor]; + } + currentProto = Object.getPrototypeOf(currentProto); + } +} +function assert(condition, message) { + if (!condition) { + throw new Error(message); + } +} +let invocationCallCounter = 1; +function createMock({ state, config, name: mockName, prototypeState, prototypeConfig, keepMembersImplementation, mockImplementation, prototypeMembers = [] }) { + const original = config.mockOriginal; + const pseudoOriginal = mockImplementation; + const name = mockName || (original === null || original === void 0 ? void 0 : original.name) || "Mock"; + const namedObject = { [name]: (function(...args) { + registerCalls(args, state, prototypeState); + registerInvocationOrder(invocationCallCounter++, state, prototypeState); + const result = { + type: "incomplete", + value: undefined + }; + const settledResult = { + type: "incomplete", + value: undefined + }; + registerResult(result, state, prototypeState); + registerSettledResult(settledResult, state, prototypeState); + const context = new.target ? undefined : this; + const [instanceIndex, instancePrototypeIndex] = registerInstance(context, state, prototypeState); + const [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState); + const implementation = config.onceMockImplementations.shift() || config.mockImplementation || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.onceMockImplementations.shift()) || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockImplementation) || original || function() {}; + let returnValue; + let thrownValue; + let didThrow = false; + try { + if (new.target) { + returnValue = Reflect.construct(implementation, args, new.target); + // jest calls this before the implementation, but we have to resolve this _after_ + // because we cannot do it before the `Reflect.construct` called the custom implementation. + // fortunetly, the constructor is always an empty functon because `prototypeMethods` + // are only used by the automocker, so this doesn't matter + for (const prop of prototypeMembers) { + const prototypeMock = returnValue[prop]; + // the method was overidden because of inheritence, ignore it + // eslint-disable-next-line ts/no-use-before-define + if (prototypeMock !== mock.prototype[prop]) { + continue; + } + const isMock = isMockFunction(prototypeMock); + const prototypeState = isMock ? prototypeMock.mock : undefined; + const prototypeConfig = isMock ? MOCK_CONFIGS.get(prototypeMock) : undefined; + returnValue[prop] = createMockInstance({ + originalImplementation: keepMembersImplementation ? prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockOriginal : undefined, + prototypeState, + prototypeConfig, + keepMembersImplementation + }); + } + } else { + returnValue = implementation.apply(this, args); + } + } catch (error) { + thrownValue = error; + didThrow = true; + if (error instanceof TypeError && error.message.includes("is not a constructor")) { + console.warn(`[vitest] The ${namedObject[name].getMockName()} mock did not use 'function' or 'class' in its implementation, see https://vitest.dev/api/vi#vi-spyon for examples.`); + } + throw error; + } finally { + if (didThrow) { + result.type = "throw"; + result.value = thrownValue; + settledResult.type = "rejected"; + settledResult.value = thrownValue; + } else { + result.type = "return"; + result.value = returnValue; + if (new.target) { + state.contexts[contextIndex - 1] = returnValue; + state.instances[instanceIndex - 1] = returnValue; + if (contextPrototypeIndex != null && prototypeState) { + prototypeState.contexts[contextPrototypeIndex - 1] = returnValue; + } + if (instancePrototypeIndex != null && prototypeState) { + prototypeState.instances[instancePrototypeIndex - 1] = returnValue; + } + } + if (returnValue instanceof Promise) { + returnValue.then((settledValue) => { + settledResult.type = "fulfilled"; + settledResult.value = settledValue; + }, (rejectedValue) => { + settledResult.type = "rejected"; + settledResult.value = rejectedValue; + }); + } else { + settledResult.type = "fulfilled"; + settledResult.value = returnValue; + } + } + } + return returnValue; + }) }; + const mock = namedObject[name]; + const copyPropertiesFrom = original || pseudoOriginal; + if (copyPropertiesFrom) { + copyOriginalStaticProperties(mock, copyPropertiesFrom); + } + return mock; +} +function registerCalls(args, state, prototypeState) { + state.calls.push(args); + prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.calls.push(args); +} +function registerInvocationOrder(order, state, prototypeState) { + state.invocationCallOrder.push(order); + prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.invocationCallOrder.push(order); +} +function registerResult(result, state, prototypeState) { + state.results.push(result); + prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.results.push(result); +} +function registerSettledResult(result, state, prototypeState) { + state.settledResults.push(result); + prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.settledResults.push(result); +} +function registerInstance(instance, state, prototypeState) { + const instanceIndex = state.instances.push(instance); + const instancePrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.instances.push(instance); + return [instanceIndex, instancePrototypeIndex]; +} +function registerContext(context, state, prototypeState) { + const contextIndex = state.contexts.push(context); + const contextPrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.contexts.push(context); + return [contextIndex, contextPrototypeIndex]; +} +function copyOriginalStaticProperties(mock, original) { + const { properties, descriptors } = getAllProperties(original); + for (const key of properties) { + const descriptor = descriptors[key]; + const mockDescriptor = getDescriptor(mock, key); + if (mockDescriptor) { + continue; + } + Object.defineProperty(mock, key, descriptor); + } +} +const ignoreProperties = new Set([ + "length", + "name", + "prototype", + Symbol.for("nodejs.util.promisify.custom") +]); +function getAllProperties(original) { + const properties = new Set(); + const descriptors = {}; + while (original && original !== Object.prototype && original !== Function.prototype) { + const ownProperties = [...Object.getOwnPropertyNames(original), ...Object.getOwnPropertySymbols(original)]; + for (const prop of ownProperties) { + if (descriptors[prop] || ignoreProperties.has(prop)) { + continue; + } + properties.add(prop); + descriptors[prop] = Object.getOwnPropertyDescriptor(original, prop); + } + original = Object.getPrototypeOf(original); + } + return { + properties, + descriptors + }; +} +function getDefaultConfig(original) { + return { + mockImplementation: undefined, + mockOriginal: original, + mockName: "vi.fn()", + onceMockImplementations: [] + }; +} +function getDefaultState() { + const state = { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + get lastCall() { + return state.calls.at(-1); + } + }; + return state; +} +function restoreAllMocks() { + for (const restore of MOCK_RESTORE) { + restore(); + } + MOCK_RESTORE.clear(); +} +function clearAllMocks() { + REGISTERED_MOCKS.forEach((mock) => mock.mockClear()); +} +function resetAllMocks() { + REGISTERED_MOCKS.forEach((mock) => mock.mockReset()); +} + +export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn }; diff --git a/vanilla/node_modules/@vitest/spy/package.json b/vanilla/node_modules/@vitest/spy/package.json new file mode 100644 index 0000000..5564c28 --- /dev/null +++ b/vanilla/node_modules/@vitest/spy/package.json @@ -0,0 +1,35 @@ +{ + "name": "@vitest/spy", + "type": "module", + "version": "4.0.18", + "description": "Lightweight Jest compatible spy implementation", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/spy#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/spy" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/@vitest/utils/LICENSE b/vanilla/node_modules/@vitest/utils/LICENSE new file mode 100644 index 0000000..0e5771d --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vanilla/node_modules/@vitest/utils/diff.d.ts b/vanilla/node_modules/@vitest/utils/diff.d.ts new file mode 100644 index 0000000..0a66b86 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/diff.d.ts @@ -0,0 +1 @@ +export * from './dist/diff.js' diff --git a/vanilla/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js b/vanilla/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js new file mode 100644 index 0000000..c9366dd --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js @@ -0,0 +1,5 @@ +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} + +export { getDefaultExportFromCjs as g }; diff --git a/vanilla/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js b/vanilla/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js new file mode 100644 index 0000000..74d0dab --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js @@ -0,0 +1,156 @@ +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} + +const _UNC_REGEX = /^[/\\]{2}/; +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; +const normalize = function(path) { + if (path.length === 0) { + return "."; + } + path = normalizeWindowsPath(path); + const isUNCPath = path.match(_UNC_REGEX); + const isPathAbsolute = isAbsolute(path); + const trailingSeparator = path[path.length - 1] === "/"; + path = normalizeString(path, !isPathAbsolute); + if (path.length === 0) { + if (isPathAbsolute) { + return "/"; + } + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) { + path += "/"; + } + if (_DRIVE_LETTER_RE.test(path)) { + path += "/"; + } + if (isUNCPath) { + if (!isPathAbsolute) { + return `//./${path}`; + } + return `//${path}`; + } + return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; +}; +const join = function(...segments) { + let path = ""; + for (const seg of segments) { + if (!seg) { + continue; + } + if (path.length > 0) { + const pathTrailing = path[path.length - 1] === "/"; + const segLeading = seg[0] === "/"; + const both = pathTrailing && segLeading; + if (both) { + path += seg.slice(1); + } else { + path += pathTrailing || segLeading ? seg : `/${seg}`; + } + } else { + path += seg; + } + } + return normalize(path); +}; +function cwd() { + if (typeof process !== "undefined" && typeof process.cwd === "function") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; +const dirname = function(p) { + const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); + if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { + segments[0] += "/"; + } + return segments.join("/") || (isAbsolute(p) ? "/" : "."); +}; + +export { dirname as d, join as j, resolve as r }; diff --git a/vanilla/node_modules/@vitest/utils/dist/constants.d.ts b/vanilla/node_modules/@vitest/utils/dist/constants.d.ts new file mode 100644 index 0000000..bd5ad65 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/constants.d.ts @@ -0,0 +1,21 @@ +declare const KNOWN_ASSET_TYPES: string[]; +declare const KNOWN_ASSET_RE: RegExp; +declare const CSS_LANGS_RE: RegExp; +/** +* Prefix for resolved Ids that are not valid browser import specifiers +*/ +declare const VALID_ID_PREFIX = "/@id/"; +/** +* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the +* module ID with `\0`, a convention from the rollup ecosystem. +* This prevents other plugins from trying to process the id (like node resolution), +* and core features like sourcemaps can use this info to differentiate between +* virtual modules and regular files. +* `\0` is not a permitted char in import URLs so we have to replace them during +* import analysis. The id will be decoded back before entering the plugins pipeline. +* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual +* modules in the browser end up encoded as `/@id/__x00__{id}` +*/ +declare const NULL_BYTE_PLACEHOLDER = "__x00__"; + +export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX }; diff --git a/vanilla/node_modules/@vitest/utils/dist/constants.js b/vanilla/node_modules/@vitest/utils/dist/constants.js new file mode 100644 index 0000000..385045b --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/constants.js @@ -0,0 +1,49 @@ +// TODO: this is all copy pasted from Vite - can they expose a module that exports only constants? +const KNOWN_ASSET_TYPES = [ + "apng", + "bmp", + "png", + "jpe?g", + "jfif", + "pjpeg", + "pjp", + "gif", + "svg", + "ico", + "webp", + "avif", + "mp4", + "webm", + "ogg", + "mp3", + "wav", + "flac", + "aac", + "woff2?", + "eot", + "ttf", + "otf", + "webmanifest", + "pdf", + "txt" +]; +const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`); +const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/; +/** +* Prefix for resolved Ids that are not valid browser import specifiers +*/ +const VALID_ID_PREFIX = `/@id/`; +/** +* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the +* module ID with `\0`, a convention from the rollup ecosystem. +* This prevents other plugins from trying to process the id (like node resolution), +* and core features like sourcemaps can use this info to differentiate between +* virtual modules and regular files. +* `\0` is not a permitted char in import URLs so we have to replace them during +* import analysis. The id will be decoded back before entering the plugins pipeline. +* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual +* modules in the browser end up encoded as `/@id/__x00__{id}` +*/ +const NULL_BYTE_PLACEHOLDER = `__x00__`; + +export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX }; diff --git a/vanilla/node_modules/@vitest/utils/dist/diff.d.ts b/vanilla/node_modules/@vitest/utils/dist/diff.d.ts new file mode 100644 index 0000000..603569d --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/diff.d.ts @@ -0,0 +1,93 @@ +import { D as DiffOptions } from './types.d-BCElaP-c.js'; +export { a as DiffOptionsColor, S as SerializedDiffOptions } from './types.d-BCElaP-c.js'; +import '@vitest/pretty-format'; + +/** +* Diff Match and Patch +* Copyright 2018 The diff-match-patch Authors. +* https://github.com/google/diff-match-patch +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* 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. +*/ +/** +* @fileoverview Computes the difference between two texts to create a patch. +* Applies the patch onto another text, allowing for errors. +* @author fraser@google.com (Neil Fraser) +*/ +/** +* CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: +* +* 1. Delete anything not needed to use diff_cleanupSemantic method +* 2. Convert from prototype properties to var declarations +* 3. Convert Diff to class from constructor and prototype +* 4. Add type annotations for arguments and return values +* 5. Add exports +*/ +/** +* The data structure representing a diff is an array of tuples: +* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] +* which means: delete 'Hello', add 'Goodbye' and keep ' world.' +*/ +declare const DIFF_DELETE = -1; +declare const DIFF_INSERT = 1; +declare const DIFF_EQUAL = 0; +/** +* Class representing one diff tuple. +* Attempts to look like a two-element array (which is what this used to be). +* @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. +* @param {string} text Text to be deleted, inserted, or retained. +* @constructor +*/ +declare class Diff { + 0: number; + 1: string; + constructor(op: number, text: string); +} + +/** +* 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. +*/ + +declare function diffLinesUnified(aLines: Array, bLines: Array, options?: DiffOptions): string; +declare function diffLinesUnified2(aLinesDisplay: Array, bLinesDisplay: Array, aLinesCompare: Array, bLinesCompare: Array, options?: DiffOptions): string; +declare function diffLinesRaw(aLines: Array, bLines: Array, options?: DiffOptions): [Array, boolean]; + +/** +* 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. +*/ + +declare function diffStringsUnified(a: string, b: string, options?: DiffOptions): string; +declare function diffStringsRaw(a: string, b: string, cleanup: boolean, options?: DiffOptions): [Array, boolean]; + +/** +* @param a Expected value +* @param b Received value +* @param options Diff options +* @returns {string | null} a string diff +*/ +declare function diff(a: any, b: any, options?: DiffOptions): string | undefined; +declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions): string | undefined; +declare function replaceAsymmetricMatcher(actual: any, expected: any, actualReplaced?: WeakSet, expectedReplaced?: WeakSet): { + replacedActual: any; + replacedExpected: any; +}; +type PrintLabel = (string: string) => string; +declare function getLabelPrinter(...strings: Array): PrintLabel; + +export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, DiffOptions, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher }; diff --git a/vanilla/node_modules/@vitest/utils/dist/diff.js b/vanilla/node_modules/@vitest/utils/dist/diff.js new file mode 100644 index 0000000..415a4f1 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/diff.js @@ -0,0 +1,2199 @@ +import { plugins, format } from '@vitest/pretty-format'; +import c from 'tinyrainbow'; +import { stringify } from './display.js'; +import { deepClone, getOwnProperties, getType as getType$1 } from './helpers.js'; +import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js'; +import './constants.js'; + +/** +* Diff Match and Patch +* Copyright 2018 The diff-match-patch Authors. +* https://github.com/google/diff-match-patch +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* 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. +*/ +/** +* @fileoverview Computes the difference between two texts to create a patch. +* Applies the patch onto another text, allowing for errors. +* @author fraser@google.com (Neil Fraser) +*/ +/** +* CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: +* +* 1. Delete anything not needed to use diff_cleanupSemantic method +* 2. Convert from prototype properties to var declarations +* 3. Convert Diff to class from constructor and prototype +* 4. Add type annotations for arguments and return values +* 5. Add exports +*/ +/** +* The data structure representing a diff is an array of tuples: +* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] +* which means: delete 'Hello', add 'Goodbye' and keep ' world.' +*/ +const DIFF_DELETE = -1; +const DIFF_INSERT = 1; +const DIFF_EQUAL = 0; +/** +* Class representing one diff tuple. +* Attempts to look like a two-element array (which is what this used to be). +* @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. +* @param {string} text Text to be deleted, inserted, or retained. +* @constructor +*/ +class Diff { + 0; + 1; + constructor(op, text) { + this[0] = op; + this[1] = text; + } +} +/** +* Determine the common prefix of two strings. +* @param {string} text1 First string. +* @param {string} text2 Second string. +* @return {number} The number of characters common to the start of each +* string. +*/ +function diff_commonPrefix(text1, text2) { + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { + return 0; + } + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + let pointermin = 0; + let pointermax = Math.min(text1.length, text2.length); + let pointermid = pointermax; + let pointerstart = 0; + while (pointermin < pointermid) { + if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; +} +/** +* Determine the common suffix of two strings. +* @param {string} text1 First string. +* @param {string} text2 Second string. +* @return {number} The number of characters common to the end of each string. +*/ +function diff_commonSuffix(text1, text2) { + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) { + return 0; + } + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + let pointermin = 0; + let pointermax = Math.min(text1.length, text2.length); + let pointermid = pointermax; + let pointerend = 0; + while (pointermin < pointermid) { + if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; +} +/** +* Determine if the suffix of one string is the prefix of another. +* @param {string} text1 First string. +* @param {string} text2 Second string. +* @return {number} The number of characters common to the end of the first +* string and the start of the second string. +* @private +*/ +function diff_commonOverlap_(text1, text2) { + // Cache the text lengths to prevent multiple calls. + const text1_length = text1.length; + const text2_length = text2.length; + // Eliminate the null case. + if (text1_length === 0 || text2_length === 0) { + return 0; + } + // Truncate the longer string. + if (text1_length > text2_length) { + text1 = text1.substring(text1_length - text2_length); + } else if (text1_length < text2_length) { + text2 = text2.substring(0, text1_length); + } + const text_length = Math.min(text1_length, text2_length); + // Quick check for the worst case. + if (text1 === text2) { + return text_length; + } + // Start by looking for a single character match + // and increase length until no match is found. + // Performance analysis: https://neil.fraser.name/news/2010/11/04/ + let best = 0; + let length = 1; + while (true) { + const pattern = text1.substring(text_length - length); + const found = text2.indexOf(pattern); + if (found === -1) { + return best; + } + length += found; + if (found === 0 || text1.substring(text_length - length) === text2.substring(0, length)) { + best = length; + length++; + } + } +} +/** +* Reduce the number of edits by eliminating semantically trivial equalities. +* @param {!Array.} diffs Array of diff tuples. +*/ +function diff_cleanupSemantic(diffs) { + let changes = false; + const equalities = []; + let equalitiesLength = 0; + /** @type {?string} */ + let lastEquality = null; + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + let pointer = 0; + // Number of characters that changed prior to the equality. + let length_insertions1 = 0; + let length_deletions1 = 0; + // Number of characters that changed after the equality. + let length_insertions2 = 0; + let length_deletions2 = 0; + while (pointer < diffs.length) { + if (diffs[pointer][0] === DIFF_EQUAL) { + // Equality found. + equalities[equalitiesLength++] = pointer; + length_insertions1 = length_insertions2; + length_deletions1 = length_deletions2; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = diffs[pointer][1]; + } else { + // An insertion or deletion. + if (diffs[pointer][0] === DIFF_INSERT) { + length_insertions2 += diffs[pointer][1].length; + } else { + length_deletions2 += diffs[pointer][1].length; + } + // Eliminate an equality that is smaller or equal to the edits on both + // sides of it. + if (lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max(length_insertions2, length_deletions2)) { + // Duplicate record. + diffs.splice(equalities[equalitiesLength - 1], 0, new Diff(DIFF_DELETE, lastEquality)); + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; + // Throw away the equality we just deleted. + equalitiesLength--; + // Throw away the previous equality (it needs to be reevaluated). + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + length_insertions1 = 0; + length_deletions1 = 0; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = null; + changes = true; + } + } + pointer++; + } + // Normalize the diff. + if (changes) { + diff_cleanupMerge(diffs); + } + diff_cleanupSemanticLossless(diffs); + // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1; + while (pointer < diffs.length) { + if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) { + const deletion = diffs[pointer - 1][1]; + const insertion = diffs[pointer][1]; + const overlap_length1 = diff_commonOverlap_(deletion, insertion); + const overlap_length2 = diff_commonOverlap_(insertion, deletion); + if (overlap_length1 >= overlap_length2) { + if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { + // Overlap found. Insert an equality and trim the surrounding edits. + diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1))); + diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); + diffs[pointer + 1][1] = insertion.substring(overlap_length1); + pointer++; + } + } else { + if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { + // Reverse overlap found. + // Insert an equality and swap and trim the surrounding edits. + diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2))); + diffs[pointer - 1][0] = DIFF_INSERT; + diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); + diffs[pointer + 1][0] = DIFF_DELETE; + diffs[pointer + 1][1] = deletion.substring(overlap_length2); + pointer++; + } + } + pointer++; + } + pointer++; + } +} +// Define some regex patterns for matching boundaries. +const nonAlphaNumericRegex_ = /[^a-z0-9]/i; +const whitespaceRegex_ = /\s/; +const linebreakRegex_ = /[\r\n]/; +const blanklineEndRegex_ = /\n\r?\n$/; +const blanklineStartRegex_ = /^\r?\n\r?\n/; +/** +* Look for single edits surrounded on both sides by equalities +* which can be shifted sideways to align the edit to a word boundary. +* e.g: The cat came. -> The cat came. +* @param {!Array.} diffs Array of diff tuples. +*/ +function diff_cleanupSemanticLossless(diffs) { + let pointer = 1; + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { + // This is a single edit surrounded by equalities. + let equality1 = diffs[pointer - 1][1]; + let edit = diffs[pointer][1]; + let equality2 = diffs[pointer + 1][1]; + // First, shift the edit as far left as possible. + const commonOffset = diff_commonSuffix(equality1, edit); + if (commonOffset) { + const commonString = edit.substring(edit.length - commonOffset); + equality1 = equality1.substring(0, equality1.length - commonOffset); + edit = commonString + edit.substring(0, edit.length - commonOffset); + equality2 = commonString + equality2; + } + // Second, step character by character right, looking for the best fit. + let bestEquality1 = equality1; + let bestEdit = edit; + let bestEquality2 = equality2; + let bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); + while (edit.charAt(0) === equality2.charAt(0)) { + equality1 += edit.charAt(0); + edit = edit.substring(1) + equality2.charAt(0); + equality2 = equality2.substring(1); + const score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); + // The >= encourages trailing rather than leading whitespace on edits. + if (score >= bestScore) { + bestScore = score; + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + } + } + if (diffs[pointer - 1][1] !== bestEquality1) { + // We have an improvement, save it back to the diff. + if (bestEquality1) { + diffs[pointer - 1][1] = bestEquality1; + } else { + diffs.splice(pointer - 1, 1); + pointer--; + } + diffs[pointer][1] = bestEdit; + if (bestEquality2) { + diffs[pointer + 1][1] = bestEquality2; + } else { + diffs.splice(pointer + 1, 1); + pointer--; + } + } + } + pointer++; + } +} +/** +* Reorder and merge like edit sections. Merge equalities. +* Any edit section can move as long as it doesn't cross an equality. +* @param {!Array.} diffs Array of diff tuples. +*/ +function diff_cleanupMerge(diffs) { + var _diffs$at; + // Add a dummy entry at the end. + diffs.push(new Diff(DIFF_EQUAL, "")); + let pointer = 0; + let count_delete = 0; + let count_insert = 0; + let text_delete = ""; + let text_insert = ""; + let commonlength; + while (pointer < diffs.length) { + switch (diffs[pointer][0]) { + case DIFF_INSERT: + count_insert++; + text_insert += diffs[pointer][1]; + pointer++; + break; + case DIFF_DELETE: + count_delete++; + text_delete += diffs[pointer][1]; + pointer++; + break; + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (count_delete + count_insert > 1) { + if (count_delete !== 0 && count_insert !== 0) { + // Factor out any common prefixes. + commonlength = diff_commonPrefix(text_insert, text_delete); + if (commonlength !== 0) { + if (pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] === DIFF_EQUAL) { + diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); + } else { + diffs.splice(0, 0, new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength))); + pointer++; + } + text_insert = text_insert.substring(commonlength); + text_delete = text_delete.substring(commonlength); + } + // Factor out any common suffixes. + commonlength = diff_commonSuffix(text_insert, text_delete); + if (commonlength !== 0) { + diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; + text_insert = text_insert.substring(0, text_insert.length - commonlength); + text_delete = text_delete.substring(0, text_delete.length - commonlength); + } + } + // Delete the offending records and add the merged ones. + pointer -= count_delete + count_insert; + diffs.splice(pointer, count_delete + count_insert); + if (text_delete.length) { + diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete)); + pointer++; + } + if (text_insert.length) { + diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert)); + pointer++; + } + pointer++; + } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { + // Merge this equality with the previous one. + diffs[pointer - 1][1] += diffs[pointer][1]; + diffs.splice(pointer, 1); + } else { + pointer++; + } + count_insert = 0; + count_delete = 0; + text_delete = ""; + text_insert = ""; + break; + } + } + if (((_diffs$at = diffs.at(-1)) === null || _diffs$at === void 0 ? void 0 : _diffs$at[1]) === "") { + diffs.pop(); + } + // Second pass: look for single edits surrounded on both sides by equalities + // which can be shifted sideways to eliminate an equality. + // e.g: ABAC -> ABAC + let changes = false; + pointer = 1; + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { + // This is a single edit surrounded by equalities. + if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) { + // Shift the edit over the previous equality. + diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); + diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; + diffs.splice(pointer - 1, 1); + changes = true; + } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) { + // Shift the edit over the next equality. + diffs[pointer - 1][1] += diffs[pointer + 1][1]; + diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; + diffs.splice(pointer + 1, 1); + changes = true; + } + } + pointer++; + } + // If shifts were made, the diff needs reordering and another shift sweep. + if (changes) { + diff_cleanupMerge(diffs); + } +} +/** +* Given two strings, compute a score representing whether the internal +* boundary falls on logical boundaries. +* Scores range from 6 (best) to 0 (worst). +* Closure, but does not reference any external variables. +* @param {string} one First string. +* @param {string} two Second string. +* @return {number} The score. +* @private +*/ +function diff_cleanupSemanticScore_(one, two) { + if (!one || !two) { + // Edges are the best. + return 6; + } + // Each port of this function behaves slightly differently due to + // subtle differences in each language's definition of things like + // 'whitespace'. Since this function's purpose is largely cosmetic, + // the choice has been made to use each language's native features + // rather than force total conformity. + const char1 = one.charAt(one.length - 1); + const char2 = two.charAt(0); + const nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_); + const nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_); + const whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_); + const whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_); + const lineBreak1 = whitespace1 && char1.match(linebreakRegex_); + const lineBreak2 = whitespace2 && char2.match(linebreakRegex_); + const blankLine1 = lineBreak1 && one.match(blanklineEndRegex_); + const blankLine2 = lineBreak2 && two.match(blanklineStartRegex_); + if (blankLine1 || blankLine2) { + // Five points for blank lines. + return 5; + } else if (lineBreak1 || lineBreak2) { + // Four points for line breaks. + return 4; + } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { + // Three points for end of sentences. + return 3; + } else if (whitespace1 || whitespace2) { + // Two points for whitespace. + return 2; + } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { + // One point for non-alphanumeric. + return 1; + } + return 0; +} + +/** +* 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. +*/ +const NO_DIFF_MESSAGE = "Compared values have no visual difference."; +const SIMILAR_MESSAGE = "Compared values serialize to the same structure.\n" + "Printing internal object structure without calling `toJSON` instead."; + +var build = {}; + +var hasRequiredBuild; + +function requireBuild () { + if (hasRequiredBuild) return build; + hasRequiredBuild = 1; + + Object.defineProperty(build, '__esModule', { + value: true + }); + build.default = diffSequence; + /** + * 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. + * + */ + + // This diff-sequences package implements the linear space variation in + // An O(ND) Difference Algorithm and Its Variations by Eugene W. Myers + + // Relationship in notation between Myers paper and this package: + // A is a + // N is aLength, aEnd - aStart, and so on + // x is aIndex, aFirst, aLast, and so on + // B is b + // M is bLength, bEnd - bStart, and so on + // y is bIndex, bFirst, bLast, and so on + // Δ = N - M is negative of baDeltaLength = bLength - aLength + // D is d + // k is kF + // k + Δ is kF = kR - baDeltaLength + // V is aIndexesF or aIndexesR (see comment below about Indexes type) + // index intervals [1, N] and [1, M] are [0, aLength) and [0, bLength) + // starting point in forward direction (0, 0) is (-1, -1) + // starting point in reverse direction (N + 1, M + 1) is (aLength, bLength) + + // The “edit graph” for sequences a and b corresponds to items: + // in a on the horizontal axis + // in b on the vertical axis + // + // Given a-coordinate of a point in a diagonal, you can compute b-coordinate. + // + // Forward diagonals kF: + // zero diagonal intersects top left corner + // positive diagonals intersect top edge + // negative diagonals insersect left edge + // + // Reverse diagonals kR: + // zero diagonal intersects bottom right corner + // positive diagonals intersect right edge + // negative diagonals intersect bottom edge + + // The graph contains a directed acyclic graph of edges: + // horizontal: delete an item from a + // vertical: insert an item from b + // diagonal: common item in a and b + // + // The algorithm solves dual problems in the graph analogy: + // Find longest common subsequence: path with maximum number of diagonal edges + // Find shortest edit script: path with minimum number of non-diagonal edges + + // Input callback function compares items at indexes in the sequences. + + // Output callback function receives the number of adjacent items + // and starting indexes of each common subsequence. + // Either original functions or wrapped to swap indexes if graph is transposed. + // Indexes in sequence a of last point of forward or reverse paths in graph. + // Myers algorithm indexes by diagonal k which for negative is bad deopt in V8. + // This package indexes by iF and iR which are greater than or equal to zero. + // and also updates the index arrays in place to cut memory in half. + // kF = 2 * iF - d + // kR = d - 2 * iR + // Division of index intervals in sequences a and b at the middle change. + // Invariant: intervals do not have common items at the start or end. + const pkg = 'diff-sequences'; // for error messages + const NOT_YET_SET = 0; // small int instead of undefined to avoid deopt in V8 + + // Return the number of common items that follow in forward direction. + // The length of what Myers paper calls a “snake” in a forward path. + const countCommonItemsF = (aIndex, aEnd, bIndex, bEnd, isCommon) => { + let nCommon = 0; + while (aIndex < aEnd && bIndex < bEnd && isCommon(aIndex, bIndex)) { + aIndex += 1; + bIndex += 1; + nCommon += 1; + } + return nCommon; + }; + + // Return the number of common items that precede in reverse direction. + // The length of what Myers paper calls a “snake” in a reverse path. + const countCommonItemsR = (aStart, aIndex, bStart, bIndex, isCommon) => { + let nCommon = 0; + while (aStart <= aIndex && bStart <= bIndex && isCommon(aIndex, bIndex)) { + aIndex -= 1; + bIndex -= 1; + nCommon += 1; + } + return nCommon; + }; + + // A simple function to extend forward paths from (d - 1) to d changes + // when forward and reverse paths cannot yet overlap. + const extendPathsF = ( + d, + aEnd, + bEnd, + bF, + isCommon, + aIndexesF, + iMaxF // return the value because optimization might decrease it + ) => { + // Unroll the first iteration. + let iF = 0; + let kF = -d; // kF = 2 * iF - d + let aFirst = aIndexesF[iF]; // in first iteration always insert + let aIndexPrev1 = aFirst; // prev value of [iF - 1] in next iteration + aIndexesF[iF] += countCommonItemsF( + aFirst + 1, + aEnd, + bF + aFirst - kF + 1, + bEnd, + isCommon + ); + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nF = d < iMaxF ? d : iMaxF; + + // The diagonals kF are odd when d is odd and even when d is even. + for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) { + // To get first point of path segment, move one change in forward direction + // from last point of previous path segment in an adjacent diagonal. + // In last possible iteration when iF === d and kF === d always delete. + if (iF !== d && aIndexPrev1 < aIndexesF[iF]) { + aFirst = aIndexesF[iF]; // vertical to insert from b + } else { + aFirst = aIndexPrev1 + 1; // horizontal to delete from a + + if (aEnd <= aFirst) { + // Optimization: delete moved past right of graph. + return iF - 1; + } + } + + // To get last point of path segment, move along diagonal of common items. + aIndexPrev1 = aIndexesF[iF]; + aIndexesF[iF] = + aFirst + + countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon); + } + return iMaxF; + }; + + // A simple function to extend reverse paths from (d - 1) to d changes + // when reverse and forward paths cannot yet overlap. + const extendPathsR = ( + d, + aStart, + bStart, + bR, + isCommon, + aIndexesR, + iMaxR // return the value because optimization might decrease it + ) => { + // Unroll the first iteration. + let iR = 0; + let kR = d; // kR = d - 2 * iR + let aFirst = aIndexesR[iR]; // in first iteration always insert + let aIndexPrev1 = aFirst; // prev value of [iR - 1] in next iteration + aIndexesR[iR] -= countCommonItemsR( + aStart, + aFirst - 1, + bStart, + bR + aFirst - kR - 1, + isCommon + ); + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nR = d < iMaxR ? d : iMaxR; + + // The diagonals kR are odd when d is odd and even when d is even. + for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) { + // To get first point of path segment, move one change in reverse direction + // from last point of previous path segment in an adjacent diagonal. + // In last possible iteration when iR === d and kR === -d always delete. + if (iR !== d && aIndexesR[iR] < aIndexPrev1) { + aFirst = aIndexesR[iR]; // vertical to insert from b + } else { + aFirst = aIndexPrev1 - 1; // horizontal to delete from a + + if (aFirst < aStart) { + // Optimization: delete moved past left of graph. + return iR - 1; + } + } + + // To get last point of path segment, move along diagonal of common items. + aIndexPrev1 = aIndexesR[iR]; + aIndexesR[iR] = + aFirst - + countCommonItemsR( + aStart, + aFirst - 1, + bStart, + bR + aFirst - kR - 1, + isCommon + ); + } + return iMaxR; + }; + + // A complete function to extend forward paths from (d - 1) to d changes. + // Return true if a path overlaps reverse path of (d - 1) changes in its diagonal. + const extendOverlappablePathsF = ( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division // update prop values if return true + ) => { + const bF = bStart - aStart; // bIndex = bF + aIndex - kF + const aLength = aEnd - aStart; + const bLength = bEnd - bStart; + const baDeltaLength = bLength - aLength; // kF = kR - baDeltaLength + + // Range of diagonals in which forward and reverse paths might overlap. + const kMinOverlapF = -baDeltaLength - (d - 1); // -(d - 1) <= kR + const kMaxOverlapF = -baDeltaLength + (d - 1); // kR <= (d - 1) + + let aIndexPrev1 = NOT_YET_SET; // prev value of [iF - 1] in next iteration + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nF = d < iMaxF ? d : iMaxF; + + // The diagonals kF = 2 * iF - d are odd when d is odd and even when d is even. + for (let iF = 0, kF = -d; iF <= nF; iF += 1, kF += 2) { + // To get first point of path segment, move one change in forward direction + // from last point of previous path segment in an adjacent diagonal. + // In first iteration when iF === 0 and kF === -d always insert. + // In last possible iteration when iF === d and kF === d always delete. + const insert = iF === 0 || (iF !== d && aIndexPrev1 < aIndexesF[iF]); + const aLastPrev = insert ? aIndexesF[iF] : aIndexPrev1; + const aFirst = insert + ? aLastPrev // vertical to insert from b + : aLastPrev + 1; // horizontal to delete from a + + // To get last point of path segment, move along diagonal of common items. + const bFirst = bF + aFirst - kF; + const nCommonF = countCommonItemsF( + aFirst + 1, + aEnd, + bFirst + 1, + bEnd, + isCommon + ); + const aLast = aFirst + nCommonF; + aIndexPrev1 = aIndexesF[iF]; + aIndexesF[iF] = aLast; + if (kMinOverlapF <= kF && kF <= kMaxOverlapF) { + // Solve for iR of reverse path with (d - 1) changes in diagonal kF: + // kR = kF + baDeltaLength + // kR = (d - 1) - 2 * iR + const iR = (d - 1 - (kF + baDeltaLength)) / 2; + + // If this forward path overlaps the reverse path in this diagonal, + // then this is the middle change of the index intervals. + if (iR <= iMaxR && aIndexesR[iR] - 1 <= aLast) { + // Unlike the Myers algorithm which finds only the middle “snake” + // this package can find two common subsequences per division. + // Last point of previous path segment is on an adjacent diagonal. + const bLastPrev = bF + aLastPrev - (insert ? kF + 1 : kF - 1); + + // Because of invariant that intervals preceding the middle change + // cannot have common items at the end, + // move in reverse direction along a diagonal of common items. + const nCommonR = countCommonItemsR( + aStart, + aLastPrev, + bStart, + bLastPrev, + isCommon + ); + const aIndexPrevFirst = aLastPrev - nCommonR; + const bIndexPrevFirst = bLastPrev - nCommonR; + const aEndPreceding = aIndexPrevFirst + 1; + const bEndPreceding = bIndexPrevFirst + 1; + division.nChangePreceding = d - 1; + if (d - 1 === aEndPreceding + bEndPreceding - aStart - bStart) { + // Optimization: number of preceding changes in forward direction + // is equal to number of items in preceding interval, + // therefore it cannot contain any common items. + division.aEndPreceding = aStart; + division.bEndPreceding = bStart; + } else { + division.aEndPreceding = aEndPreceding; + division.bEndPreceding = bEndPreceding; + } + division.nCommonPreceding = nCommonR; + if (nCommonR !== 0) { + division.aCommonPreceding = aEndPreceding; + division.bCommonPreceding = bEndPreceding; + } + division.nCommonFollowing = nCommonF; + if (nCommonF !== 0) { + division.aCommonFollowing = aFirst + 1; + division.bCommonFollowing = bFirst + 1; + } + const aStartFollowing = aLast + 1; + const bStartFollowing = bFirst + nCommonF + 1; + division.nChangeFollowing = d - 1; + if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) { + // Optimization: number of changes in reverse direction + // is equal to number of items in following interval, + // therefore it cannot contain any common items. + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + division.aStartFollowing = aStartFollowing; + division.bStartFollowing = bStartFollowing; + } + return true; + } + } + } + return false; + }; + + // A complete function to extend reverse paths from (d - 1) to d changes. + // Return true if a path overlaps forward path of d changes in its diagonal. + const extendOverlappablePathsR = ( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division // update prop values if return true + ) => { + const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR + const aLength = aEnd - aStart; + const bLength = bEnd - bStart; + const baDeltaLength = bLength - aLength; // kR = kF + baDeltaLength + + // Range of diagonals in which forward and reverse paths might overlap. + const kMinOverlapR = baDeltaLength - d; // -d <= kF + const kMaxOverlapR = baDeltaLength + d; // kF <= d + + let aIndexPrev1 = NOT_YET_SET; // prev value of [iR - 1] in next iteration + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nR = d < iMaxR ? d : iMaxR; + + // The diagonals kR = d - 2 * iR are odd when d is odd and even when d is even. + for (let iR = 0, kR = d; iR <= nR; iR += 1, kR -= 2) { + // To get first point of path segment, move one change in reverse direction + // from last point of previous path segment in an adjacent diagonal. + // In first iteration when iR === 0 and kR === d always insert. + // In last possible iteration when iR === d and kR === -d always delete. + const insert = iR === 0 || (iR !== d && aIndexesR[iR] < aIndexPrev1); + const aLastPrev = insert ? aIndexesR[iR] : aIndexPrev1; + const aFirst = insert + ? aLastPrev // vertical to insert from b + : aLastPrev - 1; // horizontal to delete from a + + // To get last point of path segment, move along diagonal of common items. + const bFirst = bR + aFirst - kR; + const nCommonR = countCommonItemsR( + aStart, + aFirst - 1, + bStart, + bFirst - 1, + isCommon + ); + const aLast = aFirst - nCommonR; + aIndexPrev1 = aIndexesR[iR]; + aIndexesR[iR] = aLast; + if (kMinOverlapR <= kR && kR <= kMaxOverlapR) { + // Solve for iF of forward path with d changes in diagonal kR: + // kF = kR - baDeltaLength + // kF = 2 * iF - d + const iF = (d + (kR - baDeltaLength)) / 2; + + // If this reverse path overlaps the forward path in this diagonal, + // then this is a middle change of the index intervals. + if (iF <= iMaxF && aLast - 1 <= aIndexesF[iF]) { + const bLast = bFirst - nCommonR; + division.nChangePreceding = d; + if (d === aLast + bLast - aStart - bStart) { + // Optimization: number of changes in reverse direction + // is equal to number of items in preceding interval, + // therefore it cannot contain any common items. + division.aEndPreceding = aStart; + division.bEndPreceding = bStart; + } else { + division.aEndPreceding = aLast; + division.bEndPreceding = bLast; + } + division.nCommonPreceding = nCommonR; + if (nCommonR !== 0) { + // The last point of reverse path segment is start of common subsequence. + division.aCommonPreceding = aLast; + division.bCommonPreceding = bLast; + } + division.nChangeFollowing = d - 1; + if (d === 1) { + // There is no previous path segment. + division.nCommonFollowing = 0; + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + // Unlike the Myers algorithm which finds only the middle “snake” + // this package can find two common subsequences per division. + // Last point of previous path segment is on an adjacent diagonal. + const bLastPrev = bR + aLastPrev - (insert ? kR - 1 : kR + 1); + + // Because of invariant that intervals following the middle change + // cannot have common items at the start, + // move in forward direction along a diagonal of common items. + const nCommonF = countCommonItemsF( + aLastPrev, + aEnd, + bLastPrev, + bEnd, + isCommon + ); + division.nCommonFollowing = nCommonF; + if (nCommonF !== 0) { + // The last point of reverse path segment is start of common subsequence. + division.aCommonFollowing = aLastPrev; + division.bCommonFollowing = bLastPrev; + } + const aStartFollowing = aLastPrev + nCommonF; // aFirstPrev + const bStartFollowing = bLastPrev + nCommonF; // bFirstPrev + + if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) { + // Optimization: number of changes in forward direction + // is equal to number of items in following interval, + // therefore it cannot contain any common items. + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + division.aStartFollowing = aStartFollowing; + division.bStartFollowing = bStartFollowing; + } + } + return true; + } + } + } + return false; + }; + + // Given index intervals and input function to compare items at indexes, + // divide at the middle change. + // + // DO NOT CALL if start === end, because interval cannot contain common items + // and because this function will throw the “no overlap” error. + const divide = ( + nChange, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + aIndexesR, + division // output + ) => { + const bF = bStart - aStart; // bIndex = bF + aIndex - kF + const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR + const aLength = aEnd - aStart; + const bLength = bEnd - bStart; + + // Because graph has square or portrait orientation, + // length difference is minimum number of items to insert from b. + // Corresponding forward and reverse diagonals in graph + // depend on length difference of the sequences: + // kF = kR - baDeltaLength + // kR = kF + baDeltaLength + const baDeltaLength = bLength - aLength; + + // Optimization: max diagonal in graph intersects corner of shorter side. + let iMaxF = aLength; + let iMaxR = aLength; + + // Initialize no changes yet in forward or reverse direction: + aIndexesF[0] = aStart - 1; // at open start of interval, outside closed start + aIndexesR[0] = aEnd; // at open end of interval + + if (baDeltaLength % 2 === 0) { + // The number of changes in paths is 2 * d if length difference is even. + const dMin = (nChange || baDeltaLength) / 2; + const dMax = (aLength + bLength) / 2; + for (let d = 1; d <= dMax; d += 1) { + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + if (d < dMin) { + iMaxR = extendPathsR(d, aStart, bStart, bR, isCommon, aIndexesR, iMaxR); + } else if ( + // If a reverse path overlaps a forward path in the same diagonal, + // return a division of the index intervals at the middle change. + extendOverlappablePathsR( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division + ) + ) { + return; + } + } + } else { + // The number of changes in paths is 2 * d - 1 if length difference is odd. + const dMin = ((nChange || baDeltaLength) + 1) / 2; + const dMax = (aLength + bLength + 1) / 2; + + // Unroll first half iteration so loop extends the relevant pairs of paths. + // Because of invariant that intervals have no common items at start or end, + // and limitation not to call divide with empty intervals, + // therefore it cannot be called if a forward path with one change + // would overlap a reverse path with no changes, even if dMin === 1. + let d = 1; + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + for (d += 1; d <= dMax; d += 1) { + iMaxR = extendPathsR( + d - 1, + aStart, + bStart, + bR, + isCommon, + aIndexesR, + iMaxR + ); + if (d < dMin) { + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + } else if ( + // If a forward path overlaps a reverse path in the same diagonal, + // return a division of the index intervals at the middle change. + extendOverlappablePathsF( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division + ) + ) { + return; + } + } + } + + /* istanbul ignore next */ + throw new Error( + `${pkg}: no overlap aStart=${aStart} aEnd=${aEnd} bStart=${bStart} bEnd=${bEnd}` + ); + }; + + // Given index intervals and input function to compare items at indexes, + // return by output function the number of adjacent items and starting indexes + // of each common subsequence. Divide and conquer with only linear space. + // + // The index intervals are half open [start, end) like array slice method. + // DO NOT CALL if start === end, because interval cannot contain common items + // and because divide function will throw the “no overlap” error. + const findSubsequences = ( + nChange, + aStart, + aEnd, + bStart, + bEnd, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division // temporary memory, not input nor output + ) => { + if (bEnd - bStart < aEnd - aStart) { + // Transpose graph so it has portrait instead of landscape orientation. + // Always compare shorter to longer sequence for consistency and optimization. + transposed = !transposed; + if (transposed && callbacks.length === 1) { + // Lazily wrap callback functions to swap args if graph is transposed. + const {foundSubsequence, isCommon} = callbacks[0]; + callbacks[1] = { + foundSubsequence: (nCommon, bCommon, aCommon) => { + foundSubsequence(nCommon, aCommon, bCommon); + }, + isCommon: (bIndex, aIndex) => isCommon(aIndex, bIndex) + }; + } + const tStart = aStart; + const tEnd = aEnd; + aStart = bStart; + aEnd = bEnd; + bStart = tStart; + bEnd = tEnd; + } + const {foundSubsequence, isCommon} = callbacks[transposed ? 1 : 0]; + + // Divide the index intervals at the middle change. + divide( + nChange, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + aIndexesR, + division + ); + const { + nChangePreceding, + aEndPreceding, + bEndPreceding, + nCommonPreceding, + aCommonPreceding, + bCommonPreceding, + nCommonFollowing, + aCommonFollowing, + bCommonFollowing, + nChangeFollowing, + aStartFollowing, + bStartFollowing + } = division; + + // Unless either index interval is empty, they might contain common items. + if (aStart < aEndPreceding && bStart < bEndPreceding) { + // Recursely find and return common subsequences preceding the division. + findSubsequences( + nChangePreceding, + aStart, + aEndPreceding, + bStart, + bEndPreceding, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division + ); + } + + // Return common subsequences that are adjacent to the middle change. + if (nCommonPreceding !== 0) { + foundSubsequence(nCommonPreceding, aCommonPreceding, bCommonPreceding); + } + if (nCommonFollowing !== 0) { + foundSubsequence(nCommonFollowing, aCommonFollowing, bCommonFollowing); + } + + // Unless either index interval is empty, they might contain common items. + if (aStartFollowing < aEnd && bStartFollowing < bEnd) { + // Recursely find and return common subsequences following the division. + findSubsequences( + nChangeFollowing, + aStartFollowing, + aEnd, + bStartFollowing, + bEnd, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division + ); + } + }; + const validateLength = (name, arg) => { + if (typeof arg !== 'number') { + throw new TypeError(`${pkg}: ${name} typeof ${typeof arg} is not a number`); + } + if (!Number.isSafeInteger(arg)) { + throw new RangeError(`${pkg}: ${name} value ${arg} is not a safe integer`); + } + if (arg < 0) { + throw new RangeError(`${pkg}: ${name} value ${arg} is a negative integer`); + } + }; + const validateCallback = (name, arg) => { + const type = typeof arg; + if (type !== 'function') { + throw new TypeError(`${pkg}: ${name} typeof ${type} is not a function`); + } + }; + + // Compare items in two sequences to find a longest common subsequence. + // Given lengths of sequences and input function to compare items at indexes, + // return by output function the number of adjacent items and starting indexes + // of each common subsequence. + function diffSequence(aLength, bLength, isCommon, foundSubsequence) { + validateLength('aLength', aLength); + validateLength('bLength', bLength); + validateCallback('isCommon', isCommon); + validateCallback('foundSubsequence', foundSubsequence); + + // Count common items from the start in the forward direction. + const nCommonF = countCommonItemsF(0, aLength, 0, bLength, isCommon); + if (nCommonF !== 0) { + foundSubsequence(nCommonF, 0, 0); + } + + // Unless both sequences consist of common items only, + // find common items in the half-trimmed index intervals. + if (aLength !== nCommonF || bLength !== nCommonF) { + // Invariant: intervals do not have common items at the start. + // The start of an index interval is closed like array slice method. + const aStart = nCommonF; + const bStart = nCommonF; + + // Count common items from the end in the reverse direction. + const nCommonR = countCommonItemsR( + aStart, + aLength - 1, + bStart, + bLength - 1, + isCommon + ); + + // Invariant: intervals do not have common items at the end. + // The end of an index interval is open like array slice method. + const aEnd = aLength - nCommonR; + const bEnd = bLength - nCommonR; + + // Unless one sequence consists of common items only, + // therefore the other trimmed index interval consists of changes only, + // find common items in the trimmed index intervals. + const nCommonFR = nCommonF + nCommonR; + if (aLength !== nCommonFR && bLength !== nCommonFR) { + const nChange = 0; // number of change items is not yet known + const transposed = false; // call the original unwrapped functions + const callbacks = [ + { + foundSubsequence, + isCommon + } + ]; + + // Indexes in sequence a of last points in furthest reaching paths + // from outside the start at top left in the forward direction: + const aIndexesF = [NOT_YET_SET]; + // from the end at bottom right in the reverse direction: + const aIndexesR = [NOT_YET_SET]; + + // Initialize one object as output of all calls to divide function. + const division = { + aCommonFollowing: NOT_YET_SET, + aCommonPreceding: NOT_YET_SET, + aEndPreceding: NOT_YET_SET, + aStartFollowing: NOT_YET_SET, + bCommonFollowing: NOT_YET_SET, + bCommonPreceding: NOT_YET_SET, + bEndPreceding: NOT_YET_SET, + bStartFollowing: NOT_YET_SET, + nChangeFollowing: NOT_YET_SET, + nChangePreceding: NOT_YET_SET, + nCommonFollowing: NOT_YET_SET, + nCommonPreceding: NOT_YET_SET + }; + + // Find and return common subsequences in the trimmed index intervals. + findSubsequences( + nChange, + aStart, + aEnd, + bStart, + bEnd, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division + ); + } + if (nCommonR !== 0) { + foundSubsequence(nCommonR, aEnd, bEnd); + } + } + } + return build; +} + +var buildExports = /*@__PURE__*/ requireBuild(); +var diffSequences = /*@__PURE__*/getDefaultExportFromCjs(buildExports); + +function formatTrailingSpaces(line, trailingSpaceFormatter) { + return line.replace(/\s+$/, (match) => trailingSpaceFormatter(match)); +} +function printDiffLine(line, isFirstOrLast, color, indicator, trailingSpaceFormatter, emptyFirstOrLastLinePlaceholder) { + return line.length !== 0 ? color(`${indicator} ${formatTrailingSpaces(line, trailingSpaceFormatter)}`) : indicator !== " " ? color(indicator) : isFirstOrLast && emptyFirstOrLastLinePlaceholder.length !== 0 ? color(`${indicator} ${emptyFirstOrLastLinePlaceholder}`) : ""; +} +function printDeleteLine(line, isFirstOrLast, { aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) { + return printDiffLine(line, isFirstOrLast, aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder); +} +function printInsertLine(line, isFirstOrLast, { bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) { + return printDiffLine(line, isFirstOrLast, bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder); +} +function printCommonLine(line, isFirstOrLast, { commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) { + return printDiffLine(line, isFirstOrLast, commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder); +} +// In GNU diff format, indexes are one-based instead of zero-based. +function createPatchMark(aStart, aEnd, bStart, bEnd, { patchColor }) { + return patchColor(`@@ -${aStart + 1},${aEnd - aStart} +${bStart + 1},${bEnd - bStart} @@`); +} +// jest --no-expand +// +// Given array of aligned strings with inverse highlight formatting, +// return joined lines with diff formatting (and patch marks, if needed). +function joinAlignedDiffsNoExpand(diffs, options) { + const iLength = diffs.length; + const nContextLines = options.contextLines; + const nContextLines2 = nContextLines + nContextLines; + // First pass: count output lines and see if it has patches. + let jLength = iLength; + let hasExcessAtStartOrEnd = false; + let nExcessesBetweenChanges = 0; + let i = 0; + while (i !== iLength) { + const iStart = i; + while (i !== iLength && diffs[i][0] === DIFF_EQUAL) { + i += 1; + } + if (iStart !== i) { + if (iStart === 0) { + // at start + if (i > nContextLines) { + jLength -= i - nContextLines; + hasExcessAtStartOrEnd = true; + } + } else if (i === iLength) { + // at end + const n = i - iStart; + if (n > nContextLines) { + jLength -= n - nContextLines; + hasExcessAtStartOrEnd = true; + } + } else { + // between changes + const n = i - iStart; + if (n > nContextLines2) { + jLength -= n - nContextLines2; + nExcessesBetweenChanges += 1; + } + } + } + while (i !== iLength && diffs[i][0] !== DIFF_EQUAL) { + i += 1; + } + } + const hasPatch = nExcessesBetweenChanges !== 0 || hasExcessAtStartOrEnd; + if (nExcessesBetweenChanges !== 0) { + jLength += nExcessesBetweenChanges + 1; + } else if (hasExcessAtStartOrEnd) { + jLength += 1; + } + const jLast = jLength - 1; + const lines = []; + let jPatchMark = 0; + if (hasPatch) { + lines.push(""); + } + // Indexes of expected or received lines in current patch: + let aStart = 0; + let bStart = 0; + let aEnd = 0; + let bEnd = 0; + const pushCommonLine = (line) => { + const j = lines.length; + lines.push(printCommonLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + bEnd += 1; + }; + const pushDeleteLine = (line) => { + const j = lines.length; + lines.push(printDeleteLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + }; + const pushInsertLine = (line) => { + const j = lines.length; + lines.push(printInsertLine(line, j === 0 || j === jLast, options)); + bEnd += 1; + }; + // Second pass: push lines with diff formatting (and patch marks, if needed). + i = 0; + while (i !== iLength) { + let iStart = i; + while (i !== iLength && diffs[i][0] === DIFF_EQUAL) { + i += 1; + } + if (iStart !== i) { + if (iStart === 0) { + // at beginning + if (i > nContextLines) { + iStart = i - nContextLines; + aStart = iStart; + bStart = iStart; + aEnd = aStart; + bEnd = bStart; + } + for (let iCommon = iStart; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else if (i === iLength) { + // at end + const iEnd = i - iStart > nContextLines ? iStart + nContextLines : i; + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else { + // between changes + const nCommon = i - iStart; + if (nCommon > nContextLines2) { + const iEnd = iStart + nContextLines; + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); + jPatchMark = lines.length; + lines.push(""); + const nOmit = nCommon - nContextLines2; + aStart = aEnd + nOmit; + bStart = bEnd + nOmit; + aEnd = aStart; + bEnd = bStart; + for (let iCommon = i - nContextLines; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else { + for (let iCommon = iStart; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } + } + } + while (i !== iLength && diffs[i][0] === DIFF_DELETE) { + pushDeleteLine(diffs[i][1]); + i += 1; + } + while (i !== iLength && diffs[i][0] === DIFF_INSERT) { + pushInsertLine(diffs[i][1]); + i += 1; + } + } + if (hasPatch) { + lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); + } + return lines.join("\n"); +} +// jest --expand +// +// Given array of aligned strings with inverse highlight formatting, +// return joined lines with diff formatting. +function joinAlignedDiffsExpand(diffs, options) { + return diffs.map((diff, i, diffs) => { + const line = diff[1]; + const isFirstOrLast = i === 0 || i === diffs.length - 1; + switch (diff[0]) { + case DIFF_DELETE: return printDeleteLine(line, isFirstOrLast, options); + case DIFF_INSERT: return printInsertLine(line, isFirstOrLast, options); + default: return printCommonLine(line, isFirstOrLast, options); + } + }).join("\n"); +} + +const noColor = (string) => string; +const DIFF_CONTEXT_DEFAULT = 5; +const DIFF_TRUNCATE_THRESHOLD_DEFAULT = 0; +function getDefaultOptions() { + return { + aAnnotation: "Expected", + aColor: c.green, + aIndicator: "-", + bAnnotation: "Received", + bColor: c.red, + bIndicator: "+", + changeColor: c.inverse, + changeLineTrailingSpaceColor: noColor, + commonColor: c.dim, + commonIndicator: " ", + commonLineTrailingSpaceColor: noColor, + compareKeys: undefined, + contextLines: DIFF_CONTEXT_DEFAULT, + emptyFirstOrLastLinePlaceholder: "", + expand: false, + includeChangeCounts: false, + omitAnnotationLines: false, + patchColor: c.yellow, + printBasicPrototype: false, + truncateThreshold: DIFF_TRUNCATE_THRESHOLD_DEFAULT, + truncateAnnotation: "... Diff result is truncated", + truncateAnnotationColor: noColor + }; +} +function getCompareKeys(compareKeys) { + return compareKeys && typeof compareKeys === "function" ? compareKeys : undefined; +} +function getContextLines(contextLines) { + return typeof contextLines === "number" && Number.isSafeInteger(contextLines) && contextLines >= 0 ? contextLines : DIFF_CONTEXT_DEFAULT; +} +// Pure function returns options with all properties. +function normalizeDiffOptions(options = {}) { + return { + ...getDefaultOptions(), + ...options, + compareKeys: getCompareKeys(options.compareKeys), + contextLines: getContextLines(options.contextLines) + }; +} + +function isEmptyString(lines) { + return lines.length === 1 && lines[0].length === 0; +} +function countChanges(diffs) { + let a = 0; + let b = 0; + diffs.forEach((diff) => { + switch (diff[0]) { + case DIFF_DELETE: + a += 1; + break; + case DIFF_INSERT: + b += 1; + break; + } + }); + return { + a, + b + }; +} +function printAnnotation({ aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator, includeChangeCounts, omitAnnotationLines }, changeCounts) { + if (omitAnnotationLines) { + return ""; + } + let aRest = ""; + let bRest = ""; + if (includeChangeCounts) { + const aCount = String(changeCounts.a); + const bCount = String(changeCounts.b); + // Padding right aligns the ends of the annotations. + const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length; + const aAnnotationPadding = " ".repeat(Math.max(0, baAnnotationLengthDiff)); + const bAnnotationPadding = " ".repeat(Math.max(0, -baAnnotationLengthDiff)); + // Padding left aligns the ends of the counts. + const baCountLengthDiff = bCount.length - aCount.length; + const aCountPadding = " ".repeat(Math.max(0, baCountLengthDiff)); + const bCountPadding = " ".repeat(Math.max(0, -baCountLengthDiff)); + aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`; + bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`; + } + const a = `${aIndicator} ${aAnnotation}${aRest}`; + const b = `${bIndicator} ${bAnnotation}${bRest}`; + return `${aColor(a)}\n${bColor(b)}\n\n`; +} +function printDiffLines(diffs, truncated, options) { + return printAnnotation(options, countChanges(diffs)) + (options.expand ? joinAlignedDiffsExpand(diffs, options) : joinAlignedDiffsNoExpand(diffs, options)) + (truncated ? options.truncateAnnotationColor(`\n${options.truncateAnnotation}`) : ""); +} +// Compare two arrays of strings line-by-line. Format as comparison lines. +function diffLinesUnified(aLines, bLines, options) { + const normalizedOptions = normalizeDiffOptions(options); + const [diffs, truncated] = diffLinesRaw(isEmptyString(aLines) ? [] : aLines, isEmptyString(bLines) ? [] : bLines, normalizedOptions); + return printDiffLines(diffs, truncated, normalizedOptions); +} +// Given two pairs of arrays of strings: +// Compare the pair of comparison arrays line-by-line. +// Format the corresponding lines in the pair of displayable arrays. +function diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options) { + if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) { + aLinesDisplay = []; + aLinesCompare = []; + } + if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) { + bLinesDisplay = []; + bLinesCompare = []; + } + if (aLinesDisplay.length !== aLinesCompare.length || bLinesDisplay.length !== bLinesCompare.length) { + // Fall back to diff of display lines. + return diffLinesUnified(aLinesDisplay, bLinesDisplay, options); + } + const [diffs, truncated] = diffLinesRaw(aLinesCompare, bLinesCompare, options); + // Replace comparison lines with displayable lines. + let aIndex = 0; + let bIndex = 0; + diffs.forEach((diff) => { + switch (diff[0]) { + case DIFF_DELETE: + diff[1] = aLinesDisplay[aIndex]; + aIndex += 1; + break; + case DIFF_INSERT: + diff[1] = bLinesDisplay[bIndex]; + bIndex += 1; + break; + default: + diff[1] = bLinesDisplay[bIndex]; + aIndex += 1; + bIndex += 1; + } + }); + return printDiffLines(diffs, truncated, normalizeDiffOptions(options)); +} +// Compare two arrays of strings line-by-line. +function diffLinesRaw(aLines, bLines, options) { + const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false; + const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0); + const aLength = truncate ? Math.min(aLines.length, truncateThreshold) : aLines.length; + const bLength = truncate ? Math.min(bLines.length, truncateThreshold) : bLines.length; + const truncated = aLength !== aLines.length || bLength !== bLines.length; + const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex]; + const diffs = []; + let aIndex = 0; + let bIndex = 0; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + for (; aIndex !== aCommon; aIndex += 1) { + diffs.push(new Diff(DIFF_DELETE, aLines[aIndex])); + } + for (; bIndex !== bCommon; bIndex += 1) { + diffs.push(new Diff(DIFF_INSERT, bLines[bIndex])); + } + for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) { + diffs.push(new Diff(DIFF_EQUAL, bLines[bIndex])); + } + }; + diffSequences(aLength, bLength, isCommon, foundSubsequence); + // After the last common subsequence, push remaining change items. + for (; aIndex !== aLength; aIndex += 1) { + diffs.push(new Diff(DIFF_DELETE, aLines[aIndex])); + } + for (; bIndex !== bLength; bIndex += 1) { + diffs.push(new Diff(DIFF_INSERT, bLines[bIndex])); + } + return [diffs, truncated]; +} + +// get the type of a value with handling the edge cases like `typeof []` +// and `typeof null` +function getType(value) { + if (value === undefined) { + return "undefined"; + } else if (value === null) { + return "null"; + } else if (Array.isArray(value)) { + return "array"; + } else if (typeof value === "boolean") { + return "boolean"; + } else if (typeof value === "function") { + return "function"; + } else if (typeof value === "number") { + return "number"; + } else if (typeof value === "string") { + return "string"; + } else if (typeof value === "bigint") { + return "bigint"; + } else if (typeof value === "object") { + if (value != null) { + if (value.constructor === RegExp) { + return "regexp"; + } else if (value.constructor === Map) { + return "map"; + } else if (value.constructor === Set) { + return "set"; + } else if (value.constructor === Date) { + return "date"; + } + } + return "object"; + } else if (typeof value === "symbol") { + return "symbol"; + } + throw new Error(`value of unknown type: ${value}`); +} + +// platforms compatible +function getNewLineSymbol(string) { + return string.includes("\r\n") ? "\r\n" : "\n"; +} +function diffStrings(a, b, options) { + const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false; + const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0); + let aLength = a.length; + let bLength = b.length; + if (truncate) { + const aMultipleLines = a.includes("\n"); + const bMultipleLines = b.includes("\n"); + const aNewLineSymbol = getNewLineSymbol(a); + const bNewLineSymbol = getNewLineSymbol(b); + // multiple-lines string expects a newline to be appended at the end + const _a = aMultipleLines ? `${a.split(aNewLineSymbol, truncateThreshold).join(aNewLineSymbol)}\n` : a; + const _b = bMultipleLines ? `${b.split(bNewLineSymbol, truncateThreshold).join(bNewLineSymbol)}\n` : b; + aLength = _a.length; + bLength = _b.length; + } + const truncated = aLength !== a.length || bLength !== b.length; + const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex]; + let aIndex = 0; + let bIndex = 0; + const diffs = []; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + if (aIndex !== aCommon) { + diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex, aCommon))); + } + if (bIndex !== bCommon) { + diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex, bCommon))); + } + aIndex = aCommon + nCommon; + bIndex = bCommon + nCommon; + diffs.push(new Diff(DIFF_EQUAL, b.slice(bCommon, bIndex))); + }; + diffSequences(aLength, bLength, isCommon, foundSubsequence); + // After the last common subsequence, push remaining change items. + if (aIndex !== aLength) { + diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex))); + } + if (bIndex !== bLength) { + diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex))); + } + return [diffs, truncated]; +} + +// Given change op and array of diffs, return concatenated string: +// * include common strings +// * include change strings which have argument op with changeColor +// * exclude change strings which have opposite op +function concatenateRelevantDiffs(op, diffs, changeColor) { + return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op && diff[1].length !== 0 ? changeColor(diff[1]) : ""), ""); +} +// Encapsulate change lines until either a common newline or the end. +class ChangeBuffer { + op; + line; + lines; + changeColor; + constructor(op, changeColor) { + this.op = op; + this.line = []; + this.lines = []; + this.changeColor = changeColor; + } + pushSubstring(substring) { + this.pushDiff(new Diff(this.op, substring)); + } + pushLine() { + // Assume call only if line has at least one diff, + // therefore an empty line must have a diff which has an empty string. + // If line has multiple diffs, then assume it has a common diff, + // therefore change diffs have change color; + // otherwise then it has line color only. + this.lines.push(this.line.length !== 1 ? new Diff(this.op, concatenateRelevantDiffs(this.op, this.line, this.changeColor)) : this.line[0][0] === this.op ? this.line[0] : new Diff(this.op, this.line[0][1])); + this.line.length = 0; + } + isLineEmpty() { + return this.line.length === 0; + } + // Minor input to buffer. + pushDiff(diff) { + this.line.push(diff); + } + // Main input to buffer. + align(diff) { + const string = diff[1]; + if (string.includes("\n")) { + const substrings = string.split("\n"); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i < iLast) { + // The first substring completes the current change line. + // A middle substring is a change line. + this.pushSubstring(substring); + this.pushLine(); + } else if (substring.length !== 0) { + // The last substring starts a change line, if it is not empty. + // Important: This non-empty condition also automatically omits + // the newline appended to the end of expected and received strings. + this.pushSubstring(substring); + } + }); + } else { + // Append non-multiline string to current change line. + this.pushDiff(diff); + } + } + // Output from buffer. + moveLinesTo(lines) { + if (!this.isLineEmpty()) { + this.pushLine(); + } + lines.push(...this.lines); + this.lines.length = 0; + } +} +// Encapsulate common and change lines. +class CommonBuffer { + deleteBuffer; + insertBuffer; + lines; + constructor(deleteBuffer, insertBuffer) { + this.deleteBuffer = deleteBuffer; + this.insertBuffer = insertBuffer; + this.lines = []; + } + pushDiffCommonLine(diff) { + this.lines.push(diff); + } + pushDiffChangeLines(diff) { + const isDiffEmpty = diff[1].length === 0; + // An empty diff string is redundant, unless a change line is empty. + if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) { + this.deleteBuffer.pushDiff(diff); + } + if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) { + this.insertBuffer.pushDiff(diff); + } + } + flushChangeLines() { + this.deleteBuffer.moveLinesTo(this.lines); + this.insertBuffer.moveLinesTo(this.lines); + } + // Input to buffer. + align(diff) { + const op = diff[0]; + const string = diff[1]; + if (string.includes("\n")) { + const substrings = string.split("\n"); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i === 0) { + const subdiff = new Diff(op, substring); + if (this.deleteBuffer.isLineEmpty() && this.insertBuffer.isLineEmpty()) { + // If both current change lines are empty, + // then the first substring is a common line. + this.flushChangeLines(); + this.pushDiffCommonLine(subdiff); + } else { + // If either current change line is non-empty, + // then the first substring completes the change lines. + this.pushDiffChangeLines(subdiff); + this.flushChangeLines(); + } + } else if (i < iLast) { + // A middle substring is a common line. + this.pushDiffCommonLine(new Diff(op, substring)); + } else if (substring.length !== 0) { + // The last substring starts a change line, if it is not empty. + // Important: This non-empty condition also automatically omits + // the newline appended to the end of expected and received strings. + this.pushDiffChangeLines(new Diff(op, substring)); + } + }); + } else { + // Append non-multiline string to current change lines. + // Important: It cannot be at the end following empty change lines, + // because newline appended to the end of expected and received strings. + this.pushDiffChangeLines(diff); + } + } + // Output from buffer. + getLines() { + this.flushChangeLines(); + return this.lines; + } +} +// Given diffs from expected and received strings, +// return new array of diffs split or joined into lines. +// +// To correctly align a change line at the end, the algorithm: +// * assumes that a newline was appended to the strings +// * omits the last newline from the output array +// +// Assume the function is not called: +// * if either expected or received is empty string +// * if neither expected nor received is multiline string +function getAlignedDiffs(diffs, changeColor) { + const deleteBuffer = new ChangeBuffer(DIFF_DELETE, changeColor); + const insertBuffer = new ChangeBuffer(DIFF_INSERT, changeColor); + const commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); + diffs.forEach((diff) => { + switch (diff[0]) { + case DIFF_DELETE: + deleteBuffer.align(diff); + break; + case DIFF_INSERT: + insertBuffer.align(diff); + break; + default: commonBuffer.align(diff); + } + }); + return commonBuffer.getLines(); +} + +function hasCommonDiff(diffs, isMultiline) { + if (isMultiline) { + // Important: Ignore common newline that was appended to multiline strings! + const iLast = diffs.length - 1; + return diffs.some((diff, i) => diff[0] === DIFF_EQUAL && (i !== iLast || diff[1] !== "\n")); + } + return diffs.some((diff) => diff[0] === DIFF_EQUAL); +} +// Compare two strings character-by-character. +// Format as comparison lines in which changed substrings have inverse colors. +function diffStringsUnified(a, b, options) { + if (a !== b && a.length !== 0 && b.length !== 0) { + const isMultiline = a.includes("\n") || b.includes("\n"); + // getAlignedDiffs assumes that a newline was appended to the strings. + const [diffs, truncated] = diffStringsRaw(isMultiline ? `${a}\n` : a, isMultiline ? `${b}\n` : b, true, options); + if (hasCommonDiff(diffs, isMultiline)) { + const optionsNormalized = normalizeDiffOptions(options); + const lines = getAlignedDiffs(diffs, optionsNormalized.changeColor); + return printDiffLines(lines, truncated, optionsNormalized); + } + } + // Fall back to line-by-line diff. + return diffLinesUnified(a.split("\n"), b.split("\n"), options); +} +// Compare two strings character-by-character. +// Optionally clean up small common substrings, also known as chaff. +function diffStringsRaw(a, b, cleanup, options) { + const [diffs, truncated] = diffStrings(a, b, options); + if (cleanup) { + diff_cleanupSemantic(diffs); + } + return [diffs, truncated]; +} + +function getCommonMessage(message, options) { + const { commonColor } = normalizeDiffOptions(options); + return commonColor(message); +} +const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher, + plugins.Error +]; +const FORMAT_OPTIONS = { + maxDepth: 20, + plugins: PLUGINS +}; +const FALLBACK_FORMAT_OPTIONS = { + callToJSON: false, + maxDepth: 8, + plugins: PLUGINS +}; +// Generate a string that will highlight the difference between two values +// with green and red. (similar to how github does code diffing) +/** +* @param a Expected value +* @param b Received value +* @param options Diff options +* @returns {string | null} a string diff +*/ +function diff(a, b, options) { + if (Object.is(a, b)) { + return ""; + } + const aType = getType(a); + let expectedType = aType; + let omitDifference = false; + if (aType === "object" && typeof a.asymmetricMatch === "function") { + if (a.$$typeof !== Symbol.for("jest.asymmetricMatcher")) { + // Do not know expected type of user-defined asymmetric matcher. + return undefined; + } + if (typeof a.getExpectedType !== "function") { + // For example, expect.anything() matches either null or undefined + return undefined; + } + expectedType = a.getExpectedType(); + // Primitive types boolean and number omit difference below. + // For example, omit difference for expect.stringMatching(regexp) + omitDifference = expectedType === "string"; + } + if (expectedType !== getType(b)) { + const { aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator } = normalizeDiffOptions(options); + const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); + let aDisplay = format(a, formatOptions); + let bDisplay = format(b, formatOptions); + // even if prettyFormat prints successfully big objects, + // large string can choke later on (concatenation? RPC?), + // so truncate it to a reasonable length here. + // (For example, playwright's ElementHandle can become about 200_000_000 length string) + const MAX_LENGTH = 1e5; + function truncate(s) { + return s.length <= MAX_LENGTH ? s : `${s.slice(0, MAX_LENGTH)}...`; + } + aDisplay = truncate(aDisplay); + bDisplay = truncate(bDisplay); + const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)} \n${aDisplay}`; + const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)} \n${bDisplay}`; + return `${aDiff}\n\n${bDiff}`; + } + if (omitDifference) { + return undefined; + } + switch (aType) { + case "string": return diffLinesUnified(a.split("\n"), b.split("\n"), options); + case "boolean": + case "number": return comparePrimitive(a, b, options); + case "map": return compareObjects(sortMap(a), sortMap(b), options); + case "set": return compareObjects(sortSet(a), sortSet(b), options); + default: return compareObjects(a, b, options); + } +} +function comparePrimitive(a, b, options) { + const aFormat = format(a, FORMAT_OPTIONS); + const bFormat = format(b, FORMAT_OPTIONS); + return aFormat === bFormat ? "" : diffLinesUnified(aFormat.split("\n"), bFormat.split("\n"), options); +} +function sortMap(map) { + return new Map(Array.from(map.entries()).sort()); +} +function sortSet(set) { + return new Set(Array.from(set.values()).sort()); +} +function compareObjects(a, b, options) { + let difference; + let hasThrown = false; + try { + const formatOptions = getFormatOptions(FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + } catch { + hasThrown = true; + } + const noDiffMessage = getCommonMessage(NO_DIFF_MESSAGE, options); + // If the comparison yields no results, compare again but this time + // without calling `toJSON`. It's also possible that toJSON might throw. + if (difference === undefined || difference === noDiffMessage) { + const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + if (difference !== noDiffMessage && !hasThrown) { + difference = `${getCommonMessage(SIMILAR_MESSAGE, options)}\n\n${difference}`; + } + } + return difference; +} +function getFormatOptions(formatOptions, options) { + const { compareKeys, printBasicPrototype, maxDepth } = normalizeDiffOptions(options); + return { + ...formatOptions, + compareKeys, + printBasicPrototype, + maxDepth: maxDepth ?? formatOptions.maxDepth + }; +} +function getObjectsDifference(a, b, formatOptions, options) { + const formatOptionsZeroIndent = { + ...formatOptions, + indent: 0 + }; + const aCompare = format(a, formatOptionsZeroIndent); + const bCompare = format(b, formatOptionsZeroIndent); + if (aCompare === bCompare) { + return getCommonMessage(NO_DIFF_MESSAGE, options); + } else { + const aDisplay = format(a, formatOptions); + const bDisplay = format(b, formatOptions); + return diffLinesUnified2(aDisplay.split("\n"), bDisplay.split("\n"), aCompare.split("\n"), bCompare.split("\n"), options); + } +} +const MAX_DIFF_STRING_LENGTH = 2e4; +function isAsymmetricMatcher(data) { + const type = getType$1(data); + return type === "Object" && typeof data.asymmetricMatch === "function"; +} +function isReplaceable(obj1, obj2) { + const obj1Type = getType$1(obj1); + const obj2Type = getType$1(obj2); + return obj1Type === obj2Type && (obj1Type === "Object" || obj1Type === "Array"); +} +function printDiffOrStringify(received, expected, options) { + const { aAnnotation, bAnnotation } = normalizeDiffOptions(options); + if (typeof expected === "string" && typeof received === "string" && expected.length > 0 && received.length > 0 && expected.length <= MAX_DIFF_STRING_LENGTH && received.length <= MAX_DIFF_STRING_LENGTH && expected !== received) { + if (expected.includes("\n") || received.includes("\n")) { + return diffStringsUnified(expected, received, options); + } + const [diffs] = diffStringsRaw(expected, received, true); + const hasCommonDiff = diffs.some((diff) => diff[0] === DIFF_EQUAL); + const printLabel = getLabelPrinter(aAnnotation, bAnnotation); + const expectedLine = printLabel(aAnnotation) + printExpected(getCommonAndChangedSubstrings(diffs, DIFF_DELETE, hasCommonDiff)); + const receivedLine = printLabel(bAnnotation) + printReceived(getCommonAndChangedSubstrings(diffs, DIFF_INSERT, hasCommonDiff)); + return `${expectedLine}\n${receivedLine}`; + } + // if (isLineDiffable(expected, received)) { + const clonedExpected = deepClone(expected, { forceWritable: true }); + const clonedReceived = deepClone(received, { forceWritable: true }); + const { replacedExpected, replacedActual } = replaceAsymmetricMatcher(clonedReceived, clonedExpected); + const difference = diff(replacedExpected, replacedActual, options); + return difference; + // } + // const printLabel = getLabelPrinter(aAnnotation, bAnnotation) + // const expectedLine = printLabel(aAnnotation) + printExpected(expected) + // const receivedLine + // = printLabel(bAnnotation) + // + (stringify(expected) === stringify(received) + // ? 'serializes to the same string' + // : printReceived(received)) + // return `${expectedLine}\n${receivedLine}` +} +function replaceAsymmetricMatcher(actual, expected, actualReplaced = new WeakSet(), expectedReplaced = new WeakSet()) { + // handle asymmetric Error.cause diff + if (actual instanceof Error && expected instanceof Error && typeof actual.cause !== "undefined" && typeof expected.cause === "undefined") { + delete actual.cause; + return { + replacedActual: actual, + replacedExpected: expected + }; + } + if (!isReplaceable(actual, expected)) { + return { + replacedActual: actual, + replacedExpected: expected + }; + } + if (actualReplaced.has(actual) || expectedReplaced.has(expected)) { + return { + replacedActual: actual, + replacedExpected: expected + }; + } + actualReplaced.add(actual); + expectedReplaced.add(expected); + getOwnProperties(expected).forEach((key) => { + const expectedValue = expected[key]; + const actualValue = actual[key]; + if (isAsymmetricMatcher(expectedValue)) { + if (expectedValue.asymmetricMatch(actualValue)) { + // When matcher matches, replace expected with actual value + // so they appear the same in the diff + expected[key] = actualValue; + } else if ("sample" in expectedValue && expectedValue.sample !== undefined && isReplaceable(actualValue, expectedValue.sample)) { + // For container matchers (ArrayContaining, ObjectContaining), unwrap and recursively process + // Matcher doesn't match: unwrap but keep structure to show mismatch + const replaced = replaceAsymmetricMatcher(actualValue, expectedValue.sample, actualReplaced, expectedReplaced); + actual[key] = replaced.replacedActual; + expected[key] = replaced.replacedExpected; + } + } else if (isAsymmetricMatcher(actualValue)) { + if (actualValue.asymmetricMatch(expectedValue)) { + actual[key] = expectedValue; + } else if ("sample" in actualValue && actualValue.sample !== undefined && isReplaceable(actualValue.sample, expectedValue)) { + const replaced = replaceAsymmetricMatcher(actualValue.sample, expectedValue, actualReplaced, expectedReplaced); + actual[key] = replaced.replacedActual; + expected[key] = replaced.replacedExpected; + } + } else if (isReplaceable(actualValue, expectedValue)) { + const replaced = replaceAsymmetricMatcher(actualValue, expectedValue, actualReplaced, expectedReplaced); + actual[key] = replaced.replacedActual; + expected[key] = replaced.replacedExpected; + } + }); + return { + replacedActual: actual, + replacedExpected: expected + }; +} +function getLabelPrinter(...strings) { + const maxLength = strings.reduce((max, string) => string.length > max ? string.length : max, 0); + return (string) => `${string}: ${" ".repeat(maxLength - string.length)}`; +} +const SPACE_SYMBOL = "·"; +function replaceTrailingSpaces(text) { + return text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length)); +} +function printReceived(object) { + return c.red(replaceTrailingSpaces(stringify(object))); +} +function printExpected(value) { + return c.green(replaceTrailingSpaces(stringify(value))); +} +function getCommonAndChangedSubstrings(diffs, op, hasCommonDiff) { + return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op ? hasCommonDiff ? c.inverse(diff[1]) : diff[1] : ""), ""); +} + +export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher }; diff --git a/vanilla/node_modules/@vitest/utils/dist/display.d.ts b/vanilla/node_modules/@vitest/utils/dist/display.d.ts new file mode 100644 index 0000000..576fa4c --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/display.d.ts @@ -0,0 +1,29 @@ +import { PrettyFormatOptions } from '@vitest/pretty-format'; + +type Inspect = (value: unknown, options: Options) => string; +interface Options { + showHidden: boolean; + depth: number; + colors: boolean; + customInspect: boolean; + showProxy: boolean; + maxArrayLength: number; + breakLength: number; + truncate: number; + seen: unknown[]; + inspect: Inspect; + stylize: (value: string, styleType: string) => string; +} +type LoupeOptions = Partial; +interface StringifyOptions extends PrettyFormatOptions { + maxLength?: number; +} +declare function stringify(object: unknown, maxDepth?: number, { maxLength, ...options }?: StringifyOptions): string; +declare const formatRegExp: RegExp; +declare function format(...args: unknown[]): string; +declare function browserFormat(...args: unknown[]): string; +declare function inspect(obj: unknown, options?: LoupeOptions): string; +declare function objDisplay(obj: unknown, options?: LoupeOptions): string; + +export { browserFormat, format, formatRegExp, inspect, objDisplay, stringify }; +export type { LoupeOptions, StringifyOptions }; diff --git a/vanilla/node_modules/@vitest/utils/dist/display.js b/vanilla/node_modules/@vitest/utils/dist/display.js new file mode 100644 index 0000000..414e9c9 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/display.js @@ -0,0 +1,742 @@ +import { plugins, format as format$1 } from '@vitest/pretty-format'; + +const ansiColors = { + bold: ['1', '22'], + dim: ['2', '22'], + italic: ['3', '23'], + underline: ['4', '24'], + // 5 & 6 are blinking + inverse: ['7', '27'], + hidden: ['8', '28'], + strike: ['9', '29'], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ['30', '39'], + red: ['31', '39'], + green: ['32', '39'], + yellow: ['33', '39'], + blue: ['34', '39'], + magenta: ['35', '39'], + cyan: ['36', '39'], + white: ['37', '39'], + brightblack: ['30;1', '39'], + brightred: ['31;1', '39'], + brightgreen: ['32;1', '39'], + brightyellow: ['33;1', '39'], + brightblue: ['34;1', '39'], + brightmagenta: ['35;1', '39'], + brightcyan: ['36;1', '39'], + brightwhite: ['37;1', '39'], + grey: ['90', '39'], +}; +const styles = { + special: 'cyan', + number: 'yellow', + bigint: 'yellow', + boolean: 'yellow', + undefined: 'grey', + null: 'bold', + string: 'green', + symbol: 'green', + date: 'magenta', + regexp: 'red', +}; +const truncator = '…'; +function colorise(value, styleType) { + const color = ansiColors[styles[styleType]] || ansiColors[styleType] || ''; + if (!color) { + return String(value); + } + return `\u001b[${color[0]}m${String(value)}\u001b[${color[1]}m`; +} +function normaliseOptions({ showHidden = false, depth = 2, colors = false, customInspect = true, showProxy = false, maxArrayLength = Infinity, breakLength = Infinity, seen = [], +// eslint-disable-next-line no-shadow +truncate = Infinity, stylize = String, } = {}, inspect) { + const options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate), + seen, + inspect, + stylize, + }; + if (options.colors) { + options.stylize = colorise; + } + return options; +} +function isHighSurrogate(char) { + return char >= '\ud800' && char <= '\udbff'; +} +function truncate(string, length, tail = truncator) { + string = String(string); + const tailLength = tail.length; + const stringLength = string.length; + if (tailLength > length && stringLength > tailLength) { + return tail; + } + if (stringLength > length && stringLength > tailLength) { + let end = length - tailLength; + if (end > 0 && isHighSurrogate(string[end - 1])) { + end = end - 1; + } + return `${string.slice(0, end)}${tail}`; + } + return string; +} +// eslint-disable-next-line complexity +function inspectList(list, options, inspectItem, separator = ', ') { + inspectItem = inspectItem || options.inspect; + const size = list.length; + if (size === 0) + return ''; + const originalLength = options.truncate; + let output = ''; + let peek = ''; + let truncated = ''; + for (let i = 0; i < size; i += 1) { + const last = i + 1 === list.length; + const secondToLast = i + 2 === list.length; + truncated = `${truncator}(${list.length - i})`; + const value = list[i]; + // If there is more than one remaining we need to account for a separator of `, ` + options.truncate = originalLength - output.length - (last ? 0 : separator.length); + const string = peek || inspectItem(value, options) + (last ? '' : separator); + const nextLength = output.length + string.length; + const truncatedLength = nextLength + truncated.length; + // If this is the last element, and adding it would + // take us over length, but adding the truncator wouldn't - then break now + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break; + } + // If this isn't the last or second to last element to scan, + // but the string is already over length then break here + if (!last && !secondToLast && truncatedLength > originalLength) { + break; + } + // Peek at the next string to determine if we should + // break early before adding this item to the output + peek = last ? '' : inspectItem(list[i + 1], options) + (secondToLast ? '' : separator); + // If we have one element left, but this element and + // the next takes over length, the break early + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break; + } + output += string; + // If the next element takes us to length - + // but there are more after that, then we should truncate now + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = `${truncator}(${list.length - i - 1})`; + break; + } + truncated = ''; + } + return `${output}${truncated}`; +} +function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key; + } + return JSON.stringify(key) + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); +} +function inspectProperty([key, value], options) { + options.truncate -= 2; + if (typeof key === 'string') { + key = quoteComplexKey(key); + } + else if (typeof key !== 'number') { + key = `[${options.inspect(key, options)}]`; + } + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key}: ${value}`; +} + +function inspectArray(array, options) { + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return '[]'; + options.truncate -= 4; + const listContents = inspectList(array, options); + options.truncate -= listContents.length; + let propertyContents = ''; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty); + } + return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ''} ]`; +} + +const getArrayName = (array) => { + // We need to special case Node.js' Buffers, which report to be Uint8Array + // @ts-ignore + if (typeof Buffer === 'function' && array instanceof Buffer) { + return 'Buffer'; + } + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag]; + } + return array.constructor.name; +}; +function inspectTypedArray(array, options) { + const name = getArrayName(array); + options.truncate -= name.length + 4; + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return `${name}[]`; + // As we know TypedArrays only contain Unsigned Integers, we can skip inspecting each one and simply + // stylise the toString() value of them + let output = ''; + for (let i = 0; i < array.length; i++) { + const string = `${options.stylize(truncate(array[i], options.truncate), 'number')}${i === array.length - 1 ? '' : ', '}`; + options.truncate -= string.length; + if (array[i] !== array.length && options.truncate <= 3) { + output += `${truncator}(${array.length - array[i] + 1})`; + break; + } + output += string; + } + let propertyContents = ''; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty); + } + return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ''} ]`; +} + +function inspectDate(dateObject, options) { + const stringRepresentation = dateObject.toJSON(); + if (stringRepresentation === null) { + return 'Invalid Date'; + } + const split = stringRepresentation.split('T'); + const date = split[0]; + // If we need to - truncate the time portion, but never the date + return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, 'date'); +} + +function inspectFunction(func, options) { + const functionType = func[Symbol.toStringTag] || 'Function'; + const name = func.name; + if (!name) { + return options.stylize(`[${functionType}]`, 'special'); + } + return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, 'special'); +} + +function inspectMapEntry([key, value], options) { + options.truncate -= 4; + key = options.inspect(key, options); + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key} => ${value}`; +} +// IE11 doesn't support `map.entries()` +function mapToEntries(map) { + const entries = []; + map.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +} +function inspectMap(map, options) { + if (map.size === 0) + return 'Map{}'; + options.truncate -= 7; + return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`; +} + +const isNaN = Number.isNaN || (i => i !== i); // eslint-disable-line no-self-compare +function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize('NaN', 'number'); + } + if (number === Infinity) { + return options.stylize('Infinity', 'number'); + } + if (number === -Infinity) { + return options.stylize('-Infinity', 'number'); + } + if (number === 0) { + return options.stylize(1 / number === Infinity ? '+0' : '-0', 'number'); + } + return options.stylize(truncate(String(number), options.truncate), 'number'); +} + +function inspectBigInt(number, options) { + let nums = truncate(number.toString(), options.truncate - 1); + if (nums !== truncator) + nums += 'n'; + return options.stylize(nums, 'bigint'); +} + +function inspectRegExp(value, options) { + const flags = value.toString().split('/')[2]; + const sourceLength = options.truncate - (2 + flags.length); + const source = value.source; + return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, 'regexp'); +} + +// IE11 doesn't support `Array.from(set)` +function arrayFromSet(set) { + const values = []; + set.forEach(value => { + values.push(value); + }); + return values; +} +function inspectSet(set, options) { + if (set.size === 0) + return 'Set{}'; + options.truncate -= 7; + return `Set{ ${inspectList(arrayFromSet(set), options)} }`; +} + +const stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5" + + '\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]', 'g'); +const escapeCharacters = { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + "'": "\\'", + '\\': '\\\\', +}; +const hex = 16; +function escape(char) { + return (escapeCharacters[char] || + `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-4)}`); +} +function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape); + } + return options.stylize(`'${truncate(string, options.truncate - 2)}'`, 'string'); +} + +function inspectSymbol(value) { + if ('description' in Symbol.prototype) { + return value.description ? `Symbol(${value.description})` : 'Symbol()'; + } + return value.toString(); +} + +const getPromiseValue = () => 'Promise{…}'; + +function inspectObject$1(object, options) { + const properties = Object.getOwnPropertyNames(object); + const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; + if (properties.length === 0 && symbols.length === 0) { + return '{}'; + } + options.truncate -= 4; + options.seen = options.seen || []; + if (options.seen.includes(object)) { + return '[Circular]'; + } + options.seen.push(object); + const propertyContents = inspectList(properties.map(key => [key, object[key]]), options, inspectProperty); + const symbolContents = inspectList(symbols.map(key => [key, object[key]]), options, inspectProperty); + options.seen.pop(); + let sep = ''; + if (propertyContents && symbolContents) { + sep = ', '; + } + return `{ ${propertyContents}${sep}${symbolContents} }`; +} + +const toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag ? Symbol.toStringTag : false; +function inspectClass(value, options) { + let name = ''; + if (toStringTag && toStringTag in value) { + name = value[toStringTag]; + } + name = name || value.constructor.name; + // Babel transforms anonymous classes to the name `_class` + if (!name || name === '_class') { + name = ''; + } + options.truncate -= name.length; + return `${name}${inspectObject$1(value, options)}`; +} + +function inspectArguments(args, options) { + if (args.length === 0) + return 'Arguments[]'; + options.truncate -= 13; + return `Arguments[ ${inspectList(args, options)} ]`; +} + +const errorKeys = [ + 'stack', + 'line', + 'column', + 'name', + 'message', + 'fileName', + 'lineNumber', + 'columnNumber', + 'number', + 'description', + 'cause', +]; +function inspectObject(error, options) { + const properties = Object.getOwnPropertyNames(error).filter(key => errorKeys.indexOf(key) === -1); + const name = error.name; + options.truncate -= name.length; + let message = ''; + if (typeof error.message === 'string') { + message = truncate(error.message, options.truncate); + } + else { + properties.unshift('message'); + } + message = message ? `: ${message}` : ''; + options.truncate -= message.length + 5; + options.seen = options.seen || []; + if (options.seen.includes(error)) { + return '[Circular]'; + } + options.seen.push(error); + const propertyContents = inspectList(properties.map(key => [key, error[key]]), options, inspectProperty); + return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ''}`; +} + +function inspectAttribute([key, value], options) { + options.truncate -= 3; + if (!value) { + return `${options.stylize(String(key), 'yellow')}`; + } + return `${options.stylize(String(key), 'yellow')}=${options.stylize(`"${value}"`, 'string')}`; +} +function inspectNodeCollection(collection, options) { + return inspectList(collection, options, inspectNode, '\n'); +} +function inspectNode(node, options) { + switch (node.nodeType) { + case 1: + return inspectHTML(node, options); + case 3: + return options.inspect(node.data, options); + default: + return options.inspect(node, options); + } +} +// @ts-ignore (Deno doesn't have Element) +function inspectHTML(element, options) { + const properties = element.getAttributeNames(); + const name = element.tagName.toLowerCase(); + const head = options.stylize(`<${name}`, 'special'); + const headClose = options.stylize(`>`, 'special'); + const tail = options.stylize(``, 'special'); + options.truncate -= name.length * 2 + 5; + let propertyContents = ''; + if (properties.length > 0) { + propertyContents += ' '; + propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, ' '); + } + options.truncate -= propertyContents.length; + const truncate = options.truncate; + let children = inspectNodeCollection(element.children, options); + if (children && children.length > truncate) { + children = `${truncator}(${element.children.length})`; + } + return `${head}${propertyContents}${headClose}${children}${tail}`; +} + +/* ! + * loupe + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ +const symbolsSupported = typeof Symbol === 'function' && typeof Symbol.for === 'function'; +const chaiInspect = symbolsSupported ? Symbol.for('chai/inspect') : '@@chai/inspect'; +const nodeInspect = Symbol.for('nodejs.util.inspect.custom'); +const constructorMap = new WeakMap(); +const stringTagMap = {}; +const baseTypesMap = { + undefined: (value, options) => options.stylize('undefined', 'undefined'), + null: (value, options) => options.stylize('null', 'null'), + boolean: (value, options) => options.stylize(String(value), 'boolean'), + Boolean: (value, options) => options.stylize(String(value), 'boolean'), + number: inspectNumber, + Number: inspectNumber, + bigint: inspectBigInt, + BigInt: inspectBigInt, + string: inspectString, + String: inspectString, + function: inspectFunction, + Function: inspectFunction, + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: getPromiseValue, + // WeakSet, WeakMap are totally opaque to us + WeakSet: (value, options) => options.stylize('WeakSet{…}', 'special'), + WeakMap: (value, options) => options.stylize('WeakMap{…}', 'special'), + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + Generator: () => '', + DataView: () => '', + ArrayBuffer: () => '', + Error: inspectObject, + HTMLCollection: inspectNodeCollection, + NodeList: inspectNodeCollection, +}; +// eslint-disable-next-line complexity +const inspectCustom = (value, options, type, inspectFn) => { + if (chaiInspect in value && typeof value[chaiInspect] === 'function') { + return value[chaiInspect](options); + } + if (nodeInspect in value && typeof value[nodeInspect] === 'function') { + return value[nodeInspect](options.depth, options, inspectFn); + } + if ('inspect' in value && typeof value.inspect === 'function') { + return value.inspect(options.depth, options); + } + if ('constructor' in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options); + } + if (stringTagMap[type]) { + return stringTagMap[type](value, options); + } + return ''; +}; +const toString = Object.prototype.toString; +// eslint-disable-next-line complexity +function inspect$1(value, opts = {}) { + const options = normaliseOptions(opts, inspect$1); + const { customInspect } = options; + let type = value === null ? 'null' : typeof value; + if (type === 'object') { + type = toString.call(value).slice(8, -1); + } + // If it is a base value that we already support, then use Loupe's inspector + if (type in baseTypesMap) { + return baseTypesMap[type](value, options); + } + // If `options.customInspect` is set to true then try to use the custom inspector + if (customInspect && value) { + const output = inspectCustom(value, options, type, inspect$1); + if (output) { + if (typeof output === 'string') + return output; + return inspect$1(output, options); + } + } + const proto = value ? Object.getPrototypeOf(value) : false; + // If it's a plain Object then use Loupe's inspector + if (proto === Object.prototype || proto === null) { + return inspectObject$1(value, options); + } + // Specifically account for HTMLElements + // @ts-ignore + if (value && typeof HTMLElement === 'function' && value instanceof HTMLElement) { + return inspectHTML(value, options); + } + if ('constructor' in value) { + // If it is a class, inspect it like an object but add the constructor name + if (value.constructor !== Object) { + return inspectClass(value, options); + } + // If it is an object with an anonymous prototype, display it as an object. + return inspectObject$1(value, options); + } + // last chance to check if it's an object + if (value === Object(value)) { + return inspectObject$1(value, options); + } + // We have run out of options! Just stringify the value + return options.stylize(String(value), type); +} + +const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher +]; +function stringify(object, maxDepth = 10, { maxLength, ...options } = {}) { + const MAX_LENGTH = maxLength ?? 1e4; + let result; + try { + result = format$1(object, { + maxDepth, + escapeString: false, + plugins: PLUGINS, + ...options + }); + } catch { + result = format$1(object, { + callToJSON: false, + maxDepth, + escapeString: false, + plugins: PLUGINS, + ...options + }); + } + // Prevents infinite loop https://github.com/vitest-dev/vitest/issues/7249 + return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object, Math.floor(Math.min(maxDepth, Number.MAX_SAFE_INTEGER) / 2), { + maxLength, + ...options + }) : result; +} +const formatRegExp = /%[sdjifoOc%]/g; +function baseFormat(args, options = {}) { + const formatArg = (item, inspecOptions) => { + if (options.prettifyObject) { + return stringify(item, undefined, { + printBasicPrototype: false, + escapeString: false + }); + } + return inspect(item, inspecOptions); + }; + if (typeof args[0] !== "string") { + const objects = []; + for (let i = 0; i < args.length; i++) { + objects.push(formatArg(args[i], { + depth: 0, + colors: false + })); + } + return objects.join(" "); + } + const len = args.length; + let i = 1; + const template = args[0]; + let str = String(template).replace(formatRegExp, (x) => { + if (x === "%%") { + return "%"; + } + if (i >= len) { + return x; + } + switch (x) { + case "%s": { + const value = args[i++]; + if (typeof value === "bigint") { + return `${value.toString()}n`; + } + if (typeof value === "number" && value === 0 && 1 / value < 0) { + return "-0"; + } + if (typeof value === "object" && value !== null) { + if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) { + return value.toString(); + } + return formatArg(value, { + depth: 0, + colors: false + }); + } + return String(value); + } + case "%d": { + const value = args[i++]; + if (typeof value === "bigint") { + return `${value.toString()}n`; + } + return Number(value).toString(); + } + case "%i": { + const value = args[i++]; + if (typeof value === "bigint") { + return `${value.toString()}n`; + } + return Number.parseInt(String(value)).toString(); + } + case "%f": return Number.parseFloat(String(args[i++])).toString(); + case "%o": return formatArg(args[i++], { + showHidden: true, + showProxy: true + }); + case "%O": return formatArg(args[i++]); + case "%c": { + i++; + return ""; + } + case "%j": try { + return JSON.stringify(args[i++]); + } catch (err) { + const m = err.message; + if (m.includes("circular structure") || m.includes("cyclic structures") || m.includes("cyclic object")) { + return "[Circular]"; + } + throw err; + } + default: return x; + } + }); + for (let x = args[i]; i < len; x = args[++i]) { + if (x === null || typeof x !== "object") { + str += ` ${x}`; + } else { + str += ` ${formatArg(x)}`; + } + } + return str; +} +function format(...args) { + return baseFormat(args); +} +function browserFormat(...args) { + return baseFormat(args, { prettifyObject: true }); +} +function inspect(obj, options = {}) { + if (options.truncate === 0) { + options.truncate = Number.POSITIVE_INFINITY; + } + return inspect$1(obj, options); +} +function objDisplay(obj, options = {}) { + if (typeof options.truncate === "undefined") { + options.truncate = 40; + } + const str = inspect(obj, options); + const type = Object.prototype.toString.call(obj); + if (options.truncate && str.length >= options.truncate) { + if (type === "[object Function]") { + const fn = obj; + return !fn.name ? "[Function]" : `[Function: ${fn.name}]`; + } else if (type === "[object Array]") { + return `[ Array(${obj.length}) ]`; + } else if (type === "[object Object]") { + const keys = Object.keys(obj); + const kstr = keys.length > 2 ? `${keys.splice(0, 2).join(", ")}, ...` : keys.join(", "); + return `{ Object (${kstr}) }`; + } else { + return str; + } + } + return str; +} + +export { browserFormat, format, formatRegExp, inspect, objDisplay, stringify }; diff --git a/vanilla/node_modules/@vitest/utils/dist/error.d.ts b/vanilla/node_modules/@vitest/utils/dist/error.d.ts new file mode 100644 index 0000000..ad5d628 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/error.d.ts @@ -0,0 +1,7 @@ +import { D as DiffOptions } from './types.d-BCElaP-c.js'; +export { serializeValue as serializeError } from './serialize.js'; +import '@vitest/pretty-format'; + +declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet): any; + +export { processError }; diff --git a/vanilla/node_modules/@vitest/utils/dist/error.js b/vanilla/node_modules/@vitest/utils/dist/error.js new file mode 100644 index 0000000..14886d0 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/error.js @@ -0,0 +1,42 @@ +import { printDiffOrStringify } from './diff.js'; +import { stringify } from './display.js'; +import { serializeValue } from './serialize.js'; +import '@vitest/pretty-format'; +import 'tinyrainbow'; +import './helpers.js'; +import './constants.js'; +import './chunk-_commonjsHelpers.js'; + +function processError(_err, diffOptions, seen = new WeakSet()) { + if (!_err || typeof _err !== "object") { + return { message: String(_err) }; + } + const err = _err; + if (err.showDiff || err.showDiff === undefined && err.expected !== undefined && err.actual !== undefined) { + err.diff = printDiffOrStringify(err.actual, err.expected, { + ...diffOptions, + ...err.diffOptions + }); + } + if ("expected" in err && typeof err.expected !== "string") { + err.expected = stringify(err.expected, 10); + } + if ("actual" in err && typeof err.actual !== "string") { + err.actual = stringify(err.actual, 10); + } + // some Error implementations may not allow rewriting cause + // in most cases, the assignment will lead to "err.cause = err.cause" + try { + if (!seen.has(err) && typeof err.cause === "object") { + seen.add(err); + err.cause = processError(err.cause, diffOptions, seen); + } + } catch {} + try { + return serializeValue(err); + } catch (e) { + return serializeValue(new Error(`Failed to fully serialize error: ${e === null || e === void 0 ? void 0 : e.message}\nInner error message: ${err === null || err === void 0 ? void 0 : err.message}`)); + } +} + +export { processError, serializeValue as serializeError }; diff --git a/vanilla/node_modules/@vitest/utils/dist/helpers.d.ts b/vanilla/node_modules/@vitest/utils/dist/helpers.d.ts new file mode 100644 index 0000000..493817b --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/helpers.d.ts @@ -0,0 +1,73 @@ +import { Nullable, Arrayable } from './types.js'; + +declare function nanoid(size?: number): string; + +declare function shuffle(array: T[], seed?: number): T[]; + +interface CloneOptions { + forceWritable?: boolean; +} +interface ErrorOptions { + message?: string; + stackTraceLimit?: number; +} + +/** +* Get original stacktrace without source map support the most performant way. +* - Create only 1 stack frame. +* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). +*/ +declare function createSimpleStackTrace(options?: ErrorOptions): string; +declare function notNullish(v: T | null | undefined): v is NonNullable; +declare function assertTypes(value: unknown, name: string, types: string[]): void; +declare function isPrimitive(value: unknown): boolean; +declare function slash(path: string): string; +declare function cleanUrl(url: string): string; +declare const isExternalUrl: (url: string) => boolean; +/** +* Prepend `/@id/` and replace null byte so the id is URL-safe. +* This is prepended to resolved ids that are not valid browser +* import specifiers by the importAnalysis plugin. +*/ +declare function wrapId(id: string): string; +/** +* Undo {@link wrapId}'s `/@id/` and null byte replacements. +*/ +declare function unwrapId(id: string): string; +declare function withTrailingSlash(path: string): string; +declare function isBareImport(id: string): boolean; +declare function toArray(array?: Nullable>): Array; +declare function isObject(item: unknown): boolean; +declare function getType(value: unknown): string; +declare function getOwnProperties(obj: any): (string | symbol)[]; +declare function deepClone(val: T, options?: CloneOptions): T; +declare function clone(val: T, seen: WeakMap, options?: CloneOptions): T; +declare function noop(): void; +declare function objectAttr(source: any, path: string, defaultValue?: undefined): any; +type DeferPromise = Promise & { + resolve: (value: T | PromiseLike) => void; + reject: (reason?: any) => void; +}; +declare function createDefer(): DeferPromise; +/** +* If code starts with a function call, will return its last index, respecting arguments. +* This will return 25 - last ending character of toMatch ")" +* Also works with callbacks +* ``` +* toMatch({ test: '123' }); +* toBeAliased('123') +* ``` +*/ +declare function getCallLastIndex(code: string): number | null; +declare function isNegativeNaN(val: number): boolean; +/** +* Deep merge :P +* +* Will merge objects only if they are plain +* +* Do not merge types - it is very expensive and usually it's better to case a type here +*/ +declare function deepMerge(target: T, ...sources: any[]): T; + +export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId }; +export type { DeferPromise }; diff --git a/vanilla/node_modules/@vitest/utils/dist/helpers.js b/vanilla/node_modules/@vitest/utils/dist/helpers.js new file mode 100644 index 0000000..b19970a --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/helpers.js @@ -0,0 +1,295 @@ +import { VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER } from './constants.js'; + +// port from nanoid +// https://github.com/ai/nanoid +const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"; +function nanoid(size = 21) { + let id = ""; + let i = size; + while (i--) { + id += urlAlphabet[Math.random() * 64 | 0]; + } + return id; +} + +const RealDate = Date; +function random(seed) { + const x = Math.sin(seed++) * 1e4; + return x - Math.floor(x); +} +function shuffle(array, seed = RealDate.now()) { + let length = array.length; + while (length) { + const index = Math.floor(random(seed) * length--); + const previous = array[length]; + array[length] = array[index]; + array[index] = previous; + ++seed; + } + return array; +} + +/** +* Get original stacktrace without source map support the most performant way. +* - Create only 1 stack frame. +* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). +*/ +function createSimpleStackTrace(options) { + const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {}; + const limit = Error.stackTraceLimit; + const prepareStackTrace = Error.prepareStackTrace; + Error.stackTraceLimit = stackTraceLimit; + Error.prepareStackTrace = (e) => e.stack; + const err = new Error(message); + const stackTrace = err.stack || ""; + Error.prepareStackTrace = prepareStackTrace; + Error.stackTraceLimit = limit; + return stackTrace; +} +function notNullish(v) { + return v != null; +} +function assertTypes(value, name, types) { + const receivedType = typeof value; + const pass = types.includes(receivedType); + if (!pass) { + throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`); + } +} +function isPrimitive(value) { + return value === null || typeof value !== "function" && typeof value !== "object"; +} +function slash(path) { + return path.replace(/\\/g, "/"); +} +const postfixRE = /[?#].*$/; +function cleanUrl(url) { + return url.replace(postfixRE, ""); +} +const externalRE = /^(?:[a-z]+:)?\/\//; +const isExternalUrl = (url) => externalRE.test(url); +/** +* Prepend `/@id/` and replace null byte so the id is URL-safe. +* This is prepended to resolved ids that are not valid browser +* import specifiers by the importAnalysis plugin. +*/ +function wrapId(id) { + return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER); +} +/** +* Undo {@link wrapId}'s `/@id/` and null byte replacements. +*/ +function unwrapId(id) { + return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id; +} +function withTrailingSlash(path) { + if (path.at(-1) !== "/") { + return `${path}/`; + } + return path; +} +const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i; +function isBareImport(id) { + return bareImportRE.test(id); +} +function toArray(array) { + if (array === null || array === undefined) { + array = []; + } + if (Array.isArray(array)) { + return array; + } + return [array]; +} +function isObject(item) { + return item != null && typeof item === "object" && !Array.isArray(item); +} +function isFinalObj(obj) { + return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype; +} +function getType(value) { + return Object.prototype.toString.apply(value).slice(8, -1); +} +function collectOwnProperties(obj, collector) { + const collect = typeof collector === "function" ? collector : (key) => collector.add(key); + Object.getOwnPropertyNames(obj).forEach(collect); + Object.getOwnPropertySymbols(obj).forEach(collect); +} +function getOwnProperties(obj) { + const ownProps = new Set(); + if (isFinalObj(obj)) { + return []; + } + collectOwnProperties(obj, ownProps); + return Array.from(ownProps); +} +const defaultCloneOptions = { forceWritable: false }; +function deepClone(val, options = defaultCloneOptions) { + const seen = new WeakMap(); + return clone(val, seen, options); +} +function clone(val, seen, options = defaultCloneOptions) { + let k, out; + if (seen.has(val)) { + return seen.get(val); + } + if (Array.isArray(val)) { + out = Array.from({ length: k = val.length }); + seen.set(val, out); + while (k--) { + out[k] = clone(val[k], seen, options); + } + return out; + } + if (Object.prototype.toString.call(val) === "[object Object]") { + out = Object.create(Object.getPrototypeOf(val)); + seen.set(val, out); + // we don't need properties from prototype + const props = getOwnProperties(val); + for (const k of props) { + const descriptor = Object.getOwnPropertyDescriptor(val, k); + if (!descriptor) { + continue; + } + const cloned = clone(val[k], seen, options); + if (options.forceWritable) { + Object.defineProperty(out, k, { + enumerable: descriptor.enumerable, + configurable: true, + writable: true, + value: cloned + }); + } else if ("get" in descriptor) { + Object.defineProperty(out, k, { + ...descriptor, + get() { + return cloned; + } + }); + } else { + Object.defineProperty(out, k, { + ...descriptor, + value: cloned + }); + } + } + return out; + } + return val; +} +function noop() {} +function objectAttr(source, path, defaultValue = undefined) { + // a[3].b -> a.3.b + const paths = path.replace(/\[(\d+)\]/g, ".$1").split("."); + let result = source; + for (const p of paths) { + result = new Object(result)[p]; + if (result === undefined) { + return defaultValue; + } + } + return result; +} +function createDefer() { + let resolve = null; + let reject = null; + const p = new Promise((_resolve, _reject) => { + resolve = _resolve; + reject = _reject; + }); + p.resolve = resolve; + p.reject = reject; + return p; +} +/** +* If code starts with a function call, will return its last index, respecting arguments. +* This will return 25 - last ending character of toMatch ")" +* Also works with callbacks +* ``` +* toMatch({ test: '123' }); +* toBeAliased('123') +* ``` +*/ +function getCallLastIndex(code) { + let charIndex = -1; + let inString = null; + let startedBracers = 0; + let endedBracers = 0; + let beforeChar = null; + while (charIndex <= code.length) { + beforeChar = code[charIndex]; + charIndex++; + const char = code[charIndex]; + const isCharString = char === "\"" || char === "'" || char === "`"; + if (isCharString && beforeChar !== "\\") { + if (inString === char) { + inString = null; + } else if (!inString) { + inString = char; + } + } + if (!inString) { + if (char === "(") { + startedBracers++; + } + if (char === ")") { + endedBracers++; + } + } + if (startedBracers && endedBracers && startedBracers === endedBracers) { + return charIndex; + } + } + return null; +} +function isNegativeNaN(val) { + if (!Number.isNaN(val)) { + return false; + } + const f64 = new Float64Array(1); + f64[0] = val; + const u32 = new Uint32Array(f64.buffer); + const isNegative = u32[1] >>> 31 === 1; + return isNegative; +} +function toString(v) { + return Object.prototype.toString.call(v); +} +function isPlainObject(val) { + return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object"); +} +function isMergeableObject(item) { + return isPlainObject(item) && !Array.isArray(item); +} +/** +* Deep merge :P +* +* Will merge objects only if they are plain +* +* Do not merge types - it is very expensive and usually it's better to case a type here +*/ +function deepMerge(target, ...sources) { + if (!sources.length) { + return target; + } + const source = sources.shift(); + if (source === undefined) { + return target; + } + if (isMergeableObject(target) && isMergeableObject(source)) { + Object.keys(source).forEach((key) => { + const _source = source; + if (isMergeableObject(_source[key])) { + if (!target[key]) { + target[key] = {}; + } + deepMerge(target[key], _source[key]); + } else { + target[key] = _source[key]; + } + }); + } + return deepMerge(target, ...sources); +} + +export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId }; diff --git a/vanilla/node_modules/@vitest/utils/dist/highlight.d.ts b/vanilla/node_modules/@vitest/utils/dist/highlight.d.ts new file mode 100644 index 0000000..b3420de --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/highlight.d.ts @@ -0,0 +1,9 @@ +import { Colors } from 'tinyrainbow'; + +interface HighlightOptions { + jsx?: boolean; + colors?: Colors; +} +declare function highlight(code: string, options?: HighlightOptions): string; + +export { highlight }; diff --git a/vanilla/node_modules/@vitest/utils/dist/highlight.js b/vanilla/node_modules/@vitest/utils/dist/highlight.js new file mode 100644 index 0000000..1250062 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/highlight.js @@ -0,0 +1,538 @@ +import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js'; +import c from 'tinyrainbow'; + +var jsTokens_1; +var hasRequiredJsTokens; + +function requireJsTokens () { + if (hasRequiredJsTokens) return jsTokens_1; + hasRequiredJsTokens = 1; + // Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell + // License: MIT. + var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace; + RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\\]).|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu; + Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y; + Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu; + StringLiteral = /(['"])(?:(?!\1)[^\\\n\r]|\\(?:\r\n|[^]))*(\1)?/y; + NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y; + Template = /[`}](?:[^`\\$]|\\[^]|\$(?!\{))*(`|\$\{)?/y; + WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu; + LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y; + MultiLineComment = /\/\*(?:[^*]|\*(?!\/))*(\*\/)?/y; + SingleLineComment = /\/\/.*/y; + JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y; + JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu; + JSXString = /(['"])(?:(?!\1)[^])*(\1)?/y; + JSXText = /[^<>{}]+/y; + TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/; + TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/; + KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/; + KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/; + Newline = RegExp(LineTerminatorSequence.source); + jsTokens_1 = function*(input, {jsx = false} = {}) { + var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack; + ({length} = input); + lastIndex = 0; + lastSignificantToken = ""; + stack = [ + {tag: "JS"} + ]; + braces = []; + parenNesting = 0; + postfixIncDec = false; + while (lastIndex < length) { + mode = stack[stack.length - 1]; + switch (mode.tag) { + case "JS": + case "JSNonExpressionParen": + case "InterpolationInTemplate": + case "InterpolationInJSX": + if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { + RegularExpressionLiteral.lastIndex = lastIndex; + if (match = RegularExpressionLiteral.exec(input)) { + lastIndex = RegularExpressionLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "RegularExpressionLiteral", + value: match[0], + closed: match[1] !== void 0 && match[1] !== "\\" + }); + continue; + } + } + Punctuator.lastIndex = lastIndex; + if (match = Punctuator.exec(input)) { + punctuator = match[0]; + nextLastIndex = Punctuator.lastIndex; + nextLastSignificantToken = punctuator; + switch (punctuator) { + case "(": + if (lastSignificantToken === "?NonExpressionParenKeyword") { + stack.push({ + tag: "JSNonExpressionParen", + nesting: parenNesting + }); + } + parenNesting++; + postfixIncDec = false; + break; + case ")": + parenNesting--; + postfixIncDec = true; + if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) { + stack.pop(); + nextLastSignificantToken = "?NonExpressionParenEnd"; + postfixIncDec = false; + } + break; + case "{": + Punctuator.lastIndex = 0; + isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken)); + braces.push(isExpression); + postfixIncDec = false; + break; + case "}": + switch (mode.tag) { + case "InterpolationInTemplate": + if (braces.length === mode.nesting) { + Template.lastIndex = lastIndex; + match = Template.exec(input); + lastIndex = Template.lastIndex; + lastSignificantToken = match[0]; + if (match[1] === "${") { + lastSignificantToken = "?InterpolationInTemplate"; + postfixIncDec = false; + yield ({ + type: "TemplateMiddle", + value: match[0] + }); + } else { + stack.pop(); + postfixIncDec = true; + yield ({ + type: "TemplateTail", + value: match[0], + closed: match[1] === "`" + }); + } + continue; + } + break; + case "InterpolationInJSX": + if (braces.length === mode.nesting) { + stack.pop(); + lastIndex += 1; + lastSignificantToken = "}"; + yield ({ + type: "JSXPunctuator", + value: "}" + }); + continue; + } + } + postfixIncDec = braces.pop(); + nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}"; + break; + case "]": + postfixIncDec = true; + break; + case "++": + case "--": + nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec"; + break; + case "<": + if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { + stack.push({tag: "JSXTag"}); + lastIndex += 1; + lastSignificantToken = "<"; + yield ({ + type: "JSXPunctuator", + value: punctuator + }); + continue; + } + postfixIncDec = false; + break; + default: + postfixIncDec = false; + } + lastIndex = nextLastIndex; + lastSignificantToken = nextLastSignificantToken; + yield ({ + type: "Punctuator", + value: punctuator + }); + continue; + } + Identifier.lastIndex = lastIndex; + if (match = Identifier.exec(input)) { + lastIndex = Identifier.lastIndex; + nextLastSignificantToken = match[0]; + switch (match[0]) { + case "for": + case "if": + case "while": + case "with": + if (lastSignificantToken !== "." && lastSignificantToken !== "?.") { + nextLastSignificantToken = "?NonExpressionParenKeyword"; + } + } + lastSignificantToken = nextLastSignificantToken; + postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]); + yield ({ + type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName", + value: match[0] + }); + continue; + } + StringLiteral.lastIndex = lastIndex; + if (match = StringLiteral.exec(input)) { + lastIndex = StringLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "StringLiteral", + value: match[0], + closed: match[2] !== void 0 + }); + continue; + } + NumericLiteral.lastIndex = lastIndex; + if (match = NumericLiteral.exec(input)) { + lastIndex = NumericLiteral.lastIndex; + lastSignificantToken = match[0]; + postfixIncDec = true; + yield ({ + type: "NumericLiteral", + value: match[0] + }); + continue; + } + Template.lastIndex = lastIndex; + if (match = Template.exec(input)) { + lastIndex = Template.lastIndex; + lastSignificantToken = match[0]; + if (match[1] === "${") { + lastSignificantToken = "?InterpolationInTemplate"; + stack.push({ + tag: "InterpolationInTemplate", + nesting: braces.length + }); + postfixIncDec = false; + yield ({ + type: "TemplateHead", + value: match[0] + }); + } else { + postfixIncDec = true; + yield ({ + type: "NoSubstitutionTemplate", + value: match[0], + closed: match[1] === "`" + }); + } + continue; + } + break; + case "JSXTag": + case "JSXTagEnd": + JSXPunctuator.lastIndex = lastIndex; + if (match = JSXPunctuator.exec(input)) { + lastIndex = JSXPunctuator.lastIndex; + nextLastSignificantToken = match[0]; + switch (match[0]) { + case "<": + stack.push({tag: "JSXTag"}); + break; + case ">": + stack.pop(); + if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") { + nextLastSignificantToken = "?JSX"; + postfixIncDec = true; + } else { + stack.push({tag: "JSXChildren"}); + } + break; + case "{": + stack.push({ + tag: "InterpolationInJSX", + nesting: braces.length + }); + nextLastSignificantToken = "?InterpolationInJSX"; + postfixIncDec = false; + break; + case "/": + if (lastSignificantToken === "<") { + stack.pop(); + if (stack[stack.length - 1].tag === "JSXChildren") { + stack.pop(); + } + stack.push({tag: "JSXTagEnd"}); + } + } + lastSignificantToken = nextLastSignificantToken; + yield ({ + type: "JSXPunctuator", + value: match[0] + }); + continue; + } + JSXIdentifier.lastIndex = lastIndex; + if (match = JSXIdentifier.exec(input)) { + lastIndex = JSXIdentifier.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXIdentifier", + value: match[0] + }); + continue; + } + JSXString.lastIndex = lastIndex; + if (match = JSXString.exec(input)) { + lastIndex = JSXString.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXString", + value: match[0], + closed: match[2] !== void 0 + }); + continue; + } + break; + case "JSXChildren": + JSXText.lastIndex = lastIndex; + if (match = JSXText.exec(input)) { + lastIndex = JSXText.lastIndex; + lastSignificantToken = match[0]; + yield ({ + type: "JSXText", + value: match[0] + }); + continue; + } + switch (input[lastIndex]) { + case "<": + stack.push({tag: "JSXTag"}); + lastIndex++; + lastSignificantToken = "<"; + yield ({ + type: "JSXPunctuator", + value: "<" + }); + continue; + case "{": + stack.push({ + tag: "InterpolationInJSX", + nesting: braces.length + }); + lastIndex++; + lastSignificantToken = "?InterpolationInJSX"; + postfixIncDec = false; + yield ({ + type: "JSXPunctuator", + value: "{" + }); + continue; + } + } + WhiteSpace.lastIndex = lastIndex; + if (match = WhiteSpace.exec(input)) { + lastIndex = WhiteSpace.lastIndex; + yield ({ + type: "WhiteSpace", + value: match[0] + }); + continue; + } + LineTerminatorSequence.lastIndex = lastIndex; + if (match = LineTerminatorSequence.exec(input)) { + lastIndex = LineTerminatorSequence.lastIndex; + postfixIncDec = false; + if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { + lastSignificantToken = "?NoLineTerminatorHere"; + } + yield ({ + type: "LineTerminatorSequence", + value: match[0] + }); + continue; + } + MultiLineComment.lastIndex = lastIndex; + if (match = MultiLineComment.exec(input)) { + lastIndex = MultiLineComment.lastIndex; + if (Newline.test(match[0])) { + postfixIncDec = false; + if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { + lastSignificantToken = "?NoLineTerminatorHere"; + } + } + yield ({ + type: "MultiLineComment", + value: match[0], + closed: match[1] !== void 0 + }); + continue; + } + SingleLineComment.lastIndex = lastIndex; + if (match = SingleLineComment.exec(input)) { + lastIndex = SingleLineComment.lastIndex; + postfixIncDec = false; + yield ({ + type: "SingleLineComment", + value: match[0] + }); + continue; + } + firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex)); + lastIndex += firstCodePoint.length; + lastSignificantToken = firstCodePoint; + postfixIncDec = false; + yield ({ + type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid", + value: firstCodePoint + }); + } + return void 0; + }; + return jsTokens_1; +} + +var jsTokensExports = /*@__PURE__*/ requireJsTokens(); +var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokensExports); + +// src/index.ts +var reservedWords = { + keyword: [ + "break", + "case", + "catch", + "continue", + "debugger", + "default", + "do", + "else", + "finally", + "for", + "function", + "if", + "return", + "switch", + "throw", + "try", + "var", + "const", + "while", + "with", + "new", + "this", + "super", + "class", + "extends", + "export", + "import", + "null", + "true", + "false", + "in", + "instanceof", + "typeof", + "void", + "delete" + ], + strict: [ + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "yield" + ] +}, keywords = new Set(reservedWords.keyword), reservedWordsStrictSet = new Set(reservedWords.strict), sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]); +function isReservedWord(word) { + return word === "await" || word === "enum"; +} +function isStrictReservedWord(word) { + return isReservedWord(word) || reservedWordsStrictSet.has(word); +} +function isKeyword(word) { + return keywords.has(word); +} +var BRACKET = /^[()[\]{}]$/, getTokenType = function(token) { + if (token.type === "IdentifierName") { + if (isKeyword(token.value) || isStrictReservedWord(token.value) || sometimesKeywords.has(token.value)) + return "Keyword"; + if (token.value[0] && token.value[0] !== token.value[0].toLowerCase()) + return "IdentifierCapitalized"; + } + return token.type === "Punctuator" && BRACKET.test(token.value) ? "Bracket" : token.type === "Invalid" && (token.value === "@" || token.value === "#") ? "Punctuator" : token.type; +}; +function getCallableType(token) { + if (token.type === "IdentifierName") + return "IdentifierCallable"; + if (token.type === "PrivateIdentifier") + return "PrivateIdentifierCallable"; + throw new Error("Not a callable token"); +} +var colorize = (defs, type, value) => { + let colorize2 = defs[type]; + return colorize2 ? colorize2(value) : value; +}, highlightTokens = (defs, text, jsx) => { + let highlighted = "", lastPotentialCallable = null, stackedHighlight = ""; + for (let token of jsTokens(text, { jsx })) { + let type = getTokenType(token); + if (type === "IdentifierName" || type === "PrivateIdentifier") { + lastPotentialCallable && (highlighted += colorize(defs, getTokenType(lastPotentialCallable), lastPotentialCallable.value) + stackedHighlight, stackedHighlight = ""), lastPotentialCallable = token; + continue; + } + if (lastPotentialCallable && (token.type === "WhiteSpace" || token.type === "LineTerminatorSequence" || token.type === "Punctuator" && (token.value === "?." || token.value === "!"))) { + stackedHighlight += colorize(defs, type, token.value); + continue; + } + if (stackedHighlight && !lastPotentialCallable && (highlighted += stackedHighlight, stackedHighlight = ""), lastPotentialCallable) { + let type2 = token.type === "Punctuator" && token.value === "(" ? getCallableType(lastPotentialCallable) : getTokenType(lastPotentialCallable); + highlighted += colorize(defs, type2, lastPotentialCallable.value) + stackedHighlight, stackedHighlight = "", lastPotentialCallable = null; + } + highlighted += colorize(defs, type, token.value); + } + return highlighted; +}; +function highlight$1(code, options = { jsx: false, colors: {} }) { + return code && highlightTokens(options.colors || {}, code, options.jsx); +} + +function getDefs(c) { + const Invalid = (text) => c.white(c.bgRed(c.bold(text))); + return { + Keyword: c.magenta, + IdentifierCapitalized: c.yellow, + Punctuator: c.yellow, + StringLiteral: c.green, + NoSubstitutionTemplate: c.green, + MultiLineComment: c.gray, + SingleLineComment: c.gray, + RegularExpressionLiteral: c.cyan, + NumericLiteral: c.blue, + TemplateHead: (text) => c.green(text.slice(0, text.length - 2)) + c.cyan(text.slice(-2)), + TemplateTail: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1)), + TemplateMiddle: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1, text.length - 2)) + c.cyan(text.slice(-2)), + IdentifierCallable: c.blue, + PrivateIdentifierCallable: (text) => `#${c.blue(text.slice(1))}`, + Invalid, + JSXString: c.green, + JSXIdentifier: c.yellow, + JSXInvalid: Invalid, + JSXPunctuator: c.yellow + }; +} +function highlight(code, options = { jsx: false }) { + return highlight$1(code, { + jsx: options.jsx, + colors: getDefs(options.colors || c) + }); +} + +export { highlight }; diff --git a/vanilla/node_modules/@vitest/utils/dist/index.d.ts b/vanilla/node_modules/@vitest/utils/dist/index.d.ts new file mode 100644 index 0000000..d4435cc --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/index.d.ts @@ -0,0 +1,5 @@ +export { LoupeOptions, StringifyOptions } from './display.js'; +export { DeferPromise } from './helpers.js'; +export { SafeTimers } from './timers.js'; +export { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError } from './types.js'; +import '@vitest/pretty-format'; diff --git a/vanilla/node_modules/@vitest/utils/dist/index.js b/vanilla/node_modules/@vitest/utils/dist/index.js new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/index.js @@ -0,0 +1 @@ + diff --git a/vanilla/node_modules/@vitest/utils/dist/offset.d.ts b/vanilla/node_modules/@vitest/utils/dist/offset.d.ts new file mode 100644 index 0000000..ae65386 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/offset.d.ts @@ -0,0 +1,5 @@ +declare const lineSplitRE: RegExp; +declare function positionToOffset(source: string, lineNumber: number, columnNumber: number): number; +declare function offsetToLineNumber(source: string, offset: number): number; + +export { lineSplitRE, offsetToLineNumber, positionToOffset }; diff --git a/vanilla/node_modules/@vitest/utils/dist/offset.js b/vanilla/node_modules/@vitest/utils/dist/offset.js new file mode 100644 index 0000000..d8cb08d --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/offset.js @@ -0,0 +1,32 @@ +const lineSplitRE = /\r?\n/; +function positionToOffset(source, lineNumber, columnNumber) { + const lines = source.split(lineSplitRE); + const nl = /\r\n/.test(source) ? 2 : 1; + let start = 0; + if (lineNumber > lines.length) { + return source.length; + } + for (let i = 0; i < lineNumber - 1; i++) { + start += lines[i].length + nl; + } + return start + columnNumber; +} +function offsetToLineNumber(source, offset) { + if (offset > source.length) { + throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`); + } + const lines = source.split(lineSplitRE); + const nl = /\r\n/.test(source) ? 2 : 1; + let counted = 0; + let line = 0; + for (; line < lines.length; line++) { + const lineLength = lines[line].length + nl; + if (counted + lineLength >= offset) { + break; + } + counted += lineLength; + } + return line + 1; +} + +export { lineSplitRE, offsetToLineNumber, positionToOffset }; diff --git a/vanilla/node_modules/@vitest/utils/dist/resolver.d.ts b/vanilla/node_modules/@vitest/utils/dist/resolver.d.ts new file mode 100644 index 0000000..71ebc63 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/resolver.d.ts @@ -0,0 +1,7 @@ +declare function findNearestPackageData(basedir: string): { + type?: "module" | "commonjs"; +}; +declare function getCachedData(cache: Map, basedir: string, originalBasedir: string): NonNullable | undefined; +declare function setCacheData(cache: Map, data: T, basedir: string, originalBasedir: string): void; + +export { findNearestPackageData, getCachedData, setCacheData }; diff --git a/vanilla/node_modules/@vitest/utils/dist/resolver.js b/vanilla/node_modules/@vitest/utils/dist/resolver.js new file mode 100644 index 0000000..83bd3c1 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/resolver.js @@ -0,0 +1,71 @@ +import fs from 'node:fs'; +import { j as join, d as dirname } from './chunk-pathe.M-eThtNZ.js'; + +const packageCache = new Map(); +function findNearestPackageData(basedir) { + const originalBasedir = basedir; + while (basedir) { + var _tryStatSync; + const cached = getCachedData(packageCache, basedir, originalBasedir); + if (cached) { + return cached; + } + const pkgPath = join(basedir, "package.json"); + if ((_tryStatSync = tryStatSync(pkgPath)) === null || _tryStatSync === void 0 ? void 0 : _tryStatSync.isFile()) { + const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8"))); + if (packageCache) { + setCacheData(packageCache, pkgData, basedir, originalBasedir); + } + return pkgData; + } + const nextBasedir = dirname(basedir); + if (nextBasedir === basedir) { + break; + } + basedir = nextBasedir; + } + return {}; +} +function stripBomTag(content) { + if (content.charCodeAt(0) === 65279) { + return content.slice(1); + } + return content; +} +function tryStatSync(file) { + try { + // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist + return fs.statSync(file, { throwIfNoEntry: false }); + } catch {} +} +function getCachedData(cache, basedir, originalBasedir) { + const pkgData = cache.get(getFnpdCacheKey(basedir)); + if (pkgData) { + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + cache.set(getFnpdCacheKey(dir), pkgData); + }); + return pkgData; + } +} +function setCacheData(cache, data, basedir, originalBasedir) { + cache.set(getFnpdCacheKey(basedir), data); + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + cache.set(getFnpdCacheKey(dir), data); + }); +} +function getFnpdCacheKey(basedir) { + return `fnpd_${basedir}`; +} +/** +* Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir. +* @param longerDir Longer dir path, e.g. `/User/foo/bar/baz` +* @param shorterDir Shorter dir path, e.g. `/User/foo` +*/ +function traverseBetweenDirs(longerDir, shorterDir, cb) { + while (longerDir !== shorterDir) { + cb(longerDir); + longerDir = dirname(longerDir); + } +} + +export { findNearestPackageData, getCachedData, setCacheData }; diff --git a/vanilla/node_modules/@vitest/utils/dist/serialize.d.ts b/vanilla/node_modules/@vitest/utils/dist/serialize.d.ts new file mode 100644 index 0000000..dd8ee7d --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/serialize.d.ts @@ -0,0 +1,3 @@ +declare function serializeValue(val: any, seen?: WeakMap): any; + +export { serializeValue }; diff --git a/vanilla/node_modules/@vitest/utils/dist/serialize.js b/vanilla/node_modules/@vitest/utils/dist/serialize.js new file mode 100644 index 0000000..f3ad0ad --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/serialize.js @@ -0,0 +1,118 @@ +const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@"; +const IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@"; +function isImmutable(v) { + return v && (v[IS_COLLECTION_SYMBOL] || v[IS_RECORD_SYMBOL]); +} +const OBJECT_PROTO = Object.getPrototypeOf({}); +function getUnserializableMessage(err) { + if (err instanceof Error) { + return `: ${err.message}`; + } + if (typeof err === "string") { + return `: ${err}`; + } + return ""; +} +// https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm +function serializeValue(val, seen = new WeakMap()) { + if (!val || typeof val === "string") { + return val; + } + if (val instanceof Error && "toJSON" in val && typeof val.toJSON === "function") { + const jsonValue = val.toJSON(); + if (jsonValue && jsonValue !== val && typeof jsonValue === "object") { + if (typeof val.message === "string") { + safe(() => jsonValue.message ?? (jsonValue.message = normalizeErrorMessage(val.message))); + } + if (typeof val.stack === "string") { + safe(() => jsonValue.stack ?? (jsonValue.stack = val.stack)); + } + if (typeof val.name === "string") { + safe(() => jsonValue.name ?? (jsonValue.name = val.name)); + } + if (val.cause != null) { + safe(() => jsonValue.cause ?? (jsonValue.cause = serializeValue(val.cause, seen))); + } + } + return serializeValue(jsonValue, seen); + } + if (typeof val === "function") { + return `Function<${val.name || "anonymous"}>`; + } + if (typeof val === "symbol") { + return val.toString(); + } + if (typeof val !== "object") { + return val; + } + if (typeof Buffer !== "undefined" && val instanceof Buffer) { + return ``; + } + if (typeof Uint8Array !== "undefined" && val instanceof Uint8Array) { + return ``; + } + // cannot serialize immutables as immutables + if (isImmutable(val)) { + return serializeValue(val.toJSON(), seen); + } + if (val instanceof Promise || val.constructor && val.constructor.prototype === "AsyncFunction") { + return "Promise"; + } + if (typeof Element !== "undefined" && val instanceof Element) { + return val.tagName; + } + if (typeof val.toJSON === "function") { + return serializeValue(val.toJSON(), seen); + } + if (seen.has(val)) { + return seen.get(val); + } + if (Array.isArray(val)) { + // eslint-disable-next-line unicorn/no-new-array -- we need to keep sparse arrays ([1,,3]) + const clone = new Array(val.length); + seen.set(val, clone); + val.forEach((e, i) => { + try { + clone[i] = serializeValue(e, seen); + } catch (err) { + clone[i] = getUnserializableMessage(err); + } + }); + return clone; + } else { + // Objects with `Error` constructors appear to cause problems during worker communication + // using `MessagePort`, so the serialized error object is being recreated as plain object. + const clone = Object.create(null); + seen.set(val, clone); + let obj = val; + while (obj && obj !== OBJECT_PROTO) { + Object.getOwnPropertyNames(obj).forEach((key) => { + if (key in clone) { + return; + } + try { + clone[key] = serializeValue(val[key], seen); + } catch (err) { + // delete in case it has a setter from prototype that might throw + delete clone[key]; + clone[key] = getUnserializableMessage(err); + } + }); + obj = Object.getPrototypeOf(obj); + } + if (val instanceof Error) { + safe(() => val.message = normalizeErrorMessage(val.message)); + } + return clone; + } +} +function safe(fn) { + try { + return fn(); + } catch {} +} +function normalizeErrorMessage(message) { + return message.replace(/__(vite_ssr_import|vi_import)_\d+__\./g, ""); +} + +export { serializeValue }; diff --git a/vanilla/node_modules/@vitest/utils/dist/source-map.d.ts b/vanilla/node_modules/@vitest/utils/dist/source-map.d.ts new file mode 100644 index 0000000..582d24f --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/source-map.d.ts @@ -0,0 +1,55 @@ +import { TestError, ParsedStack } from './types.js'; + +type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; + +interface StackTraceParserOptions { + ignoreStackEntries?: (RegExp | string)[]; + getSourceMap?: (file: string) => unknown; + getUrlId?: (id: string) => string; + frameFilter?: (error: TestError, frame: ParsedStack) => boolean | void; +} +declare const stackIgnorePatterns: (string | RegExp)[]; + +declare function parseSingleFFOrSafariStack(raw: string): ParsedStack | null; +declare function parseSingleStack(raw: string): ParsedStack | null; +declare function parseSingleV8Stack(raw: string): ParsedStack | null; +declare function createStackString(stacks: ParsedStack[]): string; +declare function parseStacktrace(stack: string, options?: StackTraceParserOptions): ParsedStack[]; +declare function parseErrorStacktrace(e: TestError | Error, options?: StackTraceParserOptions): ParsedStack[]; +interface SourceMapLike { + version: number; + mappings?: string; + names?: string[]; + sources?: string[]; + sourcesContent?: string[]; + sourceRoot?: string; +} +interface Needle { + line: number; + column: number; +} +declare class DecodedMap { + map: SourceMapLike; + _encoded: string; + _decoded: undefined | number[][][]; + _decodedMemo: Stats; + url: string; + version: number; + names: string[]; + resolvedSources: string[]; + constructor(map: SourceMapLike, from: string); +} +interface Stats { + lastKey: number; + lastNeedle: number; + lastIndex: number; +} +declare function getOriginalPosition(map: DecodedMap, needle: Needle): OriginalMapping | null; + +export { DecodedMap, createStackString, stackIgnorePatterns as defaultStackIgnorePatterns, getOriginalPosition, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace }; +export type { StackTraceParserOptions }; diff --git a/vanilla/node_modules/@vitest/utils/dist/source-map.js b/vanilla/node_modules/@vitest/utils/dist/source-map.js new file mode 100644 index 0000000..b435c91 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/source-map.js @@ -0,0 +1,478 @@ +import { isPrimitive, notNullish } from './helpers.js'; +import { r as resolve } from './chunk-pathe.M-eThtNZ.js'; +import './constants.js'; + +// src/vlq.ts +var comma = ",".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} + +// src/trace-mapping.ts + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; + +// src/binary-search.ts +var found = false; +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + (high - low >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return state.lastIndex = binarySearch(haystack, needle, low, high); +} + +// src/trace-mapping.ts +var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; +var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; +var LEAST_UPPER_BOUND = -1; +var GREATEST_LOWER_BOUND = 1; +function cast(map) { + return map; +} +function decodedMappings(map) { + var _a; + return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded)); +} +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + if (line >= decoded.length) return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND + ); + if (index === -1) return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null + ); +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + if (index === -1 || index === segments.length) return -1; + return index; +} + +const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m; +const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/; +const stackIgnorePatterns = [ + "node:internal", + /\/packages\/\w+\/dist\//, + /\/@vitest\/\w+\/dist\//, + "/vitest/dist/", + "/vitest/src/", + "/node_modules/chai/", + "/node_modules/tinyspy/", + "/vite/dist/node/module-runner", + "/rolldown-vite/dist/node/module-runner", + "/deps/chunk-", + "/deps/@vitest", + "/deps/loupe", + "/deps/chai", + "/browser-playwright/dist/locators.js", + "/browser-webdriverio/dist/locators.js", + "/browser-preview/dist/locators.js", + /node:\w+/, + /__vitest_test__/, + /__vitest_browser__/, + /\/deps\/vitest_/ +]; +function extractLocation(urlLike) { + // Fail-fast but return locations like "(native)" + if (!urlLike.includes(":")) { + return [urlLike]; + } + const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; + const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); + if (!parts) { + return [urlLike]; + } + let url = parts[1]; + if (url.startsWith("async ")) { + url = url.slice(6); + } + if (url.startsWith("http:") || url.startsWith("https:")) { + const urlObj = new URL(url); + urlObj.searchParams.delete("import"); + urlObj.searchParams.delete("browserv"); + url = urlObj.pathname + urlObj.hash + urlObj.search; + } + if (url.startsWith("/@fs/")) { + const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url); + url = url.slice(isWindows ? 5 : 4); + } + return [ + url, + parts[2] || undefined, + parts[3] || undefined + ]; +} +function parseSingleFFOrSafariStack(raw) { + let line = raw.trim(); + if (SAFARI_NATIVE_CODE_REGEXP.test(line)) { + return null; + } + if (line.includes(" > eval")) { + line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); + } + // Early return for lines that don't look like Firefox/Safari stack traces + // Firefox/Safari stack traces must contain '@' and should have location info after it + if (!line.includes("@")) { + return null; + } + // Find the correct @ that separates function name from location + // For cases like '@https://@fs/path' or 'functionName@https://@fs/path' + // we need to find the first @ that precedes a valid location (containing :) + let atIndex = -1; + let locationPart = ""; + let functionName; + // Try each @ from left to right to find the one that gives us a valid location + for (let i = 0; i < line.length; i++) { + if (line[i] === "@") { + const candidateLocation = line.slice(i + 1); + // Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1") + if (candidateLocation.includes(":") && candidateLocation.length >= 3) { + atIndex = i; + locationPart = candidateLocation; + functionName = i > 0 ? line.slice(0, i) : undefined; + break; + } + } + } + // Validate we found a valid location with minimum length (filename:line format) + if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) { + return null; + } + const [url, lineNumber, columnNumber] = extractLocation(locationPart); + if (!url || !lineNumber || !columnNumber) { + return null; + } + return { + file: url, + method: functionName || "", + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function parseSingleStack(raw) { + const line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) { + return parseSingleFFOrSafariStack(line); + } + return parseSingleV8Stack(line); +} +// Based on https://github.com/stacktracejs/error-stack-parser +// Credit to stacktracejs +function parseSingleV8Stack(raw) { + let line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) { + return null; + } + if (line.includes("(eval ")) { + line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, ""); + } + let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, ""); + // capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in + // case it has spaces in it, as the string is split on \s+ later on + const location = sanitizedLine.match(/ (\(.+\)$)/); + // remove the parenthesized location from the line, if it was matched + sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; + // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine + // because this line doesn't have function name + const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); + let method = location && sanitizedLine || ""; + let file = url && ["eval", ""].includes(url) ? undefined : url; + if (!file || !lineNumber || !columnNumber) { + return null; + } + if (method.startsWith("async ")) { + method = method.slice(6); + } + if (file.startsWith("file://")) { + file = file.slice(7); + } + // normalize Windows path (\ -> /) + file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file); + if (method) { + method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, ""); + } + return { + method, + file, + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function createStackString(stacks) { + return stacks.map((stack) => { + const line = `${stack.file}:${stack.line}:${stack.column}`; + if (stack.method) { + return ` at ${stack.method}(${line})`; + } + return ` at ${line}`; + }).join("\n"); +} +function parseStacktrace(stack, options = {}) { + const { ignoreStackEntries = stackIgnorePatterns } = options; + const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack); + return stacks.map((stack) => { + var _options$getSourceMap; + if (options.getUrlId) { + stack.file = options.getUrlId(stack.file); + } + const map = (_options$getSourceMap = options.getSourceMap) === null || _options$getSourceMap === void 0 ? void 0 : _options$getSourceMap.call(options, stack.file); + if (!map || typeof map !== "object" || !map.version) { + return shouldFilter(ignoreStackEntries, stack.file) ? null : stack; + } + const traceMap = new DecodedMap(map, stack.file); + const position = getOriginalPosition(traceMap, stack); + if (!position) { + return stack; + } + const { line, column, source, name } = position; + let file = source || stack.file; + if (file.match(/\/\w:\//)) { + file = file.slice(1); + } + if (shouldFilter(ignoreStackEntries, file)) { + return null; + } + if (line != null && column != null) { + return { + line, + column, + file, + method: name || stack.method + }; + } + return stack; + }).filter((s) => s != null); +} +function shouldFilter(ignoreStackEntries, file) { + return ignoreStackEntries.some((p) => file.match(p)); +} +function parseFFOrSafariStackTrace(stack) { + return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish); +} +function parseV8Stacktrace(stack) { + return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish); +} +function parseErrorStacktrace(e, options = {}) { + if (!e || isPrimitive(e)) { + return []; + } + if ("stacks" in e && e.stacks) { + return e.stacks; + } + const stackStr = e.stack || ""; + // if "stack" property was overwritten at runtime to be something else, + // ignore the value because we don't know how to process it + let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : []; + if (!stackFrames.length) { + const e_ = e; + if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) { + stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options); + } + if (e_.sourceURL != null && e_.line != null && e_._column != null) { + stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options); + } + } + if (options.frameFilter) { + stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false); + } + e.stacks = stackFrames; + return stackFrames; +} +class DecodedMap { + _encoded; + _decoded; + _decodedMemo; + url; + version; + names = []; + resolvedSources; + constructor(map, from) { + this.map = map; + const { mappings, names, sources } = map; + this.version = map.version; + this.names = names || []; + this._encoded = mappings || ""; + this._decodedMemo = memoizedState(); + this.url = from; + this.resolvedSources = (sources || []).map((s) => resolve(s || "", from)); + } +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1 + }; +} +function getOriginalPosition(map, needle) { + const result = originalPositionFor(map, needle); + if (result.column == null) { + return null; + } + return result; +} + +export { DecodedMap, createStackString, stackIgnorePatterns as defaultStackIgnorePatterns, getOriginalPosition, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace }; diff --git a/vanilla/node_modules/@vitest/utils/dist/timers.d.ts b/vanilla/node_modules/@vitest/utils/dist/timers.d.ts new file mode 100644 index 0000000..8dd6025 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/timers.d.ts @@ -0,0 +1,33 @@ +interface SafeTimers { + nextTick?: (cb: () => void) => void; + setImmediate?: { + (callback: (...args: TArgs) => void, ...args: TArgs): any; + __promisify__: (value?: T, options?: any) => Promise; + }; + clearImmediate?: (immediateId: any) => void; + setTimeout: typeof setTimeout; + setInterval: typeof setInterval; + clearInterval: typeof clearInterval; + clearTimeout: typeof clearTimeout; + queueMicrotask: typeof queueMicrotask; +} +declare function getSafeTimers(): SafeTimers; +declare function setSafeTimers(): void; +/** +* Returns a promise that resolves after the specified duration. +* +* @param timeout - Delay in milliseconds +* @param scheduler - Timer function to use, defaults to `setTimeout`. Useful for mocked timers. +* +* @example +* await delay(100) +* +* @example +* // With mocked timers +* const { setTimeout } = getSafeTimers() +* await delay(100, setTimeout) +*/ +declare function delay(timeout: number, scheduler?: typeof setTimeout): Promise; + +export { delay, getSafeTimers, setSafeTimers }; +export type { SafeTimers }; diff --git a/vanilla/node_modules/@vitest/utils/dist/timers.js b/vanilla/node_modules/@vitest/utils/dist/timers.js new file mode 100644 index 0000000..29229e5 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/timers.js @@ -0,0 +1,49 @@ +const SAFE_TIMERS_SYMBOL = Symbol("vitest:SAFE_TIMERS"); +function getSafeTimers() { + const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis; + const { nextTick: safeNextTick } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis.process || {}; + return { + nextTick: safeNextTick, + setTimeout: safeSetTimeout, + setInterval: safeSetInterval, + clearInterval: safeClearInterval, + clearTimeout: safeClearTimeout, + setImmediate: safeSetImmediate, + clearImmediate: safeClearImmediate, + queueMicrotask: safeQueueMicrotask + }; +} +function setSafeTimers() { + const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis; + const { nextTick: safeNextTick } = globalThis.process || {}; + const timers = { + nextTick: safeNextTick, + setTimeout: safeSetTimeout, + setInterval: safeSetInterval, + clearInterval: safeClearInterval, + clearTimeout: safeClearTimeout, + setImmediate: safeSetImmediate, + clearImmediate: safeClearImmediate, + queueMicrotask: safeQueueMicrotask + }; + globalThis[SAFE_TIMERS_SYMBOL] = timers; +} +/** +* Returns a promise that resolves after the specified duration. +* +* @param timeout - Delay in milliseconds +* @param scheduler - Timer function to use, defaults to `setTimeout`. Useful for mocked timers. +* +* @example +* await delay(100) +* +* @example +* // With mocked timers +* const { setTimeout } = getSafeTimers() +* await delay(100, setTimeout) +*/ +function delay(timeout, scheduler = setTimeout) { + return new Promise((resolve) => scheduler(resolve, timeout)); +} + +export { delay, getSafeTimers, setSafeTimers }; diff --git a/vanilla/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts b/vanilla/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts new file mode 100644 index 0000000..cba06c6 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts @@ -0,0 +1,53 @@ +import { CompareKeys } from '@vitest/pretty-format'; + +/** +* 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. +*/ + +type DiffOptionsColor = (arg: string) => string; +interface DiffOptions { + aAnnotation?: string; + aColor?: DiffOptionsColor; + aIndicator?: string; + bAnnotation?: string; + bColor?: DiffOptionsColor; + bIndicator?: string; + changeColor?: DiffOptionsColor; + changeLineTrailingSpaceColor?: DiffOptionsColor; + commonColor?: DiffOptionsColor; + commonIndicator?: string; + commonLineTrailingSpaceColor?: DiffOptionsColor; + contextLines?: number; + emptyFirstOrLastLinePlaceholder?: string; + expand?: boolean; + includeChangeCounts?: boolean; + omitAnnotationLines?: boolean; + patchColor?: DiffOptionsColor; + printBasicPrototype?: boolean; + maxDepth?: number; + compareKeys?: CompareKeys; + truncateThreshold?: number; + truncateAnnotation?: string; + truncateAnnotationColor?: DiffOptionsColor; +} +interface SerializedDiffOptions { + aAnnotation?: string; + aIndicator?: string; + bAnnotation?: string; + bIndicator?: string; + commonIndicator?: string; + contextLines?: number; + emptyFirstOrLastLinePlaceholder?: string; + expand?: boolean; + includeChangeCounts?: boolean; + omitAnnotationLines?: boolean; + printBasicPrototype?: boolean; + maxDepth?: number; + truncateThreshold?: number; + truncateAnnotation?: string; +} + +export type { DiffOptions as D, SerializedDiffOptions as S, DiffOptionsColor as a }; diff --git a/vanilla/node_modules/@vitest/utils/dist/types.d.ts b/vanilla/node_modules/@vitest/utils/dist/types.d.ts new file mode 100644 index 0000000..4e6d810 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/types.d.ts @@ -0,0 +1,34 @@ +type Awaitable = T | PromiseLike; +type Nullable = T | null | undefined; +type Arrayable = T | Array; +type ArgumentsType = T extends (...args: infer U) => any ? U : never; +type MergeInsertions = T extends object ? { [K in keyof T] : MergeInsertions } : T; +type DeepMerge< + F, + S +> = MergeInsertions<{ [K in keyof F | keyof S] : K extends keyof S & keyof F ? DeepMerge : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never }>; +interface Constructable { + new (...args: any[]): any; +} +interface ParsedStack { + method: string; + file: string; + line: number; + column: number; +} +interface SerializedError { + message: string; + stacks?: ParsedStack[]; + stack?: string; + name?: string; + cause?: SerializedError; + [key: string]: unknown; +} +interface TestError extends SerializedError { + cause?: TestError; + diff?: string; + actual?: string; + expected?: string; +} + +export type { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError }; diff --git a/vanilla/node_modules/@vitest/utils/dist/types.js b/vanilla/node_modules/@vitest/utils/dist/types.js new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/dist/types.js @@ -0,0 +1 @@ + diff --git a/vanilla/node_modules/@vitest/utils/error.d.ts b/vanilla/node_modules/@vitest/utils/error.d.ts new file mode 100644 index 0000000..9329baa --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/error.d.ts @@ -0,0 +1 @@ +export * from './dist/error.js' diff --git a/vanilla/node_modules/@vitest/utils/helpers.d.ts b/vanilla/node_modules/@vitest/utils/helpers.d.ts new file mode 100644 index 0000000..0add1d0 --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/helpers.d.ts @@ -0,0 +1 @@ +export * from './dist/helpers.js' diff --git a/vanilla/node_modules/@vitest/utils/package.json b/vanilla/node_modules/@vitest/utils/package.json new file mode 100644 index 0000000..1b8b19d --- /dev/null +++ b/vanilla/node_modules/@vitest/utils/package.json @@ -0,0 +1,98 @@ +{ + "name": "@vitest/utils", + "type": "module", + "version": "4.0.18", + "description": "Shared Vitest utility functions", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/utils" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./diff": { + "types": "./dist/diff.d.ts", + "default": "./dist/diff.js" + }, + "./resolver": { + "types": "./dist/resolver.d.ts", + "default": "./dist/resolver.js" + }, + "./error": { + "types": "./dist/error.d.ts", + "default": "./dist/error.js" + }, + "./helpers": { + "types": "./dist/helpers.d.ts", + "default": "./dist/helpers.js" + }, + "./offset": { + "types": "./dist/offset.d.ts", + "default": "./dist/offset.js" + }, + "./constants": { + "types": "./dist/constants.d.ts", + "default": "./dist/constants.js" + }, + "./timers": { + "types": "./dist/timers.d.ts", + "default": "./dist/timers.js" + }, + "./display": { + "types": "./dist/display.d.ts", + "default": "./dist/display.js" + }, + "./highlight": { + "types": "./dist/highlight.d.ts", + "default": "./dist/highlight.js" + }, + "./source-map": { + "types": "./dist/source-map.d.ts", + "default": "./dist/source-map.js" + }, + "./serialize": { + "types": "./dist/serialize.d.ts", + "default": "./dist/serialize.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "source-map": [ + "dist/source-map.d.ts" + ] + } + }, + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "tinyrainbow": "^3.0.3", + "@vitest/pretty-format": "4.0.18" + }, + "devDependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@types/estree": "^1.0.8", + "diff-sequences": "^29.6.3", + "loupe": "^3.2.1", + "tinyhighlight": "^0.3.2" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/agent-base/LICENSE b/vanilla/node_modules/agent-base/LICENSE new file mode 100644 index 0000000..008728c --- /dev/null +++ b/vanilla/node_modules/agent-base/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich + +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/vanilla/node_modules/agent-base/README.md b/vanilla/node_modules/agent-base/README.md new file mode 100644 index 0000000..b8a86b9 --- /dev/null +++ b/vanilla/node_modules/agent-base/README.md @@ -0,0 +1,69 @@ +agent-base +========== +### Turn a function into an [`http.Agent`][http.Agent] instance + +This module is a thin wrapper around the base `http.Agent` class. + +It provides an abstract class that must define a `connect()` function, +which is responsible for creating the underlying socket that the HTTP +client requests will use. + +The `connect()` function may return an arbitrary `Duplex` stream, or +another `http.Agent` instance to delegate the request to, and may be +asynchronous (by defining an `async` function). + +Instances of this agent can be used with the `http` and `https` +modules. To differentiate, the options parameter in the `connect()` +function includes a `secureEndpoint` property, which can be checked +to determine what type of socket should be returned. + +#### Some subclasses: + +Here are some more interesting uses of `agent-base`. +Send a pull request to list yours! + + * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints + * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints + * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS + * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS + +Example +------- + +Here's a minimal example that creates a new `net.Socket` or `tls.Socket` +based on the `secureEndpoint` property. This agent can be used with both +the `http` and `https` modules. + +```ts +import * as net from 'net'; +import * as tls from 'tls'; +import * as http from 'http'; +import { Agent } from 'agent-base'; + +class MyAgent extends Agent { + connect(req, opts) { + // `secureEndpoint` is true when using the "https" module + if (opts.secureEndpoint) { + return tls.connect(opts); + } else { + return net.connect(opts); + } + } +}); + +// Keep alive enabled means that `connect()` will only be +// invoked when a new connection needs to be created +const agent = new MyAgent({ keepAlive: true }); + +// Pass the `agent` option when creating the HTTP request +http.get('http://nodejs.org/api/', { agent }, (res) => { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +[http-proxy-agent]: ../http-proxy-agent +[https-proxy-agent]: ../https-proxy-agent +[pac-proxy-agent]: ../pac-proxy-agent +[socks-proxy-agent]: ../socks-proxy-agent +[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent diff --git a/vanilla/node_modules/agent-base/dist/helpers.d.ts b/vanilla/node_modules/agent-base/dist/helpers.d.ts new file mode 100644 index 0000000..b468f23 --- /dev/null +++ b/vanilla/node_modules/agent-base/dist/helpers.d.ts @@ -0,0 +1,15 @@ +/// +/// +/// +/// +/// +import * as http from 'http'; +import * as https from 'https'; +import type { Readable } from 'stream'; +export type ThenableRequest = http.ClientRequest & { + then: Promise['then']; +}; +export declare function toBuffer(stream: Readable): Promise; +export declare function json(stream: Readable): Promise; +export declare function req(url: string | URL, opts?: https.RequestOptions): ThenableRequest; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/vanilla/node_modules/agent-base/dist/helpers.d.ts.map b/vanilla/node_modules/agent-base/dist/helpers.d.ts.map new file mode 100644 index 0000000..9479c9a --- /dev/null +++ b/vanilla/node_modules/agent-base/dist/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;;;;AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAEvC,MAAM,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,GAAG;IAClD,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC;CAC5C,CAAC;AAEF,wBAAsB,QAAQ,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAQhE;AAGD,wBAAsB,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,CAUzD;AAED,wBAAgB,GAAG,CAClB,GAAG,EAAE,MAAM,GAAG,GAAG,EACjB,IAAI,GAAE,KAAK,CAAC,cAAmB,GAC7B,eAAe,CAcjB"} \ No newline at end of file diff --git a/vanilla/node_modules/agent-base/dist/helpers.js b/vanilla/node_modules/agent-base/dist/helpers.js new file mode 100644 index 0000000..ef3f920 --- /dev/null +++ b/vanilla/node_modules/agent-base/dist/helpers.js @@ -0,0 +1,66 @@ +"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.req = exports.json = exports.toBuffer = void 0; +const http = __importStar(require("http")); +const https = __importStar(require("https")); +async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); +} +exports.toBuffer = toBuffer; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +async function json(stream) { + const buf = await toBuffer(stream); + const str = buf.toString('utf8'); + try { + return JSON.parse(str); + } + catch (_err) { + const err = _err; + err.message += ` (input: ${str})`; + throw err; + } +} +exports.json = json; +function req(url, opts = {}) { + const href = typeof url === 'string' ? url : url.href; + const req = (href.startsWith('https:') ? https : http).request(url, opts); + const promise = new Promise((resolve, reject) => { + req + .once('response', resolve) + .once('error', reject) + .end(); + }); + req.then = promise.then.bind(promise); + return req; +} +exports.req = req; +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/vanilla/node_modules/agent-base/dist/helpers.js.map b/vanilla/node_modules/agent-base/dist/helpers.js.map new file mode 100644 index 0000000..19df537 --- /dev/null +++ b/vanilla/node_modules/agent-base/dist/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAC7B,6CAA+B;AAOxB,KAAK,UAAU,QAAQ,CAAC,MAAgB;IAC9C,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,MAAM,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC;QACvB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;KACnB;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AACtC,CAAC;AARD,4BAQC;AAED,8DAA8D;AACvD,KAAK,UAAU,IAAI,CAAC,MAAgB;IAC1C,MAAM,GAAG,GAAG,MAAM,QAAQ,CAAC,MAAM,CAAC,CAAC;IACnC,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACjC,IAAI;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;KACvB;IAAC,OAAO,IAAa,EAAE;QACvB,MAAM,GAAG,GAAG,IAAa,CAAC;QAC1B,GAAG,CAAC,OAAO,IAAI,YAAY,GAAG,GAAG,CAAC;QAClC,MAAM,GAAG,CAAC;KACV;AACF,CAAC;AAVD,oBAUC;AAED,SAAgB,GAAG,CAClB,GAAiB,EACjB,OAA6B,EAAE;IAE/B,MAAM,IAAI,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC;IACtD,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,CAC7D,GAAG,EACH,IAAI,CACe,CAAC;IACrB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAuB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrE,GAAG;aACD,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC;aACzB,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC;aACrB,GAAG,EAAqB,CAAC;IAC5B,CAAC,CAAC,CAAC;IACH,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACtC,OAAO,GAAG,CAAC;AACZ,CAAC;AAjBD,kBAiBC"} \ No newline at end of file diff --git a/vanilla/node_modules/agent-base/dist/index.d.ts b/vanilla/node_modules/agent-base/dist/index.d.ts new file mode 100644 index 0000000..3660ea7 --- /dev/null +++ b/vanilla/node_modules/agent-base/dist/index.d.ts @@ -0,0 +1,41 @@ +/// +/// +/// +/// +import * as net from 'net'; +import * as tls from 'tls'; +import * as http from 'http'; +import type { Duplex } from 'stream'; +export * from './helpers'; +interface HttpConnectOpts extends net.TcpNetConnectOpts { + secureEndpoint: false; + protocol?: string; +} +interface HttpsConnectOpts extends tls.ConnectionOptions { + secureEndpoint: true; + protocol?: string; + port: number; +} +export type AgentConnectOpts = HttpConnectOpts | HttpsConnectOpts; +declare const INTERNAL: unique symbol; +export declare abstract class Agent extends http.Agent { + private [INTERNAL]; + options: Partial; + keepAlive: boolean; + constructor(opts?: http.AgentOptions); + abstract connect(req: http.ClientRequest, options: AgentConnectOpts): Promise | Duplex | http.Agent; + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options?: AgentConnectOpts): boolean; + private incrementSockets; + private decrementSockets; + getName(options?: AgentConnectOpts): string; + createSocket(req: http.ClientRequest, options: AgentConnectOpts, cb: (err: Error | null, s?: Duplex) => void): void; + createConnection(): Duplex; + get defaultPort(): number; + set defaultPort(v: number); + get protocol(): string; + set protocol(v: string); +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/vanilla/node_modules/agent-base/dist/index.d.ts.map b/vanilla/node_modules/agent-base/dist/index.d.ts.map new file mode 100644 index 0000000..c0f91ab --- /dev/null +++ b/vanilla/node_modules/agent-base/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAAA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,cAAc,WAAW,CAAC;AAE1B,UAAU,eAAgB,SAAQ,GAAG,CAAC,iBAAiB;IACtD,cAAc,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,UAAU,gBAAiB,SAAQ,GAAG,CAAC,iBAAiB;IACvD,cAAc,EAAE,IAAI,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,MAAM,gBAAgB,GAAG,eAAe,GAAG,gBAAgB,CAAC;AAElE,QAAA,MAAM,QAAQ,eAAmC,CAAC;AAQlD,8BAAsB,KAAM,SAAQ,IAAI,CAAC,KAAK;IAC7C,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAgB;IAGlC,OAAO,EAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,GAAG,GAAG,CAAC,iBAAiB,CAAC,CAAC;IACjE,SAAS,EAAG,OAAO,CAAC;gBAER,IAAI,CAAC,EAAE,IAAI,CAAC,YAAY;IAKpC,QAAQ,CAAC,OAAO,CACf,GAAG,EAAE,IAAI,CAAC,aAAa,EACvB,OAAO,EAAE,gBAAgB,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,MAAM,GAAG,IAAI,CAAC,KAAK;IAErD;;OAEG;IACH,gBAAgB,CAAC,OAAO,CAAC,EAAE,gBAAgB,GAAG,OAAO;IAqCrD,OAAO,CAAC,gBAAgB;IAqBxB,OAAO,CAAC,gBAAgB;IAmBxB,OAAO,CAAC,OAAO,CAAC,EAAE,gBAAgB,GAAG,MAAM;IAU3C,YAAY,CACX,GAAG,EAAE,IAAI,CAAC,aAAa,EACvB,OAAO,EAAE,gBAAgB,EACzB,EAAE,EAAE,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI;IAgC5C,gBAAgB,IAAI,MAAM;IAW1B,IAAI,WAAW,IAAI,MAAM,CAKxB;IAED,IAAI,WAAW,CAAC,CAAC,EAAE,MAAM,EAIxB;IAED,IAAI,QAAQ,IAAI,MAAM,CAKrB;IAED,IAAI,QAAQ,CAAC,CAAC,EAAE,MAAM,EAIrB;CACD"} \ No newline at end of file diff --git a/vanilla/node_modules/agent-base/dist/index.js b/vanilla/node_modules/agent-base/dist/index.js new file mode 100644 index 0000000..57ac852 --- /dev/null +++ b/vanilla/node_modules/agent-base/dist/index.js @@ -0,0 +1,178 @@ +"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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.Agent = void 0; +const net = __importStar(require("net")); +const http = __importStar(require("http")); +const https_1 = require("https"); +__exportStar(require("./helpers"), exports); +const INTERNAL = Symbol('AgentBaseInternalState'); +class Agent extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + // First check the `secureEndpoint` property explicitly, since this + // means that a parent `Agent` is "passing through" to this instance. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof options.secureEndpoint === 'boolean') { + return options.secureEndpoint; + } + // If no explicit `secure` endpoint, check if `protocol` property is + // set. This will usually be the case since using a full string URL + // or `URL` instance should be the most common usage. + if (typeof options.protocol === 'string') { + return options.protocol === 'https:'; + } + } + // Finally, if no `protocol` property was set, then fall back to + // checking the stack trace of the current call stack, and try to + // detect the "https" module. + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack + .split('\n') + .some((l) => l.indexOf('(https.js:') !== -1 || + l.indexOf('node:https:') !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no + // need to create a fake socket because Node.js native connection pooling + // will never be invoked. + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + // All instances of `sockets` are expected TypeScript errors. The + // alternative is to add it as a private property of this class but that + // will break TypeScript subclassing. + if (!this.sockets[name]) { + // @ts-expect-error `sockets` is readonly in `@types/node` + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount--; + if (sockets.length === 0) { + // @ts-expect-error `sockets` is readonly in `@types/node` + delete this.sockets[name]; + } + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = this.isSecureEndpoint(options); + if (secureEndpoint) { + // @ts-expect-error `getName()` isn't defined in `@types/node` + return https_1.Agent.prototype.getName.call(this, options); + } + // @ts-expect-error `getName()` isn't defined in `@types/node` + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options), + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve() + .then(() => this.connect(req, connectOpts)) + .then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + try { + // @ts-expect-error `addRequest()` isn't defined in `@types/node` + return socket.addRequest(req, connectOpts); + } + catch (err) { + return cb(err); + } + } + this[INTERNAL].currentSocket = socket; + // @ts-expect-error `createSocket()` isn't defined in `@types/node` + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = undefined; + if (!socket) { + throw new Error('No socket was returned in the `connect()` function'); + } + return socket; + } + get defaultPort() { + return (this[INTERNAL].defaultPort ?? + (this.protocol === 'https:' ? 443 : 80)); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return (this[INTERNAL].protocol ?? + (this.isSecureEndpoint() ? 'https:' : 'http:')); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } +} +exports.Agent = Agent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/vanilla/node_modules/agent-base/dist/index.js.map b/vanilla/node_modules/agent-base/dist/index.js.map new file mode 100644 index 0000000..5a0d2ad --- /dev/null +++ b/vanilla/node_modules/agent-base/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAA2B;AAE3B,2CAA6B;AAC7B,iCAA4C;AAG5C,4CAA0B;AAe1B,MAAM,QAAQ,GAAG,MAAM,CAAC,wBAAwB,CAAC,CAAC;AAQlD,MAAsB,KAAM,SAAQ,IAAI,CAAC,KAAK;IAO7C,YAAY,IAAwB;QACnC,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC;IACrB,CAAC;IAOD;;OAEG;IACH,gBAAgB,CAAC,OAA0B;QAC1C,IAAI,OAAO,EAAE;YACZ,mEAAmE;YACnE,qEAAqE;YACrE,8DAA8D;YAC9D,IAAI,OAAQ,OAAe,CAAC,cAAc,KAAK,SAAS,EAAE;gBACzD,OAAO,OAAO,CAAC,cAAc,CAAC;aAC9B;YAED,oEAAoE;YACpE,mEAAmE;YACnE,qDAAqD;YACrD,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,EAAE;gBACzC,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CAAC;aACrC;SACD;QAED,gEAAgE;QAChE,iEAAiE;QACjE,6BAA6B;QAC7B,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,KAAK,EAAE,CAAC;QAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ;YAAE,OAAO,KAAK,CAAC;QAC5C,OAAO,KAAK;aACV,KAAK,CAAC,IAAI,CAAC;aACX,IAAI,CACJ,CAAC,CAAC,EAAE,EAAE,CACL,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;YAC9B,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAChC,CAAC;IACJ,CAAC;IAED,wEAAwE;IACxE,2EAA2E;IAC3E,yEAAyE;IACzE,6EAA6E;IAC7E,kEAAkE;IAClE,sBAAsB;IACd,gBAAgB,CAAC,IAAY;QACpC,2EAA2E;QAC3E,yEAAyE;QACzE,yBAAyB;QACzB,IAAI,IAAI,CAAC,UAAU,KAAK,QAAQ,IAAI,IAAI,CAAC,eAAe,KAAK,QAAQ,EAAE;YACtE,OAAO,IAAI,CAAC;SACZ;QACD,iEAAiE;QACjE,wEAAwE;QACxE,qCAAqC;QACrC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YACxB,0DAA0D;YAC1D,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;SACxB;QACD,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;QACtD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAkB,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACtD,qEAAqE;QACrE,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxB,OAAO,UAAU,CAAC;IACnB,CAAC;IAEO,gBAAgB,CAAC,IAAY,EAAE,MAAyB;QAC/D,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,MAAM,KAAK,IAAI,EAAE;YAC3C,OAAO;SACP;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAiB,CAAC;QACnD,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACtC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;YACjB,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;YACzB,sEAAsE;YACtE,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACxB,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;gBACzB,0DAA0D;gBAC1D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;aAC1B;SACD;IACF,CAAC;IAED,8EAA8E;IAC9E,oDAAoD;IACpD,OAAO,CAAC,OAA0B;QACjC,MAAM,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;QACtD,IAAI,cAAc,EAAE;YACnB,8DAA8D;YAC9D,OAAO,aAAU,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;SACxD;QACD,8DAA8D;QAC9D,OAAO,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;IAED,YAAY,CACX,GAAuB,EACvB,OAAyB,EACzB,EAA2C;QAE3C,MAAM,WAAW,GAAG;YACnB,GAAG,OAAO;YACV,cAAc,EAAE,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC;SAC9C,CAAC;QACF,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACvC,MAAM,UAAU,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;QAC/C,OAAO,CAAC,OAAO,EAAE;aACf,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;aAC1C,IAAI,CACJ,CAAC,MAAM,EAAE,EAAE;YACV,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YACxC,IAAI,MAAM,YAAY,IAAI,CAAC,KAAK,EAAE;gBACjC,IAAI;oBACH,iEAAiE;oBACjE,OAAO,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;iBAC3C;gBAAC,OAAO,GAAY,EAAE;oBACtB,OAAO,EAAE,CAAC,GAAY,CAAC,CAAC;iBACxB;aACD;YACD,IAAI,CAAC,QAAQ,CAAC,CAAC,aAAa,GAAG,MAAM,CAAC;YACtC,mEAAmE;YACnE,KAAK,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;QACtC,CAAC,EACD,CAAC,GAAG,EAAE,EAAE;YACP,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YACxC,EAAE,CAAC,GAAG,CAAC,CAAC;QACT,CAAC,CACD,CAAC;IACJ,CAAC;IAED,gBAAgB;QACf,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,aAAa,CAAC;QAC5C,IAAI,CAAC,QAAQ,CAAC,CAAC,aAAa,GAAG,SAAS,CAAC;QACzC,IAAI,CAAC,MAAM,EAAE;YACZ,MAAM,IAAI,KAAK,CACd,oDAAoD,CACpD,CAAC;SACF;QACD,OAAO,MAAM,CAAC;IACf,CAAC;IAED,IAAI,WAAW;QACd,OAAO,CACN,IAAI,CAAC,QAAQ,CAAC,CAAC,WAAW;YAC1B,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CACvC,CAAC;IACH,CAAC;IAED,IAAI,WAAW,CAAC,CAAS;QACxB,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE;YACnB,IAAI,CAAC,QAAQ,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC;SAC/B;IACF,CAAC;IAED,IAAI,QAAQ;QACX,OAAO,CACN,IAAI,CAAC,QAAQ,CAAC,CAAC,QAAQ;YACvB,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAC9C,CAAC;IACH,CAAC;IAED,IAAI,QAAQ,CAAC,CAAS;QACrB,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE;YACnB,IAAI,CAAC,QAAQ,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC;SAC5B;IACF,CAAC;CACD;AAlLD,sBAkLC"} \ No newline at end of file diff --git a/vanilla/node_modules/agent-base/package.json b/vanilla/node_modules/agent-base/package.json new file mode 100644 index 0000000..1b4964a --- /dev/null +++ b/vanilla/node_modules/agent-base/package.json @@ -0,0 +1,46 @@ +{ + "name": "agent-base", + "version": "7.1.4", + "description": "Turn a function into an `http.Agent` instance", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "https://github.com/TooTallNate/proxy-agents.git", + "directory": "packages/agent-base" + }, + "keywords": [ + "http", + "agent", + "base", + "barebones", + "https" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "devDependencies": { + "@types/debug": "^4.1.7", + "@types/jest": "^29.5.1", + "@types/node": "^14.18.45", + "@types/semver": "^7.3.13", + "@types/ws": "^6.0.4", + "async-listen": "^3.0.0", + "jest": "^29.5.0", + "ts-jest": "^29.1.0", + "typescript": "^5.0.4", + "ws": "^5.2.4", + "tsconfig": "0.0.0" + }, + "engines": { + "node": ">= 14" + }, + "scripts": { + "build": "tsc", + "test": "jest --env node --verbose --bail", + "lint": "eslint . --ext .ts", + "pack": "node ../../scripts/pack.mjs" + } +} \ No newline at end of file diff --git a/vanilla/node_modules/assertion-error/LICENSE b/vanilla/node_modules/assertion-error/LICENSE new file mode 100644 index 0000000..5e9f3ac --- /dev/null +++ b/vanilla/node_modules/assertion-error/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Jake Luer jake@qualiancy.com (http://qualiancy.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vanilla/node_modules/assertion-error/README.md b/vanilla/node_modules/assertion-error/README.md new file mode 100644 index 0000000..37c3928 --- /dev/null +++ b/vanilla/node_modules/assertion-error/README.md @@ -0,0 +1,68 @@ +

+ AssertionError and AssertionResult classes. +

+ +

+ + build:? + + downloads:? + + devDependencies:none + +

+ +## What is AssertionError? + +Assertion Error is a module that contains two classes: `AssertionError`, which +is an instance of an `Error`, and `AssertionResult` which is not an instance of +Error. + +These can be useful for returning from a function - if the function "succeeds" +return an `AssertionResult` and if the function fails return (or throw) an +`AssertionError`. + +Both `AssertionError` and `AssertionResult` implement the `Result` interface: + +```typescript +interface Result { + name: "AssertionError" | "AssertionResult"; + ok: boolean; + toJSON(...args: unknown[]): Record; +} +``` + +So if a function returns `AssertionResult | AssertionError` it is easy to check +_which_ one is returned by checking either `.name` or `.ok`, or check +`instanceof Error`. + +## Installation + +### Node.js + +`assertion-error` is available on [npm](http://npmjs.org). + +``` +$ npm install --save assertion-error +``` + +### Deno + +`assertion_error` is available on +[Deno.land](https://deno.land/x/assertion_error) + +```typescript +import { + AssertionError, + AssertionResult, +} from "https://deno.land/x/assertion_error@2.0.0/mod.ts"; +``` diff --git a/vanilla/node_modules/assertion-error/index.d.ts b/vanilla/node_modules/assertion-error/index.d.ts new file mode 100644 index 0000000..d8fda2c --- /dev/null +++ b/vanilla/node_modules/assertion-error/index.d.ts @@ -0,0 +1,27 @@ +interface Result { + name: "AssertionError" | "AssertionResult"; + ok: boolean; + toJSON(...args: unknown[]): Record; +} + +declare class AssertionError extends Error implements Result { + [key: string]: unknown + name: "AssertionError"; + ok: false; + message: string; + // deno-lint-ignore ban-types + constructor(message: string, props?: T, ssf?: Function); + stack: string; + toJSON(stack?: boolean): Record; +} + +declare class AssertionResult implements Result { + [key: string]: unknown + name: "AssertionResult"; + ok: true; + message: string; + constructor(props?: T); + toJSON(): Record; +} + +export { AssertionError, AssertionResult, Result }; diff --git a/vanilla/node_modules/assertion-error/index.js b/vanilla/node_modules/assertion-error/index.js new file mode 100644 index 0000000..2bfcb81 --- /dev/null +++ b/vanilla/node_modules/assertion-error/index.js @@ -0,0 +1,60 @@ +// deno-fmt-ignore-file +// deno-lint-ignore-file +// This code was bundled using `deno bundle` and it's not recommended to edit it manually + +const canElideFrames = "captureStackTrace" in Error; +class AssertionError extends Error { + message; + get name() { + return "AssertionError"; + } + get ok() { + return false; + } + constructor(message = "Unspecified AssertionError", props, ssf){ + super(message); + this.message = message; + if (canElideFrames) { + Error.captureStackTrace(this, ssf || AssertionError); + } + for(const key in props){ + if (!(key in this)) { + this[key] = props[key]; + } + } + } + toJSON(stack) { + return { + ...this, + name: this.name, + message: this.message, + ok: false, + stack: stack !== false ? this.stack : undefined + }; + } +} +class AssertionResult { + get name() { + return "AssertionResult"; + } + get ok() { + return true; + } + constructor(props){ + for(const key in props){ + if (!(key in this)) { + this[key] = props[key]; + } + } + } + toJSON() { + return { + ...this, + name: this.name, + ok: this.ok + }; + } +} +export { AssertionError as AssertionError }; +export { AssertionResult as AssertionResult }; + diff --git a/vanilla/node_modules/assertion-error/package.json b/vanilla/node_modules/assertion-error/package.json new file mode 100644 index 0000000..02dc0f5 --- /dev/null +++ b/vanilla/node_modules/assertion-error/package.json @@ -0,0 +1,32 @@ +{ + "name": "assertion-error", + "version": "2.0.1", + "description": "Error constructor for test and validation frameworks that implements standardized AssertionError specification.", + "author": "Jake Luer (http://qualiancy.com)", + "license": "MIT", + "types": "./index.d.ts", + "keywords": [ + "test", + "assertion", + "assertion-error" + ], + "repository": { + "type": "git", + "url": "git@github.com:chaijs/assertion-error.git" + }, + "engines": { + "node": ">=12" + }, + "files": [ + "index.d.ts" + ], + "type": "module", + "module": "index.js", + "main": "index.js", + "scripts": { + "build": "deno bundle mod.ts > index.js", + "pretest": "rm -rf coverage/", + "test": "deno test --coverage=coverage", + "posttest": "deno coverage coverage --lcov > coverage/lcov.info && lcov --summary coverage/lcov.info" + } +} diff --git a/vanilla/node_modules/ast-v8-to-istanbul/LICENSE b/vanilla/node_modules/ast-v8-to-istanbul/LICENSE new file mode 100644 index 0000000..073bd2a --- /dev/null +++ b/vanilla/node_modules/ast-v8-to-istanbul/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Ari Perkkiö + +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/vanilla/node_modules/ast-v8-to-istanbul/README.md b/vanilla/node_modules/ast-v8-to-istanbul/README.md new file mode 100644 index 0000000..e4aa256 --- /dev/null +++ b/vanilla/node_modules/ast-v8-to-istanbul/README.md @@ -0,0 +1,278 @@ +# `ast-v8-to-istanbul` + +[![Version][version-badge]][npm-url] +[![Downloads][downloads-url]][npm-url] + +> - Speed of V8 coverage 🏎 +> - Accuracy of Istanbul coverage 🔍 + +[Ignoring code](#ignoring-code) | [Source maps](#source-maps) | [Istanbul Compatibility](#istanbul-compatibility) | [Limitations](#limitations) + +--- + +AST-aware [`v8-to-istanbul`](https://www.npmjs.com/package/v8-to-istanbul). + +Unopinionated - _bring-your-own_ AST parser and source maps. + +Passes all 195 tests[*](#istanbul-compatibility) of [`istanbul-lib-instrument`](https://github.com/istanbuljs/istanbuljs/tree/main/packages/istanbul-lib-instrument/test/specs). ✅ + +Test cases run against: +- `vite/parseAst` ✅ +- `acorn` ✅ +- `oxc-parser` ✅ +- `@babel/parser` ✅ + +See example report at https://ariperkkio.github.io/ast-v8-to-istanbul. + +```ts +import { convert } from "ast-v8-to-istanbul"; +import { parseAstAsync } from "vite"; +import type { CoverageMapData } from "istanbul-lib-coverage"; + +const data: CoverageMapData = await convert({ + // Bring-your-own AST parser + ast: parseAstAsync(), + + // Code of the executed file (not the source file) + code: "function sum(a, b) {\n return a + b ...", + + // Execution wrapper offset + wrapperLength: 0, + + // Script coverage of the executed file + coverage: { + scriptId: "123", + url: "file:///absolute/path/to/dist/index.js", + functions: [ + { + functionName: "sum", + ranges: [{ startOffset: 223, endOffset: 261, count: 0 }], + isBlockCoverage: false, + }, + // ... etc + ], + }, + + // Source map of the executed file + sourceMap: { + version: 3, + sources: ["../sources.ts"], + sourcesContent: ["export function sum(a: number, b: number) {\n..."], + mappings: ";AAAO,SAAS,...", + names: [], + }, +}); +``` + +## Ignoring code + +### Ignoring source code + +#### Ignore hints + +See live example at https://ariperkkio.github.io/ast-v8-to-istanbul/ignore-examples.html. + +The typical ignore hints from `nyc` are supported: https://github.com/istanbuljs/nyc?tab=readme-ov-file#parsing-hints-ignoring-lines: + +> * `/* istanbul ignore if */`: ignore the next if statement. +> * `/* istanbul ignore else */`: ignore the else portion of an if statement. +> * `/* istanbul ignore next */`: ignore the next _thing_ in the source-code (functions, if statements, classes, you name it). +> * `/* istanbul ignore file */`: ignore an entire source-file (this should be placed at the top of the file). + +In addition to `istanbul` keyword, you can use `v8`, `c8` and `node:coverage`: + +- `/* istanbul ignore if */` +- `/* v8 ignore else */` +- `/* c8 ignore file */` +- `/* node:coverage ignore next */` + +Also `start` and `stop` ignore hints from original [`v8-to-istanbul`](https://www.npmjs.com/package/v8-to-istanbul) are supported. +These ignore hints are checked from the original sources instead of transpiled code. + +> * `/* v8 ignore start */`: start ignoring lines +> * `/* v8 ignore stop */`: stop ignoring lines +> * ``: start ignoring lines +> * ``: stop ignoring lines +> * `anything /* v8 ignore start */ anything`: start ignoring lines +> * `anything /* v8 ignore stop */ anything`: stop ignoring lines + +#### Class methods + +The `ignore-class-method` from `nyc` is also supported: https://github.com/istanbuljs/nyc?tab=readme-ov-file#ignoring-methods + +> You can ignore every instance of a method simply by adding its name to the `ignore-class-method` array in your `nyc` config. + +```ts +import { convert } from "ast-v8-to-istanbul"; + +await convert({ + ignoreClassMethods: ['render'] +}); +``` + +#### Ignore after remapping + +You can ignore source code after coverage results have been remapped back to original sources using `ignoreSourceCode`. +This is a high level API that can be exposed to end-users by tooling developers. + +It's mostly intended for excluding code that is incorrectly shown in coverage report when compilers add generated code in the source maps. + +Note that as the exclusion happens after remapping, this option is slower than [`ignoreNode`](#ignoring-generated-code) option. + +```ts +function ignoreSourceCode( + code: string, + type: "function" | "statement" | "branch", + location: Record<"start" | "end", { line: number; column: number }>, +): boolean | void; +``` + +```ts +import { convert } from "ast-v8-to-istanbul"; + +await convert({ + ignoreSourceCode: (code, type, location) => { + // Ignore all "noop()" calls + if(type === "function" && code.includes("noop(")) { + return true; + } + + // In Vue " +``` + +## Usage + +Import the library in your code, and then pick one of the styles you'd like to use - either `assert`, `expect` or `should`: + +```js +import { assert } from 'chai'; // Using Assert style +import { expect } from 'chai'; // Using Expect style +import { should } from 'chai'; // Using Should style +``` + +### Register the chai testing style globally + +```js +import 'chai/register-assert'; // Using Assert style +import 'chai/register-expect'; // Using Expect style +import 'chai/register-should'; // Using Should style +``` + +### Import assertion styles as local variables + +```js +import { assert } from 'chai'; // Using Assert style +import { expect } from 'chai'; // Using Expect style +import { should } from 'chai'; // Using Should style +should(); // Modifies `Object.prototype` + +import { expect, use } from 'chai'; // Creates local variables `expect` and `use`; useful for plugin use +``` + +### Usage with Mocha + +```bash +mocha spec.js --require chai/register-assert.js # Using Assert style +mocha spec.js --require chai/register-expect.js # Using Expect style +mocha spec.js --require chai/register-should.js # Using Should style +``` + +[Read more about these styles in our docs](http://chaijs.com/guide/styles/). + +## Plugins + +Chai offers a robust Plugin architecture for extending Chai's assertions and interfaces. + +- Need a plugin? View the [official plugin list](http://chaijs.com/plugins). +- Want to build a plugin? Read the [plugin api documentation](http://chaijs.com/guide/plugins/). +- Have a plugin and want it listed? Simply add the following keywords to your package.json: + - `chai-plugin` + - `browser` if your plugin works in the browser as well as Node.js + - `browser-only` if your plugin does not work with Node.js + +### Related Projects + +- [chaijs / chai-docs](https://github.com/chaijs/chai-docs): The chaijs.com website source code. +- [chaijs / assertion-error](https://github.com/chaijs/assertion-error): Custom `Error` constructor thrown upon an assertion failing. +- [chaijs / deep-eql](https://github.com/chaijs/deep-eql): Improved deep equality testing for Node.js and the browser. +- [chaijs / check-error](https://github.com/chaijs/check-error): Error comparison and information related utility for Node.js and the browser. +- [chaijs / loupe](https://github.com/chaijs/loupe): Inspect utility for Node.js and browsers. +- [chaijs / pathval](https://github.com/chaijs/pathval): Object value retrieval given a string path. + +### Contributing + +Thank you very much for considering to contribute! + +Please make sure you follow our [Code Of Conduct](https://github.com/chaijs/chai/blob/master/CODE_OF_CONDUCT.md) and we also strongly recommend reading our [Contributing Guide](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md). + +Here are a few issues other contributors frequently ran into when opening pull requests: + +- Please do not commit changes to the `chai.js` build. We do it once per release. +- Before pushing your commits, please make sure you [rebase](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md#pull-requests) them. + +### Contributors + +Please see the full +[Contributors Graph](https://github.com/chaijs/chai/graphs/contributors) for our +list of contributors. + +### Core Contributors + +Feel free to reach out to any of the core contributors with your questions or +concerns. We will do our best to respond in a timely manner. + +[![Keith Cirkel](https://avatars3.githubusercontent.com/u/118266?v=3&s=50)](https://github.com/keithamus) +[![James Garbutt](https://avatars3.githubusercontent.com/u/5677153?v=3&s=50)](https://github.com/43081j) +[![Kristján Oddsson](https://avatars3.githubusercontent.com/u/318208?v=3&s=50)](https://github.com/koddsson) + +### Core Contributor Alumni + +This project would not be what it is without the contributions from our prior +core contributors, for whom we are forever grateful: + +[![Jake Luer](https://avatars3.githubusercontent.com/u/58988?v=3&s=50)](https://github.com/logicalparadox) +[![Veselin Todorov](https://avatars3.githubusercontent.com/u/330048?v=3&s=50)](https://github.com/vesln) +[![Lucas Fernandes da Costa](https://avatars3.githubusercontent.com/u/6868147?v=3&s=50)](https://github.com/lucasfcosta) +[![Grant Snodgrass](https://avatars3.githubusercontent.com/u/17260989?v=3&s=50)](https://github.com/meeber) diff --git a/vanilla/node_modules/chai/index.js b/vanilla/node_modules/chai/index.js new file mode 100644 index 0000000..601eb53 --- /dev/null +++ b/vanilla/node_modules/chai/index.js @@ -0,0 +1,4172 @@ +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + +// lib/chai/utils/index.js +var utils_exports = {}; +__export(utils_exports, { + addChainableMethod: () => addChainableMethod, + addLengthGuard: () => addLengthGuard, + addMethod: () => addMethod, + addProperty: () => addProperty, + checkError: () => check_error_exports, + compareByInspect: () => compareByInspect, + eql: () => deep_eql_default, + events: () => events, + expectTypes: () => expectTypes, + flag: () => flag, + getActual: () => getActual, + getMessage: () => getMessage2, + getName: () => getName, + getOperator: () => getOperator, + getOwnEnumerableProperties: () => getOwnEnumerableProperties, + getOwnEnumerablePropertySymbols: () => getOwnEnumerablePropertySymbols, + getPathInfo: () => getPathInfo, + hasProperty: () => hasProperty, + inspect: () => inspect2, + isNaN: () => isNaN2, + isNumeric: () => isNumeric, + isProxyEnabled: () => isProxyEnabled, + isRegExp: () => isRegExp2, + objDisplay: () => objDisplay, + overwriteChainableMethod: () => overwriteChainableMethod, + overwriteMethod: () => overwriteMethod, + overwriteProperty: () => overwriteProperty, + proxify: () => proxify, + test: () => test, + transferFlags: () => transferFlags, + type: () => type +}); + +// node_modules/check-error/index.js +var check_error_exports = {}; +__export(check_error_exports, { + compatibleConstructor: () => compatibleConstructor, + compatibleInstance: () => compatibleInstance, + compatibleMessage: () => compatibleMessage, + getConstructorName: () => getConstructorName, + getMessage: () => getMessage +}); +function isErrorInstance(obj) { + return obj instanceof Error || Object.prototype.toString.call(obj) === "[object Error]"; +} +__name(isErrorInstance, "isErrorInstance"); +function isRegExp(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; +} +__name(isRegExp, "isRegExp"); +function compatibleInstance(thrown, errorLike) { + return isErrorInstance(errorLike) && thrown === errorLike; +} +__name(compatibleInstance, "compatibleInstance"); +function compatibleConstructor(thrown, errorLike) { + if (isErrorInstance(errorLike)) { + return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; + } else if ((typeof errorLike === "object" || typeof errorLike === "function") && errorLike.prototype) { + return thrown.constructor === errorLike || thrown instanceof errorLike; + } + return false; +} +__name(compatibleConstructor, "compatibleConstructor"); +function compatibleMessage(thrown, errMatcher) { + const comparisonString = typeof thrown === "string" ? thrown : thrown.message; + if (isRegExp(errMatcher)) { + return errMatcher.test(comparisonString); + } else if (typeof errMatcher === "string") { + return comparisonString.indexOf(errMatcher) !== -1; + } + return false; +} +__name(compatibleMessage, "compatibleMessage"); +function getConstructorName(errorLike) { + let constructorName = errorLike; + if (isErrorInstance(errorLike)) { + constructorName = errorLike.constructor.name; + } else if (typeof errorLike === "function") { + constructorName = errorLike.name; + if (constructorName === "") { + const newConstructorName = new errorLike().name; + constructorName = newConstructorName || constructorName; + } + } + return constructorName; +} +__name(getConstructorName, "getConstructorName"); +function getMessage(errorLike) { + let msg = ""; + if (errorLike && errorLike.message) { + msg = errorLike.message; + } else if (typeof errorLike === "string") { + msg = errorLike; + } + return msg; +} +__name(getMessage, "getMessage"); + +// lib/chai/utils/flag.js +function flag(obj, key, value) { + let flags = obj.__flags || (obj.__flags = /* @__PURE__ */ Object.create(null)); + if (arguments.length === 3) { + flags[key] = value; + } else { + return flags[key]; + } +} +__name(flag, "flag"); + +// lib/chai/utils/test.js +function test(obj, args) { + let negate = flag(obj, "negate"), expr = args[0]; + return negate ? !expr : expr; +} +__name(test, "test"); + +// lib/chai/utils/type-detect.js +function type(obj) { + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + const stringTag = obj[Symbol.toStringTag]; + if (typeof stringTag === "string") { + return stringTag; + } + const type3 = Object.prototype.toString.call(obj).slice(8, -1); + return type3; +} +__name(type, "type"); + +// node_modules/assertion-error/index.js +var canElideFrames = "captureStackTrace" in Error; +var _AssertionError = class _AssertionError extends Error { + constructor(message = "Unspecified AssertionError", props, ssf) { + super(message); + __publicField(this, "message"); + this.message = message; + if (canElideFrames) { + Error.captureStackTrace(this, ssf || _AssertionError); + } + for (const key in props) { + if (!(key in this)) { + this[key] = props[key]; + } + } + } + get name() { + return "AssertionError"; + } + get ok() { + return false; + } + toJSON(stack) { + return { + ...this, + name: this.name, + message: this.message, + ok: false, + stack: stack !== false ? this.stack : void 0 + }; + } +}; +__name(_AssertionError, "AssertionError"); +var AssertionError = _AssertionError; + +// lib/chai/utils/expectTypes.js +function expectTypes(obj, types) { + let flagMsg = flag(obj, "message"); + let ssfi = flag(obj, "ssfi"); + flagMsg = flagMsg ? flagMsg + ": " : ""; + obj = flag(obj, "object"); + types = types.map(function(t) { + return t.toLowerCase(); + }); + types.sort(); + let str = types.map(function(t, index) { + let art = ~["a", "e", "i", "o", "u"].indexOf(t.charAt(0)) ? "an" : "a"; + let or = types.length > 1 && index === types.length - 1 ? "or " : ""; + return or + art + " " + t; + }).join(", "); + let objType = type(obj).toLowerCase(); + if (!types.some(function(expected) { + return objType === expected; + })) { + throw new AssertionError( + flagMsg + "object tested must be " + str + ", but " + objType + " given", + void 0, + ssfi + ); + } +} +__name(expectTypes, "expectTypes"); + +// lib/chai/utils/getActual.js +function getActual(obj, args) { + return args.length > 4 ? args[4] : obj._obj; +} +__name(getActual, "getActual"); + +// node_modules/loupe/lib/helpers.js +var ansiColors = { + bold: ["1", "22"], + dim: ["2", "22"], + italic: ["3", "23"], + underline: ["4", "24"], + // 5 & 6 are blinking + inverse: ["7", "27"], + hidden: ["8", "28"], + strike: ["9", "29"], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ["30", "39"], + red: ["31", "39"], + green: ["32", "39"], + yellow: ["33", "39"], + blue: ["34", "39"], + magenta: ["35", "39"], + cyan: ["36", "39"], + white: ["37", "39"], + brightblack: ["30;1", "39"], + brightred: ["31;1", "39"], + brightgreen: ["32;1", "39"], + brightyellow: ["33;1", "39"], + brightblue: ["34;1", "39"], + brightmagenta: ["35;1", "39"], + brightcyan: ["36;1", "39"], + brightwhite: ["37;1", "39"], + grey: ["90", "39"] +}; +var styles = { + special: "cyan", + number: "yellow", + bigint: "yellow", + boolean: "yellow", + undefined: "grey", + null: "bold", + string: "green", + symbol: "green", + date: "magenta", + regexp: "red" +}; +var truncator = "\u2026"; +function colorise(value, styleType) { + const color = ansiColors[styles[styleType]] || ansiColors[styleType] || ""; + if (!color) { + return String(value); + } + return `\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m`; +} +__name(colorise, "colorise"); +function normaliseOptions({ + showHidden = false, + depth = 2, + colors = false, + customInspect = true, + showProxy = false, + maxArrayLength = Infinity, + breakLength = Infinity, + seen = [], + // eslint-disable-next-line no-shadow + truncate: truncate2 = Infinity, + stylize = String +} = {}, inspect3) { + const options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate2), + seen, + inspect: inspect3, + stylize + }; + if (options.colors) { + options.stylize = colorise; + } + return options; +} +__name(normaliseOptions, "normaliseOptions"); +function isHighSurrogate(char) { + return char >= "\uD800" && char <= "\uDBFF"; +} +__name(isHighSurrogate, "isHighSurrogate"); +function truncate(string, length, tail = truncator) { + string = String(string); + const tailLength = tail.length; + const stringLength = string.length; + if (tailLength > length && stringLength > tailLength) { + return tail; + } + if (stringLength > length && stringLength > tailLength) { + let end = length - tailLength; + if (end > 0 && isHighSurrogate(string[end - 1])) { + end = end - 1; + } + return `${string.slice(0, end)}${tail}`; + } + return string; +} +__name(truncate, "truncate"); +function inspectList(list, options, inspectItem, separator = ", ") { + inspectItem = inspectItem || options.inspect; + const size = list.length; + if (size === 0) + return ""; + const originalLength = options.truncate; + let output = ""; + let peek = ""; + let truncated = ""; + for (let i = 0; i < size; i += 1) { + const last = i + 1 === list.length; + const secondToLast = i + 2 === list.length; + truncated = `${truncator}(${list.length - i})`; + const value = list[i]; + options.truncate = originalLength - output.length - (last ? 0 : separator.length); + const string = peek || inspectItem(value, options) + (last ? "" : separator); + const nextLength = output.length + string.length; + const truncatedLength = nextLength + truncated.length; + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break; + } + if (!last && !secondToLast && truncatedLength > originalLength) { + break; + } + peek = last ? "" : inspectItem(list[i + 1], options) + (secondToLast ? "" : separator); + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break; + } + output += string; + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = `${truncator}(${list.length - i - 1})`; + break; + } + truncated = ""; + } + return `${output}${truncated}`; +} +__name(inspectList, "inspectList"); +function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key; + } + return JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); +} +__name(quoteComplexKey, "quoteComplexKey"); +function inspectProperty([key, value], options) { + options.truncate -= 2; + if (typeof key === "string") { + key = quoteComplexKey(key); + } else if (typeof key !== "number") { + key = `[${options.inspect(key, options)}]`; + } + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key}: ${value}`; +} +__name(inspectProperty, "inspectProperty"); + +// node_modules/loupe/lib/array.js +function inspectArray(array, options) { + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return "[]"; + options.truncate -= 4; + const listContents = inspectList(array, options); + options.truncate -= listContents.length; + let propertyContents = ""; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty); + } + return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ""} ]`; +} +__name(inspectArray, "inspectArray"); + +// node_modules/loupe/lib/typedarray.js +var getArrayName = /* @__PURE__ */ __name((array) => { + if (typeof Buffer === "function" && array instanceof Buffer) { + return "Buffer"; + } + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag]; + } + return array.constructor.name; +}, "getArrayName"); +function inspectTypedArray(array, options) { + const name = getArrayName(array); + options.truncate -= name.length + 4; + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return `${name}[]`; + let output = ""; + for (let i = 0; i < array.length; i++) { + const string = `${options.stylize(truncate(array[i], options.truncate), "number")}${i === array.length - 1 ? "" : ", "}`; + options.truncate -= string.length; + if (array[i] !== array.length && options.truncate <= 3) { + output += `${truncator}(${array.length - array[i] + 1})`; + break; + } + output += string; + } + let propertyContents = ""; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty); + } + return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`; +} +__name(inspectTypedArray, "inspectTypedArray"); + +// node_modules/loupe/lib/date.js +function inspectDate(dateObject, options) { + const stringRepresentation = dateObject.toJSON(); + if (stringRepresentation === null) { + return "Invalid Date"; + } + const split = stringRepresentation.split("T"); + const date = split[0]; + return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, "date"); +} +__name(inspectDate, "inspectDate"); + +// node_modules/loupe/lib/function.js +function inspectFunction(func, options) { + const functionType = func[Symbol.toStringTag] || "Function"; + const name = func.name; + if (!name) { + return options.stylize(`[${functionType}]`, "special"); + } + return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, "special"); +} +__name(inspectFunction, "inspectFunction"); + +// node_modules/loupe/lib/map.js +function inspectMapEntry([key, value], options) { + options.truncate -= 4; + key = options.inspect(key, options); + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key} => ${value}`; +} +__name(inspectMapEntry, "inspectMapEntry"); +function mapToEntries(map) { + const entries = []; + map.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +} +__name(mapToEntries, "mapToEntries"); +function inspectMap(map, options) { + if (map.size === 0) + return "Map{}"; + options.truncate -= 7; + return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`; +} +__name(inspectMap, "inspectMap"); + +// node_modules/loupe/lib/number.js +var isNaN = Number.isNaN || ((i) => i !== i); +function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize("NaN", "number"); + } + if (number === Infinity) { + return options.stylize("Infinity", "number"); + } + if (number === -Infinity) { + return options.stylize("-Infinity", "number"); + } + if (number === 0) { + return options.stylize(1 / number === Infinity ? "+0" : "-0", "number"); + } + return options.stylize(truncate(String(number), options.truncate), "number"); +} +__name(inspectNumber, "inspectNumber"); + +// node_modules/loupe/lib/bigint.js +function inspectBigInt(number, options) { + let nums = truncate(number.toString(), options.truncate - 1); + if (nums !== truncator) + nums += "n"; + return options.stylize(nums, "bigint"); +} +__name(inspectBigInt, "inspectBigInt"); + +// node_modules/loupe/lib/regexp.js +function inspectRegExp(value, options) { + const flags = value.toString().split("/")[2]; + const sourceLength = options.truncate - (2 + flags.length); + const source = value.source; + return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, "regexp"); +} +__name(inspectRegExp, "inspectRegExp"); + +// node_modules/loupe/lib/set.js +function arrayFromSet(set2) { + const values = []; + set2.forEach((value) => { + values.push(value); + }); + return values; +} +__name(arrayFromSet, "arrayFromSet"); +function inspectSet(set2, options) { + if (set2.size === 0) + return "Set{}"; + options.truncate -= 7; + return `Set{ ${inspectList(arrayFromSet(set2), options)} }`; +} +__name(inspectSet, "inspectSet"); + +// node_modules/loupe/lib/string.js +var stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", "g"); +var escapeCharacters = { + "\b": "\\b", + " ": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + "'": "\\'", + "\\": "\\\\" +}; +var hex = 16; +var unicodeLength = 4; +function escape(char) { + return escapeCharacters[char] || `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-unicodeLength)}`; +} +__name(escape, "escape"); +function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape); + } + return options.stylize(`'${truncate(string, options.truncate - 2)}'`, "string"); +} +__name(inspectString, "inspectString"); + +// node_modules/loupe/lib/symbol.js +function inspectSymbol(value) { + if ("description" in Symbol.prototype) { + return value.description ? `Symbol(${value.description})` : "Symbol()"; + } + return value.toString(); +} +__name(inspectSymbol, "inspectSymbol"); + +// node_modules/loupe/lib/promise.js +var getPromiseValue = /* @__PURE__ */ __name(() => "Promise{\u2026}", "getPromiseValue"); +var promise_default = getPromiseValue; + +// node_modules/loupe/lib/object.js +function inspectObject(object, options) { + const properties = Object.getOwnPropertyNames(object); + const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; + if (properties.length === 0 && symbols.length === 0) { + return "{}"; + } + options.truncate -= 4; + options.seen = options.seen || []; + if (options.seen.includes(object)) { + return "[Circular]"; + } + options.seen.push(object); + const propertyContents = inspectList(properties.map((key) => [key, object[key]]), options, inspectProperty); + const symbolContents = inspectList(symbols.map((key) => [key, object[key]]), options, inspectProperty); + options.seen.pop(); + let sep = ""; + if (propertyContents && symbolContents) { + sep = ", "; + } + return `{ ${propertyContents}${sep}${symbolContents} }`; +} +__name(inspectObject, "inspectObject"); + +// node_modules/loupe/lib/class.js +var toStringTag = typeof Symbol !== "undefined" && Symbol.toStringTag ? Symbol.toStringTag : false; +function inspectClass(value, options) { + let name = ""; + if (toStringTag && toStringTag in value) { + name = value[toStringTag]; + } + name = name || value.constructor.name; + if (!name || name === "_class") { + name = ""; + } + options.truncate -= name.length; + return `${name}${inspectObject(value, options)}`; +} +__name(inspectClass, "inspectClass"); + +// node_modules/loupe/lib/arguments.js +function inspectArguments(args, options) { + if (args.length === 0) + return "Arguments[]"; + options.truncate -= 13; + return `Arguments[ ${inspectList(args, options)} ]`; +} +__name(inspectArguments, "inspectArguments"); + +// node_modules/loupe/lib/error.js +var errorKeys = [ + "stack", + "line", + "column", + "name", + "message", + "fileName", + "lineNumber", + "columnNumber", + "number", + "description", + "cause" +]; +function inspectObject2(error, options) { + const properties = Object.getOwnPropertyNames(error).filter((key) => errorKeys.indexOf(key) === -1); + const name = error.name; + options.truncate -= name.length; + let message = ""; + if (typeof error.message === "string") { + message = truncate(error.message, options.truncate); + } else { + properties.unshift("message"); + } + message = message ? `: ${message}` : ""; + options.truncate -= message.length + 5; + options.seen = options.seen || []; + if (options.seen.includes(error)) { + return "[Circular]"; + } + options.seen.push(error); + const propertyContents = inspectList(properties.map((key) => [key, error[key]]), options, inspectProperty); + return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`; +} +__name(inspectObject2, "inspectObject"); + +// node_modules/loupe/lib/html.js +function inspectAttribute([key, value], options) { + options.truncate -= 3; + if (!value) { + return `${options.stylize(String(key), "yellow")}`; + } + return `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}`; +} +__name(inspectAttribute, "inspectAttribute"); +function inspectNodeCollection(collection, options) { + return inspectList(collection, options, inspectNode, "\n"); +} +__name(inspectNodeCollection, "inspectNodeCollection"); +function inspectNode(node, options) { + switch (node.nodeType) { + case 1: + return inspectHTML(node, options); + case 3: + return options.inspect(node.data, options); + default: + return options.inspect(node, options); + } +} +__name(inspectNode, "inspectNode"); +function inspectHTML(element, options) { + const properties = element.getAttributeNames(); + const name = element.tagName.toLowerCase(); + const head = options.stylize(`<${name}`, "special"); + const headClose = options.stylize(`>`, "special"); + const tail = options.stylize(``, "special"); + options.truncate -= name.length * 2 + 5; + let propertyContents = ""; + if (properties.length > 0) { + propertyContents += " "; + propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, " "); + } + options.truncate -= propertyContents.length; + const truncate2 = options.truncate; + let children = inspectNodeCollection(element.children, options); + if (children && children.length > truncate2) { + children = `${truncator}(${element.children.length})`; + } + return `${head}${propertyContents}${headClose}${children}${tail}`; +} +__name(inspectHTML, "inspectHTML"); + +// node_modules/loupe/lib/index.js +var symbolsSupported = typeof Symbol === "function" && typeof Symbol.for === "function"; +var chaiInspect = symbolsSupported ? /* @__PURE__ */ Symbol.for("chai/inspect") : "@@chai/inspect"; +var nodeInspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"); +var constructorMap = /* @__PURE__ */ new WeakMap(); +var stringTagMap = {}; +var baseTypesMap = { + undefined: /* @__PURE__ */ __name((value, options) => options.stylize("undefined", "undefined"), "undefined"), + null: /* @__PURE__ */ __name((value, options) => options.stylize("null", "null"), "null"), + boolean: /* @__PURE__ */ __name((value, options) => options.stylize(String(value), "boolean"), "boolean"), + Boolean: /* @__PURE__ */ __name((value, options) => options.stylize(String(value), "boolean"), "Boolean"), + number: inspectNumber, + Number: inspectNumber, + bigint: inspectBigInt, + BigInt: inspectBigInt, + string: inspectString, + String: inspectString, + function: inspectFunction, + Function: inspectFunction, + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: promise_default, + // WeakSet, WeakMap are totally opaque to us + WeakSet: /* @__PURE__ */ __name((value, options) => options.stylize("WeakSet{\u2026}", "special"), "WeakSet"), + WeakMap: /* @__PURE__ */ __name((value, options) => options.stylize("WeakMap{\u2026}", "special"), "WeakMap"), + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + Generator: /* @__PURE__ */ __name(() => "", "Generator"), + DataView: /* @__PURE__ */ __name(() => "", "DataView"), + ArrayBuffer: /* @__PURE__ */ __name(() => "", "ArrayBuffer"), + Error: inspectObject2, + HTMLCollection: inspectNodeCollection, + NodeList: inspectNodeCollection +}; +var inspectCustom = /* @__PURE__ */ __name((value, options, type3, inspectFn) => { + if (chaiInspect in value && typeof value[chaiInspect] === "function") { + return value[chaiInspect](options); + } + if (nodeInspect in value && typeof value[nodeInspect] === "function") { + return value[nodeInspect](options.depth, options, inspectFn); + } + if ("inspect" in value && typeof value.inspect === "function") { + return value.inspect(options.depth, options); + } + if ("constructor" in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options); + } + if (stringTagMap[type3]) { + return stringTagMap[type3](value, options); + } + return ""; +}, "inspectCustom"); +var toString = Object.prototype.toString; +function inspect(value, opts = {}) { + const options = normaliseOptions(opts, inspect); + const { customInspect } = options; + let type3 = value === null ? "null" : typeof value; + if (type3 === "object") { + type3 = toString.call(value).slice(8, -1); + } + if (type3 in baseTypesMap) { + return baseTypesMap[type3](value, options); + } + if (customInspect && value) { + const output = inspectCustom(value, options, type3, inspect); + if (output) { + if (typeof output === "string") + return output; + return inspect(output, options); + } + } + const proto = value ? Object.getPrototypeOf(value) : false; + if (proto === Object.prototype || proto === null) { + return inspectObject(value, options); + } + if (value && typeof HTMLElement === "function" && value instanceof HTMLElement) { + return inspectHTML(value, options); + } + if ("constructor" in value) { + if (value.constructor !== Object) { + return inspectClass(value, options); + } + return inspectObject(value, options); + } + if (value === Object(value)) { + return inspectObject(value, options); + } + return options.stylize(String(value), type3); +} +__name(inspect, "inspect"); + +// lib/chai/config.js +var config = { + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {boolean} + * @public + */ + includeStack: false, + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {boolean} + * @public + */ + showDiff: true, + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, for + * example for large data structures, the value is replaced with something + * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. + * + * Set it to zero if you want to disable truncating altogether. + * + * This is especially userful when doing assertions on arrays: having this + * set to a reasonable large value makes the failure messages readily + * inspectable. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {number} + * @public + */ + truncateThreshold: 40, + /** + * ### config.useProxy + * + * User configurable property, defines if chai will use a Proxy to throw + * an error when a non-existent property is read, which protects users + * from typos when using property-based assertions. + * + * Set it to false if you want to disable this feature. + * + * chai.config.useProxy = false; // disable use of Proxy + * + * This feature is automatically disabled regardless of this config value + * in environments that don't support proxies. + * + * @param {boolean} + * @public + */ + useProxy: true, + /** + * ### config.proxyExcludedKeys + * + * User configurable property, defines which properties should be ignored + * instead of throwing an error if they do not exist on the assertion. + * This is only applied if the environment Chai is running in supports proxies and + * if the `useProxy` configuration setting is enabled. + * By default, `then` and `inspect` will not throw an error if they do not exist on the + * assertion object because the `.inspect` property is read by `util.inspect` (for example, when + * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. + * + * // By default these keys will not throw an error if they do not exist on the assertion object + * chai.config.proxyExcludedKeys = ['then', 'inspect']; + * + * @param {Array} + * @public + */ + proxyExcludedKeys: ["then", "catch", "inspect", "toJSON"], + /** + * ### config.deepEqual + * + * User configurable property, defines which a custom function to use for deepEqual + * comparisons. + * By default, the function used is the one from the `deep-eql` package without custom comparator. + * + * // use a custom comparator + * chai.config.deepEqual = (expected, actual) => { + * return chai.util.eql(expected, actual, { + * comparator: (expected, actual) => { + * // for non number comparison, use the default behavior + * if(typeof expected !== 'number') return null; + * // allow a difference of 10 between compared numbers + * return typeof actual === 'number' && Math.abs(actual - expected) < 10 + * } + * }) + * }; + * + * @param {Function} + * @public + */ + deepEqual: null +}; + +// lib/chai/utils/inspect.js +function inspect2(obj, showHidden, depth, colors) { + let options = { + colors, + depth: typeof depth === "undefined" ? 2 : depth, + showHidden, + truncate: config.truncateThreshold ? config.truncateThreshold : Infinity + }; + return inspect(obj, options); +} +__name(inspect2, "inspect"); + +// lib/chai/utils/objDisplay.js +function objDisplay(obj) { + let str = inspect2(obj), type3 = Object.prototype.toString.call(obj); + if (config.truncateThreshold && str.length >= config.truncateThreshold) { + if (type3 === "[object Function]") { + return !obj.name || obj.name === "" ? "[Function]" : "[Function: " + obj.name + "]"; + } else if (type3 === "[object Array]") { + return "[ Array(" + obj.length + ") ]"; + } else if (type3 === "[object Object]") { + let keys = Object.keys(obj), kstr = keys.length > 2 ? keys.splice(0, 2).join(", ") + ", ..." : keys.join(", "); + return "{ Object (" + kstr + ") }"; + } else { + return str; + } + } else { + return str; + } +} +__name(objDisplay, "objDisplay"); + +// lib/chai/utils/getMessage.js +function getMessage2(obj, args) { + let negate = flag(obj, "negate"); + let val = flag(obj, "object"); + let expected = args[3]; + let actual = getActual(obj, args); + let msg = negate ? args[2] : args[1]; + let flagMsg = flag(obj, "message"); + if (typeof msg === "function") msg = msg(); + msg = msg || ""; + msg = msg.replace(/#\{this\}/g, function() { + return objDisplay(val); + }).replace(/#\{act\}/g, function() { + return objDisplay(actual); + }).replace(/#\{exp\}/g, function() { + return objDisplay(expected); + }); + return flagMsg ? flagMsg + ": " + msg : msg; +} +__name(getMessage2, "getMessage"); + +// lib/chai/utils/transferFlags.js +function transferFlags(assertion, object, includeAll) { + let flags = assertion.__flags || (assertion.__flags = /* @__PURE__ */ Object.create(null)); + if (!object.__flags) { + object.__flags = /* @__PURE__ */ Object.create(null); + } + includeAll = arguments.length === 3 ? includeAll : true; + for (let flag3 in flags) { + if (includeAll || flag3 !== "object" && flag3 !== "ssfi" && flag3 !== "lockSsfi" && flag3 != "message") { + object.__flags[flag3] = flags[flag3]; + } + } +} +__name(transferFlags, "transferFlags"); + +// node_modules/deep-eql/index.js +function type2(obj) { + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + const stringTag = obj[Symbol.toStringTag]; + if (typeof stringTag === "string") { + return stringTag; + } + const sliceStart = 8; + const sliceEnd = -1; + return Object.prototype.toString.call(obj).slice(sliceStart, sliceEnd); +} +__name(type2, "type"); +function FakeMap() { + this._key = "chai/deep-eql__" + Math.random() + Date.now(); +} +__name(FakeMap, "FakeMap"); +FakeMap.prototype = { + get: /* @__PURE__ */ __name(function get(key) { + return key[this._key]; + }, "get"), + set: /* @__PURE__ */ __name(function set(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this._key, { + value, + configurable: true + }); + } + }, "set") +}; +var MemoizeMap = typeof WeakMap === "function" ? WeakMap : FakeMap; +function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return null; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + var result = leftHandMap.get(rightHandOperand); + if (typeof result === "boolean") { + return result; + } + } + return null; +} +__name(memoizeCompare, "memoizeCompare"); +function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + leftHandMap.set(rightHandOperand, result); + } else { + leftHandMap = new MemoizeMap(); + leftHandMap.set(rightHandOperand, result); + memoizeMap.set(leftHandOperand, leftHandMap); + } +} +__name(memoizeSet, "memoizeSet"); +var deep_eql_default = deepEqual; +function deepEqual(leftHandOperand, rightHandOperand, options) { + if (options && options.comparator) { + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); + } + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); +} +__name(deepEqual, "deepEqual"); +function simpleEqual(leftHandOperand, rightHandOperand) { + if (leftHandOperand === rightHandOperand) { + return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; + } + if (leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare + rightHandOperand !== rightHandOperand) { + return true; + } + if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return false; + } + return null; +} +__name(simpleEqual, "simpleEqual"); +function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { + options = options || {}; + options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); + var comparator = options && options.comparator; + var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); + if (memoizeResultLeft !== null) { + return memoizeResultLeft; + } + var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); + if (memoizeResultRight !== null) { + return memoizeResultRight; + } + if (comparator) { + var comparatorResult = comparator(leftHandOperand, rightHandOperand); + if (comparatorResult === false || comparatorResult === true) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); + return comparatorResult; + } + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + } + var leftHandType = type2(leftHandOperand); + if (leftHandType !== type2(rightHandOperand)) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); + return false; + } + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); + var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); + return result; +} +__name(extensiveDeepEqual, "extensiveDeepEqual"); +function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { + switch (leftHandType) { + case "String": + case "Number": + case "Boolean": + case "Date": + return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); + case "Promise": + case "Symbol": + case "function": + case "WeakMap": + case "WeakSet": + return leftHandOperand === rightHandOperand; + case "Error": + return keysEqual(leftHandOperand, rightHandOperand, ["name", "message", "code"], options); + case "Arguments": + case "Int8Array": + case "Uint8Array": + case "Uint8ClampedArray": + case "Int16Array": + case "Uint16Array": + case "Int32Array": + case "Uint32Array": + case "Float32Array": + case "Float64Array": + case "Array": + return iterableEqual(leftHandOperand, rightHandOperand, options); + case "RegExp": + return regexpEqual(leftHandOperand, rightHandOperand); + case "Generator": + return generatorEqual(leftHandOperand, rightHandOperand, options); + case "DataView": + return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); + case "ArrayBuffer": + return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); + case "Set": + return entriesEqual(leftHandOperand, rightHandOperand, options); + case "Map": + return entriesEqual(leftHandOperand, rightHandOperand, options); + case "Temporal.PlainDate": + case "Temporal.PlainTime": + case "Temporal.PlainDateTime": + case "Temporal.Instant": + case "Temporal.ZonedDateTime": + case "Temporal.PlainYearMonth": + case "Temporal.PlainMonthDay": + return leftHandOperand.equals(rightHandOperand); + case "Temporal.Duration": + return leftHandOperand.total("nanoseconds") === rightHandOperand.total("nanoseconds"); + case "Temporal.TimeZone": + case "Temporal.Calendar": + return leftHandOperand.toString() === rightHandOperand.toString(); + default: + return objectEqual(leftHandOperand, rightHandOperand, options); + } +} +__name(extensiveDeepEqualByType, "extensiveDeepEqualByType"); +function regexpEqual(leftHandOperand, rightHandOperand) { + return leftHandOperand.toString() === rightHandOperand.toString(); +} +__name(regexpEqual, "regexpEqual"); +function entriesEqual(leftHandOperand, rightHandOperand, options) { + try { + if (leftHandOperand.size !== rightHandOperand.size) { + return false; + } + if (leftHandOperand.size === 0) { + return true; + } + } catch (sizeError) { + return false; + } + var leftHandItems = []; + var rightHandItems = []; + leftHandOperand.forEach(/* @__PURE__ */ __name(function gatherEntries(key, value) { + leftHandItems.push([key, value]); + }, "gatherEntries")); + rightHandOperand.forEach(/* @__PURE__ */ __name(function gatherEntries(key, value) { + rightHandItems.push([key, value]); + }, "gatherEntries")); + return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); +} +__name(entriesEqual, "entriesEqual"); +function iterableEqual(leftHandOperand, rightHandOperand, options) { + var length = leftHandOperand.length; + if (length !== rightHandOperand.length) { + return false; + } + if (length === 0) { + return true; + } + var index = -1; + while (++index < length) { + if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { + return false; + } + } + return true; +} +__name(iterableEqual, "iterableEqual"); +function generatorEqual(leftHandOperand, rightHandOperand, options) { + return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); +} +__name(generatorEqual, "generatorEqual"); +function hasIteratorFunction(target) { + return typeof Symbol !== "undefined" && typeof target === "object" && typeof Symbol.iterator !== "undefined" && typeof target[Symbol.iterator] === "function"; +} +__name(hasIteratorFunction, "hasIteratorFunction"); +function getIteratorEntries(target) { + if (hasIteratorFunction(target)) { + try { + return getGeneratorEntries(target[Symbol.iterator]()); + } catch (iteratorError) { + return []; + } + } + return []; +} +__name(getIteratorEntries, "getIteratorEntries"); +function getGeneratorEntries(generator) { + var generatorResult = generator.next(); + var accumulator = [generatorResult.value]; + while (generatorResult.done === false) { + generatorResult = generator.next(); + accumulator.push(generatorResult.value); + } + return accumulator; +} +__name(getGeneratorEntries, "getGeneratorEntries"); +function getEnumerableKeys(target) { + var keys = []; + for (var key in target) { + keys.push(key); + } + return keys; +} +__name(getEnumerableKeys, "getEnumerableKeys"); +function getEnumerableSymbols(target) { + var keys = []; + var allKeys = Object.getOwnPropertySymbols(target); + for (var i = 0; i < allKeys.length; i += 1) { + var key = allKeys[i]; + if (Object.getOwnPropertyDescriptor(target, key).enumerable) { + keys.push(key); + } + } + return keys; +} +__name(getEnumerableSymbols, "getEnumerableSymbols"); +function keysEqual(leftHandOperand, rightHandOperand, keys, options) { + var length = keys.length; + if (length === 0) { + return true; + } + for (var i = 0; i < length; i += 1) { + if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { + return false; + } + } + return true; +} +__name(keysEqual, "keysEqual"); +function objectEqual(leftHandOperand, rightHandOperand, options) { + var leftHandKeys = getEnumerableKeys(leftHandOperand); + var rightHandKeys = getEnumerableKeys(rightHandOperand); + var leftHandSymbols = getEnumerableSymbols(leftHandOperand); + var rightHandSymbols = getEnumerableSymbols(rightHandOperand); + leftHandKeys = leftHandKeys.concat(leftHandSymbols); + rightHandKeys = rightHandKeys.concat(rightHandSymbols); + if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { + if (iterableEqual(mapSymbols(leftHandKeys).sort(), mapSymbols(rightHandKeys).sort()) === false) { + return false; + } + return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); + } + var leftHandEntries = getIteratorEntries(leftHandOperand); + var rightHandEntries = getIteratorEntries(rightHandOperand); + if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { + leftHandEntries.sort(); + rightHandEntries.sort(); + return iterableEqual(leftHandEntries, rightHandEntries, options); + } + if (leftHandKeys.length === 0 && leftHandEntries.length === 0 && rightHandKeys.length === 0 && rightHandEntries.length === 0) { + return true; + } + return false; +} +__name(objectEqual, "objectEqual"); +function isPrimitive(value) { + return value === null || typeof value !== "object"; +} +__name(isPrimitive, "isPrimitive"); +function mapSymbols(arr) { + return arr.map(/* @__PURE__ */ __name(function mapSymbol(entry) { + if (typeof entry === "symbol") { + return entry.toString(); + } + return entry; + }, "mapSymbol")); +} +__name(mapSymbols, "mapSymbols"); + +// node_modules/pathval/index.js +function hasProperty(obj, name) { + if (typeof obj === "undefined" || obj === null) { + return false; + } + return name in Object(obj); +} +__name(hasProperty, "hasProperty"); +function parsePath(path) { + const str = path.replace(/([^\\])\[/g, "$1.["); + const parts = str.match(/(\\\.|[^.]+?)+/g); + return parts.map((value) => { + if (value === "constructor" || value === "__proto__" || value === "prototype") { + return {}; + } + const regexp = /^\[(\d+)\]$/; + const mArr = regexp.exec(value); + let parsed = null; + if (mArr) { + parsed = { i: parseFloat(mArr[1]) }; + } else { + parsed = { p: value.replace(/\\([.[\]])/g, "$1") }; + } + return parsed; + }); +} +__name(parsePath, "parsePath"); +function internalGetPathValue(obj, parsed, pathDepth) { + let temporaryValue = obj; + let res = null; + pathDepth = typeof pathDepth === "undefined" ? parsed.length : pathDepth; + for (let i = 0; i < pathDepth; i++) { + const part = parsed[i]; + if (temporaryValue) { + if (typeof part.p === "undefined") { + temporaryValue = temporaryValue[part.i]; + } else { + temporaryValue = temporaryValue[part.p]; + } + if (i === pathDepth - 1) { + res = temporaryValue; + } + } + } + return res; +} +__name(internalGetPathValue, "internalGetPathValue"); +function getPathInfo(obj, path) { + const parsed = parsePath(path); + const last = parsed[parsed.length - 1]; + const info = { + parent: parsed.length > 1 ? internalGetPathValue(obj, parsed, parsed.length - 1) : obj, + name: last.p || last.i, + value: internalGetPathValue(obj, parsed) + }; + info.exists = hasProperty(info.parent, info.name); + return info; +} +__name(getPathInfo, "getPathInfo"); + +// lib/chai/assertion.js +var _Assertion = class _Assertion { + /** + * Creates object for chaining. + * `Assertion` objects contain metadata in the form of flags. Three flags can + * be assigned during instantiation by passing arguments to this constructor: + * + * - `object`: This flag contains the target of the assertion. For example, in + * the assertion `expect(numKittens).to.equal(7);`, the `object` flag will + * contain `numKittens` so that the `equal` assertion can reference it when + * needed. + * + * - `message`: This flag contains an optional custom error message to be + * prepended to the error message that's generated by the assertion when it + * fails. + * + * - `ssfi`: This flag stands for "start stack function indicator". It + * contains a function reference that serves as the starting point for + * removing frames from the stack trace of the error that's created by the + * assertion when it fails. The goal is to provide a cleaner stack trace to + * end users by removing Chai's internal functions. Note that it only works + * in environments that support `Error.captureStackTrace`, and only when + * `Chai.config.includeStack` hasn't been set to `false`. + * + * - `lockSsfi`: This flag controls whether or not the given `ssfi` flag + * should retain its current value, even as assertions are chained off of + * this object. This is usually set to `true` when creating a new assertion + * from within another assertion. It's also temporarily set to `true` before + * an overwritten assertion gets called by the overwriting assertion. + * + * - `eql`: This flag contains the deepEqual function to be used by the assertion. + * + * @param {unknown} obj target of the assertion + * @param {string} [msg] (optional) custom error message + * @param {Function} [ssfi] (optional) starting point for removing stack frames + * @param {boolean} [lockSsfi] (optional) whether or not the ssfi flag is locked + */ + constructor(obj, msg, ssfi, lockSsfi) { + /** @type {{}} */ + __publicField(this, "__flags", {}); + flag(this, "ssfi", ssfi || _Assertion); + flag(this, "lockSsfi", lockSsfi); + flag(this, "object", obj); + flag(this, "message", msg); + flag(this, "eql", config.deepEqual || deep_eql_default); + return proxify(this); + } + /** @returns {boolean} */ + static get includeStack() { + console.warn( + "Assertion.includeStack is deprecated, use chai.config.includeStack instead." + ); + return config.includeStack; + } + /** @param {boolean} value */ + static set includeStack(value) { + console.warn( + "Assertion.includeStack is deprecated, use chai.config.includeStack instead." + ); + config.includeStack = value; + } + /** @returns {boolean} */ + static get showDiff() { + console.warn( + "Assertion.showDiff is deprecated, use chai.config.showDiff instead." + ); + return config.showDiff; + } + /** @param {boolean} value */ + static set showDiff(value) { + console.warn( + "Assertion.showDiff is deprecated, use chai.config.showDiff instead." + ); + config.showDiff = value; + } + /** + * @param {string} name + * @param {Function} fn + */ + static addProperty(name, fn) { + addProperty(this.prototype, name, fn); + } + /** + * @param {string} name + * @param {Function} fn + */ + static addMethod(name, fn) { + addMethod(this.prototype, name, fn); + } + /** + * @param {string} name + * @param {Function} fn + * @param {Function} chainingBehavior + */ + static addChainableMethod(name, fn, chainingBehavior) { + addChainableMethod(this.prototype, name, fn, chainingBehavior); + } + /** + * @param {string} name + * @param {Function} fn + */ + static overwriteProperty(name, fn) { + overwriteProperty(this.prototype, name, fn); + } + /** + * @param {string} name + * @param {Function} fn + */ + static overwriteMethod(name, fn) { + overwriteMethod(this.prototype, name, fn); + } + /** + * @param {string} name + * @param {Function} fn + * @param {Function} chainingBehavior + */ + static overwriteChainableMethod(name, fn, chainingBehavior) { + overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); + } + /** + * ### .assert(expression, message, negateMessage, expected, actual, showDiff) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {unknown} _expr to be tested + * @param {string | Function} msg or function that returns message to display if expression fails + * @param {string | Function} _negateMsg or function that returns negatedMessage to display if negated expression fails + * @param {unknown} expected value (remember to check for negation) + * @param {unknown} _actual (optional) will default to `this.obj` + * @param {boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails + * @returns {void} + */ + assert(_expr, msg, _negateMsg, expected, _actual, showDiff) { + const ok = test(this, arguments); + if (false !== showDiff) showDiff = true; + if (void 0 === expected && void 0 === _actual) showDiff = false; + if (true !== config.showDiff) showDiff = false; + if (!ok) { + msg = getMessage2(this, arguments); + const actual = getActual(this, arguments); + const assertionErrorObjectProperties = { + actual, + expected, + showDiff + }; + const operator = getOperator(this, arguments); + if (operator) { + assertionErrorObjectProperties.operator = operator; + } + throw new AssertionError( + msg, + assertionErrorObjectProperties, + // @ts-expect-error Not sure what to do about these types yet + config.includeStack ? this.assert : flag(this, "ssfi") + ); + } + } + /** + * Quick reference to stored `actual` value for plugin developers. + * + * @returns {unknown} + */ + get _obj() { + return flag(this, "object"); + } + /** + * Quick reference to stored `actual` value for plugin developers. + * + * @param {unknown} val + */ + set _obj(val) { + flag(this, "object", val); + } +}; +__name(_Assertion, "Assertion"); +var Assertion = _Assertion; + +// lib/chai/utils/events.js +var events = new EventTarget(); +var _PluginEvent = class _PluginEvent extends Event { + constructor(type3, name, fn) { + super(type3); + this.name = String(name); + this.fn = fn; + } +}; +__name(_PluginEvent, "PluginEvent"); +var PluginEvent = _PluginEvent; + +// lib/chai/utils/isProxyEnabled.js +function isProxyEnabled() { + return config.useProxy && typeof Proxy !== "undefined" && typeof Reflect !== "undefined"; +} +__name(isProxyEnabled, "isProxyEnabled"); + +// lib/chai/utils/addProperty.js +function addProperty(ctx, name, getter) { + getter = getter === void 0 ? function() { + } : getter; + Object.defineProperty(ctx, name, { + get: /* @__PURE__ */ __name(function propertyGetter() { + if (!isProxyEnabled() && !flag(this, "lockSsfi")) { + flag(this, "ssfi", propertyGetter); + } + let result = getter.call(this); + if (result !== void 0) return result; + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "propertyGetter"), + configurable: true + }); + events.dispatchEvent(new PluginEvent("addProperty", name, getter)); +} +__name(addProperty, "addProperty"); + +// lib/chai/utils/addLengthGuard.js +var fnLengthDesc = Object.getOwnPropertyDescriptor(function() { +}, "length"); +function addLengthGuard(fn, assertionName, isChainable) { + if (!fnLengthDesc.configurable) return fn; + Object.defineProperty(fn, "length", { + get: /* @__PURE__ */ __name(function() { + if (isChainable) { + throw Error( + "Invalid Chai property: " + assertionName + '.length. Due to a compatibility issue, "length" cannot directly follow "' + assertionName + '". Use "' + assertionName + '.lengthOf" instead.' + ); + } + throw Error( + "Invalid Chai property: " + assertionName + '.length. See docs for proper usage of "' + assertionName + '".' + ); + }, "get") + }); + return fn; +} +__name(addLengthGuard, "addLengthGuard"); + +// lib/chai/utils/getProperties.js +function getProperties(object) { + let result = Object.getOwnPropertyNames(object); + function addProperty2(property) { + if (result.indexOf(property) === -1) { + result.push(property); + } + } + __name(addProperty2, "addProperty"); + let proto = Object.getPrototypeOf(object); + while (proto !== null) { + Object.getOwnPropertyNames(proto).forEach(addProperty2); + proto = Object.getPrototypeOf(proto); + } + return result; +} +__name(getProperties, "getProperties"); + +// lib/chai/utils/proxify.js +var builtins = ["__flags", "__methods", "_obj", "assert"]; +function proxify(obj, nonChainableMethodName) { + if (!isProxyEnabled()) return obj; + return new Proxy(obj, { + get: /* @__PURE__ */ __name(function proxyGetter(target, property) { + if (typeof property === "string" && config.proxyExcludedKeys.indexOf(property) === -1 && !Reflect.has(target, property)) { + if (nonChainableMethodName) { + throw Error( + "Invalid Chai property: " + nonChainableMethodName + "." + property + '. See docs for proper usage of "' + nonChainableMethodName + '".' + ); + } + let suggestion = null; + let suggestionDistance = 4; + getProperties(target).forEach(function(prop) { + if ( + // we actually mean to check `Object.prototype` here + // eslint-disable-next-line no-prototype-builtins + !Object.prototype.hasOwnProperty(prop) && builtins.indexOf(prop) === -1 + ) { + let dist = stringDistanceCapped(property, prop, suggestionDistance); + if (dist < suggestionDistance) { + suggestion = prop; + suggestionDistance = dist; + } + } + }); + if (suggestion !== null) { + throw Error( + "Invalid Chai property: " + property + '. Did you mean "' + suggestion + '"?' + ); + } else { + throw Error("Invalid Chai property: " + property); + } + } + if (builtins.indexOf(property) === -1 && !flag(target, "lockSsfi")) { + flag(target, "ssfi", proxyGetter); + } + return Reflect.get(target, property); + }, "proxyGetter") + }); +} +__name(proxify, "proxify"); +function stringDistanceCapped(strA, strB, cap) { + if (Math.abs(strA.length - strB.length) >= cap) { + return cap; + } + let memo = []; + for (let i = 0; i <= strA.length; i++) { + memo[i] = Array(strB.length + 1).fill(0); + memo[i][0] = i; + } + for (let j = 0; j < strB.length; j++) { + memo[0][j] = j; + } + for (let i = 1; i <= strA.length; i++) { + let ch = strA.charCodeAt(i - 1); + for (let j = 1; j <= strB.length; j++) { + if (Math.abs(i - j) >= cap) { + memo[i][j] = cap; + continue; + } + memo[i][j] = Math.min( + memo[i - 1][j] + 1, + memo[i][j - 1] + 1, + memo[i - 1][j - 1] + (ch === strB.charCodeAt(j - 1) ? 0 : 1) + ); + } + } + return memo[strA.length][strB.length]; +} +__name(stringDistanceCapped, "stringDistanceCapped"); + +// lib/chai/utils/addMethod.js +function addMethod(ctx, name, method) { + let methodWrapper = /* @__PURE__ */ __name(function() { + if (!flag(this, "lockSsfi")) { + flag(this, "ssfi", methodWrapper); + } + let result = method.apply(this, arguments); + if (result !== void 0) return result; + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "methodWrapper"); + addLengthGuard(methodWrapper, name, false); + ctx[name] = proxify(methodWrapper, name); + events.dispatchEvent(new PluginEvent("addMethod", name, method)); +} +__name(addMethod, "addMethod"); + +// lib/chai/utils/overwriteProperty.js +function overwriteProperty(ctx, name, getter) { + let _get = Object.getOwnPropertyDescriptor(ctx, name), _super = /* @__PURE__ */ __name(function() { + }, "_super"); + if (_get && "function" === typeof _get.get) _super = _get.get; + Object.defineProperty(ctx, name, { + get: /* @__PURE__ */ __name(function overwritingPropertyGetter() { + if (!isProxyEnabled() && !flag(this, "lockSsfi")) { + flag(this, "ssfi", overwritingPropertyGetter); + } + let origLockSsfi = flag(this, "lockSsfi"); + flag(this, "lockSsfi", true); + let result = getter(_super).call(this); + flag(this, "lockSsfi", origLockSsfi); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingPropertyGetter"), + configurable: true + }); +} +__name(overwriteProperty, "overwriteProperty"); + +// lib/chai/utils/overwriteMethod.js +function overwriteMethod(ctx, name, method) { + let _method = ctx[name], _super = /* @__PURE__ */ __name(function() { + throw new Error(name + " is not a function"); + }, "_super"); + if (_method && "function" === typeof _method) _super = _method; + let overwritingMethodWrapper = /* @__PURE__ */ __name(function() { + if (!flag(this, "lockSsfi")) { + flag(this, "ssfi", overwritingMethodWrapper); + } + let origLockSsfi = flag(this, "lockSsfi"); + flag(this, "lockSsfi", true); + let result = method(_super).apply(this, arguments); + flag(this, "lockSsfi", origLockSsfi); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingMethodWrapper"); + addLengthGuard(overwritingMethodWrapper, name, false); + ctx[name] = proxify(overwritingMethodWrapper, name); +} +__name(overwriteMethod, "overwriteMethod"); + +// lib/chai/utils/addChainableMethod.js +var canSetPrototype = typeof Object.setPrototypeOf === "function"; +var testFn = /* @__PURE__ */ __name(function() { +}, "testFn"); +var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { + let propDesc = Object.getOwnPropertyDescriptor(testFn, name); + if (typeof propDesc !== "object") return true; + return !propDesc.configurable; +}); +var call = Function.prototype.call; +var apply = Function.prototype.apply; +var _PluginAddChainableMethodEvent = class _PluginAddChainableMethodEvent extends PluginEvent { + constructor(type3, name, fn, chainingBehavior) { + super(type3, name, fn); + this.chainingBehavior = chainingBehavior; + } +}; +__name(_PluginAddChainableMethodEvent, "PluginAddChainableMethodEvent"); +var PluginAddChainableMethodEvent = _PluginAddChainableMethodEvent; +function addChainableMethod(ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== "function") { + chainingBehavior = /* @__PURE__ */ __name(function() { + }, "chainingBehavior"); + } + let chainableBehavior = { + method, + chainingBehavior + }; + if (!ctx.__methods) { + ctx.__methods = {}; + } + ctx.__methods[name] = chainableBehavior; + Object.defineProperty(ctx, name, { + get: /* @__PURE__ */ __name(function chainableMethodGetter() { + chainableBehavior.chainingBehavior.call(this); + let chainableMethodWrapper = /* @__PURE__ */ __name(function() { + if (!flag(this, "lockSsfi")) { + flag(this, "ssfi", chainableMethodWrapper); + } + let result = chainableBehavior.method.apply(this, arguments); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "chainableMethodWrapper"); + addLengthGuard(chainableMethodWrapper, name, true); + if (canSetPrototype) { + let prototype = Object.create(this); + prototype.call = call; + prototype.apply = apply; + Object.setPrototypeOf(chainableMethodWrapper, prototype); + } else { + let asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function(asserterName) { + if (excludeNames.indexOf(asserterName) !== -1) { + return; + } + let pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(chainableMethodWrapper, asserterName, pd); + }); + } + transferFlags(this, chainableMethodWrapper); + return proxify(chainableMethodWrapper); + }, "chainableMethodGetter"), + configurable: true + }); + events.dispatchEvent( + new PluginAddChainableMethodEvent( + "addChainableMethod", + name, + method, + chainingBehavior + ) + ); +} +__name(addChainableMethod, "addChainableMethod"); + +// lib/chai/utils/overwriteChainableMethod.js +function overwriteChainableMethod(ctx, name, method, chainingBehavior) { + let chainableBehavior = ctx.__methods[name]; + let _chainingBehavior = chainableBehavior.chainingBehavior; + chainableBehavior.chainingBehavior = /* @__PURE__ */ __name(function overwritingChainableMethodGetter() { + let result = chainingBehavior(_chainingBehavior).call(this); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingChainableMethodGetter"); + let _method = chainableBehavior.method; + chainableBehavior.method = /* @__PURE__ */ __name(function overwritingChainableMethodWrapper() { + let result = method(_method).apply(this, arguments); + if (result !== void 0) { + return result; + } + let newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingChainableMethodWrapper"); +} +__name(overwriteChainableMethod, "overwriteChainableMethod"); + +// lib/chai/utils/compareByInspect.js +function compareByInspect(a, b) { + return inspect2(a) < inspect2(b) ? -1 : 1; +} +__name(compareByInspect, "compareByInspect"); + +// lib/chai/utils/getOwnEnumerablePropertySymbols.js +function getOwnEnumerablePropertySymbols(obj) { + if (typeof Object.getOwnPropertySymbols !== "function") return []; + return Object.getOwnPropertySymbols(obj).filter(function(sym) { + return Object.getOwnPropertyDescriptor(obj, sym).enumerable; + }); +} +__name(getOwnEnumerablePropertySymbols, "getOwnEnumerablePropertySymbols"); + +// lib/chai/utils/getOwnEnumerableProperties.js +function getOwnEnumerableProperties(obj) { + return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); +} +__name(getOwnEnumerableProperties, "getOwnEnumerableProperties"); + +// lib/chai/utils/isNaN.js +var isNaN2 = Number.isNaN; + +// lib/chai/utils/getOperator.js +function isObjectType(obj) { + let objectType = type(obj); + let objectTypes = ["Array", "Object", "Function"]; + return objectTypes.indexOf(objectType) !== -1; +} +__name(isObjectType, "isObjectType"); +function getOperator(obj, args) { + let operator = flag(obj, "operator"); + let negate = flag(obj, "negate"); + let expected = args[3]; + let msg = negate ? args[2] : args[1]; + if (operator) { + return operator; + } + if (typeof msg === "function") msg = msg(); + msg = msg || ""; + if (!msg) { + return void 0; + } + if (/\shave\s/.test(msg)) { + return void 0; + } + let isObject = isObjectType(expected); + if (/\snot\s/.test(msg)) { + return isObject ? "notDeepStrictEqual" : "notStrictEqual"; + } + return isObject ? "deepStrictEqual" : "strictEqual"; +} +__name(getOperator, "getOperator"); + +// lib/chai/utils/index.js +function getName(fn) { + return fn.name; +} +__name(getName, "getName"); +function isRegExp2(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; +} +__name(isRegExp2, "isRegExp"); +function isNumeric(obj) { + return ["Number", "BigInt"].includes(type(obj)); +} +__name(isNumeric, "isNumeric"); + +// lib/chai/core/assertions.js +var { flag: flag2 } = utils_exports; +[ + "to", + "be", + "been", + "is", + "and", + "has", + "have", + "with", + "that", + "which", + "at", + "of", + "same", + "but", + "does", + "still", + "also" +].forEach(function(chain) { + Assertion.addProperty(chain); +}); +Assertion.addProperty("not", function() { + flag2(this, "negate", true); +}); +Assertion.addProperty("deep", function() { + flag2(this, "deep", true); +}); +Assertion.addProperty("nested", function() { + flag2(this, "nested", true); +}); +Assertion.addProperty("own", function() { + flag2(this, "own", true); +}); +Assertion.addProperty("ordered", function() { + flag2(this, "ordered", true); +}); +Assertion.addProperty("any", function() { + flag2(this, "any", true); + flag2(this, "all", false); +}); +Assertion.addProperty("all", function() { + flag2(this, "all", true); + flag2(this, "any", false); +}); +var functionTypes = { + function: [ + "function", + "asyncfunction", + "generatorfunction", + "asyncgeneratorfunction" + ], + asyncfunction: ["asyncfunction", "asyncgeneratorfunction"], + generatorfunction: ["generatorfunction", "asyncgeneratorfunction"], + asyncgeneratorfunction: ["asyncgeneratorfunction"] +}; +function an(type3, msg) { + if (msg) flag2(this, "message", msg); + type3 = type3.toLowerCase(); + let obj = flag2(this, "object"), article = ~["a", "e", "i", "o", "u"].indexOf(type3.charAt(0)) ? "an " : "a "; + const detectedType = type(obj).toLowerCase(); + if (functionTypes["function"].includes(type3)) { + this.assert( + functionTypes[type3].includes(detectedType), + "expected #{this} to be " + article + type3, + "expected #{this} not to be " + article + type3 + ); + } else { + this.assert( + type3 === detectedType, + "expected #{this} to be " + article + type3, + "expected #{this} not to be " + article + type3 + ); + } +} +__name(an, "an"); +Assertion.addChainableMethod("an", an); +Assertion.addChainableMethod("a", an); +function SameValueZero(a, b) { + return isNaN2(a) && isNaN2(b) || a === b; +} +__name(SameValueZero, "SameValueZero"); +function includeChainingBehavior() { + flag2(this, "contains", true); +} +__name(includeChainingBehavior, "includeChainingBehavior"); +function include(val, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), objType = type(obj).toLowerCase(), flagMsg = flag2(this, "message"), negate = flag2(this, "negate"), ssfi = flag2(this, "ssfi"), isDeep = flag2(this, "deep"), descriptor = isDeep ? "deep " : "", isEql = isDeep ? flag2(this, "eql") : SameValueZero; + flagMsg = flagMsg ? flagMsg + ": " : ""; + let included = false; + switch (objType) { + case "string": + included = obj.indexOf(val) !== -1; + break; + case "weakset": + if (isDeep) { + throw new AssertionError( + flagMsg + "unable to use .deep.include with WeakSet", + void 0, + ssfi + ); + } + included = obj.has(val); + break; + case "map": + obj.forEach(function(item) { + included = included || isEql(item, val); + }); + break; + case "set": + if (isDeep) { + obj.forEach(function(item) { + included = included || isEql(item, val); + }); + } else { + included = obj.has(val); + } + break; + case "array": + if (isDeep) { + included = obj.some(function(item) { + return isEql(item, val); + }); + } else { + included = obj.indexOf(val) !== -1; + } + break; + default: { + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + "the given combination of arguments (" + objType + " and " + type(val).toLowerCase() + ") is invalid for this assertion. You can use an array, a map, an object, a set, a string, or a weakset instead of a " + type(val).toLowerCase(), + void 0, + ssfi + ); + } + let props = Object.keys(val); + let firstErr = null; + let numErrs = 0; + props.forEach(function(prop) { + let propAssertion = new Assertion(obj); + transferFlags(this, propAssertion, true); + flag2(propAssertion, "lockSsfi", true); + if (!negate || props.length === 1) { + propAssertion.property(prop, val[prop]); + return; + } + try { + propAssertion.property(prop, val[prop]); + } catch (err) { + if (!check_error_exports.compatibleConstructor(err, AssertionError)) { + throw err; + } + if (firstErr === null) firstErr = err; + numErrs++; + } + }, this); + if (negate && props.length > 1 && numErrs === props.length) { + throw firstErr; + } + return; + } + } + this.assert( + included, + "expected #{this} to " + descriptor + "include " + inspect2(val), + "expected #{this} to not " + descriptor + "include " + inspect2(val) + ); +} +__name(include, "include"); +Assertion.addChainableMethod("include", include, includeChainingBehavior); +Assertion.addChainableMethod("contain", include, includeChainingBehavior); +Assertion.addChainableMethod("contains", include, includeChainingBehavior); +Assertion.addChainableMethod("includes", include, includeChainingBehavior); +Assertion.addProperty("ok", function() { + this.assert( + flag2(this, "object"), + "expected #{this} to be truthy", + "expected #{this} to be falsy" + ); +}); +Assertion.addProperty("true", function() { + this.assert( + true === flag2(this, "object"), + "expected #{this} to be true", + "expected #{this} to be false", + flag2(this, "negate") ? false : true + ); +}); +Assertion.addProperty("numeric", function() { + const object = flag2(this, "object"); + this.assert( + ["Number", "BigInt"].includes(type(object)), + "expected #{this} to be numeric", + "expected #{this} to not be numeric", + flag2(this, "negate") ? false : true + ); +}); +Assertion.addProperty("callable", function() { + const val = flag2(this, "object"); + const ssfi = flag2(this, "ssfi"); + const message = flag2(this, "message"); + const msg = message ? `${message}: ` : ""; + const negate = flag2(this, "negate"); + const assertionMessage = negate ? `${msg}expected ${inspect2(val)} not to be a callable function` : `${msg}expected ${inspect2(val)} to be a callable function`; + const isCallable = [ + "Function", + "AsyncFunction", + "GeneratorFunction", + "AsyncGeneratorFunction" + ].includes(type(val)); + if (isCallable && negate || !isCallable && !negate) { + throw new AssertionError(assertionMessage, void 0, ssfi); + } +}); +Assertion.addProperty("false", function() { + this.assert( + false === flag2(this, "object"), + "expected #{this} to be false", + "expected #{this} to be true", + flag2(this, "negate") ? true : false + ); +}); +Assertion.addProperty("null", function() { + this.assert( + null === flag2(this, "object"), + "expected #{this} to be null", + "expected #{this} not to be null" + ); +}); +Assertion.addProperty("undefined", function() { + this.assert( + void 0 === flag2(this, "object"), + "expected #{this} to be undefined", + "expected #{this} not to be undefined" + ); +}); +Assertion.addProperty("NaN", function() { + this.assert( + isNaN2(flag2(this, "object")), + "expected #{this} to be NaN", + "expected #{this} not to be NaN" + ); +}); +function assertExist() { + let val = flag2(this, "object"); + this.assert( + val !== null && val !== void 0, + "expected #{this} to exist", + "expected #{this} to not exist" + ); +} +__name(assertExist, "assertExist"); +Assertion.addProperty("exist", assertExist); +Assertion.addProperty("exists", assertExist); +Assertion.addProperty("empty", function() { + let val = flag2(this, "object"), ssfi = flag2(this, "ssfi"), flagMsg = flag2(this, "message"), itemsCount; + flagMsg = flagMsg ? flagMsg + ": " : ""; + switch (type(val).toLowerCase()) { + case "array": + case "string": + itemsCount = val.length; + break; + case "map": + case "set": + itemsCount = val.size; + break; + case "weakmap": + case "weakset": + throw new AssertionError( + flagMsg + ".empty was passed a weak collection", + void 0, + ssfi + ); + case "function": { + const msg = flagMsg + ".empty was passed a function " + getName(val); + throw new AssertionError(msg.trim(), void 0, ssfi); + } + default: + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + ".empty was passed non-string primitive " + inspect2(val), + void 0, + ssfi + ); + } + itemsCount = Object.keys(val).length; + } + this.assert( + 0 === itemsCount, + "expected #{this} to be empty", + "expected #{this} not to be empty" + ); +}); +function checkArguments() { + let obj = flag2(this, "object"), type3 = type(obj); + this.assert( + "Arguments" === type3, + "expected #{this} to be arguments but got " + type3, + "expected #{this} to not be arguments" + ); +} +__name(checkArguments, "checkArguments"); +Assertion.addProperty("arguments", checkArguments); +Assertion.addProperty("Arguments", checkArguments); +function assertEqual(val, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + if (flag2(this, "deep")) { + let prevLockSsfi = flag2(this, "lockSsfi"); + flag2(this, "lockSsfi", true); + this.eql(val); + flag2(this, "lockSsfi", prevLockSsfi); + } else { + this.assert( + val === obj, + "expected #{this} to equal #{exp}", + "expected #{this} to not equal #{exp}", + val, + this._obj, + true + ); + } +} +__name(assertEqual, "assertEqual"); +Assertion.addMethod("equal", assertEqual); +Assertion.addMethod("equals", assertEqual); +Assertion.addMethod("eq", assertEqual); +function assertEql(obj, msg) { + if (msg) flag2(this, "message", msg); + let eql = flag2(this, "eql"); + this.assert( + eql(obj, flag2(this, "object")), + "expected #{this} to deeply equal #{exp}", + "expected #{this} to not deeply equal #{exp}", + obj, + this._obj, + true + ); +} +__name(assertEql, "assertEql"); +Assertion.addMethod("eql", assertEql); +Assertion.addMethod("eqls", assertEql); +function assertAbove(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(); + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && nType !== "date") { + throw new AssertionError( + msgPrefix + "the argument to above must be a date", + void 0, + ssfi + ); + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + throw new AssertionError( + msgPrefix + "the argument to above must be a number", + void 0, + ssfi + ); + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + throw new AssertionError( + msgPrefix + "expected " + printObj + " to be a number or a date", + void 0, + ssfi + ); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount > n, + "expected #{this} to have a " + descriptor + " above #{exp} but got #{act}", + "expected #{this} to not have a " + descriptor + " above #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj > n, + "expected #{this} to be above #{exp}", + "expected #{this} to be at most #{exp}", + n + ); + } +} +__name(assertAbove, "assertAbove"); +Assertion.addMethod("above", assertAbove); +Assertion.addMethod("gt", assertAbove); +Assertion.addMethod("greaterThan", assertAbove); +function assertLeast(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = true; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && nType !== "date") { + errorMessage = msgPrefix + "the argument to least must be a date"; + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the argument to least must be a number"; + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= n, + "expected #{this} to have a " + descriptor + " at least #{exp} but got #{act}", + "expected #{this} to have a " + descriptor + " below #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj >= n, + "expected #{this} to be at least #{exp}", + "expected #{this} to be below #{exp}", + n + ); + } +} +__name(assertLeast, "assertLeast"); +Assertion.addMethod("least", assertLeast); +Assertion.addMethod("gte", assertLeast); +Assertion.addMethod("greaterThanOrEqual", assertLeast); +function assertBelow(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = true; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && nType !== "date") { + errorMessage = msgPrefix + "the argument to below must be a date"; + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the argument to below must be a number"; + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount < n, + "expected #{this} to have a " + descriptor + " below #{exp} but got #{act}", + "expected #{this} to not have a " + descriptor + " below #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj < n, + "expected #{this} to be below #{exp}", + "expected #{this} to be at least #{exp}", + n + ); + } +} +__name(assertBelow, "assertBelow"); +Assertion.addMethod("below", assertBelow); +Assertion.addMethod("lt", assertBelow); +Assertion.addMethod("lessThan", assertBelow); +function assertMost(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = true; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && nType !== "date") { + errorMessage = msgPrefix + "the argument to most must be a date"; + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the argument to most must be a number"; + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount <= n, + "expected #{this} to have a " + descriptor + " at most #{exp} but got #{act}", + "expected #{this} to have a " + descriptor + " above #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj <= n, + "expected #{this} to be at most #{exp}", + "expected #{this} to be above #{exp}", + n + ); + } +} +__name(assertMost, "assertMost"); +Assertion.addMethod("most", assertMost); +Assertion.addMethod("lte", assertMost); +Assertion.addMethod("lessThanOrEqual", assertMost); +Assertion.addMethod("within", function(start, finish, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), startType = type(start).toLowerCase(), finishType = type(finish).toLowerCase(), errorMessage, shouldThrow = true, range = startType === "date" && finishType === "date" ? start.toISOString() + ".." + finish.toISOString() : start + ".." + finish; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && objType === "date" && (startType !== "date" || finishType !== "date")) { + errorMessage = msgPrefix + "the arguments to within must be dates"; + } else if ((!isNumeric(start) || !isNumeric(finish)) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the arguments to within must be numbers"; + } else if (!doLength && objType !== "date" && !isNumeric(obj)) { + let printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + let descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= start && itemsCount <= finish, + "expected #{this} to have a " + descriptor + " within " + range, + "expected #{this} to not have a " + descriptor + " within " + range + ); + } else { + this.assert( + obj >= start && obj <= finish, + "expected #{this} to be within " + range, + "expected #{this} to not be within " + range + ); + } +}); +function assertInstanceOf(constructor, msg) { + if (msg) flag2(this, "message", msg); + let target = flag2(this, "object"); + let ssfi = flag2(this, "ssfi"); + let flagMsg = flag2(this, "message"); + let isInstanceOf; + try { + isInstanceOf = target instanceof constructor; + } catch (err) { + if (err instanceof TypeError) { + flagMsg = flagMsg ? flagMsg + ": " : ""; + throw new AssertionError( + flagMsg + "The instanceof assertion needs a constructor but " + type(constructor) + " was given.", + void 0, + ssfi + ); + } + throw err; + } + let name = getName(constructor); + if (name == null) { + name = "an unnamed constructor"; + } + this.assert( + isInstanceOf, + "expected #{this} to be an instance of " + name, + "expected #{this} to not be an instance of " + name + ); +} +__name(assertInstanceOf, "assertInstanceOf"); +Assertion.addMethod("instanceof", assertInstanceOf); +Assertion.addMethod("instanceOf", assertInstanceOf); +function assertProperty(name, val, msg) { + if (msg) flag2(this, "message", msg); + let isNested = flag2(this, "nested"), isOwn = flag2(this, "own"), flagMsg = flag2(this, "message"), obj = flag2(this, "object"), ssfi = flag2(this, "ssfi"), nameType = typeof name; + flagMsg = flagMsg ? flagMsg + ": " : ""; + if (isNested) { + if (nameType !== "string") { + throw new AssertionError( + flagMsg + "the argument to property must be a string when using nested syntax", + void 0, + ssfi + ); + } + } else { + if (nameType !== "string" && nameType !== "number" && nameType !== "symbol") { + throw new AssertionError( + flagMsg + "the argument to property must be a string, number, or symbol", + void 0, + ssfi + ); + } + } + if (isNested && isOwn) { + throw new AssertionError( + flagMsg + 'The "nested" and "own" flags cannot be combined.', + void 0, + ssfi + ); + } + if (obj === null || obj === void 0) { + throw new AssertionError( + flagMsg + "Target cannot be null or undefined.", + void 0, + ssfi + ); + } + let isDeep = flag2(this, "deep"), negate = flag2(this, "negate"), pathInfo = isNested ? getPathInfo(obj, name) : null, value = isNested ? pathInfo.value : obj[name], isEql = isDeep ? flag2(this, "eql") : (val1, val2) => val1 === val2; + let descriptor = ""; + if (isDeep) descriptor += "deep "; + if (isOwn) descriptor += "own "; + if (isNested) descriptor += "nested "; + descriptor += "property "; + let hasProperty2; + if (isOwn) hasProperty2 = Object.prototype.hasOwnProperty.call(obj, name); + else if (isNested) hasProperty2 = pathInfo.exists; + else hasProperty2 = hasProperty(obj, name); + if (!negate || arguments.length === 1) { + this.assert( + hasProperty2, + "expected #{this} to have " + descriptor + inspect2(name), + "expected #{this} to not have " + descriptor + inspect2(name) + ); + } + if (arguments.length > 1) { + this.assert( + hasProperty2 && isEql(val, value), + "expected #{this} to have " + descriptor + inspect2(name) + " of #{exp}, but got #{act}", + "expected #{this} to not have " + descriptor + inspect2(name) + " of #{act}", + val, + value + ); + } + flag2(this, "object", value); +} +__name(assertProperty, "assertProperty"); +Assertion.addMethod("property", assertProperty); +function assertOwnProperty(_name, _value, _msg) { + flag2(this, "own", true); + assertProperty.apply(this, arguments); +} +__name(assertOwnProperty, "assertOwnProperty"); +Assertion.addMethod("ownProperty", assertOwnProperty); +Assertion.addMethod("haveOwnProperty", assertOwnProperty); +function assertOwnPropertyDescriptor(name, descriptor, msg) { + if (typeof descriptor === "string") { + msg = descriptor; + descriptor = null; + } + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + let actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); + let eql = flag2(this, "eql"); + if (actualDescriptor && descriptor) { + this.assert( + eql(descriptor, actualDescriptor), + "expected the own property descriptor for " + inspect2(name) + " on #{this} to match " + inspect2(descriptor) + ", got " + inspect2(actualDescriptor), + "expected the own property descriptor for " + inspect2(name) + " on #{this} to not match " + inspect2(descriptor), + descriptor, + actualDescriptor, + true + ); + } else { + this.assert( + actualDescriptor, + "expected #{this} to have an own property descriptor for " + inspect2(name), + "expected #{this} to not have an own property descriptor for " + inspect2(name) + ); + } + flag2(this, "object", actualDescriptor); +} +__name(assertOwnPropertyDescriptor, "assertOwnPropertyDescriptor"); +Assertion.addMethod("ownPropertyDescriptor", assertOwnPropertyDescriptor); +Assertion.addMethod("haveOwnPropertyDescriptor", assertOwnPropertyDescriptor); +function assertLengthChain() { + flag2(this, "doLength", true); +} +__name(assertLengthChain, "assertLengthChain"); +function assertLength(n, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), objType = type(obj).toLowerCase(), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"), descriptor = "length", itemsCount; + switch (objType) { + case "map": + case "set": + descriptor = "size"; + itemsCount = obj.size; + break; + default: + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + itemsCount = obj.length; + } + this.assert( + itemsCount == n, + "expected #{this} to have a " + descriptor + " of #{exp} but got #{act}", + "expected #{this} to not have a " + descriptor + " of #{act}", + n, + itemsCount + ); +} +__name(assertLength, "assertLength"); +Assertion.addChainableMethod("length", assertLength, assertLengthChain); +Assertion.addChainableMethod("lengthOf", assertLength, assertLengthChain); +function assertMatch(re, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + this.assert( + re.exec(obj), + "expected #{this} to match " + re, + "expected #{this} not to match " + re + ); +} +__name(assertMatch, "assertMatch"); +Assertion.addMethod("match", assertMatch); +Assertion.addMethod("matches", assertMatch); +Assertion.addMethod("string", function(str, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(obj, flagMsg, ssfi, true).is.a("string"); + this.assert( + ~obj.indexOf(str), + "expected #{this} to contain " + inspect2(str), + "expected #{this} to not contain " + inspect2(str) + ); +}); +function assertKeys(keys) { + let obj = flag2(this, "object"), objType = type(obj), keysType = type(keys), ssfi = flag2(this, "ssfi"), isDeep = flag2(this, "deep"), str, deepStr = "", actual, ok = true, flagMsg = flag2(this, "message"); + flagMsg = flagMsg ? flagMsg + ": " : ""; + let mixedArgsMsg = flagMsg + "when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments"; + if (objType === "Map" || objType === "Set") { + deepStr = isDeep ? "deeply " : ""; + actual = []; + obj.forEach(function(val, key) { + actual.push(key); + }); + if (keysType !== "Array") { + keys = Array.prototype.slice.call(arguments); + } + } else { + actual = getOwnEnumerableProperties(obj); + switch (keysType) { + case "Array": + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, void 0, ssfi); + } + break; + case "Object": + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, void 0, ssfi); + } + keys = Object.keys(keys); + break; + default: + keys = Array.prototype.slice.call(arguments); + } + keys = keys.map(function(val) { + return typeof val === "symbol" ? val : String(val); + }); + } + if (!keys.length) { + throw new AssertionError(flagMsg + "keys required", void 0, ssfi); + } + let len = keys.length, any = flag2(this, "any"), all = flag2(this, "all"), expected = keys, isEql = isDeep ? flag2(this, "eql") : (val1, val2) => val1 === val2; + if (!any && !all) { + all = true; + } + if (any) { + ok = expected.some(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + } + if (all) { + ok = expected.every(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + if (!flag2(this, "contains")) { + ok = ok && keys.length == actual.length; + } + } + if (len > 1) { + keys = keys.map(function(key) { + return inspect2(key); + }); + let last = keys.pop(); + if (all) { + str = keys.join(", ") + ", and " + last; + } + if (any) { + str = keys.join(", ") + ", or " + last; + } + } else { + str = inspect2(keys[0]); + } + str = (len > 1 ? "keys " : "key ") + str; + str = (flag2(this, "contains") ? "contain " : "have ") + str; + this.assert( + ok, + "expected #{this} to " + deepStr + str, + "expected #{this} to not " + deepStr + str, + expected.slice(0).sort(compareByInspect), + actual.sort(compareByInspect), + true + ); +} +__name(assertKeys, "assertKeys"); +Assertion.addMethod("keys", assertKeys); +Assertion.addMethod("key", assertKeys); +function assertThrows(errorLike, errMsgMatcher, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), ssfi = flag2(this, "ssfi"), flagMsg = flag2(this, "message"), negate = flag2(this, "negate") || false; + new Assertion(obj, flagMsg, ssfi, true).is.a("function"); + if (isRegExp2(errorLike) || typeof errorLike === "string") { + errMsgMatcher = errorLike; + errorLike = null; + } + let caughtErr; + let errorWasThrown = false; + try { + obj(); + } catch (err) { + errorWasThrown = true; + caughtErr = err; + } + let everyArgIsUndefined = errorLike === void 0 && errMsgMatcher === void 0; + let everyArgIsDefined = Boolean(errorLike && errMsgMatcher); + let errorLikeFail = false; + let errMsgMatcherFail = false; + if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { + let errorLikeString = "an error"; + if (errorLike instanceof Error) { + errorLikeString = "#{exp}"; + } else if (errorLike) { + errorLikeString = check_error_exports.getConstructorName(errorLike); + } + let actual = caughtErr; + if (caughtErr instanceof Error) { + actual = caughtErr.toString(); + } else if (typeof caughtErr === "string") { + actual = caughtErr; + } else if (caughtErr && (typeof caughtErr === "object" || typeof caughtErr === "function")) { + try { + actual = check_error_exports.getConstructorName(caughtErr); + } catch (_err) { + } + } + this.assert( + errorWasThrown, + "expected #{this} to throw " + errorLikeString, + "expected #{this} to not throw an error but #{act} was thrown", + errorLike && errorLike.toString(), + actual + ); + } + if (errorLike && caughtErr) { + if (errorLike instanceof Error) { + let isCompatibleInstance = check_error_exports.compatibleInstance( + caughtErr, + errorLike + ); + if (isCompatibleInstance === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate, + "expected #{this} to throw #{exp} but #{act} was thrown", + "expected #{this} to not throw #{exp}" + (caughtErr && !negate ? " but #{act} was thrown" : ""), + errorLike.toString(), + caughtErr.toString() + ); + } + } + } + let isCompatibleConstructor = check_error_exports.compatibleConstructor( + caughtErr, + errorLike + ); + if (isCompatibleConstructor === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate, + "expected #{this} to throw #{exp} but #{act} was thrown", + "expected #{this} to not throw #{exp}" + (caughtErr ? " but #{act} was thrown" : ""), + errorLike instanceof Error ? errorLike.toString() : errorLike && check_error_exports.getConstructorName(errorLike), + caughtErr instanceof Error ? caughtErr.toString() : caughtErr && check_error_exports.getConstructorName(caughtErr) + ); + } + } + } + if (caughtErr && errMsgMatcher !== void 0 && errMsgMatcher !== null) { + let placeholder = "including"; + if (isRegExp2(errMsgMatcher)) { + placeholder = "matching"; + } + let isCompatibleMessage = check_error_exports.compatibleMessage( + caughtErr, + errMsgMatcher + ); + if (isCompatibleMessage === negate) { + if (everyArgIsDefined && negate) { + errMsgMatcherFail = true; + } else { + this.assert( + negate, + "expected #{this} to throw error " + placeholder + " #{exp} but got #{act}", + "expected #{this} to throw error not " + placeholder + " #{exp}", + errMsgMatcher, + check_error_exports.getMessage(caughtErr) + ); + } + } + } + if (errorLikeFail && errMsgMatcherFail) { + this.assert( + negate, + "expected #{this} to throw #{exp} but #{act} was thrown", + "expected #{this} to not throw #{exp}" + (caughtErr ? " but #{act} was thrown" : ""), + errorLike instanceof Error ? errorLike.toString() : errorLike && check_error_exports.getConstructorName(errorLike), + caughtErr instanceof Error ? caughtErr.toString() : caughtErr && check_error_exports.getConstructorName(caughtErr) + ); + } + flag2(this, "object", caughtErr); +} +__name(assertThrows, "assertThrows"); +Assertion.addMethod("throw", assertThrows); +Assertion.addMethod("throws", assertThrows); +Assertion.addMethod("Throw", assertThrows); +function respondTo(method, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), itself = flag2(this, "itself"), context = "function" === typeof obj && !itself ? obj.prototype[method] : obj[method]; + this.assert( + "function" === typeof context, + "expected #{this} to respond to " + inspect2(method), + "expected #{this} to not respond to " + inspect2(method) + ); +} +__name(respondTo, "respondTo"); +Assertion.addMethod("respondTo", respondTo); +Assertion.addMethod("respondsTo", respondTo); +Assertion.addProperty("itself", function() { + flag2(this, "itself", true); +}); +function satisfy(matcher, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + let result = matcher(obj); + this.assert( + result, + "expected #{this} to satisfy " + objDisplay(matcher), + "expected #{this} to not satisfy" + objDisplay(matcher), + flag2(this, "negate") ? false : true, + result + ); +} +__name(satisfy, "satisfy"); +Assertion.addMethod("satisfy", satisfy); +Assertion.addMethod("satisfies", satisfy); +function closeTo(expected, delta, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(obj, flagMsg, ssfi, true).is.numeric; + let message = "A `delta` value is required for `closeTo`"; + if (delta == void 0) { + throw new AssertionError( + flagMsg ? `${flagMsg}: ${message}` : message, + void 0, + ssfi + ); + } + new Assertion(delta, flagMsg, ssfi, true).is.numeric; + message = "A `expected` value is required for `closeTo`"; + if (expected == void 0) { + throw new AssertionError( + flagMsg ? `${flagMsg}: ${message}` : message, + void 0, + ssfi + ); + } + new Assertion(expected, flagMsg, ssfi, true).is.numeric; + const abs = /* @__PURE__ */ __name((x) => x < 0 ? -x : x, "abs"); + const strip = /* @__PURE__ */ __name((number) => parseFloat(parseFloat(number).toPrecision(12)), "strip"); + this.assert( + strip(abs(obj - expected)) <= delta, + "expected #{this} to be close to " + expected + " +/- " + delta, + "expected #{this} not to be close to " + expected + " +/- " + delta + ); +} +__name(closeTo, "closeTo"); +Assertion.addMethod("closeTo", closeTo); +Assertion.addMethod("approximately", closeTo); +function isSubsetOf(_subset, _superset, cmp, contains, ordered) { + let superset = Array.from(_superset); + let subset = Array.from(_subset); + if (!contains) { + if (subset.length !== superset.length) return false; + superset = superset.slice(); + } + return subset.every(function(elem, idx) { + if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; + if (!cmp) { + let matchIdx = superset.indexOf(elem); + if (matchIdx === -1) return false; + if (!contains) superset.splice(matchIdx, 1); + return true; + } + return superset.some(function(elem2, matchIdx) { + if (!cmp(elem, elem2)) return false; + if (!contains) superset.splice(matchIdx, 1); + return true; + }); + }); +} +__name(isSubsetOf, "isSubsetOf"); +Assertion.addMethod("members", function(subset, msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(obj, flagMsg, ssfi, true).to.be.iterable; + new Assertion(subset, flagMsg, ssfi, true).to.be.iterable; + let contains = flag2(this, "contains"); + let ordered = flag2(this, "ordered"); + let subject, failMsg, failNegateMsg; + if (contains) { + subject = ordered ? "an ordered superset" : "a superset"; + failMsg = "expected #{this} to be " + subject + " of #{exp}"; + failNegateMsg = "expected #{this} to not be " + subject + " of #{exp}"; + } else { + subject = ordered ? "ordered members" : "members"; + failMsg = "expected #{this} to have the same " + subject + " as #{exp}"; + failNegateMsg = "expected #{this} to not have the same " + subject + " as #{exp}"; + } + let cmp = flag2(this, "deep") ? flag2(this, "eql") : void 0; + this.assert( + isSubsetOf(subset, obj, cmp, contains, ordered), + failMsg, + failNegateMsg, + subset, + obj, + true + ); +}); +Assertion.addProperty("iterable", function(msg) { + if (msg) flag2(this, "message", msg); + let obj = flag2(this, "object"); + this.assert( + obj != void 0 && obj[Symbol.iterator], + "expected #{this} to be an iterable", + "expected #{this} to not be an iterable", + obj + ); +}); +function oneOf(list, msg) { + if (msg) flag2(this, "message", msg); + let expected = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"), contains = flag2(this, "contains"), isDeep = flag2(this, "deep"), eql = flag2(this, "eql"); + new Assertion(list, flagMsg, ssfi, true).to.be.an("array"); + if (contains) { + this.assert( + list.some(function(possibility) { + return expected.indexOf(possibility) > -1; + }), + "expected #{this} to contain one of #{exp}", + "expected #{this} to not contain one of #{exp}", + list, + expected + ); + } else { + if (isDeep) { + this.assert( + list.some(function(possibility) { + return eql(expected, possibility); + }), + "expected #{this} to deeply equal one of #{exp}", + "expected #{this} to deeply equal one of #{exp}", + list, + expected + ); + } else { + this.assert( + list.indexOf(expected) > -1, + "expected #{this} to be one of #{exp}", + "expected #{this} to not be one of #{exp}", + list, + expected + ); + } + } +} +__name(oneOf, "oneOf"); +Assertion.addMethod("oneOf", oneOf); +function assertChanges(subject, prop, msg) { + if (msg) flag2(this, "message", msg); + let fn = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(fn, flagMsg, ssfi, true).is.a("function"); + let initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a("function"); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + fn(); + let final = prop === void 0 || prop === null ? subject() : subject[prop]; + let msgObj = prop === void 0 || prop === null ? initial : "." + prop; + flag2(this, "deltaMsgObj", msgObj); + flag2(this, "initialDeltaValue", initial); + flag2(this, "finalDeltaValue", final); + flag2(this, "deltaBehavior", "change"); + flag2(this, "realDelta", final !== initial); + this.assert( + initial !== final, + "expected " + msgObj + " to change", + "expected " + msgObj + " to not change" + ); +} +__name(assertChanges, "assertChanges"); +Assertion.addMethod("change", assertChanges); +Assertion.addMethod("changes", assertChanges); +function assertIncreases(subject, prop, msg) { + if (msg) flag2(this, "message", msg); + let fn = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(fn, flagMsg, ssfi, true).is.a("function"); + let initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a("function"); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + new Assertion(initial, flagMsg, ssfi, true).is.a("number"); + fn(); + let final = prop === void 0 || prop === null ? subject() : subject[prop]; + let msgObj = prop === void 0 || prop === null ? initial : "." + prop; + flag2(this, "deltaMsgObj", msgObj); + flag2(this, "initialDeltaValue", initial); + flag2(this, "finalDeltaValue", final); + flag2(this, "deltaBehavior", "increase"); + flag2(this, "realDelta", final - initial); + this.assert( + final - initial > 0, + "expected " + msgObj + " to increase", + "expected " + msgObj + " to not increase" + ); +} +__name(assertIncreases, "assertIncreases"); +Assertion.addMethod("increase", assertIncreases); +Assertion.addMethod("increases", assertIncreases); +function assertDecreases(subject, prop, msg) { + if (msg) flag2(this, "message", msg); + let fn = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(fn, flagMsg, ssfi, true).is.a("function"); + let initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a("function"); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + new Assertion(initial, flagMsg, ssfi, true).is.a("number"); + fn(); + let final = prop === void 0 || prop === null ? subject() : subject[prop]; + let msgObj = prop === void 0 || prop === null ? initial : "." + prop; + flag2(this, "deltaMsgObj", msgObj); + flag2(this, "initialDeltaValue", initial); + flag2(this, "finalDeltaValue", final); + flag2(this, "deltaBehavior", "decrease"); + flag2(this, "realDelta", initial - final); + this.assert( + final - initial < 0, + "expected " + msgObj + " to decrease", + "expected " + msgObj + " to not decrease" + ); +} +__name(assertDecreases, "assertDecreases"); +Assertion.addMethod("decrease", assertDecreases); +Assertion.addMethod("decreases", assertDecreases); +function assertDelta(delta, msg) { + if (msg) flag2(this, "message", msg); + let msgObj = flag2(this, "deltaMsgObj"); + let initial = flag2(this, "initialDeltaValue"); + let final = flag2(this, "finalDeltaValue"); + let behavior = flag2(this, "deltaBehavior"); + let realDelta = flag2(this, "realDelta"); + let expression; + if (behavior === "change") { + expression = Math.abs(final - initial) === Math.abs(delta); + } else { + expression = realDelta === Math.abs(delta); + } + this.assert( + expression, + "expected " + msgObj + " to " + behavior + " by " + delta, + "expected " + msgObj + " to not " + behavior + " by " + delta + ); +} +__name(assertDelta, "assertDelta"); +Assertion.addMethod("by", assertDelta); +Assertion.addProperty("extensible", function() { + let obj = flag2(this, "object"); + let isExtensible = obj === Object(obj) && Object.isExtensible(obj); + this.assert( + isExtensible, + "expected #{this} to be extensible", + "expected #{this} to not be extensible" + ); +}); +Assertion.addProperty("sealed", function() { + let obj = flag2(this, "object"); + let isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; + this.assert( + isSealed, + "expected #{this} to be sealed", + "expected #{this} to not be sealed" + ); +}); +Assertion.addProperty("frozen", function() { + let obj = flag2(this, "object"); + let isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; + this.assert( + isFrozen, + "expected #{this} to be frozen", + "expected #{this} to not be frozen" + ); +}); +Assertion.addProperty("finite", function(_msg) { + let obj = flag2(this, "object"); + this.assert( + typeof obj === "number" && isFinite(obj), + "expected #{this} to be a finite number", + "expected #{this} to not be a finite number" + ); +}); +function compareSubset(expected, actual) { + if (expected === actual) { + return true; + } + if (typeof actual !== typeof expected) { + return false; + } + if (typeof expected !== "object" || expected === null) { + return expected === actual; + } + if (!actual) { + return false; + } + if (Array.isArray(expected)) { + if (!Array.isArray(actual)) { + return false; + } + return expected.every(function(exp) { + return actual.some(function(act) { + return compareSubset(exp, act); + }); + }); + } + if (expected instanceof Date) { + if (actual instanceof Date) { + return expected.getTime() === actual.getTime(); + } else { + return false; + } + } + return Object.keys(expected).every(function(key) { + let expectedValue = expected[key]; + let actualValue = actual[key]; + if (typeof expectedValue === "object" && expectedValue !== null && actualValue !== null) { + return compareSubset(expectedValue, actualValue); + } + if (typeof expectedValue === "function") { + return expectedValue(actualValue); + } + return actualValue === expectedValue; + }); +} +__name(compareSubset, "compareSubset"); +Assertion.addMethod("containSubset", function(expected) { + const actual = flag(this, "object"); + const showDiff = config.showDiff; + this.assert( + compareSubset(expected, actual), + "expected #{act} to contain subset #{exp}", + "expected #{act} to not contain subset #{exp}", + expected, + actual, + showDiff + ); +}); + +// lib/chai/interface/expect.js +function expect(val, message) { + return new Assertion(val, message); +} +__name(expect, "expect"); +expect.fail = function(actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = void 0; + } + message = message || "expect.fail()"; + throw new AssertionError( + message, + { + actual, + expected, + operator + }, + expect.fail + ); +}; + +// lib/chai/interface/should.js +var should_exports = {}; +__export(should_exports, { + Should: () => Should, + should: () => should +}); +function loadShould() { + function shouldGetter() { + if (this instanceof String || this instanceof Number || this instanceof Boolean || typeof Symbol === "function" && this instanceof Symbol || typeof BigInt === "function" && this instanceof BigInt) { + return new Assertion(this.valueOf(), null, shouldGetter); + } + return new Assertion(this, null, shouldGetter); + } + __name(shouldGetter, "shouldGetter"); + function shouldSetter(value) { + Object.defineProperty(this, "should", { + value, + enumerable: true, + configurable: true, + writable: true + }); + } + __name(shouldSetter, "shouldSetter"); + Object.defineProperty(Object.prototype, "should", { + set: shouldSetter, + get: shouldGetter, + configurable: true + }); + let should2 = {}; + should2.fail = function(actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = void 0; + } + message = message || "should.fail()"; + throw new AssertionError( + message, + { + actual, + expected, + operator + }, + should2.fail + ); + }; + should2.equal = function(actual, expected, message) { + new Assertion(actual, message).to.equal(expected); + }; + should2.Throw = function(fn, errt, errs, msg) { + new Assertion(fn, msg).to.Throw(errt, errs); + }; + should2.exist = function(val, msg) { + new Assertion(val, msg).to.exist; + }; + should2.not = {}; + should2.not.equal = function(actual, expected, msg) { + new Assertion(actual, msg).to.not.equal(expected); + }; + should2.not.Throw = function(fn, errt, errs, msg) { + new Assertion(fn, msg).to.not.Throw(errt, errs); + }; + should2.not.exist = function(val, msg) { + new Assertion(val, msg).to.not.exist; + }; + should2["throw"] = should2["Throw"]; + should2.not["throw"] = should2.not["Throw"]; + return should2; +} +__name(loadShould, "loadShould"); +var should = loadShould; +var Should = loadShould; + +// lib/chai/interface/assert.js +function assert(express, errmsg) { + let test2 = new Assertion(null, null, assert, true); + test2.assert(express, errmsg, "[ negation message unavailable ]"); +} +__name(assert, "assert"); +assert.fail = function(actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = void 0; + } + message = message || "assert.fail()"; + throw new AssertionError( + message, + { + actual, + expected, + operator + }, + assert.fail + ); +}; +assert.isOk = function(val, msg) { + new Assertion(val, msg, assert.isOk, true).is.ok; +}; +assert.isNotOk = function(val, msg) { + new Assertion(val, msg, assert.isNotOk, true).is.not.ok; +}; +assert.equal = function(act, exp, msg) { + let test2 = new Assertion(act, msg, assert.equal, true); + test2.assert( + exp == flag(test2, "object"), + "expected #{this} to equal #{exp}", + "expected #{this} to not equal #{act}", + exp, + act, + true + ); +}; +assert.notEqual = function(act, exp, msg) { + let test2 = new Assertion(act, msg, assert.notEqual, true); + test2.assert( + exp != flag(test2, "object"), + "expected #{this} to not equal #{exp}", + "expected #{this} to equal #{act}", + exp, + act, + true + ); +}; +assert.strictEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); +}; +assert.notStrictEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); +}; +assert.deepEqual = assert.deepStrictEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); +}; +assert.notDeepEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); +}; +assert.isAbove = function(val, abv, msg) { + new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); +}; +assert.isAtLeast = function(val, atlst, msg) { + new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); +}; +assert.isBelow = function(val, blw, msg) { + new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); +}; +assert.isAtMost = function(val, atmst, msg) { + new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); +}; +assert.isTrue = function(val, msg) { + new Assertion(val, msg, assert.isTrue, true).is["true"]; +}; +assert.isNotTrue = function(val, msg) { + new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); +}; +assert.isFalse = function(val, msg) { + new Assertion(val, msg, assert.isFalse, true).is["false"]; +}; +assert.isNotFalse = function(val, msg) { + new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); +}; +assert.isNull = function(val, msg) { + new Assertion(val, msg, assert.isNull, true).to.equal(null); +}; +assert.isNotNull = function(val, msg) { + new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); +}; +assert.isNaN = function(val, msg) { + new Assertion(val, msg, assert.isNaN, true).to.be.NaN; +}; +assert.isNotNaN = function(value, message) { + new Assertion(value, message, assert.isNotNaN, true).not.to.be.NaN; +}; +assert.exists = function(val, msg) { + new Assertion(val, msg, assert.exists, true).to.exist; +}; +assert.notExists = function(val, msg) { + new Assertion(val, msg, assert.notExists, true).to.not.exist; +}; +assert.isUndefined = function(val, msg) { + new Assertion(val, msg, assert.isUndefined, true).to.equal(void 0); +}; +assert.isDefined = function(val, msg) { + new Assertion(val, msg, assert.isDefined, true).to.not.equal(void 0); +}; +assert.isCallable = function(value, message) { + new Assertion(value, message, assert.isCallable, true).is.callable; +}; +assert.isNotCallable = function(value, message) { + new Assertion(value, message, assert.isNotCallable, true).is.not.callable; +}; +assert.isObject = function(val, msg) { + new Assertion(val, msg, assert.isObject, true).to.be.a("object"); +}; +assert.isNotObject = function(val, msg) { + new Assertion(val, msg, assert.isNotObject, true).to.not.be.a("object"); +}; +assert.isArray = function(val, msg) { + new Assertion(val, msg, assert.isArray, true).to.be.an("array"); +}; +assert.isNotArray = function(val, msg) { + new Assertion(val, msg, assert.isNotArray, true).to.not.be.an("array"); +}; +assert.isString = function(val, msg) { + new Assertion(val, msg, assert.isString, true).to.be.a("string"); +}; +assert.isNotString = function(val, msg) { + new Assertion(val, msg, assert.isNotString, true).to.not.be.a("string"); +}; +assert.isNumber = function(val, msg) { + new Assertion(val, msg, assert.isNumber, true).to.be.a("number"); +}; +assert.isNotNumber = function(val, msg) { + new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a("number"); +}; +assert.isNumeric = function(val, msg) { + new Assertion(val, msg, assert.isNumeric, true).is.numeric; +}; +assert.isNotNumeric = function(val, msg) { + new Assertion(val, msg, assert.isNotNumeric, true).is.not.numeric; +}; +assert.isFinite = function(val, msg) { + new Assertion(val, msg, assert.isFinite, true).to.be.finite; +}; +assert.isBoolean = function(val, msg) { + new Assertion(val, msg, assert.isBoolean, true).to.be.a("boolean"); +}; +assert.isNotBoolean = function(val, msg) { + new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a("boolean"); +}; +assert.typeOf = function(val, type3, msg) { + new Assertion(val, msg, assert.typeOf, true).to.be.a(type3); +}; +assert.notTypeOf = function(value, type3, message) { + new Assertion(value, message, assert.notTypeOf, true).to.not.be.a(type3); +}; +assert.instanceOf = function(val, type3, msg) { + new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type3); +}; +assert.notInstanceOf = function(val, type3, msg) { + new Assertion(val, msg, assert.notInstanceOf, true).to.not.be.instanceOf( + type3 + ); +}; +assert.include = function(exp, inc, msg) { + new Assertion(exp, msg, assert.include, true).include(inc); +}; +assert.notInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notInclude, true).not.include(inc); +}; +assert.deepInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); +}; +assert.notDeepInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); +}; +assert.nestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); +}; +assert.notNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notNestedInclude, true).not.nested.include( + inc + ); +}; +assert.deepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepNestedInclude, true).deep.nested.include( + inc + ); +}; +assert.notDeepNestedInclude = function(exp, inc, msg) { + new Assertion( + exp, + msg, + assert.notDeepNestedInclude, + true + ).not.deep.nested.include(inc); +}; +assert.ownInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); +}; +assert.notOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); +}; +assert.deepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepOwnInclude, true).deep.own.include(inc); +}; +assert.notDeepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepOwnInclude, true).not.deep.own.include( + inc + ); +}; +assert.match = function(exp, re, msg) { + new Assertion(exp, msg, assert.match, true).to.match(re); +}; +assert.notMatch = function(exp, re, msg) { + new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); +}; +assert.property = function(obj, prop, msg) { + new Assertion(obj, msg, assert.property, true).to.have.property(prop); +}; +assert.notProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.notProperty, true).to.not.have.property(prop); +}; +assert.propertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.propertyVal, true).to.have.property(prop, val); +}; +assert.notPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.notPropertyVal, true).to.not.have.property( + prop, + val + ); +}; +assert.deepPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepPropertyVal, true).to.have.deep.property( + prop, + val + ); +}; +assert.notDeepPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.notDeepPropertyVal, + true + ).to.not.have.deep.property(prop, val); +}; +assert.ownProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.ownProperty, true).to.have.own.property(prop); +}; +assert.notOwnProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.notOwnProperty, true).to.not.have.own.property( + prop + ); +}; +assert.ownPropertyVal = function(obj, prop, value, msg) { + new Assertion(obj, msg, assert.ownPropertyVal, true).to.have.own.property( + prop, + value + ); +}; +assert.notOwnPropertyVal = function(obj, prop, value, msg) { + new Assertion( + obj, + msg, + assert.notOwnPropertyVal, + true + ).to.not.have.own.property(prop, value); +}; +assert.deepOwnPropertyVal = function(obj, prop, value, msg) { + new Assertion( + obj, + msg, + assert.deepOwnPropertyVal, + true + ).to.have.deep.own.property(prop, value); +}; +assert.notDeepOwnPropertyVal = function(obj, prop, value, msg) { + new Assertion( + obj, + msg, + assert.notDeepOwnPropertyVal, + true + ).to.not.have.deep.own.property(prop, value); +}; +assert.nestedProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.nestedProperty, true).to.have.nested.property( + prop + ); +}; +assert.notNestedProperty = function(obj, prop, msg) { + new Assertion( + obj, + msg, + assert.notNestedProperty, + true + ).to.not.have.nested.property(prop); +}; +assert.nestedPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.nestedPropertyVal, + true + ).to.have.nested.property(prop, val); +}; +assert.notNestedPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.notNestedPropertyVal, + true + ).to.not.have.nested.property(prop, val); +}; +assert.deepNestedPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.deepNestedPropertyVal, + true + ).to.have.deep.nested.property(prop, val); +}; +assert.notDeepNestedPropertyVal = function(obj, prop, val, msg) { + new Assertion( + obj, + msg, + assert.notDeepNestedPropertyVal, + true + ).to.not.have.deep.nested.property(prop, val); +}; +assert.lengthOf = function(exp, len, msg) { + new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); +}; +assert.hasAnyKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); +}; +assert.hasAllKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); +}; +assert.containsAllKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllKeys, true).to.contain.all.keys( + keys + ); +}; +assert.doesNotHaveAnyKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true).to.not.have.any.keys( + keys + ); +}; +assert.doesNotHaveAllKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllKeys, true).to.not.have.all.keys( + keys + ); +}; +assert.hasAnyDeepKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyDeepKeys, true).to.have.any.deep.keys( + keys + ); +}; +assert.hasAllDeepKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllDeepKeys, true).to.have.all.deep.keys( + keys + ); +}; +assert.containsAllDeepKeys = function(obj, keys, msg) { + new Assertion( + obj, + msg, + assert.containsAllDeepKeys, + true + ).to.contain.all.deep.keys(keys); +}; +assert.doesNotHaveAnyDeepKeys = function(obj, keys, msg) { + new Assertion( + obj, + msg, + assert.doesNotHaveAnyDeepKeys, + true + ).to.not.have.any.deep.keys(keys); +}; +assert.doesNotHaveAllDeepKeys = function(obj, keys, msg) { + new Assertion( + obj, + msg, + assert.doesNotHaveAllDeepKeys, + true + ).to.not.have.all.deep.keys(keys); +}; +assert.throws = function(fn, errorLike, errMsgMatcher, msg) { + if ("string" === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + let assertErr = new Assertion(fn, msg, assert.throws, true).to.throw( + errorLike, + errMsgMatcher + ); + return flag(assertErr, "object"); +}; +assert.doesNotThrow = function(fn, errorLike, errMsgMatcher, message) { + if ("string" === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + new Assertion(fn, message, assert.doesNotThrow, true).to.not.throw( + errorLike, + errMsgMatcher + ); +}; +assert.operator = function(val, operator, val2, msg) { + let ok; + switch (operator) { + case "==": + ok = val == val2; + break; + case "===": + ok = val === val2; + break; + case ">": + ok = val > val2; + break; + case ">=": + ok = val >= val2; + break; + case "<": + ok = val < val2; + break; + case "<=": + ok = val <= val2; + break; + case "!=": + ok = val != val2; + break; + case "!==": + ok = val !== val2; + break; + default: + msg = msg ? msg + ": " : msg; + throw new AssertionError( + msg + 'Invalid operator "' + operator + '"', + void 0, + assert.operator + ); + } + let test2 = new Assertion(ok, msg, assert.operator, true); + test2.assert( + true === flag(test2, "object"), + "expected " + inspect2(val) + " to be " + operator + " " + inspect2(val2), + "expected " + inspect2(val) + " to not be " + operator + " " + inspect2(val2) + ); +}; +assert.closeTo = function(act, exp, delta, msg) { + new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); +}; +assert.approximately = function(act, exp, delta, msg) { + new Assertion(act, msg, assert.approximately, true).to.be.approximately( + exp, + delta + ); +}; +assert.sameMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.sameMembers, true).to.have.same.members(set2); +}; +assert.notSameMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.notSameMembers, + true + ).to.not.have.same.members(set2); +}; +assert.sameDeepMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.sameDeepMembers, + true + ).to.have.same.deep.members(set2); +}; +assert.notSameDeepMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.notSameDeepMembers, + true + ).to.not.have.same.deep.members(set2); +}; +assert.sameOrderedMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.sameOrderedMembers, + true + ).to.have.same.ordered.members(set2); +}; +assert.notSameOrderedMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.notSameOrderedMembers, + true + ).to.not.have.same.ordered.members(set2); +}; +assert.sameDeepOrderedMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.sameDeepOrderedMembers, + true + ).to.have.same.deep.ordered.members(set2); +}; +assert.notSameDeepOrderedMembers = function(set1, set2, msg) { + new Assertion( + set1, + msg, + assert.notSameDeepOrderedMembers, + true + ).to.not.have.same.deep.ordered.members(set2); +}; +assert.includeMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.includeMembers, true).to.include.members( + subset + ); +}; +assert.notIncludeMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.notIncludeMembers, + true + ).to.not.include.members(subset); +}; +assert.includeDeepMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.includeDeepMembers, + true + ).to.include.deep.members(subset); +}; +assert.notIncludeDeepMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.notIncludeDeepMembers, + true + ).to.not.include.deep.members(subset); +}; +assert.includeOrderedMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.includeOrderedMembers, + true + ).to.include.ordered.members(subset); +}; +assert.notIncludeOrderedMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.notIncludeOrderedMembers, + true + ).to.not.include.ordered.members(subset); +}; +assert.includeDeepOrderedMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.includeDeepOrderedMembers, + true + ).to.include.deep.ordered.members(subset); +}; +assert.notIncludeDeepOrderedMembers = function(superset, subset, msg) { + new Assertion( + superset, + msg, + assert.notIncludeDeepOrderedMembers, + true + ).to.not.include.deep.ordered.members(subset); +}; +assert.oneOf = function(inList, list, msg) { + new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); +}; +assert.isIterable = function(obj, msg) { + if (obj == void 0 || !obj[Symbol.iterator]) { + msg = msg ? `${msg} expected ${inspect2(obj)} to be an iterable` : `expected ${inspect2(obj)} to be an iterable`; + throw new AssertionError(msg, void 0, assert.isIterable); + } +}; +assert.changes = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); +}; +assert.changesBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.changesBy, true).to.change(obj, prop).by(delta); +}; +assert.doesNotChange = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotChange, true).to.not.change( + obj, + prop + ); +}; +assert.changesButNotBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.changesButNotBy, true).to.change(obj, prop).but.not.by(delta); +}; +assert.increases = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.increases, true).to.increase(obj, prop); +}; +assert.increasesBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.increasesBy, true).to.increase(obj, prop).by(delta); +}; +assert.doesNotIncrease = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotIncrease, true).to.not.increase( + obj, + prop + ); +}; +assert.increasesButNotBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.increasesButNotBy, true).to.increase(obj, prop).but.not.by(delta); +}; +assert.decreases = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.decreases, true).to.decrease(obj, prop); +}; +assert.decreasesBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.decreasesBy, true).to.decrease(obj, prop).by(delta); +}; +assert.doesNotDecrease = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotDecrease, true).to.not.decrease( + obj, + prop + ); +}; +assert.doesNotDecreaseBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotDecreaseBy, true).to.not.decrease(obj, prop).by(delta); +}; +assert.decreasesButNotBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + let tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.decreasesButNotBy, true).to.decrease(obj, prop).but.not.by(delta); +}; +assert.ifError = function(val) { + if (val) { + throw val; + } +}; +assert.isExtensible = function(obj, msg) { + new Assertion(obj, msg, assert.isExtensible, true).to.be.extensible; +}; +assert.isNotExtensible = function(obj, msg) { + new Assertion(obj, msg, assert.isNotExtensible, true).to.not.be.extensible; +}; +assert.isSealed = function(obj, msg) { + new Assertion(obj, msg, assert.isSealed, true).to.be.sealed; +}; +assert.isNotSealed = function(obj, msg) { + new Assertion(obj, msg, assert.isNotSealed, true).to.not.be.sealed; +}; +assert.isFrozen = function(obj, msg) { + new Assertion(obj, msg, assert.isFrozen, true).to.be.frozen; +}; +assert.isNotFrozen = function(obj, msg) { + new Assertion(obj, msg, assert.isNotFrozen, true).to.not.be.frozen; +}; +assert.isEmpty = function(val, msg) { + new Assertion(val, msg, assert.isEmpty, true).to.be.empty; +}; +assert.isNotEmpty = function(val, msg) { + new Assertion(val, msg, assert.isNotEmpty, true).to.not.be.empty; +}; +assert.containsSubset = function(val, exp, msg) { + new Assertion(val, msg).to.containSubset(exp); +}; +assert.doesNotContainSubset = function(val, exp, msg) { + new Assertion(val, msg).to.not.containSubset(exp); +}; +var aliases = [ + ["isOk", "ok"], + ["isNotOk", "notOk"], + ["throws", "throw"], + ["throws", "Throw"], + ["isExtensible", "extensible"], + ["isNotExtensible", "notExtensible"], + ["isSealed", "sealed"], + ["isNotSealed", "notSealed"], + ["isFrozen", "frozen"], + ["isNotFrozen", "notFrozen"], + ["isEmpty", "empty"], + ["isNotEmpty", "notEmpty"], + ["isCallable", "isFunction"], + ["isNotCallable", "isNotFunction"], + ["containsSubset", "containSubset"] +]; +for (const [name, as] of aliases) { + assert[as] = assert[name]; +} + +// lib/chai.js +var used = []; +function use(fn) { + const exports = { + use, + AssertionError, + util: utils_exports, + config, + expect, + assert, + Assertion, + ...should_exports + }; + if (!~used.indexOf(fn)) { + fn(exports, utils_exports); + used.push(fn); + } + return exports; +} +__name(use, "use"); +export { + Assertion, + AssertionError, + Should, + assert, + config, + expect, + should, + use, + utils_exports as util +}; diff --git a/vanilla/node_modules/chai/package.json b/vanilla/node_modules/chai/package.json new file mode 100644 index 0000000..f2ad34b --- /dev/null +++ b/vanilla/node_modules/chai/package.json @@ -0,0 +1,71 @@ +{ + "author": "Jake Luer ", + "name": "chai", + "type": "module", + "description": "BDD/TDD assertion library for node.js and the browser. Test framework agnostic.", + "keywords": [ + "test", + "assertion", + "assert", + "testing", + "chai" + ], + "files": [ + "index.js", + "register-*.js" + ], + "homepage": "http://chaijs.com", + "license": "MIT", + "contributors": [ + "Jake Luer ", + "Domenic Denicola (http://domenicdenicola.com)", + "Veselin Todorov ", + "John Firebaugh " + ], + "version": "6.2.2", + "repository": { + "type": "git", + "url": "https://github.com/chaijs/chai" + }, + "bugs": { + "url": "https://github.com/chaijs/chai/issues" + }, + "main": "./index.js", + "scripts": { + "build": "esbuild --bundle --format=esm --target=es2021 --keep-names --legal-comments=none --outfile=index.js lib/chai.js", + "prebuild": "npm run clean", + "format": "prettier --write lib", + "pretest": "npm run lint", + "test": "npm run test-node && npm run test-chrome", + "test-node": "c8 --99 --check-coverage mocha --require ./test/bootstrap/index.js test/*.js", + "test-chrome": "web-test-runner --playwright", + "lint": "npm run lint:js && npm run lint:format", + "lint:js": "eslint lib/", + "lint:format": "prettier --check lib", + "lint:types": "tsc", + "clean": "rm -rf index.js coverage/" + }, + "engines": { + "node": ">=18" + }, + "devDependencies": { + "@eslint/js": "^9.17.0", + "@rollup/plugin-commonjs": "^29.0.0", + "@web/dev-server-rollup": "^0.6.1", + "@web/test-runner": "^0.20.0", + "@web/test-runner-playwright": "^0.11.0", + "assertion-error": "^2.0.1", + "c8": "^10.1.3", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "esbuild": "^0.27.0", + "eslint": "^9.0.0", + "eslint-plugin-jsdoc": "^61.0.0", + "globals": "^16.3.0", + "loupe": "^3.1.0", + "mocha": "^11.0.0", + "pathval": "^2.0.0", + "prettier": "^3.4.2", + "typescript": "~5.9.0" + } +} diff --git a/vanilla/node_modules/chai/register-assert.js b/vanilla/node_modules/chai/register-assert.js new file mode 100644 index 0000000..f593717 --- /dev/null +++ b/vanilla/node_modules/chai/register-assert.js @@ -0,0 +1,3 @@ +import {assert} from './index.js'; + +globalThis.assert = assert; diff --git a/vanilla/node_modules/chai/register-expect.js b/vanilla/node_modules/chai/register-expect.js new file mode 100644 index 0000000..2807b89 --- /dev/null +++ b/vanilla/node_modules/chai/register-expect.js @@ -0,0 +1,3 @@ +import {expect} from './index.js'; + +globalThis.expect = expect; diff --git a/vanilla/node_modules/chai/register-should.js b/vanilla/node_modules/chai/register-should.js new file mode 100644 index 0000000..1339ee4 --- /dev/null +++ b/vanilla/node_modules/chai/register-should.js @@ -0,0 +1,3 @@ +import {should} from './index.js'; + +globalThis.should = should(); diff --git a/vanilla/node_modules/css-tree/LICENSE b/vanilla/node_modules/css-tree/LICENSE new file mode 100644 index 0000000..c627ec0 --- /dev/null +++ b/vanilla/node_modules/css-tree/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2016-2024 by Roman Dvornov + +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/vanilla/node_modules/css-tree/README.md b/vanilla/node_modules/css-tree/README.md new file mode 100644 index 0000000..92e6f15 --- /dev/null +++ b/vanilla/node_modules/css-tree/README.md @@ -0,0 +1,192 @@ +CSSTree logo + +# CSSTree + +[![NPM version](https://img.shields.io/npm/v/css-tree.svg)](https://www.npmjs.com/package/css-tree) +[![Build Status](https://github.com/csstree/csstree/actions/workflows/build.yml/badge.svg)](https://github.com/csstree/csstree/actions/workflows/build.yml) +[![Coverage Status](https://coveralls.io/repos/github/csstree/csstree/badge.svg?branch=master)](https://coveralls.io/github/csstree/csstree?branch=master) +[![NPM Downloads](https://img.shields.io/npm/dm/css-tree.svg)](https://www.npmjs.com/package/css-tree) +[![Twitter](https://img.shields.io/badge/Twitter-@csstree-blue.svg)](https://twitter.com/csstree) + +CSSTree is a tool set for CSS: [fast](https://github.com/postcss/benchmark) detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks. + +## Features + +- **Detailed parsing with an adjustable level of detail** + + By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see [AST format](docs/ast.md) for all possible node types). The parsing detail level can be changed through [parser options](docs/parsing.md#parsesource-options), for example, you can disable parsing of selectors or declaration values for component parts. + +- **Tolerant to errors by design** + + Parser behaves as [spec says](https://www.w3.org/TR/css-syntax-3/#error-handling): "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (`Raw`) that allows processing it later. + +- **Fast and efficient** + + CSSTree is created with focus on performance and effective memory consumption. Therefore it's [one of the fastest CSS parsers](https://github.com/postcss/benchmark) at the moment. + +- **Syntax validation** + + The built-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses [mdn/data](https://github.com/mdn/data/) as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values and at-rules currently, but this feature will be extended to other parts of the CSS in the future. + +## Projects using CSSTree + +- [Svelte](https://github.com/sveltejs/svelte) – Cybernetically enhanced web apps +- [SVGO](https://github.com/svg/svgo) – Node.js tool for optimizing SVG files +- [CSSO](https://github.com/css/csso) – CSS minifier with structural optimizations +- [NativeScript](https://github.com/NativeScript/NativeScript) – NativeScript empowers you to access native APIs from JavaScript directly +- [react-native-svg](https://github.com/react-native-svg/react-native-svg) – SVG library for React Native, React Native Web, and plain React web projects +- [penthouse](https://github.com/pocketjoso/penthouse) – Critical Path CSS Generator +- [Bit](https://github.com/teambit/bit) – Bit is the platform for collaborating on components +- and more... + +## Documentation + +- [AST format](docs/ast.md) +- [Parsing CSS → AST](docs/parsing.md) + - [parse(source[, options])](docs/parsing.md#parsesource-options) +- [Serialization AST → CSS](docs/generate.md) + - [generate(ast[, options])](docs/generate.md#generateast-options) +- [AST traversal](docs/traversal.md) + - [walk(ast, options)](docs/traversal.md#walkast-options) + - [find(ast, fn)](docs/traversal.md#findast-fn) + - [findLast(ast, fn)](docs/traversal.md#findlastast-fn) + - [findAll(ast, fn)](docs/traversal.md#findallast-fn) +- [Util functions](docs/utils.md) + - Value encoding & decoding + - [property(name)](docs/utils.md#propertyname) + - [keyword(name)](docs/utils.md#keywordname) + - [ident](docs/utils.md#ident) + - [string](docs/utils.md#string) + - [url](docs/utils.md#url) + - [List class](docs/list.md) + - AST transforming + - [clone(ast)](docs/utils.md#cloneast) + - [fromPlainObject(object)](docs/utils.md#fromplainobjectobject) + - [toPlainObject(ast)](docs/utils.md#toplainobjectast) +- [Value Definition Syntax](docs/definition-syntax.md) + - [parse(source)](docs/definition-syntax.md#parsesource) + - [walk(node, options, context)](docs/definition-syntax.md#walknode-options-context) + - [generate(node, options)](docs/definition-syntax.md#generatenode-options) + - [AST format](docs/definition-syntax.md#ast-format) + +## Tools + +* [AST Explorer](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8) – explore CSSTree AST format with zero setup +* [CSS syntax reference](https://csstree.github.io/docs/syntax.html) +* [CSS syntax validator](https://csstree.github.io/docs/validator.html) + +## Related projects + +* [csstree-validator](https://github.com/csstree/validator) – NPM package to validate CSS +* [stylelint-csstree-validator](https://github.com/csstree/stylelint-validator) – plugin for stylelint to validate CSS +* [Grunt plugin](https://github.com/sergejmueller/grunt-csstree-validator) +* [Gulp plugin](https://github.com/csstree/gulp-csstree) +* [Sublime plugin](https://github.com/csstree/SublimeLinter-contrib-csstree) +* [VS Code plugin](https://github.com/csstree/vscode-plugin) +* [Atom plugin](https://github.com/csstree/atom-plugin) + +## Usage + +Install with npm: + +``` +npm install css-tree +``` + +Basic usage: + +```js +import * as csstree from 'css-tree'; + +// parse CSS to AST +const ast = csstree.parse('.example { world: "!" }'); + +// traverse AST and modify it +csstree.walk(ast, (node) => { + if (node.type === 'ClassSelector' && node.name === 'example') { + node.name = 'hello'; + } +}); + +// generate CSS from AST +console.log(csstree.generate(ast)); +// .hello{world:"!"} +``` + +Syntax matching: + +```js +// parse CSS to AST as a declaration value +const ast = csstree.parse('red 1px solid', { context: 'value' }); + +// match to syntax of `border` property +const matchResult = csstree.lexer.matchProperty('border', ast); + +// check first value node is a +console.log(matchResult.isType(ast.children.first, 'color')); +// true + +// get a type list matched to a node +console.log(matchResult.getTrace(ast.children.first)); +// [ { type: 'Property', name: 'border' }, +// { type: 'Type', name: 'color' }, +// { type: 'Type', name: 'named-color' }, +// { type: 'Keyword', name: 'red' } ] +``` + +### Exports + +Is it possible to import just a needed part of library like a parser or a walker. That's might useful for loading time or bundle size optimisations. + +```js +import * as tokenizer from 'css-tree/tokenizer'; +import * as parser from 'css-tree/parser'; +import * as walker from 'css-tree/walker'; +import * as lexer from 'css-tree/lexer'; +import * as definitionSyntax from 'css-tree/definition-syntax'; +import * as data from 'css-tree/definition-syntax-data'; +import * as dataPatch from 'css-tree/definition-syntax-data-patch'; +import * as utils from 'css-tree/utils'; +``` + +### Using in a browser + +Bundles are available for use in a browser: + +- `dist/csstree.js` – minified IIFE with `csstree` as global +```html + + +``` + +- `dist/csstree.esm.js` – minified ES module +```html + +``` + +One of CDN services like `unpkg` or `jsDelivr` can be used. By default (for short path) a ESM version is exposing. For IIFE version a full path to a bundle should be specified: + +```html + + + + + + +``` + +## Top level API + +![API map](https://cdn.rawgit.com/csstree/csstree/aaf327e/docs/api-map.svg) + +## License + +MIT diff --git a/vanilla/node_modules/css-tree/cjs/convertor/create.cjs b/vanilla/node_modules/css-tree/cjs/convertor/create.cjs new file mode 100644 index 0000000..55c655b --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/convertor/create.cjs @@ -0,0 +1,32 @@ +'use strict'; + +const List = require('../utils/List.cjs'); + +function createConvertor(walk) { + return { + fromPlainObject(ast) { + walk(ast, { + enter(node) { + if (node.children && node.children instanceof List.List === false) { + node.children = new List.List().fromArray(node.children); + } + } + }); + + return ast; + }, + toPlainObject(ast) { + walk(ast, { + leave(node) { + if (node.children && node.children instanceof List.List) { + node.children = node.children.toArray(); + } + } + }); + + return ast; + } + }; +} + +exports.createConvertor = createConvertor; diff --git a/vanilla/node_modules/css-tree/cjs/convertor/index.cjs b/vanilla/node_modules/css-tree/cjs/convertor/index.cjs new file mode 100644 index 0000000..6654278 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/convertor/index.cjs @@ -0,0 +1,8 @@ +'use strict'; + +const create = require('./create.cjs'); +const index$1 = require('../walker/index.cjs'); + +const index = create.createConvertor(index$1); + +module.exports = index; diff --git a/vanilla/node_modules/css-tree/cjs/data-patch.cjs b/vanilla/node_modules/css-tree/cjs/data-patch.cjs new file mode 100644 index 0000000..9103ea4 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/data-patch.cjs @@ -0,0 +1,7 @@ +'use strict'; + +const patch = require('../data/patch.json'); + +const patch$1 = patch; + +module.exports = patch$1; diff --git a/vanilla/node_modules/css-tree/cjs/data.cjs b/vanilla/node_modules/css-tree/cjs/data.cjs new file mode 100644 index 0000000..258ac6a --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/data.cjs @@ -0,0 +1,120 @@ +'use strict'; + +const dataPatch = require('./data-patch.cjs'); + +const mdnAtrules = require('mdn-data/css/at-rules.json'); +const mdnProperties = require('mdn-data/css/properties.json'); +const mdnSyntaxes = require('mdn-data/css/syntaxes.json'); + +const hasOwn = Object.hasOwn || ((object, property) => Object.prototype.hasOwnProperty.call(object, property)); +const extendSyntax = /^\s*\|\s*/; + +function preprocessAtrules(dict) { + const result = Object.create(null); + + for (const [atruleName, atrule] of Object.entries(dict)) { + let descriptors = null; + + if (atrule.descriptors) { + descriptors = Object.create(null); + + for (const [name, descriptor] of Object.entries(atrule.descriptors)) { + descriptors[name] = descriptor.syntax; + } + } + + result[atruleName.substr(1)] = { + prelude: atrule.syntax.trim().replace(/\{(.|\s)+\}/, '').match(/^@\S+\s+([^;\{]*)/)[1].trim() || null, + descriptors + }; + } + + return result; +} + +function patchDictionary(dict, patchDict) { + const result = Object.create(null); + + // copy all syntaxes for an original dict + for (const [key, value] of Object.entries(dict)) { + if (value) { + result[key] = value.syntax || value; + } + } + + // apply a patch + for (const key of Object.keys(patchDict)) { + if (hasOwn(dict, key)) { + if (patchDict[key].syntax) { + result[key] = extendSyntax.test(patchDict[key].syntax) + ? result[key] + ' ' + patchDict[key].syntax.trim() + : patchDict[key].syntax; + } else { + delete result[key]; + } + } else { + if (patchDict[key].syntax) { + result[key] = patchDict[key].syntax.replace(extendSyntax, ''); + } + } + } + + return result; +} + +function preprocessPatchAtrulesDescritors(declarations) { + const result = {}; + + for (const [key, value] of Object.entries(declarations || {})) { + result[key] = typeof value === 'string' + ? { syntax: value } + : value; + } + + return result; +} + +function patchAtrules(dict, patchDict) { + const result = {}; + + // copy all syntaxes for an original dict + for (const key in dict) { + if (patchDict[key] === null) { + continue; + } + + const atrulePatch = patchDict[key] || {}; + + result[key] = { + prelude: key in patchDict && 'prelude' in atrulePatch + ? atrulePatch.prelude + : dict[key].prelude || null, + descriptors: patchDictionary( + dict[key].descriptors || {}, + preprocessPatchAtrulesDescritors(atrulePatch.descriptors) + ) + }; + } + + // apply a patch + for (const [key, atrulePatch] of Object.entries(patchDict)) { + if (atrulePatch && !hasOwn(dict, key)) { + result[key] = { + prelude: atrulePatch.prelude || null, + descriptors: atrulePatch.descriptors + ? patchDictionary({}, preprocessPatchAtrulesDescritors(atrulePatch.descriptors)) + : null + }; + } + } + + return result; +} + +const definitions = { + types: patchDictionary(mdnSyntaxes, dataPatch.types), + atrules: patchAtrules(preprocessAtrules(mdnAtrules), dataPatch.atrules), + properties: patchDictionary(mdnProperties, dataPatch.properties) +}; + +module.exports = definitions; diff --git a/vanilla/node_modules/css-tree/cjs/definition-syntax/SyntaxError.cjs b/vanilla/node_modules/css-tree/cjs/definition-syntax/SyntaxError.cjs new file mode 100644 index 0000000..d24e7ce --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/definition-syntax/SyntaxError.cjs @@ -0,0 +1,16 @@ +'use strict'; + +const createCustomError = require('../utils/create-custom-error.cjs'); + +function SyntaxError(message, input, offset) { + return Object.assign(createCustomError.createCustomError('SyntaxError', message), { + input, + offset, + rawMessage: message, + message: message + '\n' + + ' ' + input + '\n' + + '--' + new Array((offset || input.length) + 1).join('-') + '^' + }); +} + +exports.SyntaxError = SyntaxError; diff --git a/vanilla/node_modules/css-tree/cjs/definition-syntax/generate.cjs b/vanilla/node_modules/css-tree/cjs/definition-syntax/generate.cjs new file mode 100644 index 0000000..ff9f0ad --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/definition-syntax/generate.cjs @@ -0,0 +1,139 @@ +'use strict'; + +function noop(value) { + return value; +} + +function generateMultiplier(multiplier) { + const { min, max, comma } = multiplier; + + if (min === 0 && max === 0) { + return comma ? '#?' : '*'; + } + + if (min === 0 && max === 1) { + return '?'; + } + + if (min === 1 && max === 0) { + return comma ? '#' : '+'; + } + + if (min === 1 && max === 1) { + return ''; + } + + return ( + (comma ? '#' : '') + + (min === max + ? '{' + min + '}' + : '{' + min + ',' + (max !== 0 ? max : '') + '}' + ) + ); +} + +function generateTypeOpts(node) { + switch (node.type) { + case 'Range': + return ( + ' [' + + (node.min === null ? '-∞' : node.min) + + ',' + + (node.max === null ? '∞' : node.max) + + ']' + ); + + default: + throw new Error('Unknown node type `' + node.type + '`'); + } +} + +function generateSequence(node, decorate, forceBraces, compact) { + const combinator = node.combinator === ' ' || compact ? node.combinator : ' ' + node.combinator + ' '; + const result = node.terms + .map(term => internalGenerate(term, decorate, forceBraces, compact)) + .join(combinator); + + if (node.explicit || forceBraces) { + return (compact || result[0] === ',' ? '[' : '[ ') + result + (compact ? ']' : ' ]'); + } + + return result; +} + +function internalGenerate(node, decorate, forceBraces, compact) { + let result; + + switch (node.type) { + case 'Group': + result = + generateSequence(node, decorate, forceBraces, compact) + + (node.disallowEmpty ? '!' : ''); + break; + + case 'Multiplier': + // return since node is a composition + return ( + internalGenerate(node.term, decorate, forceBraces, compact) + + decorate(generateMultiplier(node), node) + ); + + case 'Boolean': + result = ''; + break; + + case 'Type': + result = '<' + node.name + (node.opts ? decorate(generateTypeOpts(node.opts), node.opts) : '') + '>'; + break; + + case 'Property': + result = '<\'' + node.name + '\'>'; + break; + + case 'Keyword': + result = node.name; + break; + + case 'AtKeyword': + result = '@' + node.name; + break; + + case 'Function': + result = node.name + '('; + break; + + case 'String': + case 'Token': + result = node.value; + break; + + case 'Comma': + result = ','; + break; + + default: + throw new Error('Unknown node type `' + node.type + '`'); + } + + return decorate(result, node); +} + +function generate(node, options) { + let decorate = noop; + let forceBraces = false; + let compact = false; + + if (typeof options === 'function') { + decorate = options; + } else if (options) { + forceBraces = Boolean(options.forceBraces); + compact = Boolean(options.compact); + if (typeof options.decorate === 'function') { + decorate = options.decorate; + } + } + + return internalGenerate(node, decorate, forceBraces, compact); +} + +exports.generate = generate; diff --git a/vanilla/node_modules/css-tree/cjs/definition-syntax/index.cjs b/vanilla/node_modules/css-tree/cjs/definition-syntax/index.cjs new file mode 100644 index 0000000..0afb505 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/definition-syntax/index.cjs @@ -0,0 +1,13 @@ +'use strict'; + +const SyntaxError = require('./SyntaxError.cjs'); +const generate = require('./generate.cjs'); +const parse = require('./parse.cjs'); +const walk = require('./walk.cjs'); + + + +exports.SyntaxError = SyntaxError.SyntaxError; +exports.generate = generate.generate; +exports.parse = parse.parse; +exports.walk = walk.walk; diff --git a/vanilla/node_modules/css-tree/cjs/definition-syntax/parse.cjs b/vanilla/node_modules/css-tree/cjs/definition-syntax/parse.cjs new file mode 100644 index 0000000..b17b267 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/definition-syntax/parse.cjs @@ -0,0 +1,556 @@ +'use strict'; + +const scanner = require('./scanner.cjs'); + +const TAB = 9; +const N = 10; +const F = 12; +const R = 13; +const SPACE = 32; +const EXCLAMATIONMARK = 33; // ! +const NUMBERSIGN = 35; // # +const AMPERSAND = 38; // & +const APOSTROPHE = 39; // ' +const LEFTPARENTHESIS = 40; // ( +const RIGHTPARENTHESIS = 41; // ) +const ASTERISK = 42; // * +const PLUSSIGN = 43; // + +const COMMA = 44; // , +const HYPERMINUS = 45; // - +const LESSTHANSIGN = 60; // < +const GREATERTHANSIGN = 62; // > +const QUESTIONMARK = 63; // ? +const COMMERCIALAT = 64; // @ +const LEFTSQUAREBRACKET = 91; // [ +const RIGHTSQUAREBRACKET = 93; // ] +const LEFTCURLYBRACKET = 123; // { +const VERTICALLINE = 124; // | +const RIGHTCURLYBRACKET = 125; // } +const INFINITY = 8734; // ∞ +const COMBINATOR_PRECEDENCE = { + ' ': 1, + '&&': 2, + '||': 3, + '|': 4 +}; + +function readMultiplierRange(scanner) { + let min = null; + let max = null; + + scanner.eat(LEFTCURLYBRACKET); + scanner.skipWs(); + + min = scanner.scanNumber(scanner); + scanner.skipWs(); + + if (scanner.charCode() === COMMA) { + scanner.pos++; + scanner.skipWs(); + + if (scanner.charCode() !== RIGHTCURLYBRACKET) { + max = scanner.scanNumber(scanner); + scanner.skipWs(); + } + } else { + max = min; + } + + scanner.eat(RIGHTCURLYBRACKET); + + return { + min: Number(min), + max: max ? Number(max) : 0 + }; +} + +function readMultiplier(scanner) { + let range = null; + let comma = false; + + switch (scanner.charCode()) { + case ASTERISK: + scanner.pos++; + + range = { + min: 0, + max: 0 + }; + + break; + + case PLUSSIGN: + scanner.pos++; + + range = { + min: 1, + max: 0 + }; + + break; + + case QUESTIONMARK: + scanner.pos++; + + range = { + min: 0, + max: 1 + }; + + break; + + case NUMBERSIGN: + scanner.pos++; + + comma = true; + + if (scanner.charCode() === LEFTCURLYBRACKET) { + range = readMultiplierRange(scanner); + } else if (scanner.charCode() === QUESTIONMARK) { + // https://www.w3.org/TR/css-values-4/#component-multipliers + // > the # and ? multipliers may be stacked as #? + // In this case just treat "#?" as a single multiplier + // { min: 0, max: 0, comma: true } + scanner.pos++; + range = { + min: 0, + max: 0 + }; + } else { + range = { + min: 1, + max: 0 + }; + } + + break; + + case LEFTCURLYBRACKET: + range = readMultiplierRange(scanner); + break; + + default: + return null; + } + + return { + type: 'Multiplier', + comma, + min: range.min, + max: range.max, + term: null + }; +} + +function maybeMultiplied(scanner, node) { + const multiplier = readMultiplier(scanner); + + if (multiplier !== null) { + multiplier.term = node; + + // https://www.w3.org/TR/css-values-4/#component-multipliers + // > The + and # multipliers may be stacked as +#; + // Represent "+#" as nested multipliers: + // { ..., + // term: { + // ..., + // term: node + // } + // } + if (scanner.charCode() === NUMBERSIGN && + scanner.charCodeAt(scanner.pos - 1) === PLUSSIGN) { + return maybeMultiplied(scanner, multiplier); + } + + return multiplier; + } + + return node; +} + +function maybeToken(scanner) { + const ch = scanner.peek(); + + if (ch === '') { + return null; + } + + return maybeMultiplied(scanner, { + type: 'Token', + value: ch + }); +} + +function readProperty(scanner) { + let name; + + scanner.eat(LESSTHANSIGN); + scanner.eat(APOSTROPHE); + + name = scanner.scanWord(); + + scanner.eat(APOSTROPHE); + scanner.eat(GREATERTHANSIGN); + + return maybeMultiplied(scanner, { + type: 'Property', + name + }); +} + +// https://drafts.csswg.org/css-values-3/#numeric-ranges +// 4.1. Range Restrictions and Range Definition Notation +// +// Range restrictions can be annotated in the numeric type notation using CSS bracketed +// range notation—[min,max]—within the angle brackets, after the identifying keyword, +// indicating a closed range between (and including) min and max. +// For example, indicates an integer between 0 and 10, inclusive. +function readTypeRange(scanner) { + // use null for Infinity to make AST format JSON serializable/deserializable + let min = null; // -Infinity + let max = null; // Infinity + let sign = 1; + + scanner.eat(LEFTSQUAREBRACKET); + + if (scanner.charCode() === HYPERMINUS) { + scanner.peek(); + sign = -1; + } + + if (sign == -1 && scanner.charCode() === INFINITY) { + scanner.peek(); + } else { + min = sign * Number(scanner.scanNumber(scanner)); + + if (scanner.isNameCharCode()) { + min += scanner.scanWord(); + } + } + + scanner.skipWs(); + scanner.eat(COMMA); + scanner.skipWs(); + + if (scanner.charCode() === INFINITY) { + scanner.peek(); + } else { + sign = 1; + + if (scanner.charCode() === HYPERMINUS) { + scanner.peek(); + sign = -1; + } + + max = sign * Number(scanner.scanNumber(scanner)); + + if (scanner.isNameCharCode()) { + max += scanner.scanWord(); + } + } + + scanner.eat(RIGHTSQUAREBRACKET); + + return { + type: 'Range', + min, + max + }; +} + +function readType(scanner) { + let name; + let opts = null; + + scanner.eat(LESSTHANSIGN); + name = scanner.scanWord(); + + // https://drafts.csswg.org/css-values-5/#boolean + if (name === 'boolean-expr') { + scanner.eat(LEFTSQUAREBRACKET); + + const implicitGroup = readImplicitGroup(scanner, RIGHTSQUAREBRACKET); + + scanner.eat(RIGHTSQUAREBRACKET); + scanner.eat(GREATERTHANSIGN); + + return maybeMultiplied(scanner, { + type: 'Boolean', + term: implicitGroup.terms.length === 1 + ? implicitGroup.terms[0] + : implicitGroup + }); + } + + if (scanner.charCode() === LEFTPARENTHESIS && + scanner.nextCharCode() === RIGHTPARENTHESIS) { + scanner.pos += 2; + name += '()'; + } + + if (scanner.charCodeAt(scanner.findWsEnd(scanner.pos)) === LEFTSQUAREBRACKET) { + scanner.skipWs(); + opts = readTypeRange(scanner); + } + + scanner.eat(GREATERTHANSIGN); + + return maybeMultiplied(scanner, { + type: 'Type', + name, + opts + }); +} + +function readKeywordOrFunction(scanner) { + const name = scanner.scanWord(); + + if (scanner.charCode() === LEFTPARENTHESIS) { + scanner.pos++; + + return { + type: 'Function', + name + }; + } + + return maybeMultiplied(scanner, { + type: 'Keyword', + name + }); +} + +function regroupTerms(terms, combinators) { + function createGroup(terms, combinator) { + return { + type: 'Group', + terms, + combinator, + disallowEmpty: false, + explicit: false + }; + } + + let combinator; + + combinators = Object.keys(combinators) + .sort((a, b) => COMBINATOR_PRECEDENCE[a] - COMBINATOR_PRECEDENCE[b]); + + while (combinators.length > 0) { + combinator = combinators.shift(); + + let i = 0; + let subgroupStart = 0; + + for (; i < terms.length; i++) { + const term = terms[i]; + + if (term.type === 'Combinator') { + if (term.value === combinator) { + if (subgroupStart === -1) { + subgroupStart = i - 1; + } + terms.splice(i, 1); + i--; + } else { + if (subgroupStart !== -1 && i - subgroupStart > 1) { + terms.splice( + subgroupStart, + i - subgroupStart, + createGroup(terms.slice(subgroupStart, i), combinator) + ); + i = subgroupStart + 1; + } + subgroupStart = -1; + } + } + } + + if (subgroupStart !== -1 && combinators.length) { + terms.splice( + subgroupStart, + i - subgroupStart, + createGroup(terms.slice(subgroupStart, i), combinator) + ); + } + } + + return combinator; +} + +function readImplicitGroup(scanner, stopCharCode) { + const combinators = Object.create(null); + const terms = []; + let token; + let prevToken = null; + let prevTokenPos = scanner.pos; + + while (scanner.charCode() !== stopCharCode && (token = peek(scanner, stopCharCode))) { + if (token.type !== 'Spaces') { + if (token.type === 'Combinator') { + // check for combinator in group beginning and double combinator sequence + if (prevToken === null || prevToken.type === 'Combinator') { + scanner.pos = prevTokenPos; + scanner.error('Unexpected combinator'); + } + + combinators[token.value] = true; + } else if (prevToken !== null && prevToken.type !== 'Combinator') { + combinators[' '] = true; // a b + terms.push({ + type: 'Combinator', + value: ' ' + }); + } + + terms.push(token); + prevToken = token; + prevTokenPos = scanner.pos; + } + } + + // check for combinator in group ending + if (prevToken !== null && prevToken.type === 'Combinator') { + scanner.pos -= prevTokenPos; + scanner.error('Unexpected combinator'); + } + + return { + type: 'Group', + terms, + combinator: regroupTerms(terms, combinators) || ' ', + disallowEmpty: false, + explicit: false + }; +} + +function readGroup(scanner, stopCharCode) { + let result; + + scanner.eat(LEFTSQUAREBRACKET); + result = readImplicitGroup(scanner, stopCharCode); + scanner.eat(RIGHTSQUAREBRACKET); + + result.explicit = true; + + if (scanner.charCode() === EXCLAMATIONMARK) { + scanner.pos++; + result.disallowEmpty = true; + } + + return result; +} + +function peek(scanner, stopCharCode) { + let code = scanner.charCode(); + + switch (code) { + case RIGHTSQUAREBRACKET: + // don't eat, stop scan a group + break; + + case LEFTSQUAREBRACKET: + return maybeMultiplied(scanner, readGroup(scanner, stopCharCode)); + + case LESSTHANSIGN: + return scanner.nextCharCode() === APOSTROPHE + ? readProperty(scanner) + : readType(scanner); + + case VERTICALLINE: + return { + type: 'Combinator', + value: scanner.substringToPos( + scanner.pos + (scanner.nextCharCode() === VERTICALLINE ? 2 : 1) + ) + }; + + case AMPERSAND: + scanner.pos++; + scanner.eat(AMPERSAND); + + return { + type: 'Combinator', + value: '&&' + }; + + case COMMA: + scanner.pos++; + return { + type: 'Comma' + }; + + case APOSTROPHE: + return maybeMultiplied(scanner, { + type: 'String', + value: scanner.scanString() + }); + + case SPACE: + case TAB: + case N: + case R: + case F: + return { + type: 'Spaces', + value: scanner.scanSpaces() + }; + + case COMMERCIALAT: + code = scanner.nextCharCode(); + + if (scanner.isNameCharCode(code)) { + scanner.pos++; + return { + type: 'AtKeyword', + name: scanner.scanWord() + }; + } + + return maybeToken(scanner); + + case ASTERISK: + case PLUSSIGN: + case QUESTIONMARK: + case NUMBERSIGN: + case EXCLAMATIONMARK: + // prohibited tokens (used as a multiplier start) + break; + + case LEFTCURLYBRACKET: + // LEFTCURLYBRACKET is allowed since mdn/data uses it w/o quoting + // check next char isn't a number, because it's likely a disjoined multiplier + code = scanner.nextCharCode(); + + if (code < 48 || code > 57) { + return maybeToken(scanner); + } + + break; + + default: + if (scanner.isNameCharCode(code)) { + return readKeywordOrFunction(scanner); + } + + return maybeToken(scanner); + } +} + +function parse(source) { + const scanner$1 = new scanner.Scanner(source); + const result = readImplicitGroup(scanner$1); + + if (scanner$1.pos !== source.length) { + scanner$1.error('Unexpected input'); + } + + // reduce redundant groups with single group term + if (result.terms.length === 1 && result.terms[0].type === 'Group') { + return result.terms[0]; + } + + return result; +} + +exports.parse = parse; diff --git a/vanilla/node_modules/css-tree/cjs/definition-syntax/scanner.cjs b/vanilla/node_modules/css-tree/cjs/definition-syntax/scanner.cjs new file mode 100644 index 0000000..0bad36a --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/definition-syntax/scanner.cjs @@ -0,0 +1,113 @@ +'use strict'; + +const SyntaxError = require('./SyntaxError.cjs'); + +const TAB = 9; +const N = 10; +const F = 12; +const R = 13; +const SPACE = 32; +const NAME_CHAR = new Uint8Array(128).map((_, idx) => + /[a-zA-Z0-9\-]/.test(String.fromCharCode(idx)) ? 1 : 0 +); + +class Scanner { + constructor(str) { + this.str = str; + this.pos = 0; + } + + charCodeAt(pos) { + return pos < this.str.length ? this.str.charCodeAt(pos) : 0; + } + charCode() { + return this.charCodeAt(this.pos); + } + isNameCharCode(code = this.charCode()) { + return code < 128 && NAME_CHAR[code] === 1; + } + nextCharCode() { + return this.charCodeAt(this.pos + 1); + } + nextNonWsCode(pos) { + return this.charCodeAt(this.findWsEnd(pos)); + } + skipWs() { + this.pos = this.findWsEnd(this.pos); + } + findWsEnd(pos) { + for (; pos < this.str.length; pos++) { + const code = this.str.charCodeAt(pos); + if (code !== R && code !== N && code !== F && code !== SPACE && code !== TAB) { + break; + } + } + + return pos; + } + substringToPos(end) { + return this.str.substring(this.pos, this.pos = end); + } + eat(code) { + if (this.charCode() !== code) { + this.error('Expect `' + String.fromCharCode(code) + '`'); + } + + this.pos++; + } + peek() { + return this.pos < this.str.length ? this.str.charAt(this.pos++) : ''; + } + error(message) { + throw new SyntaxError.SyntaxError(message, this.str, this.pos); + } + + scanSpaces() { + return this.substringToPos(this.findWsEnd(this.pos)); + } + scanWord() { + let end = this.pos; + + for (; end < this.str.length; end++) { + const code = this.str.charCodeAt(end); + if (code >= 128 || NAME_CHAR[code] === 0) { + break; + } + } + + if (this.pos === end) { + this.error('Expect a keyword'); + } + + return this.substringToPos(end); + } + scanNumber() { + let end = this.pos; + + for (; end < this.str.length; end++) { + const code = this.str.charCodeAt(end); + + if (code < 48 || code > 57) { + break; + } + } + + if (this.pos === end) { + this.error('Expect a number'); + } + + return this.substringToPos(end); + } + scanString() { + const end = this.str.indexOf('\'', this.pos + 1); + + if (end === -1) { + this.pos = this.str.length; + this.error('Expect an apostrophe'); + } + + return this.substringToPos(end + 1); + } +} + +exports.Scanner = Scanner; diff --git a/vanilla/node_modules/css-tree/cjs/definition-syntax/tokenizer.cjs b/vanilla/node_modules/css-tree/cjs/definition-syntax/tokenizer.cjs new file mode 100644 index 0000000..2b934bd --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/definition-syntax/tokenizer.cjs @@ -0,0 +1,59 @@ +'use strict'; + +const SyntaxError = require('./SyntaxError.cjs'); + +const TAB = 9; +const N = 10; +const F = 12; +const R = 13; +const SPACE = 32; + +class Tokenizer { + constructor(str) { + this.str = str; + this.pos = 0; + } + charCodeAt(pos) { + return pos < this.str.length ? this.str.charCodeAt(pos) : 0; + } + charCode() { + return this.charCodeAt(this.pos); + } + nextCharCode() { + return this.charCodeAt(this.pos + 1); + } + nextNonWsCode(pos) { + return this.charCodeAt(this.findWsEnd(pos)); + } + skipWs() { + this.pos = this.findWsEnd(this.pos); + } + findWsEnd(pos) { + for (; pos < this.str.length; pos++) { + const code = this.str.charCodeAt(pos); + if (code !== R && code !== N && code !== F && code !== SPACE && code !== TAB) { + break; + } + } + + return pos; + } + substringToPos(end) { + return this.str.substring(this.pos, this.pos = end); + } + eat(code) { + if (this.charCode() !== code) { + this.error('Expect `' + String.fromCharCode(code) + '`'); + } + + this.pos++; + } + peek() { + return this.pos < this.str.length ? this.str.charAt(this.pos++) : ''; + } + error(message) { + throw new SyntaxError.SyntaxError(message, this.str, this.pos); + } +} + +exports.Tokenizer = Tokenizer; diff --git a/vanilla/node_modules/css-tree/cjs/definition-syntax/walk.cjs b/vanilla/node_modules/css-tree/cjs/definition-syntax/walk.cjs new file mode 100644 index 0000000..fdba065 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/definition-syntax/walk.cjs @@ -0,0 +1,57 @@ +'use strict'; + +const noop = function() {}; + +function ensureFunction(value) { + return typeof value === 'function' ? value : noop; +} + +function walk(node, options, context) { + function walk(node) { + enter.call(context, node); + + switch (node.type) { + case 'Group': + node.terms.forEach(walk); + break; + + case 'Multiplier': + case 'Boolean': + walk(node.term); + break; + + case 'Type': + case 'Property': + case 'Keyword': + case 'AtKeyword': + case 'Function': + case 'String': + case 'Token': + case 'Comma': + break; + + default: + throw new Error('Unknown type: ' + node.type); + } + + leave.call(context, node); + } + + let enter = noop; + let leave = noop; + + if (typeof options === 'function') { + enter = options; + } else if (options) { + enter = ensureFunction(options.enter); + leave = ensureFunction(options.leave); + } + + if (enter === noop && leave === noop) { + throw new Error('Neither `enter` nor `leave` walker handler is set or both aren\'t a function'); + } + + walk(node); +} + +exports.walk = walk; diff --git a/vanilla/node_modules/css-tree/cjs/generator/create.cjs b/vanilla/node_modules/css-tree/cjs/generator/create.cjs new file mode 100644 index 0000000..87a54b2 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/generator/create.cjs @@ -0,0 +1,102 @@ +'use strict'; + +const index = require('../tokenizer/index.cjs'); +const sourceMap = require('./sourceMap.cjs'); +const tokenBefore = require('./token-before.cjs'); +const types = require('../tokenizer/types.cjs'); + +const REVERSESOLIDUS = 0x005c; // U+005C REVERSE SOLIDUS (\) + +function processChildren(node, delimeter) { + if (typeof delimeter === 'function') { + let prev = null; + + node.children.forEach(node => { + if (prev !== null) { + delimeter.call(this, prev); + } + + this.node(node); + prev = node; + }); + + return; + } + + node.children.forEach(this.node, this); +} + +function processChunk(chunk) { + index.tokenize(chunk, (type, start, end) => { + this.token(type, chunk.slice(start, end)); + }); +} + +function createGenerator(config) { + const types$1 = new Map(); + + for (let [name, item] of Object.entries(config.node)) { + const fn = item.generate || item; + + if (typeof fn === 'function') { + types$1.set(name, item.generate || item); + } + } + + return function(node, options) { + let buffer = ''; + let prevCode = 0; + let handlers = { + node(node) { + if (types$1.has(node.type)) { + types$1.get(node.type).call(publicApi, node); + } else { + throw new Error('Unknown node type: ' + node.type); + } + }, + tokenBefore: tokenBefore.safe, + token(type, value) { + prevCode = this.tokenBefore(prevCode, type, value); + + this.emit(value, type, false); + + if (type === types.Delim && value.charCodeAt(0) === REVERSESOLIDUS) { + this.emit('\n', types.WhiteSpace, true); + } + }, + emit(value) { + buffer += value; + }, + result() { + return buffer; + } + }; + + if (options) { + if (typeof options.decorator === 'function') { + handlers = options.decorator(handlers); + } + + if (options.sourceMap) { + handlers = sourceMap.generateSourceMap(handlers); + } + + if (options.mode in tokenBefore) { + handlers.tokenBefore = tokenBefore[options.mode]; + } + } + + const publicApi = { + node: (node) => handlers.node(node), + children: processChildren, + token: (type, value) => handlers.token(type, value), + tokenize: processChunk + }; + + handlers.node(node); + + return handlers.result(); + }; +} + +exports.createGenerator = createGenerator; diff --git a/vanilla/node_modules/css-tree/cjs/generator/index.cjs b/vanilla/node_modules/css-tree/cjs/generator/index.cjs new file mode 100644 index 0000000..5c87cd3 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/generator/index.cjs @@ -0,0 +1,8 @@ +'use strict'; + +const create = require('./create.cjs'); +const generator = require('../syntax/config/generator.cjs'); + +const index = create.createGenerator(generator); + +module.exports = index; diff --git a/vanilla/node_modules/css-tree/cjs/generator/sourceMap.cjs b/vanilla/node_modules/css-tree/cjs/generator/sourceMap.cjs new file mode 100644 index 0000000..efbc5b9 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/generator/sourceMap.cjs @@ -0,0 +1,96 @@ +'use strict'; + +const sourceMapGenerator_js = require('source-map-js/lib/source-map-generator.js'); + +const trackNodes = new Set(['Atrule', 'Selector', 'Declaration']); + +function generateSourceMap(handlers) { + const map = new sourceMapGenerator_js.SourceMapGenerator(); + const generated = { + line: 1, + column: 0 + }; + const original = { + line: 0, // should be zero to add first mapping + column: 0 + }; + const activatedGenerated = { + line: 1, + column: 0 + }; + const activatedMapping = { + generated: activatedGenerated + }; + let line = 1; + let column = 0; + let sourceMappingActive = false; + + const origHandlersNode = handlers.node; + handlers.node = function(node) { + if (node.loc && node.loc.start && trackNodes.has(node.type)) { + const nodeLine = node.loc.start.line; + const nodeColumn = node.loc.start.column - 1; + + if (original.line !== nodeLine || + original.column !== nodeColumn) { + original.line = nodeLine; + original.column = nodeColumn; + + generated.line = line; + generated.column = column; + + if (sourceMappingActive) { + sourceMappingActive = false; + if (generated.line !== activatedGenerated.line || + generated.column !== activatedGenerated.column) { + map.addMapping(activatedMapping); + } + } + + sourceMappingActive = true; + map.addMapping({ + source: node.loc.source, + original, + generated + }); + } + } + + origHandlersNode.call(this, node); + + if (sourceMappingActive && trackNodes.has(node.type)) { + activatedGenerated.line = line; + activatedGenerated.column = column; + } + }; + + const origHandlersEmit = handlers.emit; + handlers.emit = function(value, type, auto) { + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 10) { // \n + line++; + column = 0; + } else { + column++; + } + } + + origHandlersEmit(value, type, auto); + }; + + const origHandlersResult = handlers.result; + handlers.result = function() { + if (sourceMappingActive) { + map.addMapping(activatedMapping); + } + + return { + css: origHandlersResult(), + map + }; + }; + + return handlers; +} + +exports.generateSourceMap = generateSourceMap; diff --git a/vanilla/node_modules/css-tree/cjs/generator/token-before.cjs b/vanilla/node_modules/css-tree/cjs/generator/token-before.cjs new file mode 100644 index 0000000..87bf4a3 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/generator/token-before.cjs @@ -0,0 +1,170 @@ +'use strict'; + +const types = require('../tokenizer/types.cjs'); + +const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+) +const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-) + +const code = (type, value) => { + if (type === types.Delim) { + type = value; + } + + if (typeof type === 'string') { + const charCode = type.charCodeAt(0); + return charCode > 0x7F ? 0x8000 : charCode << 8; + } + + return type; +}; + +// https://www.w3.org/TR/css-syntax-3/#serialization +// The only requirement for serialization is that it must "round-trip" with parsing, +// that is, parsing the stylesheet must produce the same data structures as parsing, +// serializing, and parsing again, except for consecutive s, +// which may be collapsed into a single token. + +const specPairs = [ + [types.Ident, types.Ident], + [types.Ident, types.Function], + [types.Ident, types.Url], + [types.Ident, types.BadUrl], + [types.Ident, '-'], + [types.Ident, types.Number], + [types.Ident, types.Percentage], + [types.Ident, types.Dimension], + [types.Ident, types.CDC], + [types.Ident, types.LeftParenthesis], + + [types.AtKeyword, types.Ident], + [types.AtKeyword, types.Function], + [types.AtKeyword, types.Url], + [types.AtKeyword, types.BadUrl], + [types.AtKeyword, '-'], + [types.AtKeyword, types.Number], + [types.AtKeyword, types.Percentage], + [types.AtKeyword, types.Dimension], + [types.AtKeyword, types.CDC], + + [types.Hash, types.Ident], + [types.Hash, types.Function], + [types.Hash, types.Url], + [types.Hash, types.BadUrl], + [types.Hash, '-'], + [types.Hash, types.Number], + [types.Hash, types.Percentage], + [types.Hash, types.Dimension], + [types.Hash, types.CDC], + + [types.Dimension, types.Ident], + [types.Dimension, types.Function], + [types.Dimension, types.Url], + [types.Dimension, types.BadUrl], + [types.Dimension, '-'], + [types.Dimension, types.Number], + [types.Dimension, types.Percentage], + [types.Dimension, types.Dimension], + [types.Dimension, types.CDC], + + ['#', types.Ident], + ['#', types.Function], + ['#', types.Url], + ['#', types.BadUrl], + ['#', '-'], + ['#', types.Number], + ['#', types.Percentage], + ['#', types.Dimension], + ['#', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 + + ['-', types.Ident], + ['-', types.Function], + ['-', types.Url], + ['-', types.BadUrl], + ['-', '-'], + ['-', types.Number], + ['-', types.Percentage], + ['-', types.Dimension], + ['-', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 + + [types.Number, types.Ident], + [types.Number, types.Function], + [types.Number, types.Url], + [types.Number, types.BadUrl], + [types.Number, types.Number], + [types.Number, types.Percentage], + [types.Number, types.Dimension], + [types.Number, '%'], + [types.Number, types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 + + ['@', types.Ident], + ['@', types.Function], + ['@', types.Url], + ['@', types.BadUrl], + ['@', '-'], + ['@', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 + + ['.', types.Number], + ['.', types.Percentage], + ['.', types.Dimension], + + ['+', types.Number], + ['+', types.Percentage], + ['+', types.Dimension], + + ['/', '*'] +]; +// validate with scripts/generate-safe +const safePairs = specPairs.concat([ + [types.Ident, types.Hash], + + [types.Dimension, types.Hash], + + [types.Hash, types.Hash], + + [types.AtKeyword, types.LeftParenthesis], + [types.AtKeyword, types.String], + [types.AtKeyword, types.Colon], + + [types.Percentage, types.Percentage], + [types.Percentage, types.Dimension], + [types.Percentage, types.Function], + [types.Percentage, '-'], + + [types.RightParenthesis, types.Ident], + [types.RightParenthesis, types.Function], + [types.RightParenthesis, types.Percentage], + [types.RightParenthesis, types.Dimension], + [types.RightParenthesis, types.Hash], + [types.RightParenthesis, '-'] +]); + +function createMap(pairs) { + const isWhiteSpaceRequired = new Set( + pairs.map(([prev, next]) => (code(prev) << 16 | code(next))) + ); + + return function(prevCode, type, value) { + const nextCode = code(type, value); + const nextCharCode = value.charCodeAt(0); + const emitWs = + (nextCharCode === HYPHENMINUS && + type !== types.Ident && + type !== types.Function && + type !== types.CDC) || + (nextCharCode === PLUSSIGN) + ? isWhiteSpaceRequired.has(prevCode << 16 | nextCharCode << 8) + : isWhiteSpaceRequired.has(prevCode << 16 | nextCode); + + if (emitWs) { + this.emit(' ', types.WhiteSpace, true); + } + + return nextCode; + }; +} + +const spec = createMap(specPairs); +const safe = createMap(safePairs); + +exports.safe = safe; +exports.spec = spec; diff --git a/vanilla/node_modules/css-tree/cjs/index.cjs b/vanilla/node_modules/css-tree/cjs/index.cjs new file mode 100644 index 0000000..cc61137 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/index.cjs @@ -0,0 +1,65 @@ +'use strict'; + +const index$1 = require('./syntax/index.cjs'); +const version = require('./version.cjs'); +const create = require('./syntax/create.cjs'); +const List = require('./utils/List.cjs'); +const Lexer = require('./lexer/Lexer.cjs'); +const index = require('./definition-syntax/index.cjs'); +const clone = require('./utils/clone.cjs'); +const names$1 = require('./utils/names.cjs'); +const ident = require('./utils/ident.cjs'); +const string = require('./utils/string.cjs'); +const url = require('./utils/url.cjs'); +const types = require('./tokenizer/types.cjs'); +const names = require('./tokenizer/names.cjs'); +const TokenStream = require('./tokenizer/TokenStream.cjs'); +const OffsetToLocation = require('./tokenizer/OffsetToLocation.cjs'); + +const { + tokenize, + parse, + generate, + lexer, + createLexer, + + walk, + find, + findLast, + findAll, + + toPlainObject, + fromPlainObject, + + fork +} = index$1; + +exports.version = version.version; +exports.createSyntax = create; +exports.List = List.List; +exports.Lexer = Lexer.Lexer; +exports.definitionSyntax = index; +exports.clone = clone.clone; +exports.isCustomProperty = names$1.isCustomProperty; +exports.keyword = names$1.keyword; +exports.property = names$1.property; +exports.vendorPrefix = names$1.vendorPrefix; +exports.ident = ident; +exports.string = string; +exports.url = url; +exports.tokenTypes = types; +exports.tokenNames = names; +exports.TokenStream = TokenStream.TokenStream; +exports.OffsetToLocation = OffsetToLocation.OffsetToLocation; +exports.createLexer = createLexer; +exports.find = find; +exports.findAll = findAll; +exports.findLast = findLast; +exports.fork = fork; +exports.fromPlainObject = fromPlainObject; +exports.generate = generate; +exports.lexer = lexer; +exports.parse = parse; +exports.toPlainObject = toPlainObject; +exports.tokenize = tokenize; +exports.walk = walk; diff --git a/vanilla/node_modules/css-tree/cjs/lexer/Lexer.cjs b/vanilla/node_modules/css-tree/cjs/lexer/Lexer.cjs new file mode 100644 index 0000000..a6d1fcb --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/lexer/Lexer.cjs @@ -0,0 +1,517 @@ +'use strict'; + +const error = require('./error.cjs'); +const names = require('../utils/names.cjs'); +const genericConst = require('./generic-const.cjs'); +const generic = require('./generic.cjs'); +const units = require('./units.cjs'); +const prepareTokens = require('./prepare-tokens.cjs'); +const matchGraph = require('./match-graph.cjs'); +const match = require('./match.cjs'); +const trace = require('./trace.cjs'); +const search = require('./search.cjs'); +const structure = require('./structure.cjs'); +const parse = require('../definition-syntax/parse.cjs'); +const generate = require('../definition-syntax/generate.cjs'); +const walk = require('../definition-syntax/walk.cjs'); + +function dumpMapSyntax(map, compact, syntaxAsAst) { + const result = {}; + + for (const name in map) { + if (map[name].syntax) { + result[name] = syntaxAsAst + ? map[name].syntax + : generate.generate(map[name].syntax, { compact }); + } + } + + return result; +} + +function dumpAtruleMapSyntax(map, compact, syntaxAsAst) { + const result = {}; + + for (const [name, atrule] of Object.entries(map)) { + result[name] = { + prelude: atrule.prelude && ( + syntaxAsAst + ? atrule.prelude.syntax + : generate.generate(atrule.prelude.syntax, { compact }) + ), + descriptors: atrule.descriptors && dumpMapSyntax(atrule.descriptors, compact, syntaxAsAst) + }; + } + + return result; +} + +function valueHasVar(tokens) { + for (let i = 0; i < tokens.length; i++) { + if (tokens[i].value.toLowerCase() === 'var(') { + return true; + } + } + + return false; +} + +function syntaxHasTopLevelCommaMultiplier(syntax) { + const singleTerm = syntax.terms[0]; + + return ( + syntax.explicit === false && + syntax.terms.length === 1 && + singleTerm.type === 'Multiplier' && + singleTerm.comma === true + ); +} + +function buildMatchResult(matched, error, iterations) { + return { + matched, + iterations, + error, + ...trace + }; +} + +function matchSyntax(lexer, syntax, value, useCssWideKeywords) { + const tokens = prepareTokens(value, lexer.syntax); + let result; + + if (valueHasVar(tokens)) { + return buildMatchResult(null, new Error('Matching for a tree with var() is not supported')); + } + + if (useCssWideKeywords) { + result = match.matchAsTree(tokens, lexer.cssWideKeywordsSyntax, lexer); + } + + if (!useCssWideKeywords || !result.match) { + result = match.matchAsTree(tokens, syntax.match, lexer); + if (!result.match) { + return buildMatchResult( + null, + new error.SyntaxMatchError(result.reason, syntax.syntax, value, result), + result.iterations + ); + } + } + + return buildMatchResult(result.match, null, result.iterations); +} + +class Lexer { + constructor(config, syntax, structure$1) { + this.cssWideKeywords = genericConst.cssWideKeywords; + this.syntax = syntax; + this.generic = false; + this.units = { ...units }; + this.atrules = Object.create(null); + this.properties = Object.create(null); + this.types = Object.create(null); + this.structure = structure$1 || structure.getStructureFromConfig(config); + + if (config) { + if (config.cssWideKeywords) { + this.cssWideKeywords = config.cssWideKeywords; + } + + if (config.units) { + for (const group of Object.keys(units)) { + if (Array.isArray(config.units[group])) { + this.units[group] = config.units[group]; + } + } + } + + if (config.types) { + for (const [name, type] of Object.entries(config.types)) { + this.addType_(name, type); + } + } + + if (config.generic) { + this.generic = true; + for (const [name, value] of Object.entries(generic.createGenericTypes(this.units))) { + this.addType_(name, value); + } + } + + if (config.atrules) { + for (const [name, atrule] of Object.entries(config.atrules)) { + this.addAtrule_(name, atrule); + } + } + + if (config.properties) { + for (const [name, property] of Object.entries(config.properties)) { + this.addProperty_(name, property); + } + } + } + + this.cssWideKeywordsSyntax = matchGraph.buildMatchGraph(this.cssWideKeywords.join(' | ')); + } + + checkStructure(ast) { + function collectWarning(node, message) { + warns.push({ node, message }); + } + + const structure = this.structure; + const warns = []; + + this.syntax.walk(ast, function(node) { + if (structure.hasOwnProperty(node.type)) { + structure[node.type].check(node, collectWarning); + } else { + collectWarning(node, 'Unknown node type `' + node.type + '`'); + } + }); + + return warns.length ? warns : false; + } + + createDescriptor(syntax, type, name, parent = null) { + const ref = { + type, + name + }; + const descriptor = { + type, + name, + parent, + serializable: typeof syntax === 'string' || (syntax && typeof syntax.type === 'string'), + syntax: null, + match: null, + matchRef: null // used for properties when a syntax referenced as <'property'> in other syntax definitions + }; + + if (typeof syntax === 'function') { + descriptor.match = matchGraph.buildMatchGraph(syntax, ref); + } else { + if (typeof syntax === 'string') { + // lazy parsing on first access + Object.defineProperty(descriptor, 'syntax', { + get() { + Object.defineProperty(descriptor, 'syntax', { + value: parse.parse(syntax) + }); + + return descriptor.syntax; + } + }); + } else { + descriptor.syntax = syntax; + } + + // lazy graph build on first access + Object.defineProperty(descriptor, 'match', { + get() { + Object.defineProperty(descriptor, 'match', { + value: matchGraph.buildMatchGraph(descriptor.syntax, ref) + }); + + return descriptor.match; + } + }); + + if (type === 'Property') { + Object.defineProperty(descriptor, 'matchRef', { + get() { + const syntax = descriptor.syntax; + const value = syntaxHasTopLevelCommaMultiplier(syntax) + ? matchGraph.buildMatchGraph({ + ...syntax, + terms: [syntax.terms[0].term] + }, ref) + : null; + + Object.defineProperty(descriptor, 'matchRef', { + value + }); + + return value; + } + }); + } + } + + return descriptor; + } + addAtrule_(name, syntax) { + if (!syntax) { + return; + } + + this.atrules[name] = { + type: 'Atrule', + name: name, + prelude: syntax.prelude ? this.createDescriptor(syntax.prelude, 'AtrulePrelude', name) : null, + descriptors: syntax.descriptors + ? Object.keys(syntax.descriptors).reduce( + (map, descName) => { + map[descName] = this.createDescriptor(syntax.descriptors[descName], 'AtruleDescriptor', descName, name); + return map; + }, + Object.create(null) + ) + : null + }; + } + addProperty_(name, syntax) { + if (!syntax) { + return; + } + + this.properties[name] = this.createDescriptor(syntax, 'Property', name); + } + addType_(name, syntax) { + if (!syntax) { + return; + } + + this.types[name] = this.createDescriptor(syntax, 'Type', name); + } + + checkAtruleName(atruleName) { + if (!this.getAtrule(atruleName)) { + return new error.SyntaxReferenceError('Unknown at-rule', '@' + atruleName); + } + } + checkAtrulePrelude(atruleName, prelude) { + const error = this.checkAtruleName(atruleName); + + if (error) { + return error; + } + + const atrule = this.getAtrule(atruleName); + + if (!atrule.prelude && prelude) { + return new SyntaxError('At-rule `@' + atruleName + '` should not contain a prelude'); + } + + if (atrule.prelude && !prelude) { + if (!matchSyntax(this, atrule.prelude, '', false).matched) { + return new SyntaxError('At-rule `@' + atruleName + '` should contain a prelude'); + } + } + } + checkAtruleDescriptorName(atruleName, descriptorName) { + const error$1 = this.checkAtruleName(atruleName); + + if (error$1) { + return error$1; + } + + const atrule = this.getAtrule(atruleName); + const descriptor = names.keyword(descriptorName); + + if (!atrule.descriptors) { + return new SyntaxError('At-rule `@' + atruleName + '` has no known descriptors'); + } + + if (!atrule.descriptors[descriptor.name] && + !atrule.descriptors[descriptor.basename]) { + return new error.SyntaxReferenceError('Unknown at-rule descriptor', descriptorName); + } + } + checkPropertyName(propertyName) { + if (!this.getProperty(propertyName)) { + return new error.SyntaxReferenceError('Unknown property', propertyName); + } + } + + matchAtrulePrelude(atruleName, prelude) { + const error = this.checkAtrulePrelude(atruleName, prelude); + + if (error) { + return buildMatchResult(null, error); + } + + const atrule = this.getAtrule(atruleName); + + if (!atrule.prelude) { + return buildMatchResult(null, null); + } + + return matchSyntax(this, atrule.prelude, prelude || '', false); + } + matchAtruleDescriptor(atruleName, descriptorName, value) { + const error = this.checkAtruleDescriptorName(atruleName, descriptorName); + + if (error) { + return buildMatchResult(null, error); + } + + const atrule = this.getAtrule(atruleName); + const descriptor = names.keyword(descriptorName); + + return matchSyntax(this, atrule.descriptors[descriptor.name] || atrule.descriptors[descriptor.basename], value, false); + } + matchDeclaration(node) { + if (node.type !== 'Declaration') { + return buildMatchResult(null, new Error('Not a Declaration node')); + } + + return this.matchProperty(node.property, node.value); + } + matchProperty(propertyName, value) { + // don't match syntax for a custom property at the moment + if (names.property(propertyName).custom) { + return buildMatchResult(null, new Error('Lexer matching doesn\'t applicable for custom properties')); + } + + const error = this.checkPropertyName(propertyName); + + if (error) { + return buildMatchResult(null, error); + } + + return matchSyntax(this, this.getProperty(propertyName), value, true); + } + matchType(typeName, value) { + const typeSyntax = this.getType(typeName); + + if (!typeSyntax) { + return buildMatchResult(null, new error.SyntaxReferenceError('Unknown type', typeName)); + } + + return matchSyntax(this, typeSyntax, value, false); + } + match(syntax, value) { + if (typeof syntax !== 'string' && (!syntax || !syntax.type)) { + return buildMatchResult(null, new error.SyntaxReferenceError('Bad syntax')); + } + + if (typeof syntax === 'string' || !syntax.match) { + syntax = this.createDescriptor(syntax, 'Type', 'anonymous'); + } + + return matchSyntax(this, syntax, value, false); + } + + findValueFragments(propertyName, value, type, name) { + return search.matchFragments(this, value, this.matchProperty(propertyName, value), type, name); + } + findDeclarationValueFragments(declaration, type, name) { + return search.matchFragments(this, declaration.value, this.matchDeclaration(declaration), type, name); + } + findAllFragments(ast, type, name) { + const result = []; + + this.syntax.walk(ast, { + visit: 'Declaration', + enter: (declaration) => { + result.push.apply(result, this.findDeclarationValueFragments(declaration, type, name)); + } + }); + + return result; + } + + getAtrule(atruleName, fallbackBasename = true) { + const atrule = names.keyword(atruleName); + const atruleEntry = atrule.vendor && fallbackBasename + ? this.atrules[atrule.name] || this.atrules[atrule.basename] + : this.atrules[atrule.name]; + + return atruleEntry || null; + } + getAtrulePrelude(atruleName, fallbackBasename = true) { + const atrule = this.getAtrule(atruleName, fallbackBasename); + + return atrule && atrule.prelude || null; + } + getAtruleDescriptor(atruleName, name) { + return this.atrules.hasOwnProperty(atruleName) && this.atrules.declarators + ? this.atrules[atruleName].declarators[name] || null + : null; + } + getProperty(propertyName, fallbackBasename = true) { + const property = names.property(propertyName); + const propertyEntry = property.vendor && fallbackBasename + ? this.properties[property.name] || this.properties[property.basename] + : this.properties[property.name]; + + return propertyEntry || null; + } + getType(name) { + return hasOwnProperty.call(this.types, name) ? this.types[name] : null; + } + + validate() { + function syntaxRef(name, isType) { + return isType ? `<${name}>` : `<'${name}'>`; + } + + function validate(syntax, name, broken, descriptor) { + if (broken.has(name)) { + return broken.get(name); + } + + broken.set(name, false); + if (descriptor.syntax !== null) { + walk.walk(descriptor.syntax, function(node) { + if (node.type !== 'Type' && node.type !== 'Property') { + return; + } + + const map = node.type === 'Type' ? syntax.types : syntax.properties; + const brokenMap = node.type === 'Type' ? brokenTypes : brokenProperties; + + if (!hasOwnProperty.call(map, node.name)) { + errors.push(`${syntaxRef(name, broken === brokenTypes)} used missed syntax definition ${syntaxRef(node.name, node.type === 'Type')}`); + broken.set(name, true); + } else if (validate(syntax, node.name, brokenMap, map[node.name])) { + errors.push(`${syntaxRef(name, broken === brokenTypes)} used broken syntax definition ${syntaxRef(node.name, node.type === 'Type')}`); + broken.set(name, true); + } + }, this); + } + } + + const errors = []; + let brokenTypes = new Map(); + let brokenProperties = new Map(); + + for (const key in this.types) { + validate(this, key, brokenTypes, this.types[key]); + } + + for (const key in this.properties) { + validate(this, key, brokenProperties, this.properties[key]); + } + + const brokenTypesArray = [...brokenTypes.keys()].filter(name => brokenTypes.get(name)); + const brokenPropertiesArray = [...brokenProperties.keys()].filter(name => brokenProperties.get(name)); + + if (brokenTypesArray.length || brokenPropertiesArray.length) { + return { + errors, + types: brokenTypesArray, + properties: brokenPropertiesArray + }; + } + + return null; + } + dump(syntaxAsAst, pretty) { + return { + generic: this.generic, + cssWideKeywords: this.cssWideKeywords, + units: this.units, + types: dumpMapSyntax(this.types, !pretty, syntaxAsAst), + properties: dumpMapSyntax(this.properties, !pretty, syntaxAsAst), + atrules: dumpAtruleMapSyntax(this.atrules, !pretty, syntaxAsAst) + }; + } + toString() { + return JSON.stringify(this.dump()); + } +} + +exports.Lexer = Lexer; diff --git a/vanilla/node_modules/css-tree/cjs/lexer/error.cjs b/vanilla/node_modules/css-tree/cjs/lexer/error.cjs new file mode 100644 index 0000000..8d252ee --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/lexer/error.cjs @@ -0,0 +1,128 @@ +'use strict'; + +const createCustomError = require('../utils/create-custom-error.cjs'); +const generate = require('../definition-syntax/generate.cjs'); + +const defaultLoc = { offset: 0, line: 1, column: 1 }; + +function locateMismatch(matchResult, node) { + const tokens = matchResult.tokens; + const longestMatch = matchResult.longestMatch; + const mismatchNode = longestMatch < tokens.length ? tokens[longestMatch].node || null : null; + const badNode = mismatchNode !== node ? mismatchNode : null; + let mismatchOffset = 0; + let mismatchLength = 0; + let entries = 0; + let css = ''; + let start; + let end; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i].value; + + if (i === longestMatch) { + mismatchLength = token.length; + mismatchOffset = css.length; + } + + if (badNode !== null && tokens[i].node === badNode) { + if (i <= longestMatch) { + entries++; + } else { + entries = 0; + } + } + + css += token; + } + + if (longestMatch === tokens.length || entries > 1) { // last + start = fromLoc(badNode || node, 'end') || buildLoc(defaultLoc, css); + end = buildLoc(start); + } else { + start = fromLoc(badNode, 'start') || + buildLoc(fromLoc(node, 'start') || defaultLoc, css.slice(0, mismatchOffset)); + end = fromLoc(badNode, 'end') || + buildLoc(start, css.substr(mismatchOffset, mismatchLength)); + } + + return { + css, + mismatchOffset, + mismatchLength, + start, + end + }; +} + +function fromLoc(node, point) { + const value = node && node.loc && node.loc[point]; + + if (value) { + return 'line' in value ? buildLoc(value) : value; + } + + return null; +} + +function buildLoc({ offset, line, column }, extra) { + const loc = { + offset, + line, + column + }; + + if (extra) { + const lines = extra.split(/\n|\r\n?|\f/); + + loc.offset += extra.length; + loc.line += lines.length - 1; + loc.column = lines.length === 1 ? loc.column + extra.length : lines.pop().length + 1; + } + + return loc; +} + +const SyntaxReferenceError = function(type, referenceName) { + const error = createCustomError.createCustomError( + 'SyntaxReferenceError', + type + (referenceName ? ' `' + referenceName + '`' : '') + ); + + error.reference = referenceName; + + return error; +}; + +const SyntaxMatchError = function(message, syntax, node, matchResult) { + const error = createCustomError.createCustomError('SyntaxMatchError', message); + const { + css, + mismatchOffset, + mismatchLength, + start, + end + } = locateMismatch(matchResult, node); + + error.rawMessage = message; + error.syntax = syntax ? generate.generate(syntax) : ''; + error.css = css; + error.mismatchOffset = mismatchOffset; + error.mismatchLength = mismatchLength; + error.message = message + '\n' + + ' syntax: ' + error.syntax + '\n' + + ' value: ' + (css || '') + '\n' + + ' --------' + new Array(error.mismatchOffset + 1).join('-') + '^'; + + Object.assign(error, start); + error.loc = { + source: (node && node.loc && node.loc.source) || '', + start, + end + }; + + return error; +}; + +exports.SyntaxMatchError = SyntaxMatchError; +exports.SyntaxReferenceError = SyntaxReferenceError; diff --git a/vanilla/node_modules/css-tree/cjs/lexer/generic-an-plus-b.cjs b/vanilla/node_modules/css-tree/cjs/lexer/generic-an-plus-b.cjs new file mode 100644 index 0000000..a5dfba3 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/lexer/generic-an-plus-b.cjs @@ -0,0 +1,235 @@ +'use strict'; + +const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs'); +const types = require('../tokenizer/types.cjs'); +const utils = require('../tokenizer/utils.cjs'); + +const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+) +const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-) +const N = 0x006E; // U+006E LATIN SMALL LETTER N (n) +const DISALLOW_SIGN = true; +const ALLOW_SIGN = false; + +function isDelim(token, code) { + return token !== null && token.type === types.Delim && token.value.charCodeAt(0) === code; +} + +function skipSC(token, offset, getNextToken) { + while (token !== null && (token.type === types.WhiteSpace || token.type === types.Comment)) { + token = getNextToken(++offset); + } + + return offset; +} + +function checkInteger(token, valueOffset, disallowSign, offset) { + if (!token) { + return 0; + } + + const code = token.value.charCodeAt(valueOffset); + + if (code === PLUSSIGN || code === HYPHENMINUS) { + if (disallowSign) { + // Number sign is not allowed + return 0; + } + valueOffset++; + } + + for (; valueOffset < token.value.length; valueOffset++) { + if (!charCodeDefinitions.isDigit(token.value.charCodeAt(valueOffset))) { + // Integer is expected + return 0; + } + } + + return offset + 1; +} + +// ... +// ... ['+' | '-'] +function consumeB(token, offset_, getNextToken) { + let sign = false; + let offset = skipSC(token, offset_, getNextToken); + + token = getNextToken(offset); + + if (token === null) { + return offset_; + } + + if (token.type !== types.Number) { + if (isDelim(token, PLUSSIGN) || isDelim(token, HYPHENMINUS)) { + sign = true; + offset = skipSC(getNextToken(++offset), offset, getNextToken); + token = getNextToken(offset); + + if (token === null || token.type !== types.Number) { + return 0; + } + } else { + return offset_; + } + } + + if (!sign) { + const code = token.value.charCodeAt(0); + if (code !== PLUSSIGN && code !== HYPHENMINUS) { + // Number sign is expected + return 0; + } + } + + return checkInteger(token, sign ? 0 : 1, sign, offset); +} + +// An+B microsyntax https://www.w3.org/TR/css-syntax-3/#anb +function anPlusB(token, getNextToken) { + /* eslint-disable brace-style*/ + let offset = 0; + + if (!token) { + return 0; + } + + // + if (token.type === types.Number) { + return checkInteger(token, 0, ALLOW_SIGN, offset); // b + } + + // -n + // -n + // -n ['+' | '-'] + // -n- + // + else if (token.type === types.Ident && token.value.charCodeAt(0) === HYPHENMINUS) { + // expect 1st char is N + if (!utils.cmpChar(token.value, 1, N)) { + return 0; + } + + switch (token.value.length) { + // -n + // -n + // -n ['+' | '-'] + case 2: + return consumeB(getNextToken(++offset), offset, getNextToken); + + // -n- + case 3: + if (token.value.charCodeAt(2) !== HYPHENMINUS) { + return 0; + } + + offset = skipSC(getNextToken(++offset), offset, getNextToken); + token = getNextToken(offset); + + return checkInteger(token, 0, DISALLOW_SIGN, offset); + + // + default: + if (token.value.charCodeAt(2) !== HYPHENMINUS) { + return 0; + } + + return checkInteger(token, 3, DISALLOW_SIGN, offset); + } + } + + // '+'? n + // '+'? n + // '+'? n ['+' | '-'] + // '+'? n- + // '+'? + else if (token.type === types.Ident || (isDelim(token, PLUSSIGN) && getNextToken(offset + 1).type === types.Ident)) { + // just ignore a plus + if (token.type !== types.Ident) { + token = getNextToken(++offset); + } + + if (token === null || !utils.cmpChar(token.value, 0, N)) { + return 0; + } + + switch (token.value.length) { + // '+'? n + // '+'? n + // '+'? n ['+' | '-'] + case 1: + return consumeB(getNextToken(++offset), offset, getNextToken); + + // '+'? n- + case 2: + if (token.value.charCodeAt(1) !== HYPHENMINUS) { + return 0; + } + + offset = skipSC(getNextToken(++offset), offset, getNextToken); + token = getNextToken(offset); + + return checkInteger(token, 0, DISALLOW_SIGN, offset); + + // '+'? + default: + if (token.value.charCodeAt(1) !== HYPHENMINUS) { + return 0; + } + + return checkInteger(token, 2, DISALLOW_SIGN, offset); + } + } + + // + // + // + // + // ['+' | '-'] + else if (token.type === types.Dimension) { + let code = token.value.charCodeAt(0); + let sign = code === PLUSSIGN || code === HYPHENMINUS ? 1 : 0; + let i = sign; + + for (; i < token.value.length; i++) { + if (!charCodeDefinitions.isDigit(token.value.charCodeAt(i))) { + break; + } + } + + if (i === sign) { + // Integer is expected + return 0; + } + + if (!utils.cmpChar(token.value, i, N)) { + return 0; + } + + // + // + // ['+' | '-'] + if (i + 1 === token.value.length) { + return consumeB(getNextToken(++offset), offset, getNextToken); + } else { + if (token.value.charCodeAt(i + 1) !== HYPHENMINUS) { + return 0; + } + + // + if (i + 2 === token.value.length) { + offset = skipSC(getNextToken(++offset), offset, getNextToken); + token = getNextToken(offset); + + return checkInteger(token, 0, DISALLOW_SIGN, offset); + } + // + else { + return checkInteger(token, i + 2, DISALLOW_SIGN, offset); + } + } + } + + return 0; +} + +module.exports = anPlusB; diff --git a/vanilla/node_modules/css-tree/cjs/lexer/generic-const.cjs b/vanilla/node_modules/css-tree/cjs/lexer/generic-const.cjs new file mode 100644 index 0000000..9b9f615 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/lexer/generic-const.cjs @@ -0,0 +1,12 @@ +'use strict'; + +// https://drafts.csswg.org/css-cascade-5/ +const cssWideKeywords = [ + 'initial', + 'inherit', + 'unset', + 'revert', + 'revert-layer' +]; + +exports.cssWideKeywords = cssWideKeywords; diff --git a/vanilla/node_modules/css-tree/cjs/lexer/generic-urange.cjs b/vanilla/node_modules/css-tree/cjs/lexer/generic-urange.cjs new file mode 100644 index 0000000..ce167bb --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/lexer/generic-urange.cjs @@ -0,0 +1,149 @@ +'use strict'; + +const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs'); +const types = require('../tokenizer/types.cjs'); +const utils = require('../tokenizer/utils.cjs'); + +const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+) +const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-) +const QUESTIONMARK = 0x003F; // U+003F QUESTION MARK (?) +const U = 0x0075; // U+0075 LATIN SMALL LETTER U (u) + +function isDelim(token, code) { + return token !== null && token.type === types.Delim && token.value.charCodeAt(0) === code; +} + +function startsWith(token, code) { + return token.value.charCodeAt(0) === code; +} + +function hexSequence(token, offset, allowDash) { + let hexlen = 0; + + for (let pos = offset; pos < token.value.length; pos++) { + const code = token.value.charCodeAt(pos); + + if (code === HYPHENMINUS && allowDash && hexlen !== 0) { + hexSequence(token, offset + hexlen + 1, false); + return 6; // dissallow following question marks + } + + if (!charCodeDefinitions.isHexDigit(code)) { + return 0; // not a hex digit + } + + if (++hexlen > 6) { + return 0; // too many hex digits + } } + + return hexlen; +} + +function withQuestionMarkSequence(consumed, length, getNextToken) { + if (!consumed) { + return 0; // nothing consumed + } + + while (isDelim(getNextToken(length), QUESTIONMARK)) { + if (++consumed > 6) { + return 0; // too many question marks + } + + length++; + } + + return length; +} + +// https://drafts.csswg.org/css-syntax/#urange +// Informally, the production has three forms: +// U+0001 +// Defines a range consisting of a single code point, in this case the code point "1". +// U+0001-00ff +// Defines a range of codepoints between the first and the second value, in this case +// the range between "1" and "ff" (255 in decimal) inclusive. +// U+00?? +// Defines a range of codepoints where the "?" characters range over all hex digits, +// in this case defining the same as the value U+0000-00ff. +// In each form, a maximum of 6 digits is allowed for each hexadecimal number (if you treat "?" as a hexadecimal digit). +// +// = +// u '+' '?'* | +// u '?'* | +// u '?'* | +// u | +// u | +// u '+' '?'+ +function urange(token, getNextToken) { + let length = 0; + + // should start with `u` or `U` + if (token === null || token.type !== types.Ident || !utils.cmpChar(token.value, 0, U)) { + return 0; + } + + token = getNextToken(++length); + if (token === null) { + return 0; + } + + // u '+' '?'* + // u '+' '?'+ + if (isDelim(token, PLUSSIGN)) { + token = getNextToken(++length); + if (token === null) { + return 0; + } + + if (token.type === types.Ident) { + // u '+' '?'* + return withQuestionMarkSequence(hexSequence(token, 0, true), ++length, getNextToken); + } + + if (isDelim(token, QUESTIONMARK)) { + // u '+' '?'+ + return withQuestionMarkSequence(1, ++length, getNextToken); + } + + // Hex digit or question mark is expected + return 0; + } + + // u '?'* + // u + // u + if (token.type === types.Number) { + const consumedHexLength = hexSequence(token, 1, true); + if (consumedHexLength === 0) { + return 0; + } + + token = getNextToken(++length); + if (token === null) { + // u + return length; + } + + if (token.type === types.Dimension || token.type === types.Number) { + // u + // u + if (!startsWith(token, HYPHENMINUS) || !hexSequence(token, 1, false)) { + return 0; + } + + return length + 1; + } + + // u '?'* + return withQuestionMarkSequence(consumedHexLength, length, getNextToken); + } + + // u '?'* + if (token.type === types.Dimension) { + return withQuestionMarkSequence(hexSequence(token, 1, true), ++length, getNextToken); + } + + return 0; +} + +module.exports = urange; diff --git a/vanilla/node_modules/css-tree/cjs/lexer/generic.cjs b/vanilla/node_modules/css-tree/cjs/lexer/generic.cjs new file mode 100644 index 0000000..8489911 --- /dev/null +++ b/vanilla/node_modules/css-tree/cjs/lexer/generic.cjs @@ -0,0 +1,589 @@ +'use strict'; + +const genericConst = require('./generic-const.cjs'); +const genericAnPlusB = require('./generic-an-plus-b.cjs'); +const genericUrange = require('./generic-urange.cjs'); +const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs'); +const types = require('../tokenizer/types.cjs'); +const utils = require('../tokenizer/utils.cjs'); + +const calcFunctionNames = ['calc(', '-moz-calc(', '-webkit-calc(']; +const balancePair = new Map([ + [types.Function, types.RightParenthesis], + [types.LeftParenthesis, types.RightParenthesis], + [types.LeftSquareBracket, types.RightSquareBracket], + [types.LeftCurlyBracket, types.RightCurlyBracket] +]); + +// safe char code getter +function charCodeAt(str, index) { + return index < str.length ? str.charCodeAt(index) : 0; +} + +function eqStr(actual, expected) { + return utils.cmpStr(actual, 0, actual.length, expected); +} + +function eqStrAny(actual, expected) { + for (let i = 0; i < expected.length; i++) { + if (eqStr(actual, expected[i])) { + return true; + } + } + + return false; +} + +// IE postfix hack, i.e. 123\0 or 123px\9 +function isPostfixIeHack(str, offset) { + if (offset !== str.length - 2) { + return false; + } + + return ( + charCodeAt(str, offset) === 0x005C && // U+005C REVERSE SOLIDUS (\) + charCodeDefinitions.isDigit(charCodeAt(str, offset + 1)) + ); +} + +function outOfRange(opts, value, numEnd) { + if (opts && opts.type === 'Range') { + const num = Number( + numEnd !== undefined && numEnd !== value.length + ? value.substr(0, numEnd) + : value + ); + + if (isNaN(num)) { + return true; + } + + // FIXME: when opts.min is a string it's a dimension, skip a range validation + // for now since it requires a type covertation which is not implmented yet + if (opts.min !== null && num < opts.min && typeof opts.min !== 'string') { + return true; + } + + // FIXME: when opts.max is a string it's a dimension, skip a range validation + // for now since it requires a type covertation which is not implmented yet + if (opts.max !== null && num > opts.max && typeof opts.max !== 'string') { + return true; + } + } + + return false; +} + +function consumeFunction(token, getNextToken) { + let balanceCloseType = 0; + let balanceStash = []; + let length = 0; + + // balanced token consuming + scan: + do { + switch (token.type) { + case types.RightCurlyBracket: + case types.RightParenthesis: + case types.RightSquareBracket: + if (token.type !== balanceCloseType) { + break scan; + } + + balanceCloseType = balanceStash.pop(); + + if (balanceStash.length === 0) { + length++; + break scan; + } + + break; + + case types.Function: + case types.LeftParenthesis: + case types.LeftSquareBracket: + case types.LeftCurlyBracket: + balanceStash.push(balanceCloseType); + balanceCloseType = balancePair.get(token.type); + break; + } + + length++; + } while (token = getNextToken(length)); + + return length; +} + +// TODO: implement +// can be used wherever , , ,