diff --git a/.gitignore b/.gitignore index 1631267c1..53a1e2eb4 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ /deno.lock /.repl_history /ROADMAP.draft.md +/SYNTAX-CHANGELOG.md +/src/data/validation.origins.json /.idea /.DS_Store /ROADMAP.md diff --git a/CHANGELOG.md b/CHANGELOG.md old mode 100644 new mode 100755 index 8be8b2861..3aa1b0f37 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,49 @@ # Changelog +# v2.1.0 + +## Bugs + +- [x] do not strip unit from dash ident #180 +- [x] deduplicate important rule #180 +- [x] incorrectly parsing keyframe rule 0% as literal token #180 + +## Feature + +- [x] now accepting arraybuffer as input data: transformSync(arraybuffer); +- [x] renamed 'word-wrap' to 'overflow-wrap', 'grid-gap' to 'gap', 'grid-row-gap' to 'row-gap', 'grid-column-gap' to 'column-gap', 'font-stretch' to 'font-width'. + +## Validation +- [x] switching syntax definitions source from mdn-data to webref/css +- [x] the validation syntaxes are generated from the CSS definitions of [W3C webref](https://github.com/w3c/webref) instead of mdn-data (deprecated): `npm run syntax-update` runs `scripts/webref.ts`, `scripts/validation.ts` is removed +- [x] the units are listed in `scripts/local-patch.json`: `@webref/css` does not list them +- [x] a function or a type defined differently for different scopes keeps its definitions: the scoped definition is inlined in the syntax of its scope (`clip: rect( , , , ) | auto`, the `` `rect()` is the shared definition) +- [x] a group is no longer matched when the value ends before its mandatory parts: `cubic-bezier(.4,0,.2)`, `[ && ]` with `` only +- [x] the range of a numeric type is checked when it is the last token: `grid-row: 0`, `width: -10px` +- [x] `#? , ` (`background`) leaves the last item to ``, a list item must match all the tokens before the next comma, `var()` may be a part of a syntax (`var(--color) 65%` in a gradient) +- [x] the longhands that follow a shorthand that contains `var()` are not merged into it: `border: var(--b); border-color: red` +- [x] a value is invalid when the tokens are not all consumed by the syntax: `color: red blue`, `width: 10px 20px` +- [x] `:` is parsed as a colon (`ValidationTokenEnum.Colon`, matches `EnumToken.ColonTokenType`) in the validation syntaxes: ` : ?`, `name: ` +- [x] a media feature length may be the number `0`: `@when media(width > 0)` +- [x] the `||` syntaxes are matched in the order that matches the most tokens: `transition: .2s ease-in-out transform` +- [x] the `&&` syntaxes are matched in any order, the optional syntaxes may be omitted: `[ && ]` matches `thin 10px` and `10px thin`, `box-shadow: 0 0 red` +- [x] new length units: `rex`, `rcap`, `rch`, `ric`, `lvmin`, `svmax`. the unit functions (`isLengthUnit()`, `isFrequencyUnit()`, ...) are case-insensitive (`Q`, `Hz`, `kHz`) +- [x] `length2Px()` converts `in` (96px) and `pc` (16px) correctly, the units are case-insensitive +- [x] a number followed by `!important` is no longer dropped: `margin: 8px 0 0!important` +- [x] the `!important` longhands are not merged into a shorthand (the minifier threw an error): `column-gap: 16px !important; row-gap: 40px !important` +- [x] new token type `EnumToken.UniCodeRange`: `U+0025-00FF`, `U+4??` are read as a single token and rendered as they are. `u+a` is a selector in a rule prelude +- [x] `unicode-range` is validated (the validation threw an error) +- [x] the units are rendered in their canonical spelling: `20hz` is rendered `20Hz`, `2q` `2Q`, `6DB` `6dB` +- [x] the numbers with an exponent are parsed: `1.5e2!important`, `1e-3`, `1e+3`, `1.5e2px` +- [x] ``, ``, `` and `` are validated (the validation threw an error): `image-resolution`, `image-set()`, `voice-pitch`, `voice-volume` +- [x] the line endings are LF +- [x] `npm run syntax-update` prints a summary of the changes between the previous and the new syntax file (added, removed and changed declarations, types and functions, selectors, at-rules, descriptors, media features, units and languages) and appends it to `SYNTAX-CHANGES.md`, ignored by git +- [x] `npm run syntax-update` reports the removed definitions grouped by origin, with the url of the file that provided them: legacy mdn-data, mdn-data patch (csstree), `local-patch.json` or removed from webref. the origins are saved in `src/data/validation.origins.json` +- [x] the syntaxes are generated from the consolidated css definitions of `@webref/css`, pulled from a versioned url (`https://cdn.jsdelivr.net/npm/@webref/css@8.7.8/css.json`, updated manually: a new version may introduce breaking changes): the definitions of the latest level of a spec are used, the extensions and the descriptors defined by other specs are merged +- [x] the renamed properties (the legacy name aliases that are not vendor prefixed) are removed from the syntax file and reported as renamed, the parser renames them: `font-stretch` -> `font-width`, `grid-gap` -> `gap`, `grid-row-gap` -> `row-gap`, `grid-column-gap` -> `column-gap`, `word-wrap` -> `overflow-wrap`. `renamedStandardProperties` is updated manually: the report flags the renamed properties it does not contain +- [x] the at-rule descriptors defined by another spec are merged: `@font-face/size-adjust` +- [x] the value types are stored without their angle brackets (`types.color` for ``) + # v2.0.1 rename file due to firefox blocking it @@ -34,7 +78,7 @@ see the [migration guide](./files/migration.md) - [x] removed `getNodeProperty()` and `setNodeProperty()`: use the arena methods (`arena.getState()`, `arena.setState()`, `arena.getErrors()`, ...) or the object view properties (`arena.toObject(id).state = ...`) - [x] `WalkerEvent` and `WalkerOptionEnum` are declared with the other enums (they are still exported by the package) -performance +## performance - [x] the parser recycles the tokens that are not attached to the tree (whitespace, `:`, `;`, `{`, `}`, ...): the arena allocates about half the nodes. `arena.recycle(id)` reuses the id of a detached leaf node - [x] the initial arena capacity is one node for every 4 bytes of css diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3dbd16ecc..943270f9e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,7 @@ npm run config-update npm run syntax-update ``` -`config-update` regenerates `src/data/properties.json`. `syntax-update` regenerates `src/data/validation.json` from upstream CSS data and therefore requires an internet connection. Review the generated changes and include them when they are relevant to your contribution. +`config-update` regenerates `src/data/properties.json`. `syntax-update` regenerates `src/data/validation.json` from the consolidated [W3C webref](https://github.com/w3c/webref) CSS definitions (`https://cdn.jsdelivr.net/npm/@webref/css@8.7.8/css.json`, `@webref/css` is not a dependency: update the version in `scripts/webref.ts` to use a newer version. mdn-data and the csstree patch are also pulled from versioned urls) and therefore requires an internet connection. It prints a summary of the syntax changes and appends it to `SYNTAX-CHANGES.md` (ignored by git): port the relevant changes to `CHANGELOG.md`. The removed definitions are grouped by origin (legacy mdn-data, mdn-data patch, `scripts/local-patch.json` or removed from webref), using the origins saved in `src/data/validation.origins.json`: commit it with `src/data/validation.json`. The properties and the selectors that webref does not define keep their mdn-data definition, with the types they reference (the non standard properties `box-orient`, `font-smooth`, `-ms-user-select`, `-webkit-tap-highlight-color`, the pseudo elements `::-webkit-slider-thumb`): the results are the same as with the syntax files generated from mdn-data. The other definitions that webref does not provide (prose syntaxes, units) are added to `scripts/local-patch.json`. The renamed properties (the legacy name aliases of webref that are not vendor prefixed) are reported as renamed: add them to `renamedStandardProperties` (`src/lib/syntax/syntax.ts`). The vendor prefixed legacy name aliases are stored as aliases of the standard property, with no other key (`"-webkit-align-content": { "alias": "align-content" }`): they are validated with its syntax and they are not renamed. When mdn-data, the csstree patch or `scripts/local-patch.json` provide a legacy syntax for a vendor prefixed alias, the syntax of the standard property is extended with it (`-webkit-mask-clip: <'mask-clip'> | [ | no-clip | border | padding | content | text ]#`): add the legacy syntax of a vendor prefixed alias to `scripts/local-patch.json`, the script adds the syntax of the standard property. The sources are applied in this order: mdn-data, the csstree patch, `scripts/local-patch.json`. A patch replaces the legacy syntax of the previous sources, or extends it when its syntax starts with `|`. Review the generated changes and include them when they are relevant to your contribution. ## Building diff --git a/README.md b/README.md index 1539abe2f..7cfa5026f 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ $ deno add @tbela99/css-parser * **CSS variable inlining** where values can be safely resolved. * **Duplicate declaration removal** to eliminate redundant rules. * **`@import` flattening** to produce self-contained stylesheets. +* **Binary input** — the css can be a string, an `ArrayBuffer` or an `ArrayBufferView` (utf-8 bytes, `Uint8Array`, `Buffer`): an ASCII buffer is tokenized without copy. * **51.5kb** once minified and gzipped. ## Vendor prefix removal @@ -113,7 +114,7 @@ Performance vs execution speed comparison | File: tailwind.css | Speed optimization | Minification optimization | | --------------------- | ------------------ | ------------------------- | | Size: 2,380,419 bytes | 1,890,835 bytes | 1,633,188 bytes | -| Time | 128.67 ms | 268.86 ms | +| Time | 116.61 ms | 224.18 ms | | Size reduction | -20.6% | -31.4% | ## Playground diff --git a/benchmark/package.json b/benchmark/package.json index 93fdb1cb8..22c0e8499 100644 --- a/benchmark/package.json +++ b/benchmark/package.json @@ -10,15 +10,15 @@ "all": "npm run sizes && npm run bench; npm run report" }, "dependencies": { - "@tbela99/css-parser": "github:tbela99/css-parser#007a292", - "@tbela99/css-parser2": "github:tbela99/css-parser#007a292", + "@tbela99/css-parser": "github:tbela99/css-parser#v2.0.1", + "@tbela99/css-parser2": "github:tbela99/css-parser#d237344", "clean-css": "^5.3.3", "css-tree": "^3.2.1", "cssnano": "^9.9.0", "csso": "^5.0.5", "esbuild": "^0.28.2", "lightningcss": "^1.33.0", - "postcss": "^8.5.32", + "postcss": "^8.5.33", "vitest": "^5.1.0", "yuku-css": "^0.2.0" } diff --git a/benchmark/src/minifiers.js b/benchmark/src/minifiers.js index dcc5048fb..384d48bd5 100644 --- a/benchmark/src/minifiers.js +++ b/benchmark/src/minifiers.js @@ -80,24 +80,24 @@ const cssnanoProcessor = postcss([cssnano]); * official table's "name - version" formatting. */ export const minifiers = [ - { - id: "clean-css", - url: versions["clean-css"].url, - label: `clean-css - ${versions["clean-css"].version}`, - minify: (css) => cleanCssInstance.minify(css).styles, - }, - { - id: "cssnano", - url: versions.cssnano.url, - label: `cssnano - ${versions.cssnano.version}`, - minify: async (css) => (await cssnanoProcessor.process(css, { from: undefined })).css, - }, - { - id: "csso", - url: versions.csso.url, - label: `csso - ${versions.csso.version}`, - minify: (css) => csso.minify(css).css, - }, + // { + // id: "clean-css", + // url: versions["clean-css"].url, + // label: `clean-css - ${versions["clean-css"].version}`, + // minify: (css) => cleanCssInstance.minify(css).styles, + // }, + // { + // id: "cssnano", + // url: versions.cssnano.url, + // label: `cssnano - ${versions.cssnano.version}`, + // minify: async (css) => (await cssnanoProcessor.process(css, { from: undefined })).css, + // }, + // { + // id: "csso", + // url: versions.csso.url, + // label: `csso - ${versions.csso.version}`, + // minify: (css) => csso.minify(css).css, + // }, // infinite loop bug { id: "css-tree", @@ -127,9 +127,18 @@ export const minifiers = [ minify: (css) => yukuTransform(css).code, }, { - id: "css-parser", + id: "css-parser-default", + url: versions["css-parser"].url, + label: `@tbela99/css-parser - ${versions["css-parser"].version}`, + minify: async (css) => + tbelaTransform({ + input: css, + }).code, + }, + { + id: "css-parser-speed", url: versions["css-parser"].url, - label: `@tbela99/css-parser (speed) - ${versions["css-parser"].version}`, + label: `@tbela99/css-parser (fast) - ${versions["css-parser"].version}`, title: `settings: { minify: false, beautify: false, removeEmpty: true, removeComments: true, convertColor: true }`, minify: async (css) => tbelaTransform({ @@ -145,7 +154,23 @@ export const minifiers = [ { id: "css-parser-dev", url: versions["css-parser-dev"].url, - label: `@tbela99/css-parser-dev (default) - ${versions["css-parser-dev"].version}`, - minify: async (css) => tbelaDevTransform({ input: css }).code, - } + label: `@tbela99/css-parser-dev - ${versions["css-parser-dev"].version}`, + minify: async (css) => tbelaDevTransform({ input: Buffer.from(css) }).code, + }, + { + id: "css-parser-dev-speed", + url: versions["css-parser-dev"].url, + label: `@tbela99/css-parser-dev (fast) - ${versions["css-parser-dev"].version}`, + title: `settings: { minify: false, beautify: false, removeEmpty: true, removeComments: true, convertColor: true }`, + minify: async (css) => + tbelaDevTransform({ + input: Buffer.from(css), + minify: false, + beautify: false, + removeEmpty: true, + removeComments: true, + convertColor: true, + // minifyValues: true, + }).code, + }, ]; diff --git a/dist/index-umd-web.js b/dist/index-umd-web.js index 92466a628..f3159be7f 100644 --- a/dist/index-umd-web.js +++ b/dist/index-umd-web.js @@ -2,7 +2,7 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ (function (global, factory) { @@ -11,18 +11,6 @@ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CSSParser = {})); })(this, (function (exports) { 'use strict'; - /** - * Syntax validation enum - */ - var SyntaxValidationResult; - (function (SyntaxValidationResult) { - /** valid syntax */ - SyntaxValidationResult[SyntaxValidationResult["Valid"] = 0] = "Valid"; - /** drop invalid syntax */ - SyntaxValidationResult[SyntaxValidationResult["Drop"] = 1] = "Drop"; - /** preserve unknown at-rules, declarations and pseudo-classes */ - SyntaxValidationResult[SyntaxValidationResult["Lenient"] = 2] = "Lenient"; - })(SyntaxValidationResult || (SyntaxValidationResult = {})); /** * Enum of node statuses */ @@ -666,6 +654,10 @@ * user defined dimension token type */ EnumToken[EnumToken["UserDefinedDimensionTokenType"] = 140] = "UserDefinedDimensionTokenType"; + /** + * unicode range token type: `U+0025-00FF`, `U+4??`. the token is rendered as it is + */ + EnumToken[EnumToken["UniCodeRange"] = 141] = "UniCodeRange"; /* aliases */ /** * alias for time token type @@ -1035,16 +1027,16 @@ function pushValues(arena, stack, value, reverse) { const first = stack.length; let token = arena.firstToken[value]; - while (token != 0) { + while (token !== 0) { stack.push(token); token = arena.nextSibling[token]; } - if ((arena.flags[value] & exports.EnumAstNodeStatus.HasChildren) == 0) { + if ((arena.flags[value] & exports.EnumAstNodeStatus.HasChildren) === 0) { let child = arena.firstChild[value]; - while (child != 0) { - if (arena.dataTypes[child] == exports.EnumToken.ListTokenType) { + while (child !== 0) { + if (arena.dataTypes[child] === exports.EnumToken.ListTokenType) { token = arena.firstToken[child]; - while (token != 0) { + while (token !== 0) { stack.push(token); token = arena.nextSibling[token]; } @@ -1083,7 +1075,7 @@ constructor(arena, node, filter, reverse) { this.arena = arena; this.stack = [node]; - if (filter != null && typeof filter == "object") { + if (filter != null && typeof filter === "object") { this.filter = filter.filter ?? null; this.reverse = filter.reverse === true; this.attributes = filter.attributes === true; @@ -1103,7 +1095,7 @@ * @param option */ expand(node, option) { - if (typeof option == "number" && option & exports.WalkerOptionEnum.IgnoreChildren) { + if (typeof option === "number" && option & exports.WalkerOptionEnum.IgnoreChildren) { return; } const arena = this.arena; @@ -1115,12 +1107,12 @@ if (this.children && arena.flags[node] & exports.EnumAstNodeStatus.HasChildren) { // children are pushed in reverse so that they are popped in document order if (this.reverse) { - for (let child = arena.firstChild[node]; child != 0; child = arena.nextSibling[child]) { + for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) { stack.push(child); } } else { - for (let child = arena.lastChild[node]; child != 0; child = arena.previousSibling[child]) { + for (let child = arena.lastChild[node]; child !== 0; child = arena.previousSibling[child]) { stack.push(child); } } @@ -1129,7 +1121,7 @@ next() { const stack = this.stack; const filter = this.filter; - if (this.current != 0) { + if (this.current !== 0) { this.expand(this.current, this.option); this.current = 0; } @@ -1138,7 +1130,7 @@ let option = null; if (filter != null) { option = filter(this.arena, node); - if (typeof option == "number") { + if (typeof option === "number") { if (option & exports.WalkerOptionEnum.Ignore) { continue; } @@ -1192,7 +1184,7 @@ constructor(arena, tokens, filter, reverse) { this.arena = arena; this.reverse = reverse === true; - if (typeof tokens == "number") { + if (typeof tokens === "number") { // the value tokens of a node or a token pushValues(arena, this.stack, tokens, this.reverse); } @@ -1207,7 +1199,7 @@ } } // the filter is read once: no filter object is created - if (typeof filter == "function") { + if (typeof filter === "function") { this.fn = filter; } else if (filter != null) { @@ -1228,7 +1220,7 @@ return (type == null || this.arena.dataTypes[token] == type || (Array.isArray(type) && type.includes(this.arena.dataTypes[token])) || - (typeof type == "function" && type(this.arena, token))); + (typeof type === "function" && type(this.arena, token))); } /** * the tokens returned by the filter are visited too @@ -1252,7 +1244,7 @@ leave(value) { const option = this.option; // the children are read after the token is visited (it may have been modified) - if (typeof option != "number" || (option & exports.WalkerOptionEnum.IgnoreChildren) === 0) { + if (typeof option !== "number" || (option & exports.WalkerOptionEnum.IgnoreChildren) === 0) { pushValues(this.arena, this.stack, value, this.reverse); } if (this.eventType & exports.WalkerEvent.Leave && this.fn != null && this.isValid(value)) { @@ -1264,7 +1256,7 @@ } next() { const stack = this.stack; - if (this.current != 0) { + if (this.current !== 0) { this.leave(this.current); this.current = 0; } @@ -1274,7 +1266,7 @@ if (this.fn != null && this.eventType & exports.WalkerEvent.Enter && this.isValid(value)) { const option = this.fn(this.arena, value, exports.WalkerEvent.Enter); this.option = option; - if (typeof option == "number") { + if (typeof option === "number") { if (option & exports.WalkerOptionEnum.Stop) { break; } @@ -1349,10 +1341,10 @@ * @param typ */ function hasValueTokens(typ) { - return (typ == exports.EnumToken.DeclarationNodeType || - typ == exports.EnumToken.CssVariableTokenType || - typ == exports.EnumToken.CssVariableImportTokenType || - typ == exports.EnumToken.CssVariableDeclarationMapTokenType); + return (typ === exports.EnumToken.DeclarationNodeType || + typ === exports.EnumToken.CssVariableTokenType || + typ === exports.EnumToken.CssVariableImportTokenType || + typ === exports.EnumToken.CssVariableDeclarationMapTokenType); } /** * convert setter values to node ids of the arena. {@link AstArenaNode} of the arena are used as is (no copy), the nodes @@ -1367,13 +1359,13 @@ } if (!Array.isArray(values)) { const value = values; - result.push(typeof value == "number" ? value : arena.fromObject(value)); + result.push(typeof value === "number" ? value : arena.fromObject(value)); return result; } const list = values; for (let i = 0; i < list.length; i++) { const value = list[i]; - result.push(typeof value == "number" ? value : arena.fromObject(value)); + result.push(typeof value === "number" ? value : arena.fromObject(value)); } return result; } @@ -1384,7 +1376,7 @@ */ function listViews(arena, first) { const result = []; - for (let id = first; id != 0; id = arena.nextSibling[id]) { + for (let id = first; id !== 0; id = arena.nextSibling[id]) { result.push(new AstArenaNode(arena, id)); } return Object.freeze(result); @@ -1451,12 +1443,16 @@ const id = this[ARENAID]; const typ = arena.dataTypes[id]; if (isNodeObjectType(typ)) { - return typ == exports.EnumToken.AtRuleNodeType || typ == exports.EnumToken.KeyframesAtRuleNodeType || hasValueTokens(typ) + return typ === exports.EnumToken.AtRuleNodeType || typ === exports.EnumToken.KeyframesAtRuleNodeType || hasValueTokens(typ) ? arena.strings[arena.name[id]] : undefined; } - return arena.name[id] == 0 ? undefined : arena.strings[arena.name[id]]; + return arena.name[id] === 0 ? undefined : arena.strings[arena.name[id]]; } + /** + * + * @param nam + */ set nam(nam) { this[ARENA].name[this[ARENAID]] = this[ARENA].internString(nam); } @@ -1467,10 +1463,14 @@ const arena = this[ARENA]; const id = this[ARENAID]; const typ = arena.dataTypes[id]; - return typ == exports.EnumToken.RuleNodeType || typ == exports.EnumToken.KeyframesRuleNodeType + return typ === exports.EnumToken.RuleNodeType || typ === exports.EnumToken.KeyframesRuleNodeType ? arena.strings[arena.name[id]] : undefined; } + /** + * + * @param sel + */ set sel(sel) { this[ARENA].name[this[ARENAID]] = this[ARENA].internString(sel); } @@ -1491,30 +1491,34 @@ if (hasValueTokens(typ)) { return listViews(arena, arena.firstToken[id]); } - return typ == exports.EnumToken.StyleSheetNodeType || - typ == exports.EnumToken.RuleNodeType || - typ == exports.EnumToken.KeyframesRuleNodeType + return typ === exports.EnumToken.StyleSheetNodeType || + typ === exports.EnumToken.RuleNodeType || + typ === exports.EnumToken.KeyframesRuleNodeType ? undefined : arena.strings[arena.stringValue[id]]; } - if (typ == exports.EnumToken.BinaryExpressionTokenType || typ == exports.EnumToken.FractionTokenType) { + if (typ === exports.EnumToken.BinaryExpressionTokenType || typ === exports.EnumToken.FractionTokenType) { return undefined; } - if (typ == exports.EnumToken.UnaryExpressionTokenType) { - return arena.firstChild[id] == 0 ? null : new AstArenaNode(arena, arena.firstChild[id]); + if (typ === exports.EnumToken.UnaryExpressionTokenType) { + return arena.firstChild[id] === 0 ? null : new AstArenaNode(arena, arena.firstChild[id]); } if (numericTokenTypes.has(typ)) { const fraction = arena.getFraction(id); - return fraction == 0 ? arena.numericValue[id] : new AstArenaNode(arena, fraction); + return fraction === 0 ? arena.numericValue[id] : new AstArenaNode(arena, fraction); } const field = this.getField("val"); if (field !== undefined) { return field; } - return arena.stringValue[id] != 0 || typ == exports.EnumToken.IdenTokenType || typ == exports.EnumToken.StringTokenType + return arena.stringValue[id] !== 0 || typ === exports.EnumToken.IdenTokenType || typ === exports.EnumToken.StringTokenType ? arena.strings[arena.stringValue[id]] : undefined; } + /** + * + * @param val + */ set val(val) { const arena = this[ARENA]; const id = this[ARENAID]; @@ -1523,7 +1527,7 @@ arena.setTokenList(id, toIds(arena, val)); return; } - if (typeof val == "string") { + if (typeof val === "string") { if (numericTokenTypes.has(typ)) { arena.numericValue[id] = +val; arena.setFraction(id, null); @@ -1533,14 +1537,14 @@ } return; } - if (typeof val == "number") { + if (typeof val === "number") { arena.numericValue[id] = val; if (numericTokenTypes.has(typ)) { arena.setFraction(id, null); } return; } - if (typ == exports.EnumToken.UnaryExpressionTokenType) { + if (typ === exports.EnumToken.UnaryExpressionTokenType) { arena.setChildList(id, toIds(arena, val)); } else if (numericTokenTypes.has(typ)) { @@ -1560,24 +1564,28 @@ if (arena.flags[id] & exports.EnumAstNodeStatus.HasChildren) { return listViews(arena, arena.firstChild[id]); } - if (isNodeObjectType(arena.dataTypes[id]) || arena.firstToken[id] == 0) { + if (isNodeObjectType(arena.dataTypes[id]) || arena.firstToken[id] === 0) { return undefined; } return listViews(arena, arena.firstToken[id]); } + /** + * + * @param chi + */ set chi(chi) { const arena = this[ARENA]; const id = this[ARENAID]; const typ = arena.dataTypes[id]; - if (typ == exports.EnumToken.StyleSheetNodeType || - typ == exports.EnumToken.RuleNodeType || - typ == exports.EnumToken.KeyframesRuleNodeType || - typ == exports.EnumToken.AtRuleNodeType || - typ == exports.EnumToken.KeyframesAtRuleNodeType) { + if (typ === exports.EnumToken.StyleSheetNodeType || + typ === exports.EnumToken.RuleNodeType || + typ === exports.EnumToken.KeyframesRuleNodeType || + typ === exports.EnumToken.AtRuleNodeType || + typ === exports.EnumToken.KeyframesAtRuleNodeType) { if (chi == null) { // an at-rule without a block arena.setChildList(id, []); - if (typ == exports.EnumToken.AtRuleNodeType || typ == exports.EnumToken.KeyframesAtRuleNodeType) { + if (typ === exports.EnumToken.AtRuleNodeType || typ === exports.EnumToken.KeyframesAtRuleNodeType) { arena.flags[id] &= ~exports.EnumAstNodeStatus.HasChildren; } return; @@ -1594,10 +1602,14 @@ get tokens() { const arena = this[ARENA]; const id = this[ARENAID]; - return (arena.flags[id] & exports.EnumAstNodeStatus.HasValues) != 0 || arena.firstToken[id] == 0 + return (arena.flags[id] & exports.EnumAstNodeStatus.HasValues) !== 0 || arena.firstToken[id] === 0 ? null : listViews(arena, arena.firstToken[id]); } + /** + * + * @param tokens + */ set tokens(tokens) { this[ARENA].setTokenList(this[ARENAID], toIds(this[ARENA], tokens)); } @@ -1608,10 +1620,14 @@ const arena = this[ARENA]; const id = this[ARENAID]; const typ = arena.dataTypes[id]; - return arena.unit[id] == 0 || typ == exports.EnumToken.ColorTokenType || typ == exports.EnumToken.MatchExpressionTokenType + return arena.unit[id] === 0 || typ === exports.EnumToken.ColorTokenType || typ === exports.EnumToken.MatchExpressionTokenType ? undefined : arena.strings[arena.unit[id]]; } + /** + * + * @param unit + */ set unit(unit) { this[ARENA].setUnitString(this[ARENAID], unit ?? null); } @@ -1621,7 +1637,7 @@ get cal() { const arena = this[ARENA]; const id = this[ARENAID]; - return arena.unit[id] == 0 || arena.dataTypes[id] != exports.EnumToken.ColorTokenType + return arena.unit[id] === 0 || arena.dataTypes[id] !== exports.EnumToken.ColorTokenType ? undefined : arena.strings[arena.unit[id]]; } @@ -1634,7 +1650,7 @@ get attr() { const arena = this[ARENA]; const id = this[ARENAID]; - return arena.unit[id] == 0 || arena.dataTypes[id] != exports.EnumToken.MatchExpressionTokenType + return arena.unit[id] === 0 || arena.dataTypes[id] !== exports.EnumToken.MatchExpressionTokenType ? undefined : arena.strings[arena.unit[id]]; } @@ -1647,7 +1663,7 @@ get kin() { const arena = this[ARENA]; const id = this[ARENAID]; - return arena.dataTypes[id] != exports.EnumToken.ColorTokenType || arena.colorType[id] == exports.ColorType.NONE + return arena.dataTypes[id] !== exports.EnumToken.ColorTokenType || arena.colorType[id] === exports.ColorType.NONE ? undefined : arena.colorType[id]; } @@ -1660,8 +1676,12 @@ get sign() { const arena = this[ARENA]; const id = this[ARENAID]; - return arena.dataTypes[id] == exports.EnumToken.UnaryExpressionTokenType ? arena.numericValue[id] : undefined; + return arena.dataTypes[id] === exports.EnumToken.UnaryExpressionTokenType ? arena.numericValue[id] : undefined; } + /** + * + * @param sign + */ set sign(sign) { this[ARENA].numericValue[this[ARENAID]] = sign; } @@ -1671,12 +1691,18 @@ get op() { const arena = this[ARENA]; const id = this[ARENAID]; - return arena.dataTypes[id] == exports.EnumToken.BinaryExpressionTokenType ? arena.numericValue[id] : this.getField("op"); + return arena.dataTypes[id] === exports.EnumToken.BinaryExpressionTokenType + ? arena.numericValue[id] + : this.getField("op"); } + /** + * + * @param op + */ set op(op) { const arena = this[ARENA]; const id = this[ARENAID]; - if (arena.dataTypes[id] == exports.EnumToken.BinaryExpressionTokenType) { + if (arena.dataTypes[id] === exports.EnumToken.BinaryExpressionTokenType) { arena.numericValue[id] = op; } else { @@ -1689,6 +1715,10 @@ get op1() { return this.getField("op1"); } + /** + * + * @param op + */ set op1(op) { this.setField("op1", op); } @@ -1698,6 +1728,10 @@ get op2() { return this.getField("op2"); } + /** + * + * @param op + */ set op2(op) { this.setField("op2", op); } @@ -1707,18 +1741,22 @@ get l() { const arena = this[ARENA]; const id = this[ARENAID]; - if (arena.dataTypes[id] == exports.EnumToken.FractionTokenType) { - return arena.firstChild[id] == 0 ? null : new AstArenaNode(arena, arena.firstChild[id]); + if (arena.dataTypes[id] === exports.EnumToken.FractionTokenType) { + return arena.firstChild[id] === 0 ? null : new AstArenaNode(arena, arena.firstChild[id]); } return this.getField("l"); } + /** + * + * @param l + */ set l(l) { const arena = this[ARENA]; const id = this[ARENAID]; - if (arena.dataTypes[id] == exports.EnumToken.FractionTokenType) { + if (arena.dataTypes[id] === exports.EnumToken.FractionTokenType) { const r = arena.lastChild[id]; const values = toIds(arena, l); - if (r != 0 && r != arena.firstChild[id]) { + if (r !== 0 && r !== arena.firstChild[id]) { values.push(r); } arena.setChildList(id, values); @@ -1732,18 +1770,22 @@ get r() { const arena = this[ARENA]; const id = this[ARENAID]; - if (arena.dataTypes[id] == exports.EnumToken.FractionTokenType) { - return arena.lastChild[id] == 0 ? null : new AstArenaNode(arena, arena.lastChild[id]); + if (arena.dataTypes[id] === exports.EnumToken.FractionTokenType) { + return arena.lastChild[id] === 0 ? null : new AstArenaNode(arena, arena.lastChild[id]); } return this.getField("r"); } + /** + * + * @param r + */ set r(r) { const arena = this[ARENA]; const id = this[ARENAID]; - if (arena.dataTypes[id] == exports.EnumToken.FractionTokenType) { + if (arena.dataTypes[id] === exports.EnumToken.FractionTokenType) { const l = arena.firstChild[id]; const values = toIds(arena, r); - if (l != 0) { + if (l !== 0) { values.unshift(l); } arena.setChildList(id, values); @@ -1759,6 +1801,10 @@ // a copy of the location: it cannot be modified, assign the property instead return loc == null ? null : Object.freeze(loc); } + /** + * + * @param loc + */ set loc(loc) { this[ARENA].setLocation(this[ARENAID], loc?.srcId, loc?.sta, loc?.end); } @@ -1768,6 +1814,10 @@ get state() { return this[ARENA].flags[this[ARENAID]] & exports.EnumAstNodeStatus.StateMask; } + /** + * + * @param state + */ set state(state) { this[ARENA].setState(this[ARENAID], state); } @@ -1779,6 +1829,10 @@ // the error list may be shared by the clones of the node: a frozen copy, assign the property instead return errors == null ? null : Object.freeze(errors.slice()); } + /** + * + * @param errors + */ set errors(errors) { this[ARENA].setErrors(this[ARENAID], errors == null ? null : errors.slice()); } @@ -1788,7 +1842,7 @@ */ get parent() { const parent = this[ARENA].getValueParent(this[ARENAID]); - return parent == 0 ? null : new AstArenaNode(this[ARENA], parent); + return parent === 0 ? null : new AstArenaNode(this[ARENA], parent); } /** * value of a structured token field. undefined when the token has no such field @@ -1799,7 +1853,7 @@ const id = this[ARENAID]; const fields = structuredFields(arena.dataTypes[id]); for (let i = 0; i < fields.length; i++) { - if (fields[i][0] != key) { + if (fields[i][0] !== key) { continue; } const list = arena.getChildAt(id, fields[i][1]); @@ -1807,7 +1861,7 @@ return undefined; } if (fields[i][2]) { - return arena.firstToken[list] == 0 ? null : new AstArenaNode(arena, arena.firstToken[list]); + return arena.firstToken[list] === 0 ? null : new AstArenaNode(arena, arena.firstToken[list]); } return listViews(arena, arena.firstToken[list]); } @@ -1823,7 +1877,7 @@ const id = this[ARENAID]; const fields = structuredFields(arena.dataTypes[id]); for (let i = 0; i < fields.length; i++) { - if (fields[i][0] == key) { + if (fields[i][0] === key) { arena.setTokenList(arena.fieldList(id, fields[i][1]), toIds(arena, value)); return true; } @@ -1854,7 +1908,7 @@ if (a == null || b == null) { return a == b; } - if (typeof a != "object" || typeof b != "object") { + if (typeof a !== "object" || typeof b !== "object") { return a === b; } if (a.constructor != b.constructor) { @@ -1874,7 +1928,7 @@ } const k1 = Object.keys(a); const k2 = Object.keys(b); - if (k1.length != k2.length) { + if (k1.length !== k2.length) { return false; } let key; @@ -1893,14 +1947,14 @@ * @param b */ function eqToken(arena, a, b) { - if (a == b) { + if (a === b) { return true; } - if (arena.dataTypes[a] != arena.dataTypes[b] || - arena.name[a] != arena.name[b] || - arena.stringValue[a] != arena.stringValue[b] || - arena.unit[a] != arena.unit[b] || - arena.colorType[a] != arena.colorType[b]) { + if (arena.dataTypes[a] !== arena.dataTypes[b] || + arena.name[a] !== arena.name[b] || + arena.stringValue[a] !== arena.stringValue[b] || + arena.unit[a] !== arena.unit[b] || + arena.colorType[a] !== arena.colorType[b]) { return false; } const x = arena.numericValue[a]; @@ -1911,29 +1965,416 @@ } let ta = arena.firstToken[a]; let tb = arena.firstToken[b]; - while (ta != 0 && tb != 0) { + while (ta !== 0 && tb !== 0) { if (!eqToken(arena, ta, tb)) { return false; } ta = arena.nextSibling[ta]; tb = arena.nextSibling[tb]; } - if (ta != tb) { + if (ta !== tb) { return false; } ta = arena.firstChild[a]; tb = arena.firstChild[b]; - while (ta != 0 && tb != 0) { + while (ta !== 0 && tb !== 0) { if (!eqToken(arena, ta, tb)) { return false; } ta = arena.nextSibling[ta]; tb = arena.nextSibling[tb]; } - return ta == tb; + return ta === tb; } + var atRules = { + "@annotation": { + syntax: "@annotation { }" + }, + "@apply": { + syntax: " @apply [ | ] [ { } ]?;" + }, + "@bottom-center": { + syntax: "@bottom-center { };" + }, + "@bottom-left": { + syntax: " @bottom-left { }" + }, + "@bottom-left-corner": { + syntax: " @bottom-left-corner { }" + }, + "@bottom-right": { + syntax: " @bottom-right { }" + }, + "@bottom-right-corner": { + syntax: " @bottom-right-corner { }" + }, + "@character-variant": { + syntax: "@character-variant { }" + }, + "@charset": { + syntax: "@charset \"\";" + }, + "@color-profile": { + syntax: "@color-profile [ | device-cmyk] { }", + descriptors: { + components: "#", + "rendering-intent": "relative-colorimetric | absolute-colorimetric | perceptual | saturation", + src: "" + } + }, + "@container": { + syntax: "@container # { }", + descriptors: { + "aspect-ratio": "", + "block-size": "", + fallback: "none | [ [ || ] | ]", + height: "", + "inline-size": "", + orientation: "portrait | landscape", + scrollable: "none | top | right | bottom | left | block-start | inline-start | block-end | inline-end | x | y | block | inline", + scrolled: "none | top | right | bottom | left | block-start | inline-start | block-end | inline-end | x | y | block | inline", + snapped: "none | x | y | block | inline | both", + stuck: "none | top | right | bottom | left | block-start | inline-start | block-end | inline-end", + width: "" + } + }, + "@contents": { + syntax: " @contents [ { } ]?;" + }, + "@counter-style": { + syntax: "@counter-style { }", + descriptors: { + "additive-symbols": "[ && ]#", + fallback: "", + negative: " ?", + pad: " && ", + prefix: "", + range: "[ [ | infinite ]{2} ]# | auto", + "speak-as": "auto | bullets | numbers | words | spell-out | ", + suffix: "", + symbols: "+", + system: "cyclic | numeric | alphabetic | symbolic | additive | [fixed ?] | [ extends ]" + } + }, + "@custom-media": { + syntax: " @custom-media [ | true | false ];" + }, + "@custom-selector": { + syntax: "@custom-selector ;" + }, + "@document": { + syntax: "@document [ | url-prefix() | domain() | media-document() | regexp() ]# {\n \n}" + }, + "@else": { + syntax: " @else ? {\n \n}" + }, + "@font-face": { + syntax: "@font-face { }", + descriptors: { + "ascent-override": "[ normal | ]{1,2}", + "descent-override": "[ normal | ]{1,2}", + "font-display": "auto | block | swap | fallback | optional", + "font-family": "", + "font-feature-settings": "normal | #", + "font-language-override": "normal | ", + "font-named-instance": "auto | ", + "font-size": "auto | []{1,2}", + "font-style": "auto | normal | italic | left | right | oblique [ {1,2} ]?", + "font-variation-settings": "normal | [ ]#", + "font-weight": "auto | {1,2}", + "font-width": "auto | <'font-width'>{1,2}", + "line-gap-override": "[ normal | ]{1,2}", + "size-adjust": "", + src: "", + "subscript-position-override": "[ normal | from-font | ]{1,2}", + "subscript-size-override": "[ normal | from-font | ]{1,2}", + "superscript-position-override": "[ normal | from-font | ]{1,2}", + "superscript-size-override": "[ normal | from-font | ]{1,2}", + "unicode-range": "#" + } + }, + "@font-feature-values": { + syntax: " @font-feature-values # { <@historical-forms> | <@styleset> | <@character-variant> | <@swash> | <@ornaments> | <@annotation> } ", + descriptors: { + "font-display": { + syntax: "auto | block | swap | fallback | optional" + } + } + }, + "@font-features-values": { + descriptors: { + "font-display": "auto | block | swap | fallback | optional" + } + }, + "@font-palette-values": { + syntax: "@font-palette-values { }", + descriptors: { + "base-palette": "light | dark | ", + "font-family": "#", + "override-colors": "[ ]#" + } + }, + "@function": { + syntax: "@function #? ) [ returns ]? { }", + descriptors: { + result: "?" + } + }, + "@historical-forms": { + syntax: " @historical-forms { }" + }, + "@import": { + syntax: "@import [ | ] [[ layer | layer( ) ] || [ scope | scope( | ) ] || ]? ;" + }, + "@keyframes": { + syntax: "@keyframes { }" + }, + "@layer": { + syntax: "@layer [ # | ? {\n \n} ]" + }, + "@left-bottom": { + syntax: " @left-bottom { }" + }, + "@left-middle": { + syntax: " @left-middle { }" + }, + "@left-top": { + syntax: " @left-top { }" + }, + "@location": { + syntax: "" + }, + "@media": { + syntax: "@media { }" + }, + "@mixin": { + syntax: "@mixin [ #? ) | ] { }" + }, + "@namespace": { + syntax: "@namespace ? [ | ] ;" + }, + "@navigation": { + syntax: "@navigation { }" + }, + "@ornaments": { + syntax: "@ornaments { }" + }, + "@page": { + syntax: "@page ? { }", + descriptors: { + bleed: "auto | ", + marks: "none | [ crop || cross ]", + "page-margin-safety": "none | clamp | add", + "page-orientation": "upright | rotate-left | rotate-right", + size: "{1,2} | auto | [ || [ portrait | landscape ] ]" + } + }, + "@position-try": { + syntax: " @position-try { } ", + descriptors: { + "align-self": "<'align-self'> | anchor-center", + "block-size": "<'block-size'>", + bottom: "<'bottom'>", + height: "<'height'>", + "inline-size": "<'inline-size'>", + inset: "<'inset'>", + "inset-block": "<'inset-block'>", + "inset-block-end": "<'inset-block-end'>", + "inset-block-start": "<'inset-block-start'>", + "inset-inline": "<'inset-inline'>", + "inset-inline-end": "<'inset-inline-end'>", + "inset-inline-start": "<'inset-inline-start'>", + "justify-self": "<'justify-self'> | anchor-center", + left: "<'left'>", + margin: "<'margin'>", + "margin-block": "<'margin-block'>", + "margin-block-end": "<'margin-block-end'>", + "margin-block-start": "<'margin-block-start'>", + "margin-bottom": "<'margin-bottom'>", + "margin-inline": "<'margin-inline'>", + "margin-inline-end": "<'margin-inline-end'>", + "margin-inline-start": "<'margin-inline-start'>", + "margin-left": "<'margin-left'>", + "margin-right": "<'margin-right'>", + "margin-top": "<'margin-top'>", + "max-block-size": "<'max-block-size'>", + "max-height": "<'max-height'>", + "max-inline-size": "<'max-inline-size'>", + "max-width": "<'max-width'>", + "min-block-size": "<'min-block-size'>", + "min-height": "<'min-height'>", + "min-inline-size": "<'min-inline-size'>", + "min-width": "<'min-width'>", + right: "<'right'>", + top: "<'top'>", + width: "<'width'>" + } + }, + "@private": { + syntax: "@private { }" + }, + "@property": { + syntax: "@property # { }", + descriptors: { + syntax: "", + inherits: "true | false", + "initial-value": "?" + } + }, + "@right-bottom": { + syntax: " @right-bottom { }" + }, + "@right-middle": { + syntax: " @right-middle { }" + }, + "@right-top": { + syntax: " @right-top { }" + }, + "@scope": { + syntax: "@scope ? { }" + }, + "@starting-style": { + syntax: "@starting-style {\n | \n}" + }, + "@styleset": { + syntax: "@styleset { }" + }, + "@stylistic": { + syntax: "@stylistic { }" + }, + "@supports": { + syntax: "@supports { }" + }, + "@supports-condition": { + syntax: "@supports-condition { }" + }, + "@swash": { + syntax: "@swash { }" + }, + "@top-center": { + syntax: " @top-center { }" + }, + "@top-left": { + syntax: " @top-left { }" + }, + "@top-left-corner": { + syntax: " @top-left-corner { }" + }, + "@top-right": { + syntax: " @top-right { }" + }, + "@top-right-corner": { + syntax: " @top-right-corner { }" + }, + "@value": { + syntax: "@value [ | [ # from ] ]" + }, + "@view-transition": { + syntax: "@view-transition { }", + descriptors: { + navigation: "auto | none", + types: "none | +" + } + }, + "@when": { + syntax: " @when {\n \n}" + } + }; var declarations = { + "-moz-appearance": { + syntax: "none | button | button-arrow-down | button-arrow-next | button-arrow-previous | button-arrow-up | button-bevel | button-focus | caret | checkbox | checkbox-container | checkbox-label | checkmenuitem | dualbutton | groupbox | listbox | listitem | menuarrow | menubar | menucheckbox | menuimage | menuitem | menuitemtext | menulist | menulist-button | menulist-text | menulist-textfield | menupopup | menuradio | menuseparator | meterbar | meterchunk | progressbar | progressbar-vertical | progresschunk | progresschunk-vertical | radio | radio-container | radio-label | radiomenuitem | range | range-thumb | resizer | resizerpanel | scale-horizontal | scalethumbend | scalethumb-horizontal | scalethumbstart | scalethumbtick | scalethumb-vertical | scale-vertical | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | separator | sheet | spinner | spinner-downbutton | spinner-textfield | spinner-upbutton | splitter | statusbar | statusbarpanel | tab | tabpanel | tabpanels | tab-scroll-arrow-back | tab-scroll-arrow-forward | textfield | textfield-multiline | toolbar | toolbarbutton | toolbarbutton-dropdown | toolbargripper | toolbox | tooltip | treeheader | treeheadercell | treeheadersortarrow | treeitem | treeline | treetwisty | treetwistyopen | treeview | -moz-mac-unified-toolbar | -moz-win-borderless-glass | -moz-win-browsertabbar-toolbox | -moz-win-communicationstext | -moz-win-communications-toolbox | -moz-win-exclude-glass | -moz-win-glass | -moz-win-mediatext | -moz-win-media-toolbox | -moz-window-button-box | -moz-window-button-box-maximized | -moz-window-button-close | -moz-window-button-maximize | -moz-window-button-minimize | -moz-window-button-restore | -moz-window-frame-bottom | -moz-window-frame-left | -moz-window-frame-right | -moz-window-titlebar | -moz-window-titlebar-maximized" + }, + "-moz-background-clip": { + syntax: "padding | border" + }, + "-moz-binding": { + syntax: " | none" + }, + "-moz-border-bottom-colors": { + syntax: "+ | none" + }, + "-moz-border-left-colors": { + syntax: "+ | none" + }, + "-moz-border-radius-bottomleft": { + syntax: "<'border-bottom-left-radius'>" + }, + "-moz-border-radius-bottomright": { + syntax: "<'border-bottom-right-radius'>" + }, + "-moz-border-radius-topleft": { + syntax: "<'border-top-left-radius'>" + }, + "-moz-border-radius-topright": { + syntax: "<'border-bottom-right-radius'>" + }, + "-moz-border-right-colors": { + syntax: "+ | none" + }, + "-moz-border-top-colors": { + syntax: "+ | none" + }, + "-moz-context-properties": { + syntax: "none | [ fill | fill-opacity | stroke | stroke-opacity ]#" + }, + "-moz-control-character-visibility": { + syntax: "visible | hidden" + }, + "-moz-float-edge": { + syntax: "border-box | content-box | margin-box | padding-box" + }, + "-moz-force-broken-image-icon": { + syntax: "0 | 1" + }, + "-moz-orient": { + syntax: "inline | block | horizontal | vertical" + }, + "-moz-osx-font-smoothing": { + syntax: "auto | grayscale" + }, + "-moz-outline-radius": { + syntax: "{1,4} [ / {1,4} ]?" + }, + "-moz-outline-radius-bottomleft": { + syntax: "" + }, + "-moz-outline-radius-bottomright": { + syntax: "" + }, + "-moz-outline-radius-topleft": { + syntax: "" + }, + "-moz-outline-radius-topright": { + syntax: "" + }, + "-moz-padding-start": { + syntax: "<'padding-top'>" + }, + "-moz-stack-sizing": { + syntax: "ignore | stretch-to-fit" + }, + "-moz-text-blink": { + syntax: "none | blink" + }, + "-moz-user-focus": { + syntax: "ignore | normal | select-after | select-before | select-menu | select-same | select-all | none" + }, + "-moz-user-input": { + syntax: "auto | none | enabled | disabled" + }, + "-moz-user-modify": { + syntax: "read-only | read-write | write-only" + }, + "-moz-user-select": { + syntax: "none | text | all | -moz-none | auto" + }, + "-moz-window-dragging": { + syntax: "drag | no-drag" + }, + "-moz-window-shadow": { + syntax: "default | menu | tooltip | sheet | none" + }, "-ms-accelerator": { syntax: "false | true" }, @@ -1965,7 +2406,31 @@ syntax: "none | zoom" }, "-ms-filter": { - syntax: "" + syntax: " " + }, + "-ms-flex-align": { + syntax: "start | end | center | baseline | stretch" + }, + "-ms-flex-item-align": { + syntax: "auto | start | end | center | baseline | stretch" + }, + "-ms-flex-line-pack": { + syntax: "start | end | center | justify | distribute | stretch" + }, + "-ms-flex-negative": { + syntax: "<'flex-shrink'>" + }, + "-ms-flex-order": { + syntax: "" + }, + "-ms-flex-pack": { + syntax: "start | end | center | justify | distribute" + }, + "-ms-flex-positive": { + syntax: "<'flex-grow'>" + }, + "-ms-flex-preferred-size": { + syntax: "<'flex-basis'>" }, "-ms-flow-from": { syntax: "[ none | ]#" @@ -1973,9 +2438,15 @@ "-ms-flow-into": { syntax: "[ none | ]#" }, + "-ms-grid-column-align": { + syntax: "start | end | center | stretch" + }, "-ms-grid-columns": { syntax: "none | | " }, + "-ms-grid-row-align": { + syntax: "start | end | center | stretch" + }, "-ms-grid-rows": { syntax: "none | | " }, @@ -1985,6 +2456,9 @@ "-ms-hyphenate-limit-chars": { syntax: "auto | {1,3}" }, + "-ms-hyphenate-limit-last": { + syntax: "none | always | column | page | spread" + }, "-ms-hyphenate-limit-lines": { syntax: "no-limit | " }, @@ -1994,6 +2468,9 @@ "-ms-ime-align": { syntax: "auto | after" }, + "-ms-interpolation-mode": { + syntax: "nearest-neighbor | bicubic" + }, "-ms-overflow-style": { syntax: " auto | none | scrollbar | -ms-autohiding-scrollbar" }, @@ -2078,74 +2555,56 @@ "-ms-wrap-through": { syntax: "wrap | none" }, - "-moz-appearance": { - syntax: "none | button | button-arrow-down | button-arrow-next | button-arrow-previous | button-arrow-up | button-bevel | button-focus | caret | checkbox | checkbox-container | checkbox-label | checkmenuitem | dualbutton | groupbox | listbox | listitem | menuarrow | menubar | menucheckbox | menuimage | menuitem | menuitemtext | menulist | menulist-button | menulist-text | menulist-textfield | menupopup | menuradio | menuseparator | meterbar | meterchunk | progressbar | progressbar-vertical | progresschunk | progresschunk-vertical | radio | radio-container | radio-label | radiomenuitem | range | range-thumb | resizer | resizerpanel | scale-horizontal | scalethumbend | scalethumb-horizontal | scalethumbstart | scalethumbtick | scalethumb-vertical | scale-vertical | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | separator | sheet | spinner | spinner-downbutton | spinner-textfield | spinner-upbutton | splitter | statusbar | statusbarpanel | tab | tabpanel | tabpanels | tab-scroll-arrow-back | tab-scroll-arrow-forward | textfield | textfield-multiline | toolbar | toolbarbutton | toolbarbutton-dropdown | toolbargripper | toolbox | tooltip | treeheader | treeheadercell | treeheadersortarrow | treeitem | treeline | treetwisty | treetwistyopen | treeview | -moz-mac-unified-toolbar | -moz-win-borderless-glass | -moz-win-browsertabbar-toolbox | -moz-win-communicationstext | -moz-win-communications-toolbox | -moz-win-exclude-glass | -moz-win-glass | -moz-win-mediatext | -moz-win-media-toolbox | -moz-window-button-box | -moz-window-button-box-maximized | -moz-window-button-close | -moz-window-button-maximize | -moz-window-button-minimize | -moz-window-button-restore | -moz-window-frame-bottom | -moz-window-frame-left | -moz-window-frame-right | -moz-window-titlebar | -moz-window-titlebar-maximized" + "-webkit-align-content": { + alias: "align-content" }, - "-moz-binding": { - syntax: " | none" + "-webkit-align-items": { + alias: "align-items" }, - "-moz-border-bottom-colors": { - syntax: "+ | none" + "-webkit-align-self": { + alias: "align-self" }, - "-moz-border-left-colors": { - syntax: "+ | none" - }, - "-moz-border-right-colors": { - syntax: "+ | none" + "-webkit-animation": { + alias: "animation" }, - "-moz-border-top-colors": { - syntax: "+ | none" - }, - "-moz-context-properties": { - syntax: "none | [ fill | fill-opacity | stroke | stroke-opacity ]#" + "-webkit-animation-delay": { + alias: "animation-delay" }, - "-moz-float-edge": { - syntax: "border-box | content-box | margin-box | padding-box" + "-webkit-animation-direction": { + alias: "animation-direction" }, - "-moz-force-broken-image-icon": { - syntax: "0 | 1" + "-webkit-animation-duration": { + alias: "animation-duration" }, - "-moz-orient": { - syntax: "inline | block | horizontal | vertical" + "-webkit-animation-fill-mode": { + alias: "animation-fill-mode" }, - "-moz-outline-radius": { - syntax: "{1,4} [ / {1,4} ]?" + "-webkit-animation-iteration-count": { + alias: "animation-iteration-count" }, - "-moz-outline-radius-bottomleft": { - syntax: "" + "-webkit-animation-name": { + alias: "animation-name" }, - "-moz-outline-radius-bottomright": { - syntax: "" + "-webkit-animation-play-state": { + alias: "animation-play-state" }, - "-moz-outline-radius-topleft": { - syntax: "" + "-webkit-animation-timing-function": { + alias: "animation-timing-function" }, - "-moz-outline-radius-topright": { - syntax: "" - }, - "-moz-stack-sizing": { - syntax: "ignore | stretch-to-fit" - }, - "-moz-text-blink": { - syntax: "none | blink" - }, - "-moz-user-focus": { - syntax: "ignore | normal | select-after | select-before | select-menu | select-same | select-all | none" - }, - "-moz-user-input": { - syntax: "auto | none | enabled | disabled" + "-webkit-appearance": { + syntax: "<'appearance'> | none | button | button-bevel | caps-lock-indicator | caret | checkbox | default-button | inner-spin-button | listbox | listitem | media-controls-background | media-controls-fullscreen-background | media-current-time-display | media-enter-fullscreen-button | media-exit-fullscreen-button | media-fullscreen-button | media-mute-button | media-overlay-play-button | media-play-button | media-seek-back-button | media-seek-forward-button | media-slider | media-sliderthumb | media-time-remaining-display | media-toggle-closed-captions-button | media-volume-slider | media-volume-slider-container | media-volume-sliderthumb | menulist | menulist-button | menulist-text | menulist-textfield | meter | progress-bar | progress-bar-value | push-button | radio | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbargripper-horizontal | scrollbargripper-vertical | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | searchfield-cancel-button | searchfield-decoration | searchfield-results-button | searchfield-results-decoration | slider-horizontal | slider-vertical | sliderthumb-horizontal | sliderthumb-vertical | square-button | textarea | textfield | -apple-pay-button" }, - "-moz-user-modify": { - syntax: "read-only | read-write | write-only" + "-webkit-backface-visibility": { + alias: "backface-visibility" }, - "-moz-window-dragging": { - syntax: "drag | no-drag" + "-webkit-background-clip": { + syntax: "<'background-clip'> | [ | border | padding | content | text ]#" }, - "-moz-window-shadow": { - syntax: "default | menu | tooltip | sheet | none" + "-webkit-background-origin": { + alias: "background-origin" }, - "-webkit-appearance": { - syntax: " none | button | button-bevel | caps-lock-indicator | caret | checkbox | default-button | inner-spin-button | listbox | listitem | media-controls-background | media-controls-fullscreen-background | media-current-time-display | media-enter-fullscreen-button | media-exit-fullscreen-button | media-fullscreen-button | media-mute-button | media-overlay-play-button | media-play-button | media-seek-back-button | media-seek-forward-button | media-slider | media-sliderthumb | media-time-remaining-display | media-toggle-closed-captions-button | media-volume-slider | media-volume-slider-container | media-volume-sliderthumb | menulist | menulist-button | menulist-text | menulist-textfield | meter | progress-bar | progress-bar-value | push-button | radio | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbargripper-horizontal | scrollbargripper-vertical | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | searchfield-cancel-button | searchfield-decoration | searchfield-results-button | searchfield-results-decoration | slider-horizontal | slider-vertical | sliderthumb-horizontal | sliderthumb-vertical | square-button | textarea | textfield | -apple-pay-button" + "-webkit-background-size": { + alias: "background-size" }, "-webkit-border-after": { syntax: "<'border-top'>" @@ -2171,6 +2630,12 @@ "-webkit-border-before-width": { syntax: "<'border-top-width'>" }, + "-webkit-border-bottom-left-radius": { + alias: "border-bottom-left-radius" + }, + "-webkit-border-bottom-right-radius": { + alias: "border-bottom-right-radius" + }, "-webkit-border-end": { syntax: "<'border-top'>" }, @@ -2183,6 +2648,9 @@ "-webkit-border-end-width": { syntax: "<'border-top-width'>" }, + "-webkit-border-radius": { + alias: "border-radius" + }, "-webkit-border-start": { syntax: "<'border-top'>" }, @@ -2195,32 +2663,104 @@ "-webkit-border-start-width": { syntax: "<'border-top-width'>" }, + "-webkit-border-top-left-radius": { + alias: "border-top-left-radius" + }, + "-webkit-border-top-right-radius": { + alias: "border-top-right-radius" + }, "-webkit-box-reflect": { syntax: "[ above | below | right | left ]? ? ?" }, + "-webkit-box-shadow": { + alias: "box-shadow" + }, + "-webkit-box-sizing": { + alias: "box-sizing" + }, + "-webkit-column-break-after": { + syntax: "always | auto | avoid" + }, + "-webkit-column-break-before": { + syntax: "always | auto | avoid" + }, + "-webkit-column-break-inside": { + syntax: "always | auto | avoid" + }, + "-webkit-filter": { + alias: "filter" + }, + "-webkit-flex": { + alias: "flex" + }, + "-webkit-flex-basis": { + alias: "flex-basis" + }, + "-webkit-flex-direction": { + alias: "flex-direction" + }, + "-webkit-flex-flow": { + alias: "flex-flow" + }, + "-webkit-flex-grow": { + alias: "flex-grow" + }, + "-webkit-flex-shrink": { + alias: "flex-shrink" + }, + "-webkit-flex-wrap": { + alias: "flex-wrap" + }, + "-webkit-font-smoothing": { + syntax: "auto | none | antialiased | subpixel-antialiased" + }, + "-webkit-justify-content": { + alias: "justify-content" + }, "-webkit-line-clamp": { - syntax: "none | " + syntax: "none | " + }, + "-webkit-margin-end": { + syntax: "<'margin-block-end'>" }, "-webkit-mask": { - syntax: "[ || [ / ]? || || [ | border | padding | content | text ] || [ | border | padding | content ] ]#" + syntax: "<'mask'> | [ || [ / ]? || || [ | border | padding | content | text ] || [ | no-clip | border | padding | content | text ] || [ | ] || ]#" }, "-webkit-mask-attachment": { syntax: "#" }, + "-webkit-mask-box-image": { + syntax: "<'mask-border'> | [ | | none ] [ {4} <-webkit-mask-box-repeat>{2} ]?" + }, + "-webkit-mask-box-image-outset": { + alias: "mask-border-outset" + }, + "-webkit-mask-box-image-repeat": { + alias: "mask-border-repeat" + }, + "-webkit-mask-box-image-slice": { + alias: "mask-border-slice" + }, + "-webkit-mask-box-image-source": { + alias: "mask-border-source" + }, + "-webkit-mask-box-image-width": { + alias: "mask-border-width" + }, "-webkit-mask-clip": { - syntax: "[ | no-clip | border | padding | content | text ]#" + syntax: "<'mask-clip'> | [ | no-clip | border | padding | content | text ]#" }, "-webkit-mask-composite": { - syntax: "#" + syntax: "<'mask-composite'> | [ | ]#" }, "-webkit-mask-image": { - syntax: "#" + alias: "mask-image" }, "-webkit-mask-origin": { - syntax: "[ | border | padding | content ]#" + syntax: "<'mask-origin'> | [ | border | padding | content ]#" }, "-webkit-mask-position": { - syntax: "#" + alias: "mask-position" }, "-webkit-mask-position-x": { syntax: "[ | left | center | right ]#" @@ -2229,7 +2769,7 @@ syntax: "[ | top | center | bottom ]#" }, "-webkit-mask-repeat": { - syntax: "#" + alias: "mask-repeat" }, "-webkit-mask-repeat-x": { syntax: "repeat | no-repeat | space | round" @@ -2238,34 +2778,79 @@ syntax: "repeat | no-repeat | space | round" }, "-webkit-mask-size": { - syntax: "#" + alias: "mask-size" + }, + "-webkit-order": { + alias: "order" }, "-webkit-overflow-scrolling": { syntax: "auto | touch" }, + "-webkit-perspective": { + alias: "perspective" + }, + "-webkit-perspective-origin": { + alias: "perspective-origin" + }, + "-webkit-print-color-adjust": { + syntax: "economy | exact" + }, "-webkit-tap-highlight-color": { syntax: "" }, "-webkit-text-fill-color": { syntax: "" }, + "-webkit-text-security": { + syntax: "none | circle | disc | square" + }, + "-webkit-text-size-adjust": { + alias: "text-size-adjust" + }, "-webkit-text-stroke": { - syntax: " || " + syntax: " || " }, "-webkit-text-stroke-color": { syntax: "" }, "-webkit-text-stroke-width": { - syntax: "" + syntax: "" }, "-webkit-touch-callout": { syntax: "default | none" }, + "-webkit-transform": { + alias: "transform" + }, + "-webkit-transform-origin": { + alias: "transform-origin" + }, + "-webkit-transform-style": { + alias: "transform-style" + }, + "-webkit-transition": { + alias: "transition" + }, + "-webkit-transition-delay": { + alias: "transition-delay" + }, + "-webkit-transition-duration": { + alias: "transition-duration" + }, + "-webkit-transition-property": { + alias: "transition-property" + }, + "-webkit-transition-timing-function": { + alias: "transition-timing-function" + }, + "-webkit-user-drag": { + syntax: "none | element | auto" + }, "-webkit-user-modify": { syntax: "read-only | read-write | read-write-plaintext-only" }, "-webkit-user-select": { - syntax: " auto | none | text | all" + syntax: "auto | text | none | contain | all" }, "accent-color": { syntax: "auto | " @@ -2274,25 +2859,25 @@ syntax: "normal | | | ? " }, "align-items": { - syntax: "normal | stretch | | [ ? ] | anchor-center" + syntax: "normal | stretch | | ? " }, "align-self": { - syntax: "auto | normal | stretch | | ? | anchor-center" + syntax: "auto | ? [ normal | ]| stretch | | anchor-center" }, "align-tracks": { syntax: "[ normal | | | ? ]#" }, "alignment-baseline": { - syntax: " auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical" + syntax: "baseline | " }, all: { - syntax: "initial | inherit | unset | revert | revert-layer" + syntax: "initial | inherit | unset | revert | revert-layer | revert-rule" }, "anchor-name": { - syntax: "none | #" + syntax: "none | #" }, "anchor-scope": { - syntax: "none | all | #" + syntax: "none | all | #" }, animation: { syntax: "#" @@ -2301,6 +2886,12 @@ syntax: "#" }, "animation-delay": { + syntax: "[ <'animation-delay-start'> <'animation-delay-end'>? ]#" + }, + "animation-delay-end": { + syntax: "?`, `*`, `[ ? ? ]`, `[ [ and ]* | [ or ]* ]` + * @param syntax + */ + function isNullable(syntax) { + if (syntax.typ === ValidationTokenEnum.Whitespace) { + return true; + } + // `[ ? ? ]!`: at least one token + if (syntax.isMandatatoryGroup) { + return false; + } + if (syntax.isOptional || syntax.isRepeatable || syntax.match?.min?.val === 0) { + return true; + } + let nullable = nullableSyntaxes.get(syntax); + if (nullable == null) { + switch (syntax.typ) { + case ValidationTokenEnum.Bracket: + nullable = syntax.chi.every(isNullable); + break; + case ValidationTokenEnum.PipeToken: + nullable = syntax.chi.some((syntaxes) => syntaxes.every(isNullable)); + break; + case ValidationTokenEnum.AmpersandToken: + nullable = + syntax.l.every(isNullable) && + syntax.r.every(isNullable); + break; + default: + nullable = false; + } + nullableSyntaxes.set(syntax, nullable); + } + return nullable; + } + /** + * index of the first syntax that must be matched, starting at index. -1 if the remaining syntaxes may match no token + * @param syntaxes + * @param index + */ + function findMandatorySyntax(syntaxes, index) { + for (let i = index; i < syntaxes.length; i++) { + if (!isNullable(syntaxes[i])) { + return i; + } + } + return -1; + } + /** + * true if a numeric token is in the range of the syntax: `` + * @param arena + * @param token + * @param syntax + */ + function isInRange(arena, token, syntax) { + if (syntax.range == null || + arena.dataTypes[token] === exports.EnumToken.MathFunctionTokenType || + arena.dataTypes[token] === exports.EnumToken.MathFunctionTokenDefType || + arena.dataTypes[token] === exports.EnumToken.WildCardFunctionTokenType || + arena.dataTypes[token] === exports.EnumToken.WildCardFunctionTokenDefType) { + return true; + } + const range = syntax.range; + // a null lower bound is -∞ + let success = !arena.hasFraction(token) && (range.min == null || arena.numericValue[token] >= range.min.val); + if (range.min?.typ === ValidationTokenEnum.Dimension) { + success = + arena.dataTypes[token] === + exports.EnumToken[ + // @ts-expect-error + range.min.unit]; + } + if (success && range.max != null) { + success = arena.numericValue[token] <= range.max.val; + } + return success; + } + /** + * the wildcard functions being matched with a syntax, see {@link matchWildCardFunction} + */ + const wildCardProbes = new Map(); + /** + * var(), env() and if() may be substituted by any number of values. the function is matched: + * - as a part of the syntax at index: `var(--color) 65%` is matched by `` (`` is the function) + * - as the syntax at index, or as all the remaining syntaxes when it is the last token + * + * the next syntaxes must match the tokens that follow. otherwise, the syntax at index is skipped if it is optional and + * the function is matched with the next syntax + * @param arena + * @param syntaxes + * @param index index of the syntax matched by the function + * @param context + * @param token the function token + * @param end last token of the function + * @param options + * @param out + * @returns the result, null if the syntax at index is skipped + */ + function matchWildCardFunction(arena, syntaxes, index, context, token, end, options, out) { + let errors = noErrors; + const candidates = []; + // the function is a part of the syntax. a keyword, a comma, ... is matched by the function + if (syntaxes[index].typ !== ValidationTokenEnum.Keyword && + syntaxes[index].typ !== ValidationTokenEnum.Comma && + syntaxes[index].typ !== ValidationTokenEnum.Separator && + syntaxes[index].typ !== ValidationTokenEnum.StringToken && + syntaxes[index].typ !== ValidationTokenEnum.OpenParenthesis && + syntaxes[index].typ !== ValidationTokenEnum.CloseParenthesis) { + const previous = wildCardProbes.get(token); + let probe; + wildCardProbes.set(token, syntaxes[index]); + try { + probe = matchSyntax(arena, [syntaxes[index]], context.slice(), options); + } + finally { + if (previous == null) { + wildCardProbes.delete(token); + } + else { + wildCardProbes.set(token, previous); + } + } + if (probe.success) { + if (probe.context.done()) { + // the syntax matched all the tokens: the remaining syntaxes must be optional + if (findMandatorySyntax(syntaxes, index + 1) === -1) { + context.end(); + return setMatch(out, true, probe.valid, null, context, null, probe.errors); + } + } + else if (probe.context.current() != null) { + // the syntax matched some tokens + candidates.push(probe.context); + } + } + } + // the function is the syntax + const next = context.slice(); + next.update(end); + if (next.done()) { + // all the remaining syntaxes + context.end(); + return setMatch(out, true, true, null, context, null, noErrors); + } + candidates.push(next); + for (const candidate of candidates) { + const rest = matchSyntax(arena, syntaxes.slice(index + 1), candidate.slice(), options); + if (rest.success) { + if (rest.context.done()) { + context.end(); + } + else { + context.update(rest.context.current() ?? candidate.current()); + } + return setMatch(out, true, rest.valid, rest.token, context, null, rest.errors); + } + errors = rest.errors; + } + if (isNullable(syntaxes[index])) { + return null; + } + return setMatch(out, false, true, token, context, syntaxes[index], errors); + } + /** + * the tokens are consumed: the match succeeds if the remaining syntaxes, starting at index, are optional. + * `[ , ]` does not match `.2` + * @param out + * @param syntaxes + * @param index index of the next syntax + * @param valid + * @param token + * @param context + * @param errors + */ + function setDoneMatch(out, syntaxes, index, valid, token, context, errors) { + const mandatory = findMandatorySyntax(syntaxes, index); + if (mandatory !== -1) { + return setMatch(out, false, valid, token, context, syntaxes[mandatory], noErrors); + } + return setMatch(out, true, valid, token, context, syntaxes[index] ?? null, errors); + } + /** + * matches a list of syntaxes + * @param arena + * @param syntaxes + * @param context + * @param options + * @param out + * @returns + */ function matchSyntax(arena, syntaxes, context, options, out = createMatch()) { if (syntaxes == null) { return setMatch(out, true, false, context.peek(), context, null, noErrors); @@ -13893,14 +15432,14 @@ let token = null; let result = null; let isOptional; - if (context.tokens.length == 1 && - arena.dataTypes[context.tokens[0]] == exports.EnumToken.IdenTokenType && + if (context.tokens.length === 1 && + arena.dataTypes[context.tokens[0]] === exports.EnumToken.IdenTokenType && isCssWideKeyword(arena.strings[arena.stringValue[context.tokens[0]]])) { context.end(); return setMatch(out, true, true, context.peek(), context, null, noErrors); } while (++i < syntaxes.length) { - if (syntaxes[i].typ == ValidationTokenEnum.Whitespace) { + if (syntaxes[i].typ === ValidationTokenEnum.Whitespace) { continue; } isOptional = @@ -13910,36 +15449,44 @@ !syntaxes[i].isMandatatoryGroup; token = context.peek(); if (token == null) { - if (!isOptional) { - return setMatch(out, false, true, null, context, syntaxes[i], [ + // the remaining syntaxes must be optional: `? ` + const mandatory = findMandatorySyntax(syntaxes, isOptional ? i + 1 : i); + if (mandatory !== -1) { + return setMatch(out, false, true, null, context, syntaxes[mandatory], [ { action: "drop", message: "could not match syntax", node: null, - syntax: syntaxes[i], + syntax: syntaxes[mandatory], }, ]); } break; } - if (arena.dataTypes[token] === exports.EnumToken.WildCardFunctionTokenType && arena.strings[arena.stringValue[token]] === "var") { + if (arena.dataTypes[token] === exports.EnumToken.WildCardFunctionTokenType && + arena.strings[arena.stringValue[token]] === "var" && + wildCardProbes.get(token) !== syntaxes[i]) { result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, arena.strings[arena.stringValue[token]] + "()")?.[0]?.chi, createValidationContext(arena, arena.tokens(token)), options, out); if (result.success && result.context.done()) { - context.next(); - continue; + const wildCardResult = matchWildCardFunction(arena, syntaxes, i, context, token, token, options, out); + if (wildCardResult == null) { + continue; + } + return wildCardResult; } } if ( // @ts-ignore - arena.dataTypes[token] === exports.EnumToken.WildCardFunctionTokenDefType) { + arena.dataTypes[token] === exports.EnumToken.WildCardFunctionTokenDefType && + wildCardProbes.get(token) !== syntaxes[i]) { const range = trimArray(arena, context.peekRange()); result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, arena.strings[arena.stringValue[token]] + "()")?.[0]?.chi, createValidationContext(arena, range.slice(1, -1)), options, out); if (result.success) { - context.update(range.at(-1)); - if (context.done()) { - return setMatch(out, result.success, result.valid, result.token, context, syntaxes[i + 1], result.errors); + const wildCardResult = matchWildCardFunction(arena, syntaxes, i, context, token, range.at(-1), options, out); + if (wildCardResult == null) { + continue; } - continue; + return wildCardResult; } } if (syntaxes[i].isRepeatableAtLeastOnce || syntaxes[i].isRepeatable) { @@ -13947,7 +15494,7 @@ if (result.success) { if (result.context.done()) { context.end(); - return setMatch(out, result.success, result.valid, result.token, result.context, syntaxes[i + 1], result.errors); + return setDoneMatch(out, syntaxes, i + 1, result.valid, result.token, result.context, result.errors); } context.update(result.context.current()); continue; @@ -13963,7 +15510,7 @@ options.visited.get(token)?.delete?.(syntaxes[i]); if (result.context.done()) { context.end(); - return setMatch(out, true, true, null, context, syntaxes[i + 1], result.errors); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, result.errors); } context.update(result.context.current()); continue; @@ -13979,7 +15526,7 @@ options.visited.get(token).delete(syntaxes[i]); if (result.context.done()) { context.end(); - return setMatch(out, result.success, result.valid, result.token, context, syntaxes[++i], result.errors); + return setDoneMatch(out, syntaxes, i + 1, result.valid, result.token, context, result.errors); } context.update(result.context.current()); continue; @@ -13998,240 +15545,250 @@ } options.visited.get(token).add(syntaxes[i]); success = false; - switch (syntaxes[i].typ) { - case ValidationTokenEnum.Comma: - if (arena.dataTypes[token] == exports.EnumToken.CommaTokenType) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.Keyword: - if (arena.dataTypes[token] == exports.EnumToken.IdenTokenType && - lowercase(arena.strings[arena.stringValue[token]]) === - lowercase(syntaxes[i].val)) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - if (isOptional) { - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.DeclarationType: - result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Declarations, syntaxes[i].val), context, options, out); - if (result.success) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - if (result.context.done()) { - context.end(); - return setMatch(out, result.success, result.valid, token, context, syntaxes[1 + i], result.errors); + try { + switch (syntaxes[i].typ) { + case ValidationTokenEnum.Colon: + // ` : ?` + if (arena.dataTypes[token] === exports.EnumToken.ColonTokenType) { + success = true; + context.next(); + break; } - else { - if (result.context.current() != null) { - context.update(result.context.current()); - } + if (isOptional) { + break; } - } - if (success || isOptional) { - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], result.errors); - case ValidationTokenEnum.OptionalGroupToken: { - // - const tokens = context.split(); - let j = 0; - for (; j < tokens.length; j++) { - result = matchSyntax(arena, syntaxes[i].chi, context.slice(), options, out); - if (result.success) { - context.update(tokens[j].at(-1)); + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.Comma: + if (arena.dataTypes[token] === exports.EnumToken.CommaTokenType) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.Keyword: + if (arena.dataTypes[token] === exports.EnumToken.IdenTokenType && + lowercase(arena.strings[arena.stringValue[token]]) === + lowercase(syntaxes[i].val)) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; } - break; - } - if (result?.context?.done?.()) { - return result; - } - break; - } - case ValidationTokenEnum.StringToken: - if (arena.dataTypes[token] === exports.EnumToken.Add) { - success = syntaxes[i].val.slice(1, -1) === "+"; - } - else if (arena.dataTypes[token] === exports.EnumToken.Sub) { - success = syntaxes[i].val.slice(1, -1) === "-"; - } - else if (arena.dataTypes[token] === exports.EnumToken.LiteralTokenType) { - success = arena.strings[arena.stringValue[token]] === syntaxes[i].val.slice(1, -1); - } - else if (arena.dataTypes[token] == exports.EnumToken.Plus) { - success = true; - } - if (success) { - context.next(); - break; - } - if (isOptional) { - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.PropertyType: - result = matchProperty(arena, syntaxes[i], context, options); - if (!result.success) { if (isOptional) { break; } - return setMatch(out, false, true, context.current() ?? token, context, syntaxes[i], noErrors); - } - success = true; - options.visited.get(token).delete(syntaxes[i]); - if (result.context.done()) { - context.end(); - return setMatch(out, success, true, null, context, syntaxes[i + 1], noErrors); - } - else { - context.update(result.context.current()); - } - break; - case ValidationTokenEnum.PipeToken: - { - // each alternative is matched in the same scratch result, the best match is copied - const scratch = createMatch(); - let best = null; - let tmp = null; - for (const syntax of syntaxes[i].chi) { - tmp = matchSyntax(arena, syntax, context.slice(), options, scratch); - if (tmp.success) { - if (best == null || tmp.context.index >= best.context.index) { - best = copyMatch(best ?? createMatch(), tmp); + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.DeclarationType: + result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Declarations, syntaxes[i].val), context, options, out); + if (result.success) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, result.valid, token, context, result.errors); + } + else { + if (result.context.current() != null) { + context.update(result.context.current()); + } + } + } + if (success || isOptional) { + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], result.errors); + case ValidationTokenEnum.OptionalGroupToken: { + const chi = syntaxes[i].chi; + // `#? , ` (the group of the optional list, the comma is the list separator) is + // matched as `[ , ]* `: the last item is left to the next syntax + if (chi.length === 1 && chi[0].isList) { + const { isList, isOptional, match, ...item } = chi[0]; + const group = [ + item, + { typ: ValidationTokenEnum.Comma }, + ]; + while (context.peek() != null) { + const tmp = matchSyntax(arena, group, context.slice(), options); + if (!tmp.success || tmp.context.current() == null) { + break; } + context.update(tmp.context.current()); if (tmp.context.done()) { - context.end(); - return setMatch(out, tmp.success, tmp.valid, tmp.token, context, syntaxes[i + 1], tmp.errors); + break; } } - } - result = best; - if (result?.success) { success = true; - options.visited.get(token).delete(syntaxes[i]); - context.update(result.context.current()); break; } - } - return setMatch(out, false, true, token, context, syntaxes[i], [ - { - action: "drop", - message: "could not match syntax", - node: token, - // @ts-ignore - // location: options.source!.getSourceLocation(token[LOC]?.sta), - syntax: syntaxes[i], - }, - ]); - case ValidationTokenEnum.Bracket: - result = matchSyntax(arena, syntaxes[i].chi, context.slice(), options, out); - if (result.success) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - if (result.context.done()) { - context.end(); - return setMatch(out, success, true, null, context, syntaxes[1 + i], noErrors); - } - else { + // the group is optional: it is skipped if it does not match + result = matchSyntax(arena, chi, context.slice(), options); + if (result.success) { + success = true; + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, result.errors); + } context.update(result.context.current()); } break; } - if (isOptional) { - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.ColumnToken: - result = matchColumnSyntax(arena, syntaxes[i], context.slice(), options); - if (result.success) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - if (result.context.done()) { - context.end(); - return setMatch(out, success, true, null, context, syntaxes[1 + i], noErrors); + case ValidationTokenEnum.StringToken: + if (arena.dataTypes[token] === exports.EnumToken.Add) { + success = syntaxes[i].val.slice(1, -1) === "+"; } - else { - context.update(result.context.current()); + else if (arena.dataTypes[token] === exports.EnumToken.Sub) { + success = syntaxes[i].val.slice(1, -1) === "-"; + } + else if (arena.dataTypes[token] === exports.EnumToken.LiteralTokenType) { + success = + arena.strings[arena.stringValue[token]] === + syntaxes[i].val.slice(1, -1); + } + else if (arena.dataTypes[token] === exports.EnumToken.Plus) { + success = true; + } + if (success) { + context.next(); + break; + } + if (isOptional) { + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.PropertyType: + result = matchProperty(arena, syntaxes[i], context, options); + if (!result.success) { + if (isOptional) { + break; + } + return setMatch(out, false, true, context.current() ?? token, context, syntaxes[i], noErrors); } - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.AmpersandToken: - result = matchAmpersandSyntax(arena, syntaxes[i], context.slice(), options); - if (result.success) { success = true; options.visited.get(token).delete(syntaxes[i]); if (result.context.done()) { + if (!isInRange(arena, token, syntaxes[i])) { + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + } context.end(); - return setMatch(out, success, true, null, context, syntaxes[1 + i], noErrors); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, noErrors); } else { context.update(result.context.current()); } break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.Function: - if ((!tokensfuncDefMap.has(arena.dataTypes[token]) && - !funcLike.includes(arena.dataTypes[token]) && - !funcTypes.includes(arena.dataTypes[token])) || - !equalsIgnoreCase(syntaxes[i].val, arena.strings[arena.stringValue[token]].toLowerCase())) { + case ValidationTokenEnum.PipeToken: + { + // each alternative is matched in the same scratch result, the best match is copied + const scratch = createMatch(); + let best = null; + let tmp = null; + for (const syntax of syntaxes[i].chi) { + tmp = matchSyntax(arena, syntax, context.slice(), options, scratch); + if (tmp.success) { + // an alternative that consumes the tokens is skipped if mandatory syntaxes remain + if (tmp.context.done() && findMandatorySyntax(syntaxes, i + 1) !== -1) { + continue; + } + if (best == null || tmp.context.index >= best.context.index) { + best = copyMatch(best ?? createMatch(), tmp); + } + if (tmp.context.done()) { + context.end(); + return setMatch(out, tmp.success, tmp.valid, tmp.token, context, syntaxes[i + 1], tmp.errors); + } + } + } + result = best; + if (result?.success) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.update(result.context.current()); + break; + } + } return setMatch(out, false, true, token, context, syntaxes[i], [ { action: "drop", - message: `Expecting a function ${exports.EnumToken[arena.dataTypes[token]]}`, + message: "could not match syntax", node: token, + // @ts-ignore + // location: options.source!.getSourceLocation(token[LOC]?.sta), + syntax: syntaxes[i], }, ]); - } - if (tokensfuncDefMap.has(arena.dataTypes[token])) { - const range = context.peekRange(); - result = matchSyntax(arena, syntaxes[i].chi, createValidationContext(arena, range.slice(1, -1)), options, out); - if (result.success && result.context.done()) { - context.update(range.at(-1)); + case ValidationTokenEnum.Bracket: + result = matchSyntax(arena, syntaxes[i].chi, context.slice(), options, out); + if (result.success) { + success = true; options.visited.get(token).delete(syntaxes[i]); + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, noErrors); + } + else { + context.update(result.context.current()); + } break; } - } - else { - result = matchSyntax(arena, syntaxes[i].chi, createValidationContext(arena, arena.tokens(token)), options, out); - if (result.success && result.context.done()) { + if (isOptional) { + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.ColumnToken: + result = matchColumnSyntax(arena, syntaxes[i], context.slice(), options); + if (result.success) { success = true; options.visited.get(token).delete(syntaxes[i]); - context.next(); + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, noErrors); + } + else { + context.update(result.context.current()); + } break; } - } - return setMatch(out, false, true, token, context, syntaxes[i], result.errors); - case ValidationTokenEnum.Separator: - if (arena.dataTypes[token] === exports.EnumToken.LiteralTokenType && arena.strings[arena.stringValue[token]] === "/") { - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.FunctionDefinition: - if (arena.strings[arena.stringValue[token]] && - equalsIgnoreCase(arena.strings[arena.stringValue[token]], syntaxes[i].val)) { + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.AmpersandToken: + result = matchAmpersandSyntax(arena, syntaxes[i], context.slice(), options); + if (result.success) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, noErrors); + } + else { + context.update(result.context.current()); + } + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.Function: + if ((!tokensfuncDefMap.has(arena.dataTypes[token]) && + !funcLike.includes(arena.dataTypes[token]) && + !funcTypes.includes(arena.dataTypes[token])) || + !equalsIgnoreCase(syntaxes[i].val, arena.strings[arena.stringValue[token]].toLowerCase())) { + return setMatch(out, false, true, token, context, syntaxes[i], [ + { + action: "drop", + message: `Expecting a function ${exports.EnumToken[arena.dataTypes[token]]}`, + node: token, + }, + ]); + } if (tokensfuncDefMap.has(arena.dataTypes[token])) { - const children = trimArray(arena, context.peekRange()); - result = matchSyntax(arena, (getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, syntaxes[i].val + "()")?.[0]).chi ?? [], createValidationContext(arena, children.slice(1, -1)), options, out); + const range = context.peekRange(); + result = matchSyntax(arena, syntaxes[i].chi, createValidationContext(arena, range.slice(1, -1)), options, out); if (result.success && result.context.done()) { - success = true; + context.update(range.at(-1)); options.visited.get(token).delete(syntaxes[i]); - context.update(children.at(-1)); break; } } - else if (tokensfuncSet.has(arena.dataTypes[token])) { - result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, syntaxes[i].val + "()") ?? [], createValidationContext(arena, [token]), options, out); + else { + result = matchSyntax(arena, syntaxes[i].chi, createValidationContext(arena, arena.tokens(token)), options, out); if (result.success && result.context.done()) { success = true; options.visited.get(token).delete(syntaxes[i]); @@ -14239,99 +15796,112 @@ break; } } - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.OpenParenthesis: - if (arena.dataTypes[token] === exports.EnumToken.StartParensTokenType) { - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.OpenCurlyBrace: - if (arena.dataTypes[token] === exports.EnumToken.BlockStartTokenType) { - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.CloseParenthesis: - if (arena.dataTypes[token] === exports.EnumToken.EndParensTokenType) { - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - default: - throw new Error(`Unexpected syntax ${ValidationTokenEnum[syntaxes[i].typ]}`); - } - if (success && - "range" in syntaxes[i] && - !(arena.dataTypes[token] === exports.EnumToken.MathFunctionTokenType || - arena.dataTypes[token] === exports.EnumToken.MathFunctionTokenDefType || - arena.dataTypes[token] === exports.EnumToken.WildCardFunctionTokenDefType)) { - let success = false; - success = - !arena.hasFraction(token) && - arena.numericValue[token] >= - syntaxes[i].range.min.val; - if (syntaxes[i].range.min.typ === ValidationTokenEnum.Dimension) { - success = - arena.dataTypes[token] === - exports.EnumToken[ - // @ts-expect-error - syntaxes[i].range.min - .unit]; - } - if (success && - syntaxes[i].range.max != null) { - success = - arena.numericValue[token] <= - syntaxes[i].range.max.val; - } - if (!success) { - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + return setMatch(out, false, true, token, context, syntaxes[i], result.errors); + case ValidationTokenEnum.Separator: + if (arena.dataTypes[token] === exports.EnumToken.LiteralTokenType && + arena.strings[arena.stringValue[token]] === "/") { + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.FunctionDefinition: + if (arena.strings[arena.stringValue[token]] && + equalsIgnoreCase(arena.strings[arena.stringValue[token]], syntaxes[i].val)) { + if (tokensfuncDefMap.has(arena.dataTypes[token])) { + const children = trimArray(arena, context.peekRange()); + result = matchSyntax(arena, (getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, syntaxes[i].val + "()")?.[0]).chi ?? [], createValidationContext(arena, children.slice(1, -1)), options, out); + if (result.success && result.context.done()) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.update(children.at(-1)); + break; + } + } + else if (tokensfuncSet.has(arena.dataTypes[token])) { + result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, syntaxes[i].val + "()") ?? [], createValidationContext(arena, [token]), options, out); + if (result.success && result.context.done()) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + } + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.OpenParenthesis: + if (arena.dataTypes[token] === exports.EnumToken.StartParensTokenType) { + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.OpenCurlyBrace: + if (arena.dataTypes[token] === exports.EnumToken.BlockStartTokenType) { + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.CloseParenthesis: + if (arena.dataTypes[token] === exports.EnumToken.EndParensTokenType) { + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + default: + throw new Error(`Unexpected syntax ${ValidationTokenEnum[syntaxes[i].typ]}`); } } + finally { + // the syntax is no longer being matched: a token may be matched again with the same syntax (the + // alternatives of an optional group, ...). only the syntaxes being matched detect a cyclic definition + options.visited.get(token)?.delete(syntaxes[i]); + } + if (success && !isInRange(arena, token, syntaxes[i])) { + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + } } - return result?.success ? result : setMatch(out, true, true, token, context, syntaxes[i] ?? null, noErrors); + // the context of this list of syntaxes: the last result may not include the tokens matched after it (`,`, ...) + return setMatch(out, true, result?.success ? result.valid : true, token, context, syntaxes[i] ?? null, result?.success ? result.errors : noErrors); } /** - * matches a column of syntaxes + * matches a column of syntaxes: ` || || `, one or more syntaxes in any order. the syntaxes are matched in + * the order that matches the most tokens: `[ none | ] || ? && ?` matches no token + success: best != null || + (all && syntaxes.every((syntaxes) => findMandatorySyntax(syntaxes, 0) === -1)), valid: true, token: context.current(), context, @@ -14340,32 +15910,134 @@ }; } /** - * matches an ampersand of syntaxes + * position of a context in the tokens of the unordered syntaxes, see {@link searchUnorderedSyntaxes} + * @param base + * @param context + */ + function unorderedPosition(base, context) { + return context.done() ? Number.POSITIVE_INFINITY : base.tokens.indexOf(context.current()); + } + /** + * the context after the unordered syntaxes that match the most tokens. null if the syntaxes do not match + * @param arena + * @param syntaxes the unordered syntaxes + * @param remaining the indexes of the syntaxes that are not matched + * @param all all the syntaxes must be matched, except the syntaxes that match no token + * @param base the context of the syntaxes + * @param context + * @param options + * @param cache the context after a syntax, by syntax index and position + */ + function searchUnorderedSyntaxes(arena, syntaxes, remaining, all, base, context, options, cache) { + const position = unorderedPosition(base, context); + let best = null; + for (let k = 0; k < remaining.length; k++) { + const key = remaining[k] + ":" + position; + let next = cache.get(key); + if (next === undefined) { + const result = matchSyntax(arena, syntaxes[remaining[k]], context.slice(), options); + next = null; + // the syntax matched some tokens + if (result.success && (result.context.done() || result.context.current() !== context.current())) { + next = context.slice(); + if (result.context.done()) { + next.end(); + } + else { + next.update(result.context.current()); + } + } + cache.set(key, next); + } + if (next == null) { + continue; + } + const rest = remaining.slice(0, k).concat(remaining.slice(k + 1)); + // the match may stop after this syntax + const complete = !all || rest.every((index) => findMandatorySyntax(syntaxes[index], 0) === -1); + const candidates = []; + if (!next.done() && rest.length > 0) { + const deeper = searchUnorderedSyntaxes(arena, syntaxes, rest, all, base, next, options, cache); + if (deeper != null) { + candidates.push(deeper); + } + } + if (complete) { + candidates.push(next); + } + for (const candidate of candidates) { + if (candidate.done()) { + return candidate; + } + if (best == null || unorderedPosition(base, candidate) > unorderedPosition(base, best)) { + best = candidate; + } + } + } + return best; + } + /** + * the operands of chained ampersands: ` && && ` is parsed as `[ && ] && ` + * @param syntax + * @param operands + */ + function ampersandOperands(syntax, operands = []) { + for (const side of [syntax.l, syntax.r]) { + const tokens = side.filter((token) => token.typ !== ValidationTokenEnum.Whitespace); + if (tokens.length === 1 && + tokens[0].typ === ValidationTokenEnum.AmpersandToken && + !tokens[0].isOptional && + !tokens[0].isRepeatable && + !tokens[0].isRepeatableAtLeastOnce && + !tokens[0].isList && + tokens[0].match == null) { + ampersandOperands(tokens[0], operands); + } + else { + operands.push(side); + } + } + return operands; + } + /** + * matches an ampersand of syntaxes: ` && && `, all the syntaxes in any order, except the optional syntaxes + * that match no token. `[ && ]` matches `thin 10px` and `10px thin` + * @param arena * @param syntax * @param context * @param options * @returns */ function matchAmpersandSyntax(arena, syntax, context, options) { - const syntaxes = [syntax.l, syntax.r]; - let result; - let i; - for (i = 0; i < syntaxes.length; i++) { - result = matchSyntax(arena, syntaxes[i], context.slice(), options); - if (result.success) { - if (result.context.done()) { - context.end(); - break; - } - context.update(result.context.current()); - syntaxes.splice(i, 1); - i = -1; + return matchUnorderedSyntaxes(arena, syntax, ampersandOperands(syntax), true, context, options); + } + /** + * the tokens of a media / container feature: the tokens before the closing parenthesis, `width >= 700px` in + * `(width >= 700px)`. the whitespace and the comments are skipped + * @param arena + * @param context + */ + function peekFeatureTokens(arena, context) { + const tokens = []; + let depth = 0; + for (let index = context.index + 1; index < context.tokens.length; index++) { + const token = context.tokens[index]; + if (arena.dataTypes[token] === exports.EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[token])) { + depth++; + } + else if (arena.dataTypes[token] === exports.EnumToken.EndParensTokenType && depth-- === 0) { + break; + } + if (arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[token] !== exports.EnumToken.CommentTokenType) { + tokens.push(token); } } - return result; + return tokens; } /** * matches a property + * @param arena * @param property * @param context * @param options @@ -14376,7 +16048,7 @@ const token = context.peek(); // inlined: arena.typeOf(token) let t = (token == null ? null : arena.dataTypes[token]); - let checkCalc = (t == exports.EnumToken.MathFunctionTokenDefType || t == exports.EnumToken.MathFunctionTokenType) && + let checkCalc = (t === exports.EnumToken.MathFunctionTokenDefType || t === exports.EnumToken.MathFunctionTokenType) && [ "number", "zero", @@ -14434,7 +16106,6 @@ }; } switch (property.val) { - case "function-parameter": case "declaration-value": { // consume a declaration value @@ -14444,21 +16115,24 @@ // if semicolon or end curly brace is encountered, stop let expectToken = true; let token; + // one or more tokens + let consumed = 0; const stack = []; token = context.peek(); if (token != null) { success = false; while ((token = context.peek()) != null) { - if (arena.dataTypes[token] == exports.EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[token])) { + if (arena.dataTypes[token] === exports.EnumToken.StartParensTokenType || + tokensfuncDefMap.has(arena.dataTypes[token])) { stack.push(token); } if (expectToken) { expectToken = false; } - if (arena.dataTypes[token] == exports.EnumToken.CommaTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.CommaTokenType) { expectToken = true; } - if (arena.dataTypes[token] == exports.EnumToken.EndParensTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.EndParensTokenType) { if (stack.length > 0) { stack.pop(); } @@ -14468,9 +16142,10 @@ } } context.next(); + consumed++; } } - success = !expectToken; + success = consumed > 0 && !expectToken; if (success) { return { success, @@ -14533,26 +16208,20 @@ break; } // inlined: arena.typeOf(token) - if (arena.dataTypes[token] === exports.EnumToken.LiteralTokenType || arena.dataTypes[token] === exports.EnumToken.IdenTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.LiteralTokenType || + arena.dataTypes[token] === exports.EnumToken.IdenTokenType) { let match = /^(([+-]?[0-9]*)?n)?([+-]?[0-9]+)?$/.exec(arena.strings[arena.stringValue[token]]); success = match != null; - if (match?.[3] == null) { - token = context.peek(1); - if ( - // inlined: arena.typeOf(token) - arena.dataTypes[token] === exports.EnumToken.Add || - // inlined: arena.typeOf(token) - arena.dataTypes[token] === exports.EnumToken.NextSiblingCombinatorTokenType || - // inlined: arena.typeOf(token) - arena.dataTypes[token] === exports.EnumToken.Sub) { - token = context.peek(2); - success = - // inlined: arena.typeOf(token) - arena.dataTypes[token] === exports.EnumToken.NumberTokenType && - Number.isInteger(arena.numericValue[token]); - } - if (success) { - context.update(token); + // `n + 1`: the sign and the number follow the ident + if (success && match?.[3] == null) { + const sign = context.peek(1); + // `n+1`: the sign is a part of the number + if (arena.dataTypes[sign] === exports.EnumToken.NumberTokenType) { + if (!Number.isInteger(arena.numericValue[sign])) { + success = false; + break; + } + context.update(sign); return { success: true, valid: true, @@ -14562,6 +16231,30 @@ errors: [], }; } + if ( + // inlined: arena.typeOf(sign) + arena.dataTypes[sign] === exports.EnumToken.Add || + // inlined: arena.typeOf(sign) + arena.dataTypes[sign] === exports.EnumToken.NextSiblingCombinatorTokenType || + // inlined: arena.typeOf(sign) + arena.dataTypes[sign] === exports.EnumToken.Sub) { + token = context.peek(2); + success = + // inlined: arena.typeOf(token) + arena.dataTypes[token] === exports.EnumToken.NumberTokenType && + Number.isInteger(arena.numericValue[token]); + if (success) { + context.update(token); + return { + success: true, + valid: true, + token: null, + context, + syntaxToken: property, + errors: [], + }; + } + } } break; } @@ -14575,7 +16268,13 @@ break; } if (arena.dataTypes[token] === exports.EnumToken.NumberTokenType) { - // the sign of the number is not tracked by the tokenizer + // `2n+1`, `-2n -0`: the sign is a part of the number + if (Number.isInteger(arena.numericValue[token])) { + context.next(); + } + else { + success = false; + } break; } if (arena.dataTypes[token] === exports.EnumToken.NextSiblingCombinatorTokenType) { @@ -14603,11 +16302,13 @@ case "content-position": { let values = propertyKeywordValues.get(property.val); if (values == null) { - values = new Set(config$3.syntaxes[property.val].syntax.split(/[\s|]+/)); + values = new Set((getSyntax(property.val) ?? "").split(/[\s|]+/)); propertyKeywordValues.set(property.val, values); } // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == exports.EnumToken.IdenTokenType && values.has(arena.strings[arena.stringValue[token]].toLowerCase()); + success = + arena.dataTypes[token] === exports.EnumToken.IdenTokenType && + values.has(arena.strings[arena.stringValue[token]].toLowerCase()); break; } case "mf-name": @@ -14623,7 +16324,7 @@ case "extension-name": case "custom-property-name": // inlined: arena.typeOf(context.peek()) - success = arena.dataTypes[context.peek()] == exports.EnumToken.DashedIdenTokenType; + success = arena.dataTypes[context.peek()] === exports.EnumToken.DashedIdenTokenType; break; case "namespace-prefix": case "ident": @@ -14632,7 +16333,9 @@ case "counter-name": case "counter-style-name": // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == exports.EnumToken.IdenTokenType || arena.dataTypes[token] == exports.EnumToken.DashedIdenTokenType; + success = + arena.dataTypes[token] === exports.EnumToken.IdenTokenType || + arena.dataTypes[token] === exports.EnumToken.DashedIdenTokenType; // inlined: arena.typeOf(token) if (success && arena.dataTypes[token] === exports.EnumToken.IdenTokenType) { const val = arena.strings[arena.stringValue[token]].toLowerCase(); @@ -14658,6 +16361,21 @@ ].includes(arena.dataTypes[token]); break; } + case "unicode-range-token": + // `U+0025-00FF` + // inlined: arena.typeOf(context.peek()) + success = arena.dataTypes[context.peek()] === exports.EnumToken.UniCodeRange; + break; + case "hash-token": { + // : `#foo`. a valid hex color such as `#fade` is tokenized as a color + const token = context.peek(); + success = + // inlined: arena.typeOf(token) + arena.dataTypes[token] === exports.EnumToken.HashTokenType || + (arena.dataTypes[token] === exports.EnumToken.ColorTokenType && + arena.colorType[token] === exports.ColorType.HEX); + break; + } case "string": { const token = context.peek(); // inlined: arena.typeOf(token) @@ -14666,7 +16384,7 @@ } case "wq-name": { // inlined: arena.typeOf(context.peek()) - const success = arena.dataTypes[context.peek()] == exports.EnumToken.IdenTokenType; + const success = arena.dataTypes[context.peek()] === exports.EnumToken.IdenTokenType; return { success, valid: true, @@ -14680,13 +16398,15 @@ { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == exports.EnumToken.NumberTokenType; + success = arena.dataTypes[token] === exports.EnumToken.NumberTokenType; } break; case "zero": { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == exports.EnumToken.NumberTokenType && arena.numericValue[token] === 0; + success = + arena.dataTypes[token] === exports.EnumToken.NumberTokenType && + arena.numericValue[token] === 0; break; } case "integer": @@ -14694,44 +16414,50 @@ const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.NumberTokenType && Number.isInteger(Number(arena.numericValue[token])); + arena.dataTypes[token] === exports.EnumToken.NumberTokenType && + Number.isInteger(Number(arena.numericValue[token])); } break; case "dimension": { const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.DimensionTokenType || + arena.dataTypes[token] === exports.EnumToken.DimensionTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.AngleTokenType || + arena.dataTypes[token] === exports.EnumToken.AngleTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.LengthTokenType || + arena.dataTypes[token] === exports.EnumToken.LengthTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.PercentageTokenType || + arena.dataTypes[token] === exports.EnumToken.PercentageTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.ResolutionTokenType || + arena.dataTypes[token] === exports.EnumToken.ResolutionTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.TimeTokenType || + arena.dataTypes[token] === exports.EnumToken.TimeTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.FrequencyTokenType || + arena.dataTypes[token] === exports.EnumToken.FrequencyTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.UserDefinedDimensionTokenType || + arena.dataTypes[token] === exports.EnumToken.UserDefinedDimensionTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.FlexTokenType; + arena.dataTypes[token] === exports.EnumToken.FlexTokenType; break; } case "angle": { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] === exports.EnumToken.AngleTokenType || arena.dataTypes[token] === exports.EnumToken.UserDefinedDimensionTokenType; + success = + arena.dataTypes[token] === exports.EnumToken.AngleTokenType || + arena.dataTypes[token] === exports.EnumToken.UserDefinedDimensionTokenType; } break; case "angle-percentage": { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] === exports.EnumToken.AngleTokenType || arena.dataTypes[token] === exports.EnumToken.UserDefinedDimensionTokenType || arena.dataTypes[token] === exports.EnumToken.PercentageTokenType; + success = + arena.dataTypes[token] === exports.EnumToken.AngleTokenType || + arena.dataTypes[token] === exports.EnumToken.UserDefinedDimensionTokenType || + arena.dataTypes[token] === exports.EnumToken.PercentageTokenType; } break; case "percentage": @@ -14748,28 +16474,49 @@ const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.PercentageTokenType || + arena.dataTypes[token] === exports.EnumToken.PercentageTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.LengthTokenType || + arena.dataTypes[token] === exports.EnumToken.LengthTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.UserDefinedDimensionTokenType || + arena.dataTypes[token] === exports.EnumToken.UserDefinedDimensionTokenType || // inlined: arena.typeOf(token) - (arena.dataTypes[token] == exports.EnumToken.NumberTokenType && arena.numericValue[token] === 0); + (arena.dataTypes[token] === exports.EnumToken.NumberTokenType && + arena.numericValue[token] === 0); } break; case "flex": // inlined: arena.typeOf(context.peek()) - success = arena.dataTypes[context.peek()] == exports.EnumToken.FlexTokenType || arena.dataTypes[context.peek()] == exports.EnumToken.UserDefinedDimensionTokenType; + success = + arena.dataTypes[context.peek()] === exports.EnumToken.FlexTokenType || + arena.dataTypes[context.peek()] === exports.EnumToken.UserDefinedDimensionTokenType; break; case "length": { const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.LengthTokenType || + arena.dataTypes[token] === exports.EnumToken.LengthTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.UserDefinedDimensionTokenType || + arena.dataTypes[token] === exports.EnumToken.UserDefinedDimensionTokenType || // inlined: arena.typeOf(token) - (arena.dataTypes[token] == exports.EnumToken.NumberTokenType && arena.numericValue[token] === 0); + (arena.dataTypes[token] === exports.EnumToken.NumberTokenType && + arena.numericValue[token] === 0); + break; + } + case "resolution": + // inlined: arena.typeOf(context.peek()) + success = arena.dataTypes[context.peek()] === exports.EnumToken.ResolutionTokenType; + break; + case "frequency": + // inlined: arena.typeOf(context.peek()) + success = arena.dataTypes[context.peek()] === exports.EnumToken.FrequencyTokenType; + break; + case "decibel": + case "semitones": { + // `6dB`, `2st` + const token = context.peek(); + success = + arena.dataTypes[token] === exports.EnumToken.DimensionTokenType && + equalsIgnoreCase(arena.strings[arena.unit[token]], property.val === "decibel" ? "dB" : "st"); break; } case "time": @@ -14778,7 +16525,9 @@ if (token == null) { break; } - success = arena.dataTypes[token] == exports.EnumToken.TimeTokenType || arena.dataTypes[token] == exports.EnumToken.UserDefinedDimensionTokenType; + success = + arena.dataTypes[token] === exports.EnumToken.TimeTokenType || + arena.dataTypes[token] === exports.EnumToken.UserDefinedDimensionTokenType; } break; case "color": @@ -14791,7 +16540,7 @@ const range = context.peekRange(); const newRange = range.map((t) => arena.clone(t, true)); parseTokens(arena, newRange, { parseColor: true }, errors); - success = newRange.length == 1 && isColor(arena, newRange[0], errors); + success = newRange.length === 1 && isColor(arena, newRange[0], errors); if (success) { context.update(range.at(-1)); return { @@ -14836,11 +16585,11 @@ case "complex-selector-list": { const tokens = context.getRemainingTokens(); const result = matchSelectorSyntax(arena, tokens, [], options, property.val.startsWith("forgiving-relative-selector-list")); - if (result.success || property.val == "forgiving-relative-selector-list") { + if (result.success || property.val === "forgiving-relative-selector-list") { context.update(tokens.at(-1)); } return { - success: result.success || property.val == "forgiving-relative-selector-list", + success: result.success || property.val === "forgiving-relative-selector-list", valid: true, token: context.peek(), context, @@ -14851,8 +16600,8 @@ case "function-token": // inlined: arena.typeOf(context.peek()). the type of a null id is undefined: not a key of the map either if (tokensfuncDefMap.has(arena.dataTypes[context.peek()])) { + // the token is consumed below success = true; - context.next(); break; } return { @@ -14867,68 +16616,54 @@ const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == exports.EnumToken.IdenTokenType && + arena.dataTypes[token] === exports.EnumToken.IdenTokenType && // @ts-expect-error - config$3.languages.some((t) => t === arena.strings[arena.stringValue[token]] || arena.strings[arena.stringValue[token]].startsWith(t + "-")); + config$3.languages.some((t) => t === arena.strings[arena.stringValue[token]] || + arena.strings[arena.stringValue[token]].startsWith(t + "-")); break; } case "size-feature": { - const range = context.peekRange(); - const filteredRange = range.filter((token) => arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== exports.EnumToken.CommentTokenType); - if (filteredRange.length === 1) { - success = - arena.dataTypes[filteredRange[0]] === exports.EnumToken.IdenTokenType || - arena.dataTypes[filteredRange[0]] === exports.EnumToken.DashedIdenTokenType; - context.update(filteredRange[0]); - return { - success, - valid: true, - token: filteredRange[0], - context, - syntaxToken: property, - errors: [], - }; - } - if (!mFLT.has(arena.dataTypes[filteredRange[1]]) && - !mFGT.has(arena.dataTypes[filteredRange[1]]) && - arena.dataTypes[filteredRange[1]] !== exports.EnumToken.ColonTokenType && - arena.dataTypes[filteredRange[1]] !== exports.EnumToken.DelimTokenType) { - return { - success: false, - valid: true, - token: filteredRange[1], - context, - syntaxToken: property, - errors: [], - }; + // | : | . the feature is validated by the at-rule parser + const filteredRange = peekFeatureTokens(arena, context); + success = + filteredRange.length === 1 + ? arena.dataTypes[filteredRange[0]] === exports.EnumToken.IdenTokenType || + arena.dataTypes[filteredRange[0]] === exports.EnumToken.DashedIdenTokenType + : filteredRange.length > 2 && + (mFLT.has(arena.dataTypes[filteredRange[1]]) || + mFGT.has(arena.dataTypes[filteredRange[1]]) || + arena.dataTypes[filteredRange[1]] === exports.EnumToken.ColonTokenType || + arena.dataTypes[filteredRange[1]] === exports.EnumToken.DelimTokenType); + if (success) { + context.update(filteredRange.at(-1)); } - break; + return { + success, + valid: true, + token: success ? null : (filteredRange[1] ?? context.peek()), + context, + syntaxToken: property, + errors: [], + }; } case "style-feature": { - // case 'style-feature-value': - // match - // match - // match - const range = context.peekRange(); - const filteredRange = range.filter((token) => arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== exports.EnumToken.CommentTokenType); - if (filteredRange.length === 1) { - success = - arena.dataTypes[filteredRange[0]] === exports.EnumToken.IdenTokenType || - arena.dataTypes[filteredRange[0]] === exports.EnumToken.DashedIdenTokenType; - context.update(filteredRange[0]); - return { - success, - valid: true, - token: filteredRange[0], - context, - syntaxToken: property, - errors: [], - }; + // | | + const filteredRange = peekFeatureTokens(arena, context); + success = + filteredRange.length === 1 + ? arena.dataTypes[filteredRange[0]] === exports.EnumToken.IdenTokenType || + arena.dataTypes[filteredRange[0]] === exports.EnumToken.DashedIdenTokenType + : filteredRange.length > 2 && + (mFLT.has(arena.dataTypes[filteredRange[1]]) || + mFGT.has(arena.dataTypes[filteredRange[1]]) || + arena.dataTypes[filteredRange[1]] === exports.EnumToken.ColonTokenType); + if (success) { + context.update(filteredRange.at(-1)); } return { - success: false, - valid: false, - token: context.peek(), + success, + valid: success, + token: success ? null : context.peek(), context, syntaxToken: property, errors: [], @@ -14938,25 +16673,27 @@ const token = context.peek(); let l; // inlined: arena.typeOf(token) - if (arena.dataTypes[token] == exports.EnumToken.UrlFunctionTokenDefType) { + if (arena.dataTypes[token] === exports.EnumToken.UrlFunctionTokenDefType) { l = 0; let token; while ((token = context.peek(++l))) { - if (arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[token] !== exports.EnumToken.CommentTokenType) { break; } } if (token != null && - (arena.dataTypes[token] == exports.EnumToken.StringTokenType || - arena.dataTypes[token] == exports.EnumToken.IdenTokenType || - arena.dataTypes[token] == exports.EnumToken.UrlTokenTokenType)) { + (arena.dataTypes[token] === exports.EnumToken.StringTokenType || + arena.dataTypes[token] === exports.EnumToken.IdenTokenType || + arena.dataTypes[token] === exports.EnumToken.UrlTokenTokenType)) { while ((token = context.peek(++l))) { - if (arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[token] !== exports.EnumToken.CommentTokenType) { break; } } // inlined: arena.typeOf(token) - if (arena.dataTypes[token] == exports.EnumToken.EndParensTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.EndParensTokenType) { success = true; context.update(token); return { @@ -14972,7 +16709,7 @@ break; } // inlined: arena.typeOf(token) - if (arena.dataTypes[token] != exports.EnumToken.UrlFunctionTokenType) { + if (arena.dataTypes[token] !== exports.EnumToken.UrlFunctionTokenType) { success = false; break; } @@ -14986,9 +16723,9 @@ } if (l < urlTokens.length) { success = - arena.dataTypes[urlTokens[l]] == exports.EnumToken.StringTokenType || - arena.dataTypes[urlTokens[l]] == exports.EnumToken.IdenTokenType || - arena.dataTypes[urlTokens[l]] == exports.EnumToken.UrlTokenTokenType; + arena.dataTypes[urlTokens[l]] === exports.EnumToken.StringTokenType || + arena.dataTypes[urlTokens[l]] === exports.EnumToken.IdenTokenType || + arena.dataTypes[urlTokens[l]] === exports.EnumToken.UrlTokenTokenType; context.next(); return { success: true, @@ -15002,10 +16739,38 @@ break; } case "css-type": { - // inlined: arena.typeOf(context.peek()) - success = arena.dataTypes[context.peek()] == exports.EnumToken.CssTypeTokenType; + const token = context.peek(); + // `type( | )`: the css type syntax + if ((arena.dataTypes[token] === exports.EnumToken.FunctionTokenDefType || + arena.dataTypes[token] === exports.EnumToken.FunctionTokenType) && + equalsIgnoreCase(arena.strings[arena.stringValue[token]], "type")) { + if (arena.dataTypes[token] === exports.EnumToken.FunctionTokenDefType) { + context.update(context.peekRange().at(-1)); + } + else { + context.next(); + } + return { + success: true, + valid: true, + token: null, + context, + syntaxToken: null, + errors: [], + }; + } + // inlined: arena.typeOf(token) + success = arena.dataTypes[token] === exports.EnumToken.CssTypeTokenType; if (success) { context.next(); + // the multiplier follows the type: `#`, `+` + const multiplier = context.tokens[context.index + 1]; + if (multiplier != null && + (arena.dataTypes[multiplier] === exports.EnumToken.Plus || + (arena.dataTypes[multiplier] === exports.EnumToken.LiteralTokenType && + arena.strings[arena.stringValue[multiplier]] === "#"))) { + context.next(); + } return { success: true, valid: true, @@ -15020,9 +16785,17 @@ case "dashed-function": { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == exports.EnumToken.CustomFunctionTokenDefType; + success = + arena.dataTypes[token] === exports.EnumToken.CustomFunctionTokenDefType || + arena.dataTypes[token] === exports.EnumToken.CustomFunctionTokenType; if (success) { - context.next(); + // `--name()`: the function and its arguments + if (arena.dataTypes[token] === exports.EnumToken.CustomFunctionTokenDefType) { + context.update(context.peekRange().at(-1)); + } + else { + context.next(); + } return { success: true, valid: true, @@ -15036,7 +16809,7 @@ } case "block-contents": // inlined: arena.typeOf(context.peek()) - success = arena.dataTypes[context.peek()] == exports.EnumToken.StartParensTokenType; + success = arena.dataTypes[context.peek()] === exports.EnumToken.StartParensTokenType; if (success) { context.next(); return { @@ -15057,7 +16830,7 @@ errors: [], }; default: - if (!(property.val in config$3.syntaxes)) { + if (!hasSyntax(property.val)) { console.debug("Unknown syntax", context.peek(), property); throw new Error(`Unexpected validation property ${property.val}`); } @@ -15065,7 +16838,7 @@ } if (!success && // inlined: arena.typeOf(context.peek()) - arena.dataTypes[context.peek()] == exports.EnumToken.IdenTokenType && + arena.dataTypes[context.peek()] === exports.EnumToken.IdenTokenType && allValues.includes(arena.strings[arena.stringValue[context.peek()]])) { success = true; } @@ -15091,6 +16864,7 @@ } /** * matches a repeatable syntax + * @param arena * @param syntax * @param context * @param options @@ -15110,7 +16884,8 @@ context.end(); break; } - if (tmpResult.context.index === context.index) { + // no token matched. the indexes of the contexts are not comparable: the result context is a slice + if (tmpResult.context.current() === context.current()) { break; } context.update(result.context.current()); @@ -15128,6 +16903,7 @@ /** * Create a color token + * @param arena * @param kind * @param components * @param alpha @@ -15139,14 +16915,15 @@ } const alphaValue = alpha == null ? 1 - : arena.dataTypes[alpha] === exports.EnumToken.IdenTokenType && equalsIgnoreCase(arena.strings[arena.stringValue[alpha]], "none") + : arena.dataTypes[alpha] === exports.EnumToken.IdenTokenType && + equalsIgnoreCase(arena.strings[arena.stringValue[alpha]], "none") ? 0 : minmax(getNumber(arena, alpha), 0, 1); components.length = 3; // the components may belong to another color token: a token belongs to one token list for (let i = 0; i < components.length; i++) { // inlined: arena.take(components[i]) - components[i] = arena.parents[components[i]] == 0 ? components[i] : arena.clone(components[i], true); + components[i] = arena.parents[components[i]] === 0 ? components[i] : arena.clone(components[i], true); } if (alphaValue !== 1) { components.push(arena.createToken(exports.EnumToken.NumberTokenType, alphaValue)); @@ -15185,7 +16962,9 @@ return null; } return arena.colorType[color] === exports.ColorType.COLOR_MIX - ? exports.ColorType[arena.strings[arena.stringValue[token]]?.toUpperCase?.()?.replace?.("-", "_")] + ? exports.ColorType[arena.strings[arena.stringValue[token]] + ?.toUpperCase?.() + ?.replace?.("-", "_")] : getColorType(arena, token); } return arena.colorType[color]; @@ -15193,6 +16972,7 @@ /** * Compute alpha color + * @param arena * @param color * @param alpha * @returns @@ -15229,7 +17009,7 @@ } } const result = evaluate(arena, [alpha]); - if (result.length == 1) { + if (result.length === 1) { alpha = result[0]; } // else { @@ -15277,6 +17057,7 @@ /** * Converts a color to another color space + * @param arena * @param token * @param to * @@ -15288,13 +17069,16 @@ * ``` */ function convertColor(arena, token, to) { - if (arena.colorType[token] == exports.ColorType.SYS || - arena.colorType[token] == exports.ColorType.DPSYS || - (isIdentColor(arena, token) && "currentcolor" == arena.strings[arena.stringValue[token]])) { + if (arena.colorType[token] === exports.ColorType.SYS || + arena.colorType[token] === exports.ColorType.DPSYS || + (isIdentColor(arena, token) && "currentcolor" === arena.strings[arena.stringValue[token]])) { return token; } - if (arena.colorType[token] == exports.ColorType.ALPHA) { - const args = arena.tokens(token).filter((token) => arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== exports.EnumToken.CommentTokenType); + if (arena.colorType[token] === exports.ColorType.ALPHA) { + const args = arena + .tokens(token) + .filter((token) => arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[token] !== exports.EnumToken.CommentTokenType); if (args.length > 1 && arena.dataTypes[args[args.length - 2]] === exports.EnumToken.LiteralTokenType && "/" === arena.strings[arena.stringValue[args[args.length - 2]]]) { @@ -15307,12 +17091,13 @@ } token = result; } - if (arena.colorType[token] == exports.ColorType.COLOR_MIX && to != exports.ColorType.COLOR_MIX) { + if (arena.colorType[token] === exports.ColorType.COLOR_MIX && to !== exports.ColorType.COLOR_MIX) { const children = arena.tokens(token).reduce((acc, t) => { if (arena.dataTypes[t] === exports.EnumToken.CommaTokenType) { acc.push([]); } - else if (arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[t] !== exports.EnumToken.CommentTokenType) { + else if (arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[t] !== exports.EnumToken.CommentTokenType) { acc[acc.length - 1].push(t); } return acc; @@ -15323,10 +17108,10 @@ } token = result; } - if (arena.strings[arena.unit[token]] == "rel" && + if (arena.strings[arena.unit[token]] === "rel" && ["rgb", "hsl", "hwb", "lab", "lch", "oklab", "oklch", "color"].some((t) => equalsIgnoreCase(t, arena.strings[arena.stringValue[token]]))) { const chi = getColorComponents(arena, token); - const offset = arena.strings[arena.stringValue[token]] == "color" ? 2 : 1; + const offset = arena.strings[arena.stringValue[token]] === "color" ? 2 : 1; if (chi != null) { // @ts-ignore const color = chi[1]; @@ -15337,40 +17122,40 @@ return null; } const name = arena.strings[arena.stringValue[token]]; - const tk = arena.createColor(name, exports.ColorType[name.toUpperCase().replaceAll("-", "_")], name == "color" ? [arena.clone(chi[offset])] : []); + const tk = arena.createColor(name, exports.ColorType[name.toUpperCase().replaceAll("-", "_")], name === "color" ? [arena.clone(chi[offset])] : []); const seen = new Set(); for (const t of Object.values(components)) { // a component token may be used more than once: rgb(from #ff0 r g r) // inlined: arena.take(t) - arena.appendToken(tk, seen.has(t) ? arena.clone(t, true) : (arena.parents[t] == 0 ? t : arena.clone(t, true))); + arena.appendToken(tk, seen.has(t) ? arena.clone(t, true) : arena.parents[t] === 0 ? t : arena.clone(t, true)); seen.add(t); } arena.copyLocation(tk, token); token = tk; } } - if (arena.colorType[token] == to) { - if (arena.colorType[token] == exports.ColorType.HEX || arena.colorType[token] == exports.ColorType.LIT) { + if (arena.colorType[token] === to) { + if (arena.colorType[token] === exports.ColorType.HEX || arena.colorType[token] === exports.ColorType.LIT) { const val = reduceHexValue(arena.strings[arena.stringValue[token]]); // inlined: arena.setStr(token, val) arena.stringValue[token] = arena.internString(val); - arena.colorType[token] = val[0] == "#" ? exports.ColorType.HEX : exports.ColorType.LIT; + arena.colorType[token] = val[0] === "#" ? exports.ColorType.HEX : exports.ColorType.LIT; } return token; } - if (arena.colorType[token] == exports.ColorType.COLOR) { + if (arena.colorType[token] === exports.ColorType.COLOR) { const colorSpace = arena.findToken(token, (arena, t) => ![exports.EnumToken.WhitespaceTokenType, exports.EnumToken.CommentTokenType].includes(arena.dataTypes[t])); if (colorSpace != null && - arena.strings[arena.stringValue[colorSpace]] == exports.ColorType[to].toLowerCase().replaceAll("_", "-")) { + arena.strings[arena.stringValue[colorSpace]] === exports.ColorType[to].toLowerCase().replaceAll("_", "-")) { for (const chi of arena.tokens(token)) { - if (arena.dataTypes[chi] == exports.EnumToken.NumberTokenType && !arena.hasFraction(chi)) { + if (arena.dataTypes[chi] === exports.EnumToken.NumberTokenType && !arena.hasFraction(chi)) { arena.numericValue[chi] = getNumber(arena, chi); } } return token; } } - if (to == exports.ColorType.HSL) { + if (to === exports.ColorType.HSL) { switch (arena.colorType[token]) { case exports.ColorType.RGB: case exports.ColorType.RGBA: @@ -15394,7 +17179,7 @@ return color2HslToken(arena, token); } } - else if (to == exports.ColorType.HWB) { + else if (to === exports.ColorType.HWB) { switch (arena.colorType[token]) { case exports.ColorType.RGB: case exports.ColorType.RGBA: @@ -15419,7 +17204,7 @@ return color2hwbToken(arena, token); } } - else if (to == exports.ColorType.DEVICE_CMYK) { + else if (to === exports.ColorType.DEVICE_CMYK) { switch (arena.colorType[token]) { case exports.ColorType.RGB: case exports.ColorType.RGBA: @@ -15444,12 +17229,12 @@ return color2cmykToken(arena, token); } } - else if (to == exports.ColorType.HEX || to == exports.ColorType.LIT) { + else if (to === exports.ColorType.HEX || to === exports.ColorType.LIT) { switch (arena.colorType[token]) { case exports.ColorType.HEX: case exports.ColorType.LIT: { const val = reduceHexValue(arena.strings[arena.stringValue[token]]); - return arena.createColor(val, val[0] == "#" ? exports.ColorType.HEX : exports.ColorType.LIT); + return arena.createColor(val, val[0] === "#" ? exports.ColorType.HEX : exports.ColorType.LIT); } case exports.ColorType.HSL: return hsl2HexToken(arena, token); @@ -15472,7 +17257,7 @@ return rgb2HexToken(arena, token); } } - else if (to == exports.ColorType.RGB) { + else if (to === exports.ColorType.RGB) { switch (arena.colorType[token]) { case exports.ColorType.HEX: case exports.ColorType.LIT: @@ -15495,7 +17280,7 @@ return color2RgbToken(arena, token); } } - else if (to == exports.ColorType.LAB) { + else if (to === exports.ColorType.LAB) { switch (arena.colorType[token]) { case exports.ColorType.HEX: case exports.ColorType.LIT: @@ -15520,7 +17305,7 @@ return color2labToken(arena, token); } } - else if (to == exports.ColorType.LCH) { + else if (to === exports.ColorType.LCH) { switch (arena.colorType[token]) { case exports.ColorType.HEX: case exports.ColorType.LIT: @@ -15545,7 +17330,7 @@ return color2lchToken(arena, token); } } - else if (to == exports.ColorType.OKLAB) { + else if (to === exports.ColorType.OKLAB) { switch (arena.colorType[token]) { case exports.ColorType.HEX: case exports.ColorType.LIT: @@ -15570,7 +17355,7 @@ return color2oklabToken(arena, token); } } - else if (to == exports.ColorType.OKLCH) { + else if (to === exports.ColorType.OKLCH) { switch (arena.colorType[token]) { case exports.ColorType.HEX: case exports.ColorType.LIT: @@ -15755,7 +17540,7 @@ values = xyzd502srgb(values[0], values[1], values[2], values[3]); break; } - if (values.length == 4) { + if (values.length === 4) { values[3] = values[3]; } return values; @@ -15771,7 +17556,7 @@ arena.createToken(exports.EnumToken.NumberTokenType, values[1]), arena.createToken(exports.EnumToken.NumberTokenType, values[2]), ]; - if (values.length == 4) { + if (values.length === 4) { chi.push(arena.createToken(exports.EnumToken.LiteralTokenType, "/"), arena.createToken(exports.EnumToken.PercentageTokenType, values[3] * 100)); } const colorSpace = exports.ColorType[to].toLowerCase().replaceAll("_", "-"); @@ -15786,18 +17571,18 @@ */ function getNumber(arena, token) { const typ = arena.dataTypes[token]; - if (typ == exports.EnumToken.IdenTokenType && arena.strings[arena.stringValue[token]] == "none") { + if (typ === exports.EnumToken.IdenTokenType && arena.strings[arena.stringValue[token]] === "none") { return 0; } let val; const fraction = arena.getFraction(token); - if (fraction != 0) { + if (fraction !== 0) { val = arena.numericValue[arena.firstChild[fraction]] / arena.numericValue[arena.lastChild[fraction]]; } else { val = arena.numericValue[token]; } - return typ == exports.EnumToken.PercentageTokenType ? val / 100 : val; + return typ === exports.EnumToken.PercentageTokenType ? val / 100 : val; } /** * convert angle to turn @@ -15806,13 +17591,13 @@ */ function getAngle(arena, token) { const typ = arena.dataTypes[token]; - if (typ == exports.EnumToken.IdenTokenType) { - if (arena.strings[arena.stringValue[token]] == "none") { + if (typ === exports.EnumToken.IdenTokenType) { + if (arena.strings[arena.stringValue[token]] === "none") { return 0; } } const val = getNumber(arena, token); - if (typ == exports.EnumToken.AngleTokenType) { + if (typ === exports.EnumToken.AngleTokenType) { switch (arena.strings[arena.unit[token]]) { case "deg": return val / 360; @@ -15845,7 +17630,7 @@ const integer_to_char = {}; const char_to_integer = {}; let i = 0; - for (const char of 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=') { + for (const char of "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=") { char_to_integer[char] = i; integer_to_char[i++] = char; } @@ -15859,9 +17644,6 @@ let value = 0; for (let i = 0; i < str.length; i += 1) { let integer = char_to_integer[str[i]]; - // if (integer === undefined) { - // throw new Error('Invalid character (' + str[i] + ')'); - // } const has_continuation_bit = integer & 32; integer &= 31; value += integer << shift; @@ -15892,7 +17674,7 @@ // if (typeof value === 'number') { // return encode_integer(value); // } - let result = ''; + let result = ""; for (let i = 0; i < value.length; i += 1) { result += encode_integer(value[i]); } @@ -15904,7 +17686,7 @@ * @returns */ function encode_integer(num) { - let result = ''; + let result = ""; if (num < 0) { num = (-num << 1) | 1; } @@ -16010,13 +17792,13 @@ if (sourcemaps.startsWith("data:")) { let encoding = ""; let offset = sourcemaps.indexOf(",") + 1; - if (offset == 0) { + if (offset === 0) { offset = sourcemaps.lastIndexOf(";") + 1; } else { encoding = sourcemaps.slice(sourcemaps.lastIndexOf(";") + 1, offset - 1); } - if (encoding == "base64") { + if (encoding === "base64") { sourcemaps = atob(sourcemaps.slice(offset)); } else { @@ -16033,8 +17815,8 @@ .map((mapping) => mapping.split(",").map((mapping) => decode(mapping))); this.line = decodedMappings.length - 1; for (let index = 0; index < decodedMappings.length; index++) { - if (decodedMappings[index].length == 0 || - (decodedMappings[index].length == 1 && decodedMappings[index][0].length == 0)) { + if (decodedMappings[index].length === 0 || + (decodedMappings[index].length === 1 && decodedMappings[index][0].length === 0)) { continue; } this.map.set(index, decodedMappings[index]); @@ -16076,7 +17858,7 @@ this.line = line; } srcIndex = this.sourcesMap.indexOf(srcId); - if (srcIndex == -1) { + if (srcIndex === -1) { throw new Error(`Source file ${srcId} not added to sourcemap`); } if (!this.map.has(line)) { @@ -16119,12 +17901,12 @@ if (segment.length === 0) { return []; } - generatedCodeColumn = index == 0 ? segment[0] : segment[0] + array[0][0]; + generatedCodeColumn = index === 0 ? segment[0] : segment[0] + array[0][0]; result = [generatedCodeColumn]; if (segment.length <= 1) { return result; } - sourceFileIndex = index == 0 ? segment[1] : segment[1] + array[0][1]; + sourceFileIndex = index === 0 ? segment[1] : segment[1] + array[0][1]; sourceCodeLine += segment[2]; sourceCodeColumn += segment[3]; result.push(sourceFileIndex, sourceCodeLine, sourceCodeColumn); @@ -16141,7 +17923,7 @@ } return a[0] - b[0]; }); - if (line.length == 0 || (line.length == 1 && line[0].length == 0)) { + if (line.length === 0 || (line.length === 1 && line[0].length === 0)) { continue; } this.reverseMap.set(i, line); @@ -16153,7 +17935,7 @@ * @param column generated column */ find(line, column) { - if (this.reverseMap.size == 0) { + if (this.reverseMap.size === 0) { this.computePositions(); } if (!this.reverseMap.has(--line)) { @@ -16162,7 +17944,7 @@ column--; const result = []; for (const record of this.reverseMap.get(line)) { - if (record.length == 0 || record[0] < column) { + if (record.length === 0 || record[0] < column) { continue; } if (record[0] > column) { @@ -16175,7 +17957,7 @@ this.sourcesContent?.[record[1]] ?? null, ]); } - return result.length == 0 ? null : result; + return result.length === 0 ? null : result; } /** * Convert to URL encoded string @@ -16260,7 +18042,7 @@ const line = this.search(offset); const column = offset - this.lineStarts[line]; // [line, column] - return [line + 1, line == 0 ? column + 1 : column]; + return [line + 1, line === 0 ? column + 1 : column]; } /** * search the greatest index of the value less than or equal to offset @@ -16285,19 +18067,6 @@ } return result; } - /** - * get line starts - * @returns - */ - getLineStarts() { - return this.lineStarts; - } - /** - * add line start - */ - addLineStart(lineStart) { - this.lineStarts.push(lineStart); - } } /** @@ -16322,7 +18091,7 @@ let parts = [""]; for (; i < path.length; i++) { const chr = path.charAt(i); - if (chr == "/") { + if (chr === "/") { parts.push(""); } else { @@ -16338,14 +18107,14 @@ * @private */ function splitPath(result) { - if (result.length == 0) { + if (result.length === 0) { return { parts: [], i: 0 }; } - const parts = result == "/" ? [] : [""]; + const parts = result === "/" ? [] : [""]; let i = 0; for (; i < result.length; i++) { const chr = result.charAt(i); - if (chr == "/") { + if (chr === "/") { parts.push(""); } // else if (chr == "?" || chr == "#") { @@ -16367,7 +18136,7 @@ return { parts, i }; } /** - * Nomalize path + * Normalize path * @param path * @private */ @@ -16382,16 +18151,16 @@ } for (; i < path.length; i++) { const chr = path.charAt(i); - if (chr == "/") { - if (parts.length == 0 || parts[parts.length - 1] !== "") { + if (chr === "/") { + if (parts.length === 0 || parts[parts.length - 1] !== "") { parts.push(""); } } - else if (chr == "?" || chr == "#") { + else if (chr === "?" || chr === "#") { break; } else { - if (parts.length == 0) { + if (parts.length === 0) { parts.push(""); } parts[parts.length - 1] += chr; @@ -16402,12 +18171,12 @@ // if (parts[k] == ".") { // parts.splice(k--, 1); // } else - if (k > 0 && parts[k] == "..") { + if (k > 0 && parts[k] === "..") { parts.splice(k - 1, 2); k -= 2; } } - return (path.charAt(0) == "/" ? "/" : "") + parts.join("/"); + return (path.charAt(0) === "/" ? "/" : "") + parts.join("/"); }); /** * diff path @@ -16419,7 +18188,7 @@ let { parts } = splitPath(path1); const { parts: dirs } = splitPath(path2); for (const p of dirs) { - if (parts[0] == p) { + if (parts[0] === p) { parts.shift(); } else { @@ -16456,7 +18225,7 @@ if (windowsPathnameRegexp.test(dir)) { dir = dir.replace(windowsPathnameRegexp, ""); } - const absolute = dir == "" || url.startsWith("/") || url.startsWith(dir) || windowsPathnameRegexp.test(url) + const absolute = dir === "" || url.startsWith("/") || url.startsWith(dir) || windowsPathnameRegexp.test(url) ? resolvePath(url) : resolvePath(dir, url); return { @@ -16542,62 +18311,6 @@ append(content) { this.content += content; } - /** - * get file name - * @returns - */ - getFileName() { - return this.file; - } - /** - * get content - * @returns - */ - getContent() { - return this.content; - } - /** - * get text - * @param start - * @param length - * @returns - */ - getText(start, length) { - return this.content.slice(start, start + length); - } - /** - * Compute line and column of the offset - * @param offset - * @returns - */ - getOffsets(offset) { - return this.lineStarts.getOffsets(offset); - } - /** - * get source location - * @param offset - * @returns - */ - getSourceLocation(offset) { - // inlined: this.getOffsets(offset) - return [this.file, ...this.lineStarts.getOffsets(offset)]; - } - /** - * get line starts - * @returns - */ - getLineStarts() { - // inlined: this.lineStarts.getLineStarts() - return this.lineStarts.lineStarts; - } - /** - * add line start - * @param lineStart - */ - addLineStart(lineStart) { - // inlined: this.lineStarts.addLineStart(lineStart) - this.lineStarts.lineStarts.push(lineStart); - } /** * set input source map * @param inputSourceMap @@ -16649,7 +18362,7 @@ * @param value */ function normalize$1(value) { - return value !== value ? NaN : value + 0; + return value !== value ? NaN : value; } /** * Memoize values by token structure. Lookups return a slot, the value of a slot is `undefined` until it is set. @@ -16682,6 +18395,14 @@ * @internal */ values = []; + /** + * number of distinct structures (lookups that inserted a new entry) + */ + size = 0; + /** + * number of lookups that found an existing entry + */ + hits = 0; /** * key hash, key offset in the pool and key length of each slot (3 values per slot) */ @@ -16690,6 +18411,10 @@ * serialized keys. the key being looked up is serialized after the last key: it is kept when it is inserted */ pool = new Int32Array(1024); + /** + * length of the pool: the length of a typed array is a getter + */ + poolLength = 1024; /** * used length of the pool */ @@ -16702,14 +18427,6 @@ * end of the key being looked up in the pool */ used = 0; - /** - * number of distinct structures (lookups that inserted a new entry) - */ - size = 0; - /** - * number of lookups that found an existing entry - */ - hits = 0; /** * @param numericEquality compare the numeric values with `==` semantics (`0` and `-0` are equal) and consider * all the `NaN` values equal. the raw bits are compared otherwise @@ -16731,11 +18448,11 @@ */ list(arena, first, prefix = 0) { let used = this.poolSize; - if (used + 1 > this.pool.length) { + if (used + 1 > this.poolLength) { this.growPool(used + 1); } this.pool[used++] = prefix; - for (let token = first; token != 0; token = arena.nextSibling[token]) { + for (let token = first; token !== 0; token = arena.nextSibling[token]) { used = this.serialize(arena, token, used); } this.used = used; @@ -16786,7 +18503,7 @@ */ serialize(arena, token, used) { // header, 5 fields, end marker - let buffer = used + 7 > this.pool.length ? this.growPool(used + 7) : this.pool; + let buffer = used + 7 > this.poolLength ? this.growPool(used + 7) : this.pool; const name = arena.name[token]; const str = arena.stringValue[token]; const unit = arena.unit[token]; @@ -16796,15 +18513,15 @@ // type and color type are 8 bits values let header = arena.dataTypes[token] | (arena.colorType[token] << 8); const index = used++; - if (name != 0) { + if (name !== 0) { header |= 65536 /* Field.Name */; buffer[used++] = name; } - if (str != 0) { + if (str !== 0) { header |= 131072 /* Field.String */; buffer[used++] = str; } - if (unit != 0) { + if (unit !== 0) { header |= 262144 /* Field.Unit */; buffer[used++] = unit; } @@ -16824,25 +18541,25 @@ buffer[used++] = bits[1]; } } - if (firstToken != 0) { + if (firstToken !== 0) { header |= 2097152 /* Field.Tokens */; } - if (firstChild != 0) { + if (firstChild !== 0) { header |= 4194304 /* Field.Children */; } buffer[index] = header; - if (firstToken != 0) { - for (let child = firstToken; child != 0; child = arena.nextSibling[child]) { + if (firstToken !== 0) { + for (let child = firstToken; child !== 0; child = arena.nextSibling[child]) { used = this.serialize(arena, child, used); } - buffer = used + 1 > this.pool.length ? this.growPool(used + 1) : this.pool; + buffer = used + 1 > this.poolLength ? this.growPool(used + 1) : this.pool; buffer[used++] = End; } - if (firstChild != 0) { - for (let child = firstChild; child != 0; child = arena.nextSibling[child]) { + if (firstChild !== 0) { + for (let child = firstChild; child !== 0; child = arena.nextSibling[child]) { used = this.serialize(arena, child, used); } - buffer = used + 1 > this.pool.length ? this.growPool(used + 1) : this.pool; + buffer = used + 1 > this.poolLength ? this.growPool(used + 1) : this.pool; buffer[used++] = End; } return used; @@ -16853,6 +18570,7 @@ */ growPool(size) { this.pool = grow(this.pool, size); + this.poolLength = this.pool.length; return this.pool; } /** @@ -16877,16 +18595,16 @@ const mask = table.length - 1; let index = hash & mask; let slot; - while ((slot = table[index]) != 0) { + while ((slot = table[index]) !== 0) { slot--; const meta = slot * 3; - if (this.slots[meta] == hash && this.slots[meta + 2] == length) { + if (this.slots[meta] === hash && this.slots[meta + 2] === length) { const offset = this.slots[meta + 1]; let i = 0; - while (i < length && pool[offset + i] == pool[base + i]) { + while (i < length && pool[offset + i] === pool[base + i]) { i++; } - if (i == length) { + if (i === length) { this.hits++; return slot; } @@ -16895,7 +18613,7 @@ } // insert: the serialized key is kept in the pool slot = this.size++; - if (slot * 3 == this.slots.length) { + if (slot * 3 === this.slots.length) { this.slots = grow(this.slots, slot * 3 + 3); } this.slots[slot * 3] = hash; @@ -16916,7 +18634,7 @@ const mask = table.length - 1; for (let slot = 0; slot < this.size; slot++) { let index = this.slots[slot * 3] & mask; - while (table[index] != 0) { + while (table[index] !== 0) { index = (index + 1) & mask; } table[index] = slot + 1; @@ -16962,6 +18680,13 @@ * collection when no instance is alive, and the optimized code that depends on it discarded (deoptimized) */ static shape = new RenderMemo(); + /** + * cleared memos, reused by the next renders: their buffers are not allocated again. read by the library + * (see {@link acquire}) + * + * @internal + */ + static free = []; /** * rendered declarations (`name:value`), by name and value tokens */ @@ -16970,13 +18695,6 @@ * rendered constructs: colors and tokens with sub tokens (functions, parentheses, binary expressions, ...) */ constructs = new StructuralMemo(); - /** - * cleared memos, reused by the next renders: their buffers are not allocated again. read by the library - * (see {@link acquire}) - * - * @internal - */ - static free = []; /** * a cleared memo */ @@ -17195,7 +18913,7 @@ options = resolveRenderOptions(options); const expandNesting = options.expandNestingRules && [exports.EnumToken.StyleSheetNodeType, exports.EnumToken.AtRuleNodeType, exports.EnumToken.RuleNodeType].includes(arena.dataTypes[data]) && - (arena.flags[data] & exports.EnumAstNodeStatus.HasChildren) != 0; + (arena.flags[data] & exports.EnumAstNodeStatus.HasChildren) !== 0; // temporary stylesheet holding the rendered copy let sheet = 0; if (options.withParents || expandNesting) { @@ -17206,7 +18924,7 @@ data = arena.clone(data, true); if (options.withParents) { // wrap the node into shallow copies of its ancestors - while (parent != 0) { + while (parent !== 0) { const clone = arena.clone(parent, false); arena.appendChild(clone, data); data = clone; @@ -17228,7 +18946,7 @@ // reused by the next renders const ownMemo = memo == null; // inlined: RenderMemo.acquire() - const cache = new RenderCache(memo ?? (RenderMemo.free.pop() ?? new RenderMemo()), options); + const cache = new RenderCache(memo ?? RenderMemo.free.pop() ?? new RenderMemo(), options); const sourceLocation = { end: 0, }; @@ -17265,7 +18983,7 @@ if (ownMemo) { RenderMemo.release(cache.memo); } - if (sheet != 0) { + if (sheet !== 0) { // drop the temporary stylesheet. the tokens allocated while rendering (color conversion, gradients, ...) // are not attached to the tree either: the memory is not reclaimed, the ids are never reused arena.detach(data); @@ -17300,7 +19018,7 @@ */ function updateSourceMap(arena, node, options, cache, sourcemaps, sourceLocation, linesMap, str) { let offset = 0; - // eat leanding whitespace + // eat leading whitespace while (offset < str.length && isWhiteSpace(str.charCodeAt(offset))) { offset++; } @@ -17317,7 +19035,7 @@ // generated position, see LineMap.getOffsets() const line = linesMap.search(sourceLocation.end); const newLine = line + 1; - const newColumn = sourceLocation.end - linesMap.lineStarts[line] + (line == 0 ? 1 : 0); + const newColumn = sourceLocation.end - linesMap.lineStarts[line] + (line === 0 ? 1 : 0); let records = null; // inlined: source.getFileName() let sourceFileName = source.file || null; @@ -17341,7 +19059,8 @@ // resolution is relative to the source file const absoluteSourceFileName = options.resolve(sourceFileName, absoluteSourcePath) .absolute; - cache.paths[sourceFileName] = options.resolve(absoluteSourceFileName, absolute).relative; + cache.paths[sourceFileName] = options.resolve(absoluteSourceFileName, absolute) + .relative; } sourceFileName = cache.paths[sourceFileName]; } @@ -17399,15 +19118,15 @@ for (; i < j; i++) { codepoint = str.charCodeAt(i); sourceLocation.end++; - if (codepoint == 0xa || // \n - codepoint == 0xb || // \v - codepoint == 0xc || // \f - codepoint == 0xd || // \r - codepoint == 0x2028 || // \u2028 - codepoint == 0x2029 // \u2029 + if (codepoint === 0xa || // \n + codepoint === 0xb || // \v + codepoint === 0xc || // \f + codepoint === 0xd || // \r + codepoint === 0x2028 || // \u2028 + codepoint === 0x2029 // \u2029 ) { - if (codepoint == 0xd && i + 1 < str.length && str.charCodeAt(i + 1) == 0xa) ; - else if (codepoint == 0xa && i > 0 && str.charCodeAt(i - 1) == 0xd) ; + if (codepoint === 0xd && i + 1 < str.length && str.charCodeAt(i + 1) === 0xa) ; + else if (codepoint === 0xa && i > 0 && str.charCodeAt(i - 1) === 0xd) ; else { // inlined: linesMap.addLineStart(sourceLocation.end) linesMap.lineStarts.push(sourceLocation.end); @@ -17457,7 +19176,7 @@ return !options.removeComments || (options.preserveLicense && val.startsWith("/*!")) ? val : ""; } case exports.EnumToken.StyleSheetNodeType: - for (let node = arena.firstChild[data]; node != 0; node = arena.nextSibling[node]) { + for (let node = arena.firstChild[data]; node !== 0; node = arena.nextSibling[node]) { str = renderAstNode(arena, node, options, sourcemaps, sourceLocation, linesMap, errors, reducer, cache, level, indents); if (str === "") { continue; @@ -17475,7 +19194,7 @@ case exports.EnumToken.RuleNodeType: case exports.EnumToken.KeyframesRuleNodeType: case exports.EnumToken.KeyframesAtRuleNodeType: { - const isAtRule = typ == exports.EnumToken.AtRuleNodeType || typ == exports.EnumToken.KeyframesAtRuleNodeType; + const isAtRule = typ === exports.EnumToken.AtRuleNodeType || typ === exports.EnumToken.KeyframesAtRuleNodeType; const nam = arena.strings[arena.name[data]]; const val = arena.strings[arena.stringValue[data]]; if (isAtRule && !(arena.flags[data] & exports.EnumAstNodeStatus.HasChildren)) { @@ -17493,22 +19212,22 @@ } let node; let nodeType; - let recordDeclarationSourceMap = typ == exports.EnumToken.AtRuleNodeType; + let recordDeclarationSourceMap = typ === exports.EnumToken.AtRuleNodeType; // rendering of the last child, without its trailing semicolon, appended to the children when the next child // is rendered. the trailing semicolon of the last child is dropped: it is known from the type of the child, // the rendered strings are not read (reading a concatenated string flattens it) let last = ""; let semicolon = false; - for (node = arena.firstChild[data]; node != 0; node = arena.nextSibling[node]) { + for (node = arena.firstChild[data]; node !== 0; node = arena.nextSibling[node]) { nodeType = arena.dataTypes[node]; - if (nodeType == exports.EnumToken.CommentNodeType) { + if (nodeType === exports.EnumToken.CommentNodeType) { const comment = arena.strings[arena.stringValue[node]]; str = options.removeComments && (!options.preserveLicense || !comment.startsWith("/*!")) ? "" : comment; } - else if (nodeType == exports.EnumToken.DeclarationNodeType) { + else if (nodeType === exports.EnumToken.DeclarationNodeType) { // the semicolon is not part of the rendered declaration str = renderDeclaration(arena, node, options, cache, reducer); } @@ -17529,17 +19248,17 @@ } str = options.newLine + indentSub + str; children += semicolon ? last + ";" : last; - if (nodeType == exports.EnumToken.DeclarationNodeType) { + if (nodeType === exports.EnumToken.DeclarationNodeType) { last = str; semicolon = true; } else { // comments are flat strings - semicolon = str.charCodeAt(str.length - 1) == 0x3b; + semicolon = str.charCodeAt(str.length - 1) === 0x3b; last = semicolon ? str.slice(0, -1) : str; } if (sourcemaps != null) { - if (nodeType == exports.EnumToken.DeclarationNodeType && recordDeclarationSourceMap) { + if (nodeType === exports.EnumToken.DeclarationNodeType && recordDeclarationSourceMap) { // if declaration is child of at-rule, then record it // .rule { // @media screen { @@ -17551,7 +19270,7 @@ else { move(sourceLocation, linesMap, str); } - if (nodeType == exports.EnumToken.DeclarationNodeType) { + if (nodeType === exports.EnumToken.DeclarationNodeType) { // the semicolon sourceLocation.end++; } @@ -17598,7 +19317,7 @@ return false; default: // comments: flat strings - return rendered.charCodeAt(rendered.length - 1) == 0x3b; + return rendered.charCodeAt(rendered.length - 1) === 0x3b; } } function renderTokenList(tokens, reducer) { @@ -17619,6 +19338,16 @@ */ function renderDeclaration(arena, node, options, cache, reducer) { const memo = getRenderMemo(cache, options); + let minifyValues = options.minifyValues; + if (minifyValues) { + minifyValues = !arena.startsWith(node, "nam", "--"); + if (!minifyValues) { + // override options to avoid minifying values for custom properties + options = { ...options, minifyValues: false }; + // override the reducer + reducer = createReducer(arena, options, cache); + } + } if (memo == null) { return `${arena.strings[arena.name[node]]}:${options.indent}${renderDeclarationValue(arena, node, options.minifyValues, reducer).trimEnd()}`; } @@ -17646,7 +19375,7 @@ let rendered = ""; let token = arena.firstToken[node]; if (!minifyValues) { - for (; token != 0; token = arena.nextSibling[token]) { + for (; token !== 0; token = arena.nextSibling[token]) { rendered = reducer(rendered, token); } return rendered; @@ -17656,37 +19385,37 @@ let pending = 0; let check = true; let dropWhitespace = false; - for (; token != 0; token = arena.nextSibling[token]) { + for (; token !== 0; token = arena.nextSibling[token]) { const type = dataTypes[token]; if (dropWhitespace) { dropWhitespace = false; - if (type == exports.EnumToken.WhitespaceTokenType) { + if (type === exports.EnumToken.WhitespaceTokenType) { continue; } } if (!check) { check = true; } - else if (type == exports.EnumToken.ImportantTokenType && - pending != 0 && + else if (type === exports.EnumToken.ImportantTokenType && + pending !== 0 && dataTypes[pending] === exports.EnumToken.WhitespaceTokenType) { pending = 0; check = false; } else if (tokensfuncSet.has(type) && // color keywords and hex colors are not functions - (type != exports.EnumToken.ColorTokenType || arena.firstToken[token] != 0) && - type != exports.EnumToken.WildCardFunctionTokenType && - arena.nextSibling[token] != 0 && - dataTypes[arena.nextSibling[token]] == exports.EnumToken.WhitespaceTokenType) { + (type !== exports.EnumToken.ColorTokenType || arena.firstToken[token] !== 0) && + type !== exports.EnumToken.WildCardFunctionTokenType && + arena.nextSibling[token] !== 0 && + dataTypes[arena.nextSibling[token]] === exports.EnumToken.WhitespaceTokenType) { dropWhitespace = true; } - if (pending != 0) { + if (pending !== 0) { rendered = reducer(rendered, pending); } pending = token; } - return pending == 0 ? rendered : reducer(rendered, pending); + return pending === 0 ? rendered : reducer(rendered, pending); } /** * shared default arguments of {@link renderValue}: no object is created per call. the cache is only written when @@ -17703,7 +19432,7 @@ */ function createReducer(arena, options, cache, errors) { const reducer = (acc, curr) => { - if (arena.dataTypes[curr] == exports.EnumToken.CommentTokenType && options.removeComments) { + if (arena.dataTypes[curr] === exports.EnumToken.CommentTokenType && options.removeComments) { if (!options.preserveLicense || !arena.strings[arena.stringValue[curr]].startsWith("/*!")) { return acc; } @@ -17725,11 +19454,11 @@ */ function renderReduced(arena, first, options, cache, reducer, errors) { let result = ""; - for (let token = first; token != 0; token = arena.nextSibling[token]) { + for (let token = first; token !== 0; token = arena.nextSibling[token]) { if (reducer != null) { result = reducer(result, token); } - else if (arena.dataTypes[token] == exports.EnumToken.CommentTokenType && options.removeComments) { + else if (arena.dataTypes[token] === exports.EnumToken.CommentTokenType && options.removeComments) { if (options.preserveLicense && arena.strings[arena.stringValue[token]].startsWith("/*!")) { result += arena.strings[arena.stringValue[token]]; } @@ -17751,7 +19480,7 @@ */ function renderList(arena, first, options, cache, reducer, errors) { let result = ""; - for (let token = first; token != 0; token = arena.nextSibling[token]) { + for (let token = first; token !== 0; token = arena.nextSibling[token]) { result += renderValue(arena, token, options, cache, reducer); } return result; @@ -17789,7 +19518,7 @@ if (value != null) { token = value; } - if (arena.colorType[token] == exports.ColorType.HEX || arena.colorType[token] == exports.ColorType.LIT) { + if (arena.colorType[token] === exports.ColorType.HEX || arena.colorType[token] === exports.ColorType.LIT) { return reduceHexValue(arena.strings[arena.stringValue[token]]); } } @@ -17798,10 +19527,10 @@ arena.colorType[token] === exports.ColorType.NON_STD) { return arena.strings[arena.stringValue[token]]; } - if (arena.colorType[token] == exports.ColorType.HEX || arena.colorType[token] == exports.ColorType.LIT) { + if (arena.colorType[token] === exports.ColorType.HEX || arena.colorType[token] === exports.ColorType.LIT) { return arena.strings[arena.stringValue[token]]; } - if (arena.firstToken[token] == 0) { + if (arena.firstToken[token] === 0) { // rendered like a function (no argument) return ((arena.strings[arena.stringValue[token]] ?? "") + "(" + @@ -17812,31 +19541,33 @@ const count = arena.tokenCount(token); const isLegacy = legacyColorFunctions.has(fnName); const hasAlpha = alphaColorFunctions.has(fnName); - const useAlpha = (hasAlpha && count == (isLegacy ? 7 : 4)) || ("color" == fnName && count == 5); + const useAlpha = (hasAlpha && count === (isLegacy ? 7 : 4)) || ("color" === fnName && count === 5); let result = ""; let index = 0; - for (let curr = arena.firstToken[token]; curr != 0; curr = arena.nextSibling[curr], index++) { + for (let curr = arena.firstToken[token]; curr !== 0; curr = arena.nextSibling[curr], index++) { if (trailingSeparator.test(result)) { - if (arena.dataTypes[curr] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[curr] === exports.EnumToken.WhitespaceTokenType) { result = result.trimEnd(); continue; } result = result.trimStart() + renderValue(arena, curr, options, cache); continue; } - if (isLegacy && arena.dataTypes[curr] == exports.EnumToken.CommaTokenType) { + if (isLegacy && arena.dataTypes[curr] === exports.EnumToken.CommaTokenType) { result = result.trimEnd() + " "; } - else if (arena.dataTypes[curr] == exports.EnumToken.WhitespaceTokenType) { + else if (arena.dataTypes[curr] === exports.EnumToken.WhitespaceTokenType) { result = result.trimEnd() + " "; } - else if (arena.dataTypes[curr] == exports.EnumToken.CommaTokenType || - (arena.dataTypes[curr] == exports.EnumToken.LiteralTokenType && arena.strings[arena.stringValue[curr]] == "/")) { - result = result.trimEnd() + (arena.dataTypes[curr] == exports.EnumToken.CommaTokenType ? "," : "/"); + else if (arena.dataTypes[curr] === exports.EnumToken.CommaTokenType || + (arena.dataTypes[curr] === exports.EnumToken.LiteralTokenType && arena.strings[arena.stringValue[curr]] === "/")) { + result = result.trimEnd() + (arena.dataTypes[curr] === exports.EnumToken.CommaTokenType ? "," : "/"); } else { result = - result.trimEnd() + (useAlpha && index == count - 1 ? "/" : " ") + renderValue(arena, curr, options, cache); + result.trimEnd() + + (useAlpha && index === count - 1 ? "/" : " ") + + renderValue(arena, curr, options, cache); } } return (hasAlpha && fnName.endsWith("a") ? fnName.slice(0, -1) : fnName) + "(" + result.trimStart() + ")"; @@ -17844,6 +19575,7 @@ /** * render ast token. identical constructs (colors and tokens with sub tokens: functions, parentheses, binary * expressions, ...) are rendered once per render, see {@link RenderMemo} + * @param arena * @param token * @param options * @param cache @@ -17852,9 +19584,9 @@ * @private */ function renderValue(arena, token, options = defaultRenderOptions, cache = defaultCache, reducer, errors) { - if (arena.dataTypes[token] == exports.EnumToken.ColorTokenType || - arena.firstToken[token] != 0 || - arena.firstChild[token] != 0) { + if (arena.dataTypes[token] === exports.EnumToken.ColorTokenType || + arena.firstToken[token] !== 0 || + arena.firstChild[token] !== 0) { const memo = getRenderMemo(cache, options); if (memo != null) { const slot = memo.constructs.token(arena, token); @@ -17916,16 +19648,16 @@ const r = (arena.getChildAt(token, exports.TokenField.R) == null ? null : arena.fieldTokens(token, exports.TokenField.R))[0]; if (exports.EnumToken.Mul === op || exports.EnumToken.Div === op) { let result = ""; - if (arena.dataTypes[l] == exports.EnumToken.BinaryExpressionTokenType && - (arena.numericValue[l] == exports.EnumToken.Add || arena.numericValue[l] == exports.EnumToken.Sub)) { + if (arena.dataTypes[l] === exports.EnumToken.BinaryExpressionTokenType && + (arena.numericValue[l] === exports.EnumToken.Add || arena.numericValue[l] === exports.EnumToken.Sub)) { result = "(" + renderValue(arena, l, options, cache) + ")"; } else { result = renderValue(arena, l, options, cache); } - result += op == exports.EnumToken.Mul ? "*" : "/"; - if (arena.dataTypes[r] == exports.EnumToken.BinaryExpressionTokenType && - (arena.numericValue[r] == exports.EnumToken.Add || arena.numericValue[r] == exports.EnumToken.Sub)) { + result += op === exports.EnumToken.Mul ? "*" : "/"; + if (arena.dataTypes[r] === exports.EnumToken.BinaryExpressionTokenType && + (arena.numericValue[r] === exports.EnumToken.Add || arena.numericValue[r] === exports.EnumToken.Sub)) { result += "(" + renderValue(arena, r, options, cache) + ")"; } else { @@ -17934,7 +19666,7 @@ return result; } return (renderValue(arena, l, options, cache) + - (op == exports.EnumToken.Add ? " + " : " - ") + + (op === exports.EnumToken.Add ? " + " : " - ") + renderValue(arena, r, options, cache)); } case exports.EnumToken.FractionTokenType: { @@ -17943,7 +19675,7 @@ // inlined: arena.denominator(token) const denominator = arena.lastChild[token]; const fraction = renderValue(arena, numerator) + "/" + renderValue(arena, denominator); - if (arena.numericValue[denominator] != 0) { + if (arena.numericValue[denominator] !== 0) { const value = minifyNumber(arena.numericValue[numerator] / arena.numericValue[denominator]); if (value.length <= fraction.length) { return value; @@ -17964,10 +19696,10 @@ case exports.EnumToken.WrappedValuesTokenType: return "{" + renderList(arena, arena.firstToken[token], options, cache) + "}"; case exports.EnumToken.ColorTokenType: { - if (arena.colorType[token] == exports.ColorType.LIGHT_DARK || - (arena.firstToken[token] != 0 && options.convertColor === false && arena.tokenCount(token) == 2)) { + if (arena.colorType[token] === exports.ColorType.LIGHT_DARK || + (arena.firstToken[token] !== 0 && options.convertColor === false && arena.tokenCount(token) === 2)) { let result = ""; - for (let curr = arena.firstToken[token]; curr != 0; curr = arena.nextSibling[curr]) { + for (let curr = arena.firstToken[token]; curr !== 0; curr = arena.nextSibling[curr]) { if (arena.dataTypes[curr] === exports.EnumToken.IdenTokenType) { // the token is updated in place parseColor(arena, curr); @@ -17984,7 +19716,7 @@ if (arena.dataTypes[arena.firstToken[token]] === exports.EnumToken.BadUrlTokenType) { return "url()"; } - for (let child = arena.firstToken[token]; child != 0; child = arena.nextSibling[child]) { + for (let child = arena.firstToken[token]; child !== 0; child = arena.nextSibling[child]) { if (arena.dataTypes[child] === exports.EnumToken.StringTokenType) { const val = arena.strings[arena.stringValue[child]]; if (val.slice(1, 5) !== "data:" && urlTokenMatcher.test(val)) { @@ -18011,11 +19743,11 @@ let j; let key; for (i = 0; i < slice.length; i++) { - if (arena.dataTypes[slice[i]] == exports.EnumToken.ColorTokenType || + if (arena.dataTypes[slice[i]] === exports.EnumToken.ColorTokenType || arena.dataTypes[slice[i]] === exports.EnumToken.CommaTokenType) { break; } - if (arena.dataTypes[slice[i]] == exports.EnumToken.IdenTokenType && + if (arena.dataTypes[slice[i]] === exports.EnumToken.IdenTokenType && equalsIgnoreCase(arena.strings[arena.stringValue[slice[i]]], "to")) { k = i + 1; while (k < slice.length && @@ -18041,7 +19773,8 @@ arena.dataTypes[slice[j]] === exports.EnumToken.CommentTokenType)) { j++; } - if (j < slice.length && arena.dataTypes[slice[j]] !== exports.EnumToken.CommaTokenType) { + if (j < slice.length && + arena.dataTypes[slice[j]] !== exports.EnumToken.CommaTokenType) { i = j - 1; break; } @@ -18049,7 +19782,7 @@ if (key === "bottom") { // to bottom -> 180deg is the default angle and will be removed while (k < slice.length && - arena.dataTypes[slice[k]] != exports.EnumToken.CommaTokenType) { + arena.dataTypes[slice[k]] !== exports.EnumToken.CommaTokenType) { k++; } slice.splice(i, k - i + 1); @@ -18062,7 +19795,7 @@ } } } - else if (arena.dataTypes[slice[i]] == exports.EnumToken.AngleTokenType) { + else if (arena.dataTypes[slice[i]] === exports.EnumToken.AngleTokenType) { if ((180 - arena.numericValue[toDegrees(arena, slice[i])]) % 360 === 0) { k = i + 1; // while (k < slice.length && arena.dataTypes[slice[k]] !== EnumToken.CommaTokenType) { @@ -18149,7 +19882,8 @@ i++; } if (arena.dataTypes[slice[i]] === exports.EnumToken.PercentageTokenType || - (arena.dataTypes[slice[i]] === exports.EnumToken.NumberTokenType && 0 === arena.numericValue[slice[i]]) || + (arena.dataTypes[slice[i]] === exports.EnumToken.NumberTokenType && + 0 === arena.numericValue[slice[i]]) || (arena.dataTypes[slice[i]] === exports.EnumToken.IdenTokenType && (equalsIgnoreCase(arena.strings[arena.stringValue[slice[i]]], "center") || equalsIgnoreCase(arena.strings[arena.stringValue[slice[i]]], "top") || @@ -18322,7 +20056,7 @@ i++; } else if (arena.dataTypes[slice[i]] !== exports.EnumToken.CommaTokenType && - arena.dataTypes[slice[i]] != exports.EnumToken.IdenTokenType) { + arena.dataTypes[slice[i]] !== exports.EnumToken.IdenTokenType) { angles.push(slice[i++]); } while (i < slice.length && @@ -18428,7 +20162,10 @@ } break; } - return arena.strings[arena.stringValue[token]] + "(" + renderTokenList(slice, reducer ?? createReducer(arena, options, cache)) + ")"; + return (arena.strings[arena.stringValue[token]] + + "(" + + renderTokenList(slice, reducer ?? createReducer(arena, options, cache)) + + ")"); } case exports.EnumToken.TimingFunctionTokenType: case exports.EnumToken.PseudoClassFuncTokenType: @@ -18441,13 +20178,13 @@ case exports.EnumToken.GeneralEnclosedFunctionTokenType: case exports.EnumToken.CustomFunctionTokenType: case exports.EnumToken.WildCardFunctionTokenType: - if (arena.dataTypes[token] == exports.EnumToken.MathFunctionTokenType && arena.tokenCount(token) == 1) { + if (arena.dataTypes[token] === exports.EnumToken.MathFunctionTokenType && arena.tokenCount(token) === 1) { // a single argument const first = arena.firstToken[token]; const firstType = arena.dataTypes[first]; - if (firstType != exports.EnumToken.BinaryExpressionTokenType && - firstType != exports.EnumToken.FractionTokenType && - firstType != exports.EnumToken.IdenTokenType && + if (firstType !== exports.EnumToken.BinaryExpressionTokenType && + firstType !== exports.EnumToken.FractionTokenType && + firstType !== exports.EnumToken.IdenTokenType && !arena.hasFraction(first)) { return (arena.strings[arena.stringValue[token]] + "(" + @@ -18457,7 +20194,10 @@ ")"); } } - return (arena.strings[arena.stringValue[token]] ?? "") + "(" + renderReduced(arena, arena.firstToken[token], options, cache, reducer) + ")"; + return ((arena.strings[arena.stringValue[token]] ?? "") + + "(" + + renderReduced(arena, arena.firstToken[token], options, cache, reducer) + + ")"); case exports.EnumToken.BlockStartTokenType: return "{"; case exports.EnumToken.BlockEndTokenType: @@ -18529,12 +20269,12 @@ ? renderValue(arena, arena.getFraction(token), options, cache) : minifyNumber(arena.numericValue[token]); let unit = arena.strings[arena.unit[token]]; - if (arena.dataTypes[token] == exports.EnumToken.AngleTokenType && !val.includes("/")) { + if (arena.dataTypes[token] === exports.EnumToken.AngleTokenType && !val.includes("/")) { const angle = getAngle(arena, token); let v; let value = val + unit; for (const u of angleUnits$1) { - if (arena.strings[arena.unit[token]] == u) { + if (arena.strings[arena.unit[token]] === u) { continue; } switch (u) { @@ -18574,20 +20314,20 @@ } } if (val === "0") { - if (arena.dataTypes[token] == exports.EnumToken.TimeTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.TimeTokenType) { return "0s"; } - if (arena.dataTypes[token] == exports.EnumToken.FrequencyTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.FrequencyTokenType) { return "0Hz"; } // @ts-ignore - if (arena.dataTypes[token] == exports.EnumToken.ResolutionTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.ResolutionTokenType) { return "0x"; } - return "0"; + return options.minifyValues ? "0" : "0" + unit; } - if (arena.dataTypes[token] == exports.EnumToken.TimeTokenType) { - if (unit == "ms") { + if (arena.dataTypes[token] === exports.EnumToken.TimeTokenType) { + if (unit === "ms") { // @ts-ignore const v = minifyNumber(val / 1000); if (v.length + 1 <= val.length) { @@ -18597,17 +20337,17 @@ } return val + "s"; } - if (arena.dataTypes[token] == exports.EnumToken.ResolutionTokenType && unit == "dppx") { + if (arena.dataTypes[token] === exports.EnumToken.ResolutionTokenType && unit === "dppx") { unit = "x"; } return val.includes("/") ? val.replace("/", unit + "/") : minifyNumber(toPrecisionValue(val)) + unit; case exports.EnumToken.FlexTokenType: case exports.EnumToken.PercentageTokenType: - const uni = arena.dataTypes[token] == exports.EnumToken.PercentageTokenType ? "%" : "fr"; + const uni = arena.dataTypes[token] === exports.EnumToken.PercentageTokenType ? "%" : "fr"; const perc = arena.hasFraction(token) ? renderValue(arena, arena.getFraction(token), options, cache) : minifyNumber(arena.numericValue[token]); - return options.minifyValues && perc == "0" + return options.minifyValues && perc === "0" ? "0" : perc.includes("/") ? perc.replace("/", uni + "/") @@ -18633,7 +20373,7 @@ case exports.EnumToken.PseudoClassTokenType: case exports.EnumToken.PseudoElementTokenType: // https://www.w3.org/TR/selectors-4/#single-colon-pseudos - if (arena.dataTypes[token] == exports.EnumToken.PseudoElementTokenType && + if (arena.dataTypes[token] === exports.EnumToken.PseudoElementTokenType && pseudoElements.includes(arena.strings[arena.stringValue[token]].slice(1))) { return arena.strings[arena.stringValue[token]].slice(1); } @@ -18643,6 +20383,7 @@ case exports.EnumToken.IdenTokenType: case exports.EnumToken.StringTokenType: case exports.EnumToken.LiteralTokenType: + case exports.EnumToken.UniCodeRange: case exports.EnumToken.DashedIdenTokenType: case exports.EnumToken.PseudoPageTokenType: case exports.EnumToken.ClassSelectorTokenType: @@ -18684,12 +20425,12 @@ case exports.EnumToken.MediaQueryConditionTokenType: { const op = arena.field(token, exports.TokenField.Op); const opType = arena.dataTypes[op]; - const indent = opType == exports.EnumToken.LtTokenType || - opType == exports.EnumToken.GtTokenType || - opType == exports.EnumToken.ColonTokenType || - opType == exports.EnumToken.DelimTokenType || - opType == exports.EnumToken.LteTokenType || - opType == exports.EnumToken.GteTokenType + const indent = opType === exports.EnumToken.LtTokenType || + opType === exports.EnumToken.GtTokenType || + opType === exports.EnumToken.ColonTokenType || + opType === exports.EnumToken.DelimTokenType || + opType === exports.EnumToken.LteTokenType || + opType === exports.EnumToken.GteTokenType ? "" : " "; return (renderField(arena, token, exports.TokenField.L, options, cache, reducer) + @@ -18730,6 +20471,7 @@ } /** * Remove whitespace tokens that are not needed + * @param arena * @param values * * @internal @@ -18737,14 +20479,15 @@ function filterValues(arena, values) { let i = 0; for (; i < values.length; i++) { - if (arena.dataTypes[values[i]] == exports.EnumToken.ImportantTokenType && arena.dataTypes[values[i - 1]] === exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[values[i]] === exports.EnumToken.ImportantTokenType && + arena.dataTypes[values[i - 1]] === exports.EnumToken.WhitespaceTokenType) { values.splice(i - 1, 1); } else if (tokensfuncSet.has(arena.dataTypes[values[i]]) && // color keywords and hex colors are not functions - (arena.dataTypes[values[i]] != exports.EnumToken.ColorTokenType || arena.firstToken[values[i]] != 0) && - arena.dataTypes[values[i]] != exports.EnumToken.WildCardFunctionTokenType && - arena.dataTypes[values[i + 1]] == exports.EnumToken.WhitespaceTokenType) { + (arena.dataTypes[values[i]] !== exports.EnumToken.ColorTokenType || arena.firstToken[values[i]] !== 0) && + arena.dataTypes[values[i]] !== exports.EnumToken.WildCardFunctionTokenType && + arena.dataTypes[values[i + 1]] === exports.EnumToken.WhitespaceTokenType) { values.splice(i + 1, 1); } } @@ -18777,7 +20520,7 @@ let result = []; for (let i = 0; i < tokenList.length; i++) { const typ = arena.dataTypes[tokenList[i]]; - if (typ == exports.EnumToken.CommentTokenType || typ == exports.EnumToken.CommaTokenType) { + if (typ === exports.EnumToken.CommentTokenType || typ === exports.EnumToken.CommaTokenType) { continue; } result.push(tokenList[i]); @@ -18829,10 +20572,10 @@ // inlined: arena.walkValues(tokens) for (const value of new ValueWalker(arena, tokens)) { const typ = arena.dataTypes[value]; - if (typ == exports.EnumToken.MediaQueryConditionTokenType) { + if (typ === exports.EnumToken.MediaQueryConditionTokenType) { const token = arena .fieldTokens(value, exports.TokenField.L) - .find((t) => arena.dataTypes[t] == exports.EnumToken.IdenTokenType); + .find((t) => arena.dataTypes[t] === exports.EnumToken.IdenTokenType); if (token != null) { let val = arena.strings[arena.stringValue[token]]; if (val in pseudoAliasMap) { @@ -18842,7 +20585,7 @@ const r = arena.fieldTokens(value, exports.TokenField.R); if ((equalsIgnoreCase(val, "min-resolution") || equalsIgnoreCase(val, "max-resolution")) && r.length > 0 && - arena.dataTypes[r[0]] == exports.EnumToken.NumberTokenType) { + arena.dataTypes[r[0]] === exports.EnumToken.NumberTokenType) { arena.dataTypes[r[0]] = exports.EnumToken.ResolutionTokenType; // inlined: arena.setUnitString(r[0], "x") arena.unit[r[0]] = arena.internString("x"); @@ -18860,16 +20603,16 @@ } } } - else if (typ == exports.EnumToken.IdenTokenType || - typ == exports.EnumToken.PseudoClassFuncTokenType || - typ == exports.EnumToken.PseudoClassTokenType || - typ == exports.EnumToken.PseudoElementTokenType) { - let key = arena.strings[arena.stringValue[value]] + (typ == exports.EnumToken.PseudoClassFuncTokenType ? "()" : ""); + else if (typ === exports.EnumToken.IdenTokenType || + typ === exports.EnumToken.PseudoClassFuncTokenType || + typ === exports.EnumToken.PseudoClassTokenType || + typ === exports.EnumToken.PseudoElementTokenType) { + let key = arena.strings[arena.stringValue[value]] + (typ === exports.EnumToken.PseudoClassFuncTokenType ? "()" : ""); if (key in pseudoAliasMap) { const isPseudClass = pseudoAliasMap[key].startsWith("::"); // inlined: arena.setStr(value, pseudoAliasMap[key]) arena.stringValue[value] = arena.internString(pseudoAliasMap[key]); - if (isPseudClass && typ == exports.EnumToken.PseudoElementTokenType) { + if (isPseudClass && typ === exports.EnumToken.PseudoElementTokenType) { arena.dataTypes[value] = exports.EnumToken.PseudoClassTokenType; } result = true; @@ -18877,7 +20620,7 @@ } } // remove duplicate tokens - if (tokens.find((t) => arena.dataTypes[t] == exports.EnumToken.CommaTokenType) != null) { + if (tokens.find((t) => arena.dataTypes[t] === exports.EnumToken.CommaTokenType) != null) { const set = new Set(); const split = splitTokenList(arena, tokens, [exports.EnumToken.CommaTokenType]); tokens.length = 0; @@ -18910,24 +20653,29 @@ options.features.push(new ComputePrefixFeature(options)); } } + /** + * + * @param arena + * @param node + */ run(arena, node) { if (arena.flags[node] & (exports.EnumAstNodeStatus.Disallowed | exports.EnumAstNodeStatus.Invalid | exports.EnumAstNodeStatus.Malformed)) { return null; } const typ = arena.dataTypes[node]; - if (typ == exports.EnumToken.RuleNodeType) { + if (typ === exports.EnumToken.RuleNodeType) { // inlined: arena.setSelector(node, replacePseudo(splitRule(arena.strings[arena.name[node]])).reduce((acc, curr, index) => acc + (index > 0 ? "," : "") + curr.join(""), "")) arena.name[node] = arena.internString(replacePseudo(splitRule(arena.strings[arena.name[node]])).reduce((acc, curr, index) => acc + (index > 0 ? "," : "") + curr.join(""), "")); - if (arena.firstToken[node] != 0) { + if (arena.firstToken[node] !== 0) { const tokens = arena.tokens(node); replaceAstNodes(arena, tokens); arena.setTokenList(node, tokens); } } - else if (typ == exports.EnumToken.DeclarationNodeType) { + else if (typ === exports.EnumToken.DeclarationNodeType) { const name = arena.strings[arena.name[node]]; - if (name.charAt(0) == "-") { + if (name.charAt(0) === "-") { const match = name.match(/^-([^-]+)-(.+)$/); if (match != null) { let nam = match[2]; @@ -18946,7 +20694,8 @@ for (const value of new ValueWalker(arena, node)) { const typ = arena.dataTypes[value]; const val = arena.strings[arena.stringValue[value]]; - if ((typ == exports.EnumToken.IdenTokenType || (typ != exports.EnumToken.ParensTokenType && funcLike.includes(typ))) && + if ((typ === exports.EnumToken.IdenTokenType || + (typ !== exports.EnumToken.ParensTokenType && funcLike.includes(typ))) && val.match(/^-([^-]+)-(.+)$/) != null) { if (val.endsWith("-gradient")) { if (regMatchLinearGradient.test(val)) { @@ -18968,7 +20717,8 @@ if (hasPrefix) { // inlined: arena.walkValues(node) for (const value of new ValueWalker(arena, node)) { - if (arena.dataTypes[value] == exports.EnumToken.IdenTokenType || funcLike.includes(arena.dataTypes[value])) { + if (arena.dataTypes[value] === exports.EnumToken.IdenTokenType || + funcLike.includes(arena.dataTypes[value])) { const match = arena.strings[arena.stringValue[value]].match(/^-([^-]+)-(.+)$/); if (match != null) { // inlined: arena.setStr(value, match[2]) @@ -18978,7 +20728,7 @@ } } } - else if (typ == exports.EnumToken.AtRuleNodeType || typ == exports.EnumToken.KeyframesAtRuleNodeType) { + else if (typ === exports.EnumToken.AtRuleNodeType || typ === exports.EnumToken.KeyframesAtRuleNodeType) { const name = arena.strings[arena.name[node]]; if (name.startsWith("-")) { const match = name.match(/^-([^-]+)-(.+)$/); @@ -18986,7 +20736,7 @@ arena.name[node] = arena.internString(match[2]); } } - if (typ == exports.EnumToken.AtRuleNodeType && arena.stringValue[node] !== 0) { + if (typ === exports.EnumToken.AtRuleNodeType && arena.stringValue[node] !== 0) { const tokens = arena.tokens(node); const result = replaceAstNodes(arena, tokens); arena.setTokenList(node, tokens); @@ -18999,8 +20749,9 @@ } /** * Convert -webkit-linear-gradient to linear-gradient syntax - * @param tokens * @returns + * @param arena + * @param token */ webkitLinearToLinearGradient(arena, token) { let i; @@ -19026,27 +20777,27 @@ // - to bottom -> 180deg // - to left -> 270deg for (i = 0; i < tokens.length; i++) { - if (arena.dataTypes[tokens[i]] == exports.EnumToken.AngleTokenType || - (arena.dataTypes[tokens[i]] == exports.EnumToken.NumberTokenType && arena.numericValue[tokens[i]] == 0)) { + if (arena.dataTypes[tokens[i]] === exports.EnumToken.AngleTokenType || + (arena.dataTypes[tokens[i]] === exports.EnumToken.NumberTokenType && arena.numericValue[tokens[i]] === 0)) { arena.numericValue[tokens[i]] = (90 - - (arena.dataTypes[tokens[i]] == exports.EnumToken.NumberTokenType + (arena.dataTypes[tokens[i]] === exports.EnumToken.NumberTokenType ? arena.numericValue[tokens[i]] : arena.numericValue[toDegrees(arena, tokens[i])])) % 360; } - else if (arena.dataTypes[tokens[i]] == exports.EnumToken.IdenTokenType) { + else if (arena.dataTypes[tokens[i]] === exports.EnumToken.IdenTokenType) { key = arena.strings[arena.stringValue[tokens[i]]].toLowerCase(); switch (key) { case "right": case "left": - tokens.splice(i, 1, arena.createToken(exports.EnumToken.IdenTokenType, "to"), arena.createToken(exports.EnumToken.WhitespaceTokenType), arena.createToken(exports.EnumToken.IdenTokenType, key == "right" ? "left" : "right")); + tokens.splice(i, 1, arena.createToken(exports.EnumToken.IdenTokenType, "to"), arena.createToken(exports.EnumToken.WhitespaceTokenType), arena.createToken(exports.EnumToken.IdenTokenType, key === "right" ? "left" : "right")); i += 2; break; case "top": case "bottom": k = i + 1; - to = key == "top" ? "bottom" : "top"; + to = key === "top" ? "bottom" : "top"; while (k < tokens.length && (arena.dataTypes[tokens[k]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[tokens[k]] === exports.EnumToken.CommentTokenType)) { @@ -19073,13 +20824,14 @@ } } // inlined: arena.setStr(token, equalsIgnoreCase(arena.strings[arena.stringValue[token]], "-webkit-repeating-linear-gradient") ? "repeating-linear-gradient" : "linear-gradient") - arena.stringValue[token] = arena.internString((equalsIgnoreCase(arena.strings[arena.stringValue[token]], "-webkit-repeating-linear-gradient") + arena.stringValue[token] = arena.internString(equalsIgnoreCase(arena.strings[arena.stringValue[token]], "-webkit-repeating-linear-gradient") ? "repeating-linear-gradient" - : "linear-gradient")); + : "linear-gradient"); arena.setTokenList(token, tokens); } /** * Convert -webkit-gradient(linear) to linear-gradient or linear-gradient syntax + * @param arena * @param token * @returns */ @@ -19193,14 +20945,16 @@ } /** * Convert -webkit-radial-gradient to radial-gradient syntax - * @param tokens * @returns + * @param arena + * @param token */ webkitRadialToRadialGradient(arena, token) { let i = 0; const tokens = arena.tokens(token); while (i < tokens.length && - (arena.dataTypes[tokens[i]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[tokens[i]] === exports.EnumToken.CommentTokenType)) { + (arena.dataTypes[tokens[i]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[tokens[i]] === exports.EnumToken.CommentTokenType)) { i++; } const positions = []; @@ -19234,7 +20988,8 @@ equalsIgnoreCase(arena.strings[arena.stringValue[tokens[i]]], "ellipse")) { form.push(tokens[i++]); } - while (arena.dataTypes[tokens[i]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[tokens[i]] === exports.EnumToken.CommentTokenType) { + while (arena.dataTypes[tokens[i]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[tokens[i]] === exports.EnumToken.CommentTokenType) { i++; } if (arena.dataTypes[tokens[i]] === exports.EnumToken.CommaTokenType) { @@ -19252,7 +21007,8 @@ equalsIgnoreCase(arena.strings[arena.stringValue[tokens[i]]], "ellipse")) { form.push(tokens[i++]); } - while (arena.dataTypes[tokens[i]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[tokens[i]] === exports.EnumToken.CommentTokenType) { + while (arena.dataTypes[tokens[i]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[tokens[i]] === exports.EnumToken.CommentTokenType) { i++; } if (arena.dataTypes[tokens[i]] === exports.EnumToken.CommaTokenType) { @@ -19285,9 +21041,9 @@ tokens.push(arena.createToken(exports.EnumToken.CommaTokenType)); } // inlined: arena.setStr(token, equalsIgnoreCase(arena.strings[arena.stringValue[token]], "-webkit-repeating-radial-gradient") ? "repeating-radial-gradient" : "radial-gradient") - arena.stringValue[token] = arena.internString((equalsIgnoreCase(arena.strings[arena.stringValue[token]], "-webkit-repeating-radial-gradient") + arena.stringValue[token] = arena.internString(equalsIgnoreCase(arena.strings[arena.stringValue[token]], "-webkit-repeating-radial-gradient") ? "repeating-radial-gradient" - : "radial-gradient")); + : "radial-gradient"); for (const colorStop of colorStops) { tokens.push(colorStop); } @@ -19303,7 +21059,7 @@ */ function inlineExpression(arena, token) { const result = []; - if (arena.dataTypes[token] == exports.EnumToken.BinaryExpressionTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.BinaryExpressionTokenType) { const chi = inlineExpression(arena, arena.field(token, exports.TokenField.L)); chi.push(arena.createToken(arena.numericValue[token])); for (const child of inlineExpression(arena, arena.field(token, exports.TokenField.R))) { @@ -19321,24 +21077,26 @@ for (const value of new ValueWalker(arena, node)) { // the parent of a detached token is the declaration const parentValue = arena.getValueParent(value) || node; - if (arena.dataTypes[value] == exports.EnumToken.BinaryExpressionTokenType && + if (arena.dataTypes[value] === exports.EnumToken.BinaryExpressionTokenType && parentValue != null && - parentValue != node && + parentValue !== node && // the token belongs to the parent token list (function arguments) - arena.parents[value] == parentValue) { + arena.parents[value] === parentValue) { arena.replaceToken(value, ...inlineExpression(arena, value)); } } // inlined: arena.walkValues(node) for (const value of new ValueWalker(arena, node)) { const typ = arena.dataTypes[value]; - if (typ == exports.EnumToken.MathFunctionTokenType || - (typ == exports.EnumToken.WildCardFunctionTokenType && arena.strings[arena.stringValue[value]] == "var")) { + if (typ === exports.EnumToken.MathFunctionTokenType || + (typ === exports.EnumToken.WildCardFunctionTokenType && arena.strings[arena.stringValue[value]] === "var")) { const first = arena.firstToken[value]; - if (first != 0 && arena.nextSibling[first] == 0 && arena.dataTypes[first] == exports.EnumToken.DashedIdenTokenType) { + if (first !== 0 && + arena.nextSibling[first] === 0 && + arena.dataTypes[first] === exports.EnumToken.DashedIdenTokenType) { const info = (variableScope.get(arena.strings[arena.stringValue[first]])); // the variable declaration may have been released - if (info?.replaceable && arena.name[info.node] != 0 && arena.parents[value] != 0) { + if (info?.replaceable && arena.name[info.node] !== 0 && arena.parents[value] !== 0) { arena.replaceToken(value, ...arena.tokens(info.node).map((t) => arena.clone(t, true))); } } @@ -19359,6 +21117,14 @@ options.features.push(new InlineCssVariablesFeature()); } } + /** + * + * @param arena + * @param ast + * @param _options + * @param parent + * @param context + */ run(arena, ast, _options = {}, parent, context) { if (!(arena.flags[ast] & exports.EnumAstNodeStatus.HasChildren)) { return null; @@ -19367,11 +21133,11 @@ context.variableScope = new Map(); } // [':root', 'html'] - const isRoot = arena.dataTypes[parent] == exports.EnumToken.StyleSheetNodeType && - arena.dataTypes[ast] == exports.EnumToken.RuleNodeType && - (arena.raw[ast] ?? splitRule(arena.strings[arena.name[ast]])).some((segment) => segment.some((s) => s == ":root" || s == "html")); + const isRoot = arena.dataTypes[parent] === exports.EnumToken.StyleSheetNodeType && + arena.dataTypes[ast] === exports.EnumToken.RuleNodeType && + (arena.raw[ast] ?? splitRule(arena.strings[arena.name[ast]])).some((segment) => segment.some((s) => s === ":root" || s === "html")); const variableScope = context.variableScope; - for (let node = arena.firstChild[ast]; node != 0; node = arena.nextSibling[node]) { + for (let node = arena.firstChild[ast]; node !== 0; node = arena.nextSibling[node]) { if (arena.dataTypes[node] !== exports.EnumToken.DeclarationNodeType) { continue; } @@ -19393,8 +21159,8 @@ let recursive = false; // inlined: arena.walkValues(node) for (const value of new ValueWalker(arena, node)) { - if (arena.dataTypes[value] == exports.EnumToken.MathFunctionTokenDefType || - (arena.dataTypes[value] == exports.EnumToken.WildCardFunctionTokenType && + if (arena.dataTypes[value] === exports.EnumToken.MathFunctionTokenDefType || + (arena.dataTypes[value] === exports.EnumToken.WildCardFunctionTokenType && (mathFuncs.includes(arena.strings[arena.stringValue[value]]) || arena.strings[arena.stringValue[value]] === "var"))) { recursive = true; @@ -19411,6 +21177,13 @@ } return null; } + /** + * + * @param arena + * @param _ast + * @param _options + * @param context + */ cleanup(arena, _ast, _options = {}, context) { const variableScope = context.variableScope; if (variableScope == null) { @@ -19420,7 +21193,7 @@ if (info.replaceable) { // drop declarations from :root{} for (const parent of info.parent) { - if (arena.parents[info.node] == parent) { + if (arena.parents[info.node] === parent) { const comment = arena.createComment(exports.EnumToken.CommentTokenType, `/* ${arena.strings[arena.name[info.node]]}: ${info.values.reduce((acc, curr) => acc + renderValue(arena, curr, { convertColor: false }), "")} */`); arena.replaceChild(info.node, comment); arena.detach(info.node); @@ -19436,18 +21209,18 @@ let i = value.length; while (i-- > 1) { const t = value[i]; - const k = value[i == 1 ? 0 : i % 2]; + const k = value[i === 1 ? 0 : i % 2]; if ( // inlined: arena.isNumeric(t) numericTokenTypes.has(arena.dataTypes[t]) && // inlined: arena.isNumeric(k) numericTokenTypes.has(arena.dataTypes[k]) && - arena.numericValue[t] == 0 && - arena.numericValue[k] == 0 && + arena.numericValue[t] === 0 && + arena.numericValue[k] === 0 && !arena.hasFraction(t) && !arena.hasFraction(k)) { - if ((arena.dataTypes[t] == exports.EnumToken.NumberTokenType && isLength(arena, k)) || - (arena.dataTypes[k] == exports.EnumToken.NumberTokenType && isLength(arena, t)) || + if ((arena.dataTypes[t] === exports.EnumToken.NumberTokenType && isLength(arena, k)) || + (arena.dataTypes[k] === exports.EnumToken.NumberTokenType && isLength(arena, t)) || isLength(arena, k) || isLength(arena, t)) { value.splice(i, 1); @@ -19479,7 +21252,7 @@ add(declaration) { const arena = this.arena; const nam = arena.strings[arena.name[declaration]]; - if (nam == this.config.shorthand) { + if (nam === this.config.shorthand) { this.declarations = new Map(); } else { @@ -19493,29 +21266,29 @@ if ( // @ts-expect-error this.config.types.some((t) => typ == exports.EnumToken[t]) || - (typ == exports.EnumToken.NumberTokenType && - arena.numericValue[token] == 0 && + (typ === exports.EnumToken.NumberTokenType && + arena.numericValue[token] === 0 && (this.config.types.includes("Length") || this.config.types.includes("Angle") || this.config.types.includes("Dimension")))) { - if (tokens.length == 0) { + if (tokens.length === 0) { tokens.push([]); current++; } tokens[current].push(token); continue; } - if (typ != exports.EnumToken.WhitespaceTokenType && typ != exports.EnumToken.CommentTokenType) { - if (typ == exports.EnumToken.IdenTokenType && + if (typ !== exports.EnumToken.WhitespaceTokenType && typ !== exports.EnumToken.CommentTokenType) { + if (typ === exports.EnumToken.IdenTokenType && this.config.keywords.includes(arena.strings[arena.stringValue[token]])) { - if (tokens.length == 0) { + if (tokens.length === 0) { tokens.push([]); current++; } tokens[current].push(token); } - if (typ == exports.EnumToken.LiteralTokenType && - arena.strings[arena.stringValue[token]] == this.config.separator?.val) { + if (typ === exports.EnumToken.LiteralTokenType && + arena.strings[arena.stringValue[token]] === this.config.separator?.val) { tokens.push([]); current++; continue; @@ -19541,7 +21314,7 @@ } } const node = this.declarations.get(property); - if (arena.firstToken[node] != 0) { + if (arena.firstToken[node] !== 0) { arena.appendToken(node, arena.createToken(exports.EnumToken.WhitespaceTokenType)); } arena.appendToken(node, arena.clone(values[index], true)); @@ -19557,20 +21330,25 @@ } isShortHand() { if (this.declarations.has(this.config.shorthand)) { - return this.declarations.size == 1; + return this.declarations.size === 1; } - return this.config.properties.length == this.declarations.size; + return this.config.properties.length === this.declarations.size; } [Symbol.iterator]() { let iterator; const arena = this.arena; const declarations = this.declarations; + // the !important declarations are not merged: `column-gap: 16px !important; row-gap: 40px !important` + if (!declarations.has(this.config.shorthand) && + [...declarations.values()].some((declaration) => arena.flags[declaration] & exports.EnumAstNodeStatus.ImportantDeclaration)) { + return [...declarations.values()][Symbol.iterator](); + } if (declarations.size < this.config.properties.length) { const values = [...declarations.values()]; if (this.isShortHand()) { const val = arena.tokens(values[0]).reduce((acc, curr) => { - if (arena.dataTypes[curr] != exports.EnumToken.WhitespaceTokenType && - arena.dataTypes[curr] != exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[curr] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[curr] !== exports.EnumToken.CommentTokenType) { acc.push(curr); } return acc; @@ -19592,10 +21370,10 @@ let index = 0; const id = this.declarations.get(property); for (const token of id == null ? [] : arena.tokens(id)) { - if (arena.dataTypes[token] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.WhitespaceTokenType) { continue; } - if (values.length == index) { + if (values.length === index) { values.push([]); } values[index].push(token); @@ -19620,7 +21398,7 @@ } for (const token of curr) { // tokens are shared with the original declarations - acc.push(arena.parents[token] != 0 ? arena.clone(token, true) : token); + acc.push(arena.parents[token] !== 0 ? arena.clone(token, true) : token); } return acc; }, []), null, null), @@ -21598,11 +23376,11 @@ return properties.types.some((type) => { // @ts-ignore const typ = exports.EnumToken[type]; - return typ == exports.EnumToken.LengthTokenType || typ == exports.EnumToken.AngleTokenType; + return typ === exports.EnumToken.LengthTokenType || typ === exports.EnumToken.AngleTokenType; }); } if (tokensfuncSet.has(typ) && typ === exports.EnumToken.MathFunctionTokenType) { - for (let t = arena.firstToken[val]; t != 0; t = arena.nextSibling[t]) { + for (let t = arena.firstToken[val]; t !== 0; t = arena.nextSibling[t]) { if (!mathTokenTypes.includes(arena.dataTypes[t]) && !matchType(arena, t, properties)) { return false; } @@ -21639,8 +23417,8 @@ */ function matchConfigToken(arena, token, config) { return (config != null && - arena.dataTypes[token] == configType(config) && - (config.val == null || arena.strings[arena.stringValue[token]] == config.val)); + arena.dataTypes[token] === configType(config) && + (config.val == null || arena.strings[arena.stringValue[token]] === config.val)); } /** * map of declarations that can be merged into a single shorthand declaration. @@ -21677,16 +23455,13 @@ this.pattern = config.pattern.split(/\s/); } /** - * tokens of a value (default values of the properties, ...) - * @param value + * + * @param declaration */ - parse(value) { - return this.memo == null ? parseString(this.arena, value) : this.memo.parse(this.arena, value); - } add(declaration) { const arena = this.arena; const nam = arena.strings[arena.name[declaration]]; - if (nam == this.config.shorthand) { + if (nam === this.config.shorthand) { this.declarations.clear(); this.declarations.set(nam, declaration); this.matchTypes(declaration); @@ -21710,13 +23485,13 @@ // let current: number = 0; const props = this.config.properties[property]; for (let i = 0; i < acc.length; i++) { - if (arena.dataTypes[acc[i]] == exports.EnumToken.CommentTokenType || - arena.dataTypes[acc[i]] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[acc[i]] === exports.EnumToken.CommentTokenType || + arena.dataTypes[acc[i]] === exports.EnumToken.WhitespaceTokenType) { acc.splice(i, 1); i--; continue; } - if (this.propertyNames.get(acc[i]) == property || matchType(arena, acc[i], props)) { + if (this.propertyNames.get(acc[i]) === property || matchType(arena, acc[i], props)) { if ("prefix" in props && props.previous != null && !(props.previous in tokens)) { return acc; } @@ -21724,7 +23499,7 @@ tokens[property] = [[acc[i]]]; } else { - if (current == tokens[property].length) { + if (current === tokens[property].length) { tokens[property].push([acc[i]]); } else { @@ -21756,12 +23531,14 @@ // default if (props.default.length > 0) { // inlined: this.parse(props.default[0]) - const defaults = this.memo == null ? parseString(this.arena, props.default[0]) : this.memo.parse(this.arena, props.default[0]); + const defaults = this.memo == null + ? parseString(this.arena, props.default[0]) + : this.memo.parse(this.arena, props.default[0]); if (!(property in tokens)) { tokens[property] = [[...defaults]]; } else { - if (current == tokens[property].length) { + if (current === tokens[property].length) { tokens[property].push([]); for (let i = 0; i < defaults.length; i++) { tokens[property][current].push(defaults[i]); @@ -21778,7 +23555,7 @@ return acc; }, val[current])); } - if (values.length == 0) { + if (values.length === 0) { this.declarations = Object.entries(tokens).reduce((acc, curr) => { acc.set(curr[0], arena.createDeclaration(exports.EnumToken.DeclarationNodeType, curr[0], curr[1].reduce((acc, curr) => { if (acc.length > 0) { @@ -21839,23 +23616,25 @@ for (const value of declarations.values()) { if (value instanceof PropertyMap) { for (const [k, v] of value.declarations) { - if (k == value.config.shorthand) { + if (k === value.config.shorthand) { const values = arena.tokens(v); for (const [key] of Object.entries(value.config.properties)) { mapped[key] = arena.clone(v); const mappedValues = []; for (let i = 0; i < values.length; i++) { - if (key == value.propertyNames.get(values[i])) { + if (key === value.propertyNames.get(values[i])) { if (mappedValues.length > 0) { mappedValues.push(arena.createToken(exports.EnumToken.WhitespaceTokenType)); } mappedValues.push(value.take(values[i])); } } - if (mappedValues.length == 0) { + if (mappedValues.length === 0) { mappedValues.push( // inlined: this.parse((value as PropertyMap).config.properties[key].default[0]) - ...(this.memo == null ? parseString(this.arena, value.config.properties[key].default[0]) : this.memo.parse(this.arena, value.config.properties[key].default[0]))); + ...(this.memo == null + ? parseString(this.arena, value.config.properties[key].default[0]) + : this.memo.parse(this.arena, value.config.properties[key].default[0]))); } arena.setTokenList(mapped[key], mappedValues); } @@ -21923,7 +23702,7 @@ if (!cache.has(t)) { cache.set(t, renderValue(arena, t, { minify: true })); } - if (arena.dataTypes[t] == typ && separator == cache.get(t)) { + if (arena.dataTypes[t] === typ && separator === cache.get(t)) { this.removeDefaults(map, value); value = []; values.push(value); @@ -21949,19 +23728,20 @@ acc.push(configToken(arena, sep)); } for (const cr of curr) { - if (arena.dataTypes[cr] == exports.EnumToken.WhitespaceTokenType && + if (arena.dataTypes[cr] === exports.EnumToken.WhitespaceTokenType && acc.length > 0 && - arena.dataTypes[acc[acc.length - 1]] == exports.EnumToken.WhitespaceTokenType) { + arena.dataTypes[acc[acc.length - 1]] === exports.EnumToken.WhitespaceTokenType) { continue; } acc.push(cr); } return acc; }, []); - while (result.length > 0 && arena.dataTypes[result[result.length - 1]] == exports.EnumToken.WhitespaceTokenType) { + while (result.length > 0 && + arena.dataTypes[result[result.length - 1]] === exports.EnumToken.WhitespaceTokenType) { result.pop(); } - while (result.length > 0 && arena.dataTypes[result[0]] == exports.EnumToken.WhitespaceTokenType) { + while (result.length > 0 && arena.dataTypes[result[0]] === exports.EnumToken.WhitespaceTokenType) { result.shift(); } arena.setTokenList(declaration, result); @@ -21984,20 +23764,22 @@ for (const declaration of values) { dec = removeDefaults(declaration); for (const t of arena.tokens(dec)) { - if (arena.dataTypes[t] == exports.EnumToken.ImportantTokenType) { + if (arena.dataTypes[t] === exports.EnumToken.ImportantTokenType) { isImportant = true; } - if (filtered.length == 0 && - arena.dataTypes[t] != exports.EnumToken.WhitespaceTokenType && - arena.dataTypes[t] != exports.EnumToken.ImportantTokenType) { + if (filtered.length === 0 && + arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[t] !== exports.EnumToken.ImportantTokenType) { filtered.push(dec); } } } - if (filtered.length == 0 && this.config.default.length > 0) { + if (filtered.length === 0 && this.config.default.length > 0) { filtered.push(arena.createDeclaration(exports.EnumToken.DeclarationNodeType, this.config.shorthand, // inlined: this.parse(this.config.default[0]) - this.memo == null ? parseString(this.arena, this.config.default[0]) : this.memo.parse(this.arena, this.config.default[0]), null, null)); + this.memo == null + ? parseString(this.arena, this.config.default[0]) + : this.memo.parse(this.arena, this.config.default[0]), null, null)); if (isImportant) { arena.appendToken(filtered[0], arena.createToken(exports.EnumToken.ImportantTokenType)); } @@ -22009,7 +23791,7 @@ continue; } const nam = arena.strings[arena.name[declaration]]; - const config = nam == this.config.shorthand ? this.config : (propertiesMapping[nam] ?? this.config); + const config = nam === this.config.shorthand ? this.config : (propertiesMapping[nam] ?? this.config); if (!("mapping" in config)) { continue; } @@ -22018,12 +23800,14 @@ for (const [key, val] of Object.entries(config.mapping)) { // inlined: this.parse(key) const keys = this.memo == null ? parseString(this.arena, key) : this.memo.parse(this.arena, key); - if (keys.length != declarationValues.length) { + if (keys.length !== declarationValues.length) { continue; } if (keys.every((k, index) => eqToken(arena, k, declarationValues[index]))) { // inlined: this.parse(val as string) - arena.setTokenList(declaration, this.memo == null ? parseString(this.arena, val) : this.memo.parse(this.arena, val)); + arena.setTokenList(declaration, this.memo == null + ? parseString(this.arena, val) + : this.memo.parse(this.arena, val)); break; } } @@ -22054,27 +23838,27 @@ for (const val of arena.tokens(declaration)) { if (matchConfigToken(arena, val, separator)) { current++; - if (tokens[curr[0]].length == current) { + if (tokens[curr[0]].length === current) { tokens[curr[0]].push([]); } continue; } const valType = arena.dataTypes[val]; - if (valType == exports.EnumToken.WhitespaceTokenType || valType == exports.EnumToken.CommentTokenType) { + if (valType === exports.EnumToken.WhitespaceTokenType || valType === exports.EnumToken.CommentTokenType) { continue; } if (props.multiple && props.separator != null && configType(props.separator) === valType && (valType === exports.EnumToken.CommaTokenType || - props.separator.val == arena.strings[arena.stringValue[val]])) { + props.separator.val === arena.strings[arena.stringValue[val]])) { continue; } match = matchType(arena, val, curr[1]); if (isShorthand) { isShorthand = match; } - if (this.propertyNames.get(val) == property || match) { + if (this.propertyNames.get(val) === property || match) { if (!(curr[0] in tokens)) { tokens[curr[0]] = [[]]; } @@ -22093,7 +23877,7 @@ return acc; }, []); // grid-template - if (this.config.shorthand == "grid-template" && patterns.length == Object.keys(tokens).length) { + if (this.config.shorthand === "grid-template" && patterns.length === Object.keys(tokens).length) { const k = tokens[patterns[0]][0].length; const l = tokens[patterns[1]][0].length; const j = k < l ? k : l; @@ -22136,12 +23920,12 @@ !Object.values(tokens).every((v) => // `v` holds token groups: only single token groups were type checked by the former // `arena.dataTypes[group]` lookup (the group is converted to a string key) - v.filter((t) => t.length != 1 || arena.dataTypes[t[0]] != exports.EnumToken.CommentTokenType).length === count)) { + v.filter((t) => t.length !== 1 || arena.dataTypes[t[0]] !== exports.EnumToken.CommentTokenType).length === count)) { // @ts-ignore iterable = declarations.values(); } else if (hasMapping) { - if (patterns.length == Object.keys(tokens).length) { + if (patterns.length === Object.keys(tokens).length) { const declaration = arena.clone(declarations.get(patterns[0])); const declarationValues = arena.tokens(declaration); arena.name[declaration] = arena.internString(this.config.shorthand); @@ -22173,7 +23957,7 @@ .reduce((acc, curr) => { const props = propertiesMapping[curr[0]]; for (let i = 0; i < curr[1].length; i++) { - if (acc.length == i) { + if (acc.length === i) { acc.push([]); } // if (acc[acc.length - 1].length > 0) { @@ -22213,7 +23997,7 @@ exports.EnumToken.CommentTokenType, exports.EnumToken.IdenTokenType, ].includes(arena.dataTypes[v]) || - (arena.dataTypes[v] == exports.EnumToken.IdenTokenType && + (arena.dataTypes[v] === exports.EnumToken.IdenTokenType && !propertiesMapping[curr[0]].default.includes(arena.strings[arena.stringValue[v]]))) { doFilterDefault = false; break; @@ -22222,12 +24006,12 @@ } // remove default values const filtered = values.filter((val) => { - if (arena.dataTypes[val] == exports.EnumToken.WhitespaceTokenType || - arena.dataTypes[val] == exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[val] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[val] === exports.EnumToken.CommentTokenType) { return false; } return (!doFilterDefault || - !(arena.dataTypes[val] == exports.EnumToken.IdenTokenType && + !(arena.dataTypes[val] === exports.EnumToken.IdenTokenType && props.default.includes(arena.strings[arena.stringValue[val]]))); }); if (filtered.length > 0 || @@ -22242,15 +24026,17 @@ values.length <= props.constraints.mapping.max) { let i = values.length; while (i--) { - if (arena.dataTypes[values[i]] == exports.EnumToken.IdenTokenType && + if (arena.dataTypes[values[i]] === exports.EnumToken.IdenTokenType && // @ts-expect-error arena.strings[arena.stringValue[values[i]]] in props.mapping) { // inlined: this.parse(props.mapping[arena.strings[arena.stringValue[values[i]]]]) values.splice(i, 1, ...(this.memo == null - ? // @ts-ignore - parseString(this.arena, props.mapping[arena.strings[arena.stringValue[values[i]]]]) - : // @ts-ignore - this.memo.parse(this.arena, props.mapping[arena.strings[arena.stringValue[values[i]]]]))); + ? parseString(this.arena, + // @ts-ignore + props.mapping[arena.strings[arena.stringValue[values[i]]]]) + : this.memo.parse(this.arena, + // @ts-ignore + props.mapping[arena.strings[arena.stringValue[values[i]]]]))); } } } @@ -22278,10 +24064,12 @@ if (acc.length > 0) { acc.push(configToken(arena, separator)); } - if (curr.length == 0 && this.config.default.length > 0) { + if (curr.length === 0 && this.config.default.length > 0) { curr.push( // inlined: this.parse(this.config.default[0]) - ...(this.memo == null ? parseString(this.arena, this.config.default[0]) : this.memo.parse(this.arena, this.config.default[0])).reduce((acc, curr) => { + ...(this.memo == null + ? parseString(this.arena, this.config.default[0]) + : this.memo.parse(this.arena, this.config.default[0])).reduce((acc, curr) => { if (acc.length > 0) { acc.push(arena.createToken(exports.EnumToken.WhitespaceTokenType)); } @@ -22309,12 +24097,15 @@ this.config.mapping[val])); } } - if (values.length == 1 && - arena.stringValue[values[0]] != 0 && + if (values.length === 1 && + arena.stringValue[values[0]] !== 0 && this.config.default.includes(arena.strings[arena.stringValue[values[0]]].toLowerCase()) && - this.config.default[0] != arena.strings[arena.stringValue[values[0]]].toLowerCase()) { + this.config.default[0] !== arena.strings[arena.stringValue[values[0]]].toLowerCase()) { // inlined: this.parse(this.config.default[0]) - values = this.memo == null ? parseString(this.arena, this.config.default[0]) : this.memo.parse(this.arena, this.config.default[0]); + values = + this.memo == null + ? parseString(this.arena, this.config.default[0]) + : this.memo.parse(this.arena, this.config.default[0]); } iterable = [ arena.createDeclaration(exports.EnumToken.DeclarationNodeType, this.config.shorthand, values, null, null), @@ -22341,7 +24132,7 @@ iterable = iterators.pop(); v = iterable.next(); } - if (v.done && iterators.length == 0) { + if (v.done && iterators.length === 0) { break; } } @@ -22355,7 +24146,7 @@ * @param token */ take(token) { - if (this.arena.parents[token] == 0) { + if (this.arena.parents[token] === 0) { return token; } const clone = this.arena.clone(token, true); @@ -22396,10 +24187,10 @@ if (map.has(key)) { for (const v of val) { // missing - if (map.get(v) == 1) { + if (map.get(v) === 1) { let i = declarationValues.length; while (i--) { - if (this.propertyNames.get(declarationValues[i]) == key) { + if (this.propertyNames.get(declarationValues[i]) === key) { const val = arena.clone(declarationValues[i], true); this.propertyNames.set(val, v); declarationValues.splice(i, 0, val, arena.createToken(exports.EnumToken.WhitespaceTokenType)); @@ -22422,14 +24213,14 @@ continue; } const v = val.value.join(" "); - if (config.default.includes(v) || (value.length == 1 && this.config.default.includes(v))) { + if (config.default.includes(v) || (value.length === 1 && this.config.default.includes(v))) { for (const token of value) { if (val.t.includes(token)) { let index = value.indexOf(token); value.splice(index, 1); if (config.prefix != null) { while (index-- > 0) { - if (this.arena.dataTypes[value[index]] == exports.EnumToken.WhitespaceTokenType) { + if (this.arena.dataTypes[value[index]] === exports.EnumToken.WhitespaceTokenType) { continue; } if (matchConfigToken(this.arena, value[index], config.prefix)) { @@ -22503,6 +24294,20 @@ return key; } } + /** + * true if the value of a declaration contains var(), env() or if() + * @param arena + * @param declaration + */ + function hasWildCardFunction(arena, declaration) { + for (const token of arena.tokens(declaration)) { + if (arena.dataTypes[token] === exports.EnumToken.WildCardFunctionTokenType || + arena.dataTypes[token] === exports.EnumToken.WildCardFunctionTokenDefType) { + return true; + } + } + return false; + } /** * Represents a list of property declarations, compute shorthand and remove duplicate declarations. */ @@ -22535,17 +24340,6 @@ this.declarations = new Map(); this.memo = memo ?? new DeclarationMemo(); } - /** - * add declarations - * @param declarations node ids - * @returns - */ - add(declarations) { - for (const declaration of declarations) { - this.addDeclaration(declaration); - } - return this; - } /** * add a declaration * @param declaration node id @@ -22555,7 +24349,7 @@ let syntaxRules = null; const arena = this.arena; name = - arena.dataTypes[declaration] != exports.EnumToken.DeclarationNodeType + arena.dataTypes[declaration] !== exports.EnumToken.DeclarationNodeType ? null : arena.strings[arena.name[declaration]]; // do not compute shorthand for invalid declarations @@ -22627,20 +24421,28 @@ // @ts-ignore shorthand = config.property[propertyName]; } + // the value of a shorthand that contains var(), env() or if() cannot be expanded: the longhands that follow + // it are not merged into it. `background: var(--bg); background-clip: text` + if (shorthand === name && + (shortHandType === "map" || shortHandType === "set") && + hasWildCardFunction(arena, declaration)) { + this.declarations.set(this.memo.key(arena, declaration), declaration); + return this; + } if (this.declarations.has(shorthand)) { let existing = this.declarations.get(shorthand); if (existing instanceof PropertySet || existing instanceof PropertyMap) { existing = existing.declarations.get(name); } if (existing != null && - typeof existing == "number" && + typeof existing === "number" && arena.flags[existing] & exports.EnumAstNodeStatus.ImportantDeclaration && - arena.flags[declaration] & ~exports.EnumAstNodeStatus.ImportantDeclaration) { + (arena.flags[declaration] & exports.EnumAstNodeStatus.ImportantDeclaration) == 0) { return this; } } // @ts-ignore - if (shortHandType == "map") { + if (shortHandType === "map") { let owner = this; const mapName = // @ts-ignore @@ -22654,8 +24456,9 @@ owner = this.declarations.get(mapName); } else if (!this.declarations.has(shorthand)) { + this.declarations.set(shorthand, // @ts-ignore - this.declarations.set(shorthand, new PropertyMap(arena, config.map[shorthand], this.memo)); + new PropertyMap(arena, config.map[shorthand], this.memo)); } if (owner == this) { // @ts-ignore @@ -22672,7 +24475,7 @@ } } // @ts-ignore - else if (shortHandType == "set") { + else if (shortHandType === "set") { // @ts-ignore if (!this.declarations.has(shorthand)) { // @ts-ignore @@ -22753,7 +24556,7 @@ } } } - if (values != declarationValues) { + if (values !== declarationValues) { arena.setTokenList(declaration, values); } } @@ -22807,8 +24610,16 @@ options.features.push(new ComputeShorthandFeature(options)); } } + /** + * + * @param arena + * @param ast + * @param options + * @param _parent + * @param context + */ run(arena, ast, options, _parent, context) { - if (!(arena.flags[ast] & exports.EnumAstNodeStatus.HasChildren) || arena.firstChild[ast] == 0) { + if (!(arena.flags[ast] & exports.EnumAstNodeStatus.HasChildren) || arena.firstChild[ast] === 0) { return null; } // the keys of the declarations are shared by the rules of the minification @@ -22816,7 +24627,7 @@ const list = new PropertyList(arena, options, memo); let doNotSort = false; let hasDeclarations = false; - if (arena.dataTypes[ast] == exports.EnumToken.AtRuleNodeType) { + if (arena.dataTypes[ast] === exports.EnumToken.AtRuleNodeType) { switch (arena.strings[arena.name[ast]]) { case "function": case "mixin": @@ -22827,19 +24638,19 @@ // the declarations (with their leading comments) are moved into the property list, // the rules (with their leading comments) stay in place let child = arena.firstChild[ast]; - while (child != 0) { + while (child !== 0) { let last = child; if (!doNotSort) { // capture comments with the next node - while (arena.nextSibling[last] != 0 && arena.dataTypes[last] == exports.EnumToken.CommentNodeType) { + while (arena.nextSibling[last] !== 0 && arena.dataTypes[last] === exports.EnumToken.CommentNodeType) { last = arena.nextSibling[last]; } } const next = arena.nextSibling[last]; // https://drafts.csswg.org/css-mixins/#:~:text=The%20value%20of%20the%20result%20descriptor%20is%20always%2016px%20in%20the%20above%20example - if (doNotSort || arena.dataTypes[last] == exports.EnumToken.DeclarationNodeType) { + if (doNotSort || arena.dataTypes[last] === exports.EnumToken.DeclarationNodeType) { hasDeclarations = true; - for (let node = child; node != next;) { + for (let node = child; node !== next;) { const nextNode = arena.nextSibling[node]; arena.detach(node); list.addDeclaration(node); @@ -22852,7 +24663,7 @@ // the declarations are inserted before the rules const first = arena.firstChild[ast]; for (const node of list) { - if (first == 0) { + if (first === 0) { arena.appendChild(ast, node); } else { @@ -22878,12 +24689,17 @@ options.features.push(new ComputeCalcExpressionFeature()); } } + /** + * + * @param arena + * @param ast + */ run(arena, ast) { if (!(arena.flags[ast] & exports.EnumAstNodeStatus.HasChildren)) { return null; } - for (let node = arena.firstChild[ast]; node != 0; node = arena.nextSibling[node]) { - if (arena.dataTypes[node] != exports.EnumToken.DeclarationNodeType) { + for (let node = arena.firstChild[ast]; node !== 0; node = arena.nextSibling[node]) { + if (arena.dataTypes[node] !== exports.EnumToken.DeclarationNodeType) { continue; } if (!hasExpression(arena, node)) { @@ -22895,11 +24711,11 @@ for (const value of new ValueWalker(arena, node)) { // the parent of a detached token is the declaration const parent = arena.getValueParent(value) || node; - if (parent != null && arena.dataTypes[parent] == exports.EnumToken.BinaryExpressionTokenType) { + if (parent != null && arena.dataTypes[parent] === exports.EnumToken.BinaryExpressionTokenType) { continue; } const typ = arena.dataTypes[value]; - if (typ == exports.EnumToken.BinaryExpressionTokenType) { + if (typ === exports.EnumToken.BinaryExpressionTokenType) { const result = evaluate(arena, [value]); try { if (result.length > 0) { @@ -22916,36 +24732,39 @@ if (parent != null) { const name = arena.strings[arena.stringValue[value]]; const shouldEvaluate = typ === exports.EnumToken.MathFunctionTokenType || - (typ == exports.EnumToken.FunctionTokenType && mathFuncs.includes(name)); + (typ === exports.EnumToken.FunctionTokenType && mathFuncs.includes(name)); if (shouldEvaluate) { - const cp = name != "calc" ? [value] : arena.tokens(value); + const cp = name !== "calc" ? [value] : arena.tokens(value); const values = evaluate(arena, cp); // fix a + -b into a - b // inlined: arena.walkValues(values) for (const value of new ValueWalker(arena, values)) { if (arena.dataTypes[value] === exports.EnumToken.BinaryExpressionTokenType) { // inlined: arena.getRight(value) - const r = (arena.getChildAt(value, exports.TokenField.R) == null ? null : arena.fieldTokens(value, exports.TokenField.R))[0]; + const r = (arena.getChildAt(value, exports.TokenField.R) == null + ? null + : arena.fieldTokens(value, exports.TokenField.R))[0]; if (arena.numericValue[value] === exports.EnumToken.Add && // inlined: arena.isNumeric(r) numericTokenTypes.has(arena.dataTypes[r]) && - Math.sign(arena.numericValue[r]) == -1) { + Math.sign(arena.numericValue[r]) === -1) { arena.numericValue[value] = exports.EnumToken.Sub; arena.numericValue[r] *= -1; } } } // the value is replaced by the computed tokens or wrapped into a calc() function - if (values.length == 1 && - arena.dataTypes[values[0]] != exports.EnumToken.BinaryExpressionTokenType) { + if (values.length === 1 && + arena.dataTypes[values[0]] !== exports.EnumToken.BinaryExpressionTokenType) { const parentType = arena.dataTypes[parent]; const wrap = !(parentType === exports.EnumToken.MathFunctionTokenType || - (parentType == exports.EnumToken.FunctionTokenType && - arena.strings[arena.stringValue[parent]] == "calc")) && + (parentType === exports.EnumToken.FunctionTokenType && + arena.strings[arena.stringValue[parent]] === "calc")) && // inlined: arena.isNumeric(values[0]) - (!numericTokenTypes.has(arena.dataTypes[values[0]]) || arena.hasFraction(values[0])) && - !(arena.dataTypes[values[0]] == exports.EnumToken.MathFunctionTokenType || - (arena.dataTypes[values[0]] == exports.EnumToken.FunctionTokenType && + (!numericTokenTypes.has(arena.dataTypes[values[0]]) || + arena.hasFraction(values[0])) && + !(arena.dataTypes[values[0]] === exports.EnumToken.MathFunctionTokenType || + (arena.dataTypes[values[0]] === exports.EnumToken.FunctionTokenType && mathFuncs.includes(arena.strings[arena.stringValue[values[0]]]))); arena.replaceToken(value, wrap ? createCalc(arena, value, values) : values[0]); } @@ -22979,11 +24798,11 @@ * @param node */ function hasExpression(arena, node) { - for (let token = arena.firstToken[node]; token != 0; token = arena.nextSibling[token]) { - if (arena.dataTypes[token] == exports.EnumToken.BinaryExpressionTokenType || + for (let token = arena.firstToken[node]; token !== 0; token = arena.nextSibling[token]) { + if (arena.dataTypes[token] === exports.EnumToken.BinaryExpressionTokenType || tokensfuncSet.has(arena.dataTypes[token]) || - arena.firstToken[token] != 0 || - arena.firstChild[token] != 0) { + arena.firstToken[token] !== 0 || + arena.firstChild[token] !== 0) { return true; } } @@ -23212,7 +25031,7 @@ } [qx, qy, qz] = toZero([qx, qy, qz]); let q = [Math.abs(qx), Math.abs(qy), Math.abs(qz)].reduce((acc, curr) => { - if (acc == 0 || (curr > 0 && curr < acc)) { + if (acc === 0 || (curr > 0 && curr < acc)) { acc = curr; } return acc; @@ -23363,13 +25182,13 @@ } function parseMatrix(arena, mat) { - if (arena.dataTypes[mat] == exports.EnumToken.IdenTokenType) { - return arena.strings[arena.stringValue[mat]] == "none" ? identity() : null; + if (arena.dataTypes[mat] === exports.EnumToken.IdenTokenType) { + return arena.strings[arena.stringValue[mat]] === "none" ? identity() : null; } - const children = arena.tokens(mat).filter((t) => arena.dataTypes[t] == exports.EnumToken.NumberTokenType || arena.dataTypes[t] == exports.EnumToken.IdenTokenType); + const children = arena.tokens(mat).filter((t) => arena.dataTypes[t] === exports.EnumToken.NumberTokenType || arena.dataTypes[t] === exports.EnumToken.IdenTokenType); const values = []; for (const child of children) { - if (arena.dataTypes[child] != exports.EnumToken.NumberTokenType) { + if (arena.dataTypes[child] !== exports.EnumToken.NumberTokenType) { return null; } // @ts-ignore @@ -23448,47 +25267,47 @@ const skew = new Set(["x", "y"]); let result = []; // check identity - if (round(decomposed.translate[0]) == 0 && - round(decomposed.translate[1]) == 0 && - round(decomposed.translate[2]) == 0) { + if (round(decomposed.translate[0]) === 0 && + round(decomposed.translate[1]) === 0 && + round(decomposed.translate[2]) === 0) { transforms.delete("translate"); } - if (round(decomposed.scale[0]) == 1 && round(decomposed.scale[1]) == 1 && round(decomposed.scale[2]) == 1) { + if (round(decomposed.scale[0]) === 1 && round(decomposed.scale[1]) === 1 && round(decomposed.scale[2]) === 1) { transforms.delete("scale"); } - if (round(decomposed.skew[0]) == 0 && round(decomposed.skew[1]) == 0) { + if (round(decomposed.skew[0]) === 0 && round(decomposed.skew[1]) === 0) { transforms.delete("skew"); } - if (round(decomposed.perspective[2]) == 0) { + if (round(decomposed.perspective[2]) === 0) { transforms.delete("perspective"); } - if (round(decomposed.rotate[3]) == 0) { + if (round(decomposed.rotate[3]) === 0) { transforms.delete("rotate"); } if (transforms.has("translate")) { let coordinates = new Set(["x", "y", "z"]); for (let i = 0; i < 3; i++) { - if (round(decomposed.translate[i]) == 0) { - coordinates.delete(i == 0 ? "x" : i == 1 ? "y" : "z"); + if (round(decomposed.translate[i]) === 0) { + coordinates.delete(i === 0 ? "x" : i === 1 ? "y" : "z"); } } - if (coordinates.size == 1) { + if (coordinates.size === 1) { if (coordinates.has("x")) { result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "translate", [arena.createToken(exports.EnumToken.LengthTokenType, round(decomposed.translate[0]), "px")])); } else { let axis = coordinates.has("y") ? "y" : "z"; - let index = axis == "y" ? 1 : 2; + let index = axis === "y" ? 1 : 2; result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "translate" + axis.toUpperCase(), [arena.createToken(exports.EnumToken.LengthTokenType, round(decomposed.translate[index]), "px")])); } } else if (coordinates.has("z")) { result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "translate3d", [ - decomposed.translate[0] == 0 + decomposed.translate[0] === 0 ? arena.createToken(exports.EnumToken.NumberTokenType, 0) : arena.createToken(exports.EnumToken.LengthTokenType, round(decomposed.translate[0]), "px"), arena.createToken(exports.EnumToken.CommaTokenType), - decomposed.translate[1] == 0 + decomposed.translate[1] === 0 ? arena.createToken(exports.EnumToken.NumberTokenType, 0) : arena.createToken(exports.EnumToken.LengthTokenType, round(decomposed.translate[1]), "px"), arena.createToken(exports.EnumToken.CommaTokenType), @@ -23505,17 +25324,17 @@ } if (transforms.has("rotate")) { const [x, y, z, angle] = decomposed.rotate; - if (y == 0 && z == 0) { + if (y === 0 && z === 0) { result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "rotateX", [ arena.createToken(exports.EnumToken.AngleTokenType, round(angle), "deg"), ])); } - else if (x == 0 && z == 0) { + else if (x === 0 && z === 0) { result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "rotateY", [ arena.createToken(exports.EnumToken.AngleTokenType, round(angle), "deg"), ])); } - else if (x == 0 && y == 0) { + else if (x === 0 && y === 0) { result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "rotate", [ arena.createToken(exports.EnumToken.AngleTokenType, round(angle), "deg"), ])); @@ -23533,13 +25352,13 @@ } } if (transforms.has("skew")) { - if (round(decomposed.skew[1]) == 0) { + if (round(decomposed.skew[1]) === 0) { skew.delete("y"); } for (let i = 0; i < 2; i++) { decomposed.skew[i] = round((Math.atan(decomposed.skew[i]) * 180) / Math.PI); } - if (skew.size == 1) { + if (skew.size === 1) { result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "skew" + (skew.has("x") ? "" : "Y"), [arena.createToken(exports.EnumToken.AngleTokenType, round(decomposed.skew[0]), "deg")])); } else { @@ -23552,18 +25371,18 @@ } if (transforms.has("scale")) { const [sx, sy, sz] = toZero(decomposed.scale); - if (sz == 1) { + if (sz === 1) { scales.delete("z"); } - if (sy == 1) { + if (sy === 1) { scales.delete("y"); } - if (sx == 1) { + if (sx === 1) { scales.delete("x"); } - if (scales.size == 1) { + if (scales.size === 1) { let prefix = scales.has("x") ? "X" : scales.has("y") ? "Y" : "Z"; - result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "scale" + prefix, [arena.createToken(exports.EnumToken.NumberTokenType, round(prefix == "Z" ? sz : prefix == "Y" ? sy : sx))])); + result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "scale" + prefix, [arena.createToken(exports.EnumToken.NumberTokenType, round(prefix === "Z" ? sz : prefix === "Y" ? sy : sx))])); } else if (!scales.has("z")) { result.push(arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "scale", [ @@ -23583,7 +25402,7 @@ } } // identity - return result.length == 0 || (result.length == 1 && eqMatrix(arena, identity(), result)) + return result.length === 0 || (result.length === 1 && eqMatrix(arena, identity(), result)) ? [ arena.createToken(exports.EnumToken.IdenTokenType, "none"), ] @@ -23614,7 +25433,7 @@ } function minifyTransformFunctions(arena, transform) { const name = arena.strings[arena.stringValue[transform]]; - if ("skewX" == name) { + if ("skewX" === name) { // inlined: arena.setStr(transform, "skew") arena.stringValue[transform] = arena.internString("skew"); return transform; @@ -23624,9 +25443,9 @@ } const values = []; for (const token of arena.tokens(transform)) { - if (arena.dataTypes[token] == exports.EnumToken.CommentTokenType || - arena.dataTypes[token] == exports.EnumToken.WhitespaceTokenType || - arena.dataTypes[token] == exports.EnumToken.CommaTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.CommentTokenType || + arena.dataTypes[token] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[token] === exports.EnumToken.CommaTokenType) { continue; } if (![ @@ -23637,7 +25456,7 @@ ].includes(arena.dataTypes[token])) { return transform; } - if (arena.dataTypes[token] == exports.EnumToken.PercentageTokenType && + if (arena.dataTypes[token] === exports.EnumToken.PercentageTokenType && !arena.hasFraction(token) && name.startsWith("scale")) { arena.dataTypes[token] = exports.EnumToken.NumberTokenType; @@ -23645,42 +25464,42 @@ } values.push(token); } - if (values.length == 0) { + if (values.length === 0) { return transform; } - if ((name == "translate" || name == "scale") && values.length > 2) { + if ((name === "translate" || name === "scale") && values.length > 2) { return transform; } const ignoredValue = name.startsWith("scale") ? 1 : 0; const t = new Set(["x", "y", "z"]); for (let i = 0; i < 3; i++) { - const axis = i == 0 ? "x" : i == 1 ? "y" : "z"; - if (values.length <= i || arena.numericValue[values[i]] == ignoredValue) { + const axis = i === 0 ? "x" : i === 1 ? "y" : "z"; + if (values.length <= i || arena.numericValue[values[i]] === ignoredValue) { t.delete(axis); } } - if (name == "translate3d" || name == "translate") { - if (t.size == 0) { + if (name === "translate3d" || name === "translate") { + if (t.size === 0) { return arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "translate", [arena.createToken(exports.EnumToken.NumberTokenType, 0)]); } - if (t.size == 1) { + if (t.size === 1) { return arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "translate" + (t.has("x") ? "" : t.has("y") ? "Y" : "Z"), [values[t.has("x") ? 0 : t.has("y") ? 1 : 2]]); } - if (t.size == 2) { + if (t.size === 2) { if (t.has("z")) { return transform; } return arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "translate", [values[0], arena.createToken(exports.EnumToken.CommaTokenType), values[1]]); } } - if (name == "scale3d" || name == "scale") { - if (t.size == 0) { + if (name === "scale3d" || name === "scale") { + if (t.size === 0) { return arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "scale", [arena.createToken(exports.EnumToken.NumberTokenType, 1)]); } - if (t.size == 1) { + if (t.size === 1) { return arena.createFunction(exports.EnumToken.TransformFunctionTokenType, "scale" + (t.has("x") ? "X" : t.has("y") ? "Y" : "Z"), [values[t.has("x") ? 0 : t.has("y") ? 1 : 2]]); } - if (t.size == 2) { + if (t.size === 2) { if (t.has("z")) { return transform; } @@ -23712,7 +25531,7 @@ function perspective(x, from) { const matrix = identity(); - matrix[2 * 4 + 3] = x == "none" ? 0 : x == 0 ? Number.NEGATIVE_INFINITY : -1 / x; + matrix[2 * 4 + 3] = x == "none" ? 0 : x === 0 ? Number.NEGATIVE_INFINITY : -1 / x; return multiply(from, matrix); } @@ -23732,12 +25551,13 @@ case "rotateZ": case "rotate3d": for (const child of arena.tokens(transform)) { - if (arena.dataTypes[child] == exports.EnumToken.WhitespaceTokenType || arena.dataTypes[child] == exports.EnumToken.CommaTokenType) { + if (arena.dataTypes[child] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[child] === exports.EnumToken.CommaTokenType) { continue; } - if ((arena.dataTypes[child] != exports.EnumToken.AngleTokenType && - arena.dataTypes[child] != exports.EnumToken.NumberTokenType && - arena.dataTypes[child] != exports.EnumToken.PercentageTokenType) || + if ((arena.dataTypes[child] !== exports.EnumToken.AngleTokenType && + arena.dataTypes[child] !== exports.EnumToken.NumberTokenType && + arena.dataTypes[child] !== exports.EnumToken.PercentageTokenType) || // angle >= 360deg, do not transform Math.abs(getAngle(arena, child)) >= 1) { return null; @@ -23760,27 +25580,27 @@ const serialized = serialize(arena, matrix); if (cumulative.length > 0) { for (let i = 0; i < cumulative.length; i++) { - if (arena.dataTypes[cumulative[i]] == exports.EnumToken.IdenTokenType && arena.strings[arena.stringValue[cumulative[i]]] == "none") { + if (arena.dataTypes[cumulative[i]] === exports.EnumToken.IdenTokenType && + arena.strings[arena.stringValue[cumulative[i]]] === "none") { cumulative.splice(i--, 1); } } - if (cumulative.length == 0) { + if (cumulative.length === 0) { cumulative.push(arena.createToken(exports.EnumToken.IdenTokenType, "none")); } } - const result = { + return { matrix: serialize(arena, toZero(matrix)), cumulative, minified: minify$1(arena, matrix) ?? [serialized], }; - return result; } function computeMatrix(arena, transformList, matrixVar) { let values = []; let val; let i = 0; for (; i < transformList.length; i++) { - if (arena.dataTypes[transformList[i]] != exports.EnumToken.TransformFunctionTokenType || + if (arena.dataTypes[transformList[i]] !== exports.EnumToken.TransformFunctionTokenType || !transformFunctions.includes(arena.strings[arena.stringValue[transformList[i]]])) { return null; } @@ -23792,14 +25612,14 @@ case "translate3d": { values.length = 0; - const children = (stripCommaToken(arena, arena.tokens(transformList[i])) ?? []); - const valCount = arena.strings[arena.stringValue[transformList[i]]] == "translate3d" + const children = stripCommaToken(arena, arena.tokens(transformList[i])) ?? []; + const valCount = arena.strings[arena.stringValue[transformList[i]]] === "translate3d" ? 3 - : arena.strings[arena.stringValue[transformList[i]]] == "translate" + : arena.strings[arena.stringValue[transformList[i]]] === "translate" ? 2 : 1; for (let j = 0; j < children.length; j++) { - if (arena.dataTypes[children[j]] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[children[j]] === exports.EnumToken.WhitespaceTokenType) { continue; } val = length2Px(arena, children[j]); @@ -23808,19 +25628,19 @@ } values.push(val); } - if (values.length == 0 || values.length > valCount) { + if (values.length === 0 || values.length > valCount) { return null; } - if (arena.strings[arena.stringValue[transformList[i]]] == "translateX") { + if (arena.strings[arena.stringValue[transformList[i]]] === "translateX") { matrixVar = translateX(values[0], matrixVar); } - else if (arena.strings[arena.stringValue[transformList[i]]] == "translateY") { + else if (arena.strings[arena.stringValue[transformList[i]]] === "translateY") { matrixVar = translateY(values[0], matrixVar); } - else if (arena.strings[arena.stringValue[transformList[i]]] == "translateZ") { + else if (arena.strings[arena.stringValue[transformList[i]]] === "translateZ") { matrixVar = translateZ(values[0], matrixVar); } - else if (arena.strings[arena.stringValue[transformList[i]]] == "translate") { + else if (arena.strings[arena.stringValue[transformList[i]]] === "translate") { matrixVar = translate(values, matrixVar); } else { @@ -23840,34 +25660,34 @@ let z = 0; let angle; let values = []; - let valuesCount = arena.strings[arena.stringValue[transformList[i]]] == "rotate3d" ? 4 : 1; - for (const child of (stripCommaToken(arena, arena.tokens(transformList[i])) ?? [])) { + let valuesCount = arena.strings[arena.stringValue[transformList[i]]] === "rotate3d" ? 4 : 1; + for (const child of stripCommaToken(arena, arena.tokens(transformList[i])) ?? []) { values.push(child); - if (arena.strings[arena.stringValue[transformList[i]]] == "rotateX") { + if (arena.strings[arena.stringValue[transformList[i]]] === "rotateX") { x = 1; } - else if (arena.strings[arena.stringValue[transformList[i]]] == "rotateY") { + else if (arena.strings[arena.stringValue[transformList[i]]] === "rotateY") { y = 1; } - else if (arena.strings[arena.stringValue[transformList[i]]] == "rotate" || - arena.strings[arena.stringValue[transformList[i]]] == "rotateZ") { + else if (arena.strings[arena.stringValue[transformList[i]]] === "rotate" || + arena.strings[arena.stringValue[transformList[i]]] === "rotateZ") { z = 1; } } - if (values.length != valuesCount) { + if (values.length !== valuesCount) { return null; } - if (arena.strings[arena.stringValue[transformList[i]]] == "rotate3d") { + if (arena.strings[arena.stringValue[transformList[i]]] === "rotate3d") { x = getNumber(arena, values[0]); y = getNumber(arena, values[1]); z = getNumber(arena, values[2]); } angle = getAngle(arena, values[values.length - 1]); - if ([x, y, z, angle].some((t) => typeof t != "number" || Number.isNaN(+t))) { + if ([x, y, z, angle].some((t) => typeof t !== "number" || Number.isNaN(+t))) { return null; } - if (arena.strings[arena.stringValue[transformList[i]]] == "rotate" || - arena.strings[arena.stringValue[transformList[i]]] == "rotateZ") { + if (arena.strings[arena.stringValue[transformList[i]]] === "rotate" || + arena.strings[arena.stringValue[transformList[i]]] === "rotateZ") { matrixVar = rotate(angle * 2 * Math.PI, matrixVar); } else { @@ -23883,38 +25703,39 @@ { values.length = 0; let child; - const children = (stripCommaToken(arena, arena.tokens(transformList[i])) ?? []); + const children = stripCommaToken(arena, arena.tokens(transformList[i])) ?? []; for (let k = 0; k < children.length; k++) { child = children[k]; - if (arena.dataTypes[child] != exports.EnumToken.NumberTokenType && arena.dataTypes[child] != exports.EnumToken.PercentageTokenType) { + if (arena.dataTypes[child] !== exports.EnumToken.NumberTokenType && + arena.dataTypes[child] !== exports.EnumToken.PercentageTokenType) { return null; } values.push(getNumber(arena, child)); } - if (arena.strings[arena.stringValue[transformList[i]]] == "scale3d") { - if (values.length != 3) { + if (arena.strings[arena.stringValue[transformList[i]]] === "scale3d") { + if (values.length !== 3) { return null; } matrixVar = scale3d(values[0], values[1], values[2], matrixVar); break; } - if (arena.strings[arena.stringValue[transformList[i]]] == "scale") { - if (values.length != 1 && values.length != 2) { + if (arena.strings[arena.stringValue[transformList[i]]] === "scale") { + if (values.length !== 1 && values.length !== 2) { return null; } matrixVar = scale(values[0], values[1] ?? values[0], matrixVar); break; } - if (values.length != 1) { + if (values.length !== 1) { return null; } - else if (arena.strings[arena.stringValue[transformList[i]]] == "scaleX") { + else if (arena.strings[arena.stringValue[transformList[i]]] === "scaleX") { matrixVar = scaleX(values[0], matrixVar); } - else if (arena.strings[arena.stringValue[transformList[i]]] == "scaleY") { + else if (arena.strings[arena.stringValue[transformList[i]]] === "scaleY") { matrixVar = scaleY(values[0], matrixVar); } - else if (arena.strings[arena.stringValue[transformList[i]]] == "scaleZ") { + else if (arena.strings[arena.stringValue[transformList[i]]] === "scaleZ") { matrixVar = scaleZ(values[0], matrixVar); } } @@ -23928,24 +25749,24 @@ let value; for (let k = 0; k < arena.tokens(transformList[i]).length; k++) { child = arena.tokens(transformList[i])[k]; - if (arena.dataTypes[child] == exports.EnumToken.CommentTokenType || - arena.dataTypes[child] == exports.EnumToken.CommaTokenType || - arena.dataTypes[child] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[child] === exports.EnumToken.CommentTokenType || + arena.dataTypes[child] === exports.EnumToken.CommaTokenType || + arena.dataTypes[child] === exports.EnumToken.WhitespaceTokenType) { continue; } value = getAngle(arena, child); values.push(value * 2 * Math.PI); } - if (values.length == 0 || - values.length > (arena.strings[arena.stringValue[transformList[i]]] == "skew" ? 2 : 1)) { + if (values.length === 0 || + values.length > (arena.strings[arena.stringValue[transformList[i]]] === "skew" ? 2 : 1)) { return null; } - if (arena.strings[arena.stringValue[transformList[i]]] == "skew") { + if (arena.strings[arena.stringValue[transformList[i]]] === "skew") { matrixVar = skew(values, matrixVar); } else { matrixVar = - arena.strings[arena.stringValue[transformList[i]]] == "skewX" + arena.strings[arena.stringValue[transformList[i]]] === "skewX" ? skewX(values[0], matrixVar) : skewY(values[0], matrixVar); } @@ -23958,10 +25779,12 @@ let value; for (let k = 0; k < arena.tokens(transformList[i]).length; k++) { child = arena.tokens(transformList[i])[k]; - if (arena.dataTypes[child] == exports.EnumToken.CommentTokenType || arena.dataTypes[child] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[child] === exports.EnumToken.CommentTokenType || + arena.dataTypes[child] === exports.EnumToken.WhitespaceTokenType) { continue; } - if (arena.dataTypes[child] == exports.EnumToken.IdenTokenType && arena.strings[arena.stringValue[child]] == "none") { + if (arena.dataTypes[child] === exports.EnumToken.IdenTokenType && + arena.strings[arena.stringValue[child]] === "none") { values.push("none"); continue; } @@ -23971,7 +25794,7 @@ } values.push(value); } - if (values.length != 1) { + if (values.length !== 1) { return null; } matrixVar = perspective(values[0], matrixVar); @@ -23996,12 +25819,12 @@ } values.push(value); } - if (arena.strings[arena.stringValue[transformList[i]]] == "matrix") { - if (values.length != 6) { + if (arena.strings[arena.stringValue[transformList[i]]] === "matrix") { + if (values.length !== 6) { return null; } } - else if (values.length != 16) { + else if (values.length !== 16) { return null; } matrixVar = multiply(matrixVar, matrix(values)); @@ -24017,14 +25840,14 @@ let pattern = null; const tokens = []; for (let i = 0; i < transformList.length; i++) { - if (arena.dataTypes[transformList[i]] == exports.EnumToken.CommentTokenType || - arena.dataTypes[transformList[i]] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[transformList[i]] === exports.EnumToken.CommentTokenType || + arena.dataTypes[transformList[i]] === exports.EnumToken.WhitespaceTokenType) { continue; } if (pattern == null || - (arena.dataTypes[transformList[i]] == exports.EnumToken.TransformFunctionTokenType && + (arena.dataTypes[transformList[i]] === exports.EnumToken.TransformFunctionTokenType && !arena.strings[arena.stringValue[transformList[i]]].startsWith(pattern))) { - if (arena.dataTypes[transformList[i]] == exports.EnumToken.TransformFunctionTokenType) { + if (arena.dataTypes[transformList[i]] === exports.EnumToken.TransformFunctionTokenType) { if (arena.strings[arena.stringValue[transformList[i]]].startsWith("scale")) { pattern = "scale"; } @@ -24042,7 +25865,7 @@ } } if (pattern != null && - arena.dataTypes[transformList[i]] == exports.EnumToken.TransformFunctionTokenType && + arena.dataTypes[transformList[i]] === exports.EnumToken.TransformFunctionTokenType && arena.strings[arena.stringValue[transformList[i]]].startsWith(pattern)) { tokens[tokens.length - 1].push(transformList[i]); continue; @@ -24075,22 +25898,27 @@ options.features.push(new TransformCssFeature()); } } + /** + * + * @param arena + * @param ast + */ run(arena, ast) { if (!(arena.flags[ast] & exports.EnumAstNodeStatus.HasChildren)) { return null; } let node; - for (node = arena.firstChild[ast]; node != 0; node = arena.nextSibling[node]) { + for (node = arena.firstChild[ast]; node !== 0; node = arena.nextSibling[node]) { if (arena.flags[node] & (exports.EnumAstNodeStatus.Invalid | exports.EnumAstNodeStatus.ValidationFailed)) { continue; } - if (arena.dataTypes[node] != exports.EnumToken.DeclarationNodeType || + if (arena.dataTypes[node] !== exports.EnumToken.DeclarationNodeType || !transformProperty.test(arena.strings[arena.name[node]])) { continue; } const children = []; for (const child of arena.tokens(node)) { - children.push(arena.dataTypes[child] == exports.EnumToken.TransformFunctionTokenType + children.push(arena.dataTypes[child] === exports.EnumToken.TransformFunctionTokenType ? minifyTransformFunctions(arena, child) : child); } @@ -24154,10 +25982,10 @@ */ function createAtRule(arena, declaration, parent, nam, tokens, options = {}) { const atRule = arena.createAtRule(exports.EnumToken.AtRuleNodeType, nam, tokens.reduce((acc, curr) => acc + renderValue(arena, curr, options), ""), true, tokens, null, null); - if (arena.parents[declaration] != 0) { + if (arena.parents[declaration] !== 0) { parent = arena.parents[declaration]; } - if (parent != 0) { + if (parent !== 0) { arena.copyLocation(atRule, parent); } return atRule; @@ -24170,8 +25998,8 @@ function conditionLeft(arena, condition) { return (arena .fieldTokens(condition, exports.TokenField.L) - .find((t) => arena.dataTypes[t] != exports.EnumToken.CommentTokenType && - arena.dataTypes[t] != exports.EnumToken.WhitespaceTokenType) ?? null); + .find((t) => arena.dataTypes[t] !== exports.EnumToken.CommentTokenType && + arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType) ?? null); } /** * value tokens of an if condition (right side). the trailing semicolon is removed @@ -24193,7 +26021,7 @@ let targetParentWrapper = parentWrapper; let targetWrapper = wrapper; // map a token or the declaration itself to its clone - const mapped = (target) => target == declaration ? clonedDeclaration : nodeMap.get(target); + const mapped = (target) => target === declaration ? clonedDeclaration : nodeMap.get(target); if (arena.dataTypes[node] === exports.EnumToken.IfElseConditionTokenType) { // clonedDeclaration = cloneDeclaration(arena, declaration, nodeMap); @@ -24206,10 +26034,10 @@ arena.dataTypes[target] === exports.EnumToken.IdenTokenType && equalsIgnoreCase("else", arena.strings[arena.stringValue[target]])) { arena.replaceToken(mapped(targetWrapper), ...conditionValue(arena, elseCondition, nodeMap)); - if (targetParentWrapper != declaration) { + if (targetParentWrapper !== declaration) { const siblings = arena.tokens(targetParentWrapper); let index = siblings.indexOf(targetWrapper); - if (index != -1) { + if (index !== -1) { let i; let siblingWrapper; let left = conditionLeft(arena, arena.field(node, exports.TokenField.L)); @@ -24244,7 +26072,7 @@ const leftType = arena.dataTypes[left]; if (leftType === exports.EnumToken.IdenTokenType && equalsIgnoreCase("else", arena.strings[arena.stringValue[left]])) { clonedDeclaration = cloneDeclaration(arena, declaration, nodeMap); - arena.replaceToken(mapped(targetWrapper == declaration ? node : targetWrapper), ...conditionValue(arena, node, nodeMap)); + arena.replaceToken(mapped(targetWrapper === declaration ? node : targetWrapper), ...conditionValue(arena, node, nodeMap)); result.push(clonedDeclaration); } else if (leftType === exports.EnumToken.WhenElseFunctionTokenType) { @@ -24266,7 +26094,7 @@ else if (leftType === exports.EnumToken.ContainerFunctionTokenType) { const atRule = createAtRule(arena, declaration, parent, "container", [arena.clone(left, true)]); clonedDeclaration = cloneDeclaration(arena, declaration, nodeMap); - const isWildCard = targetWrapper != declaration && arena.dataTypes[targetWrapper] === exports.EnumToken.WildCardFunctionTokenType; + const isWildCard = targetWrapper !== declaration && arena.dataTypes[targetWrapper] === exports.EnumToken.WildCardFunctionTokenType; arena.replaceToken(mapped(isWildCard ? targetWrapper : node), ...conditionValue(arena, node, nodeMap)); // inlined: arena.appendChildren(atRule, clonedDeclaration) arena.appendChildList(atRule, [clonedDeclaration]); @@ -24290,7 +26118,7 @@ const result = []; const stack = [declarationNode]; // the generated nodes are detached: remember the parent for the location of the generated at-rules - if (arena.parents[declarationNode] != 0) { + if (arena.parents[declarationNode] !== 0) { parent = arena.parents[declarationNode]; } while (++k < stack.length) { @@ -24304,7 +26132,7 @@ const value = found.value; // the parent of a detached token is the declaration const parentWrapper = arena.getValueParent(value) || declaration; - const grandParent = parentWrapper == declaration ? declaration : arena.getValueParent(parentWrapper) || declaration; + const grandParent = parentWrapper === declaration ? declaration : arena.getValueParent(parentWrapper) || declaration; if (arena.dataTypes[value] === exports.EnumToken.WildCardFunctionTokenType) { const conditions = arena.tokens(value); for (i = 0; i < conditions.length; i++) { @@ -24315,11 +26143,11 @@ stack.push(...substituteIfElseNode(arena, declaration, value, parentWrapper, grandParent, cache, parent)); } // the node is substituted: release it unless it is the node being replaced - if (astNode != declarationNode) { + if (astNode !== declarationNode) { arena.detach(astNode); } } - if (result.length > 0 && arena.parents[declarationNode] != 0) { + if (result.length > 0 && arena.parents[declarationNode] !== 0) { arena.replaceChild(declarationNode, ...result); if (!result.includes(declarationNode)) { arena.detach(declarationNode); @@ -24342,6 +26170,11 @@ options.features.push(new ExpandIfFeature()); } } + /** + * + * @param arena + * @param declaration + */ run(arena, declaration) { return processNode(arena, declaration, new Set()); } @@ -24411,7 +26244,7 @@ for (let k = 0; k < queue.length; k++) { node = queue[k]; typ = arena.dataTypes[node]; - if (typ == exports.EnumToken.CommentTokenType || typ == exports.EnumToken.CDOCOMMTokenType) { + if (typ === exports.EnumToken.CommentTokenType || typ === exports.EnumToken.CDOCOMMTokenType) { continue; } replacement = node; @@ -24424,7 +26257,7 @@ } // the prelude tokens of the rules whose selector has been rewritten are not parsed again: // the features and the renderer use the selector / prelude string - const result = feature.run(arena, replacement, options2, arena.parents[node] == 0 ? ast : arena.parents[node], context, mode); + const result = feature.run(arena, replacement, options2, arena.parents[node] === 0 ? ast : arena.parents[node], context, mode); if (result != null) { replacement = result; } @@ -24432,11 +26265,11 @@ if (replacement != null && (!Array.isArray(replacement) || replacement.length > 0) && replacement != node && - arena.parents[node] != 0) { + arena.parents[node] !== 0) { arena.replaceChild(node, ...(Array.isArray(replacement) ? replacement : [replacement])); } if (!Array.isArray(replacement) && arena.flags[replacement] & exports.EnumAstNodeStatus.HasChildren) { - for (let child = arena.firstChild[replacement]; child != 0; child = arena.nextSibling[child]) { + for (let child = arena.firstChild[replacement]; child !== 0; child = arena.nextSibling[child]) { queue.push(child); } } @@ -24466,6 +26299,7 @@ * - generate range queries * * @private + * @param arena * @param tokens */ function minifyAtRuleMedia(arena, tokens) { @@ -24508,8 +26342,8 @@ */ function reduce(acc, curr) { // trim :is() - if (curr[0] == "&") { - if (curr[1] == " " && !isIdent(curr[2]) && !isFunction(curr[2])) { + if (curr[0] === "&") { + if (curr[1] === " " && !isIdent(curr[2]) && !isFunction(curr[2])) { const all = new Array(Math.max(curr.length - 2, 0)); let write = 0; for (let read = 2; read < curr.length; read++) { @@ -24544,10 +26378,10 @@ return ast; } context.nodes.add(ast); - if (arena.flags[ast] & exports.EnumAstNodeStatus.HasChildren && arena.firstChild[ast] != 0) { + if (arena.flags[ast] & exports.EnumAstNodeStatus.HasChildren && arena.firstChild[ast] !== 0) { const reducer = reduce.bind(ast); if (!nestingContent) { - nestingContent = options.nestingRules && arena.dataTypes[ast] == exports.EnumToken.RuleNodeType; + nestingContent = options.nestingRules && arena.dataTypes[ast] === exports.EnumToken.RuleNodeType; } // the children list is modified while it is visited: every branch sets the next child to visit let cursor = arena.firstChild[ast]; @@ -24561,13 +26395,13 @@ * @param count */ const before = (child, count) => { - let result = child == 0 ? arena.lastChild[ast] : arena.previousSibling[child]; - while (--count > 0 && result != 0) { + let result = child === 0 ? arena.lastChild[ast] : arena.previousSibling[child]; + while (--count > 0 && result !== 0) { result = arena.previousSibling[result]; } - return result == 0 ? null : result; + return result === 0 ? null : result; }; - while (cursor != 0) { + while (cursor !== 0) { if (arena.dataTypes[cursor] === exports.EnumToken.CommentNodeType) { cursor = arena.nextSibling[cursor]; continue; @@ -24588,7 +26422,7 @@ if (equalsIgnoreCase(nam, "function")) { let k = arena.lastChild[node]; let slice = false; - while (k != 0) { + while (k !== 0) { if (arena.dataTypes[k] === exports.EnumToken.CommentNodeType || arena.dataTypes[k] === exports.EnumToken.WhitespaceTokenType) { k = arena.previousSibling[k]; @@ -24601,9 +26435,9 @@ } k = arena.previousSibling[k]; } - if (k != 0 && slice) { + if (k !== 0 && slice) { k = arena.previousSibling[k]; - while (k != 0) { + while (k !== 0) { const previousNode = arena.previousSibling[k]; if (arena.dataTypes[k] === exports.EnumToken.AtRuleNodeType) { arena.detach(k); @@ -24637,17 +26471,17 @@ continue; } let k = arena.firstChild[node]; - while (k != 0) { + while (k !== 0) { const next = arena.nextSibling[k]; - if (arena.dataTypes[k] == exports.EnumToken.DeclarationNodeType) { + if (arena.dataTypes[k] === exports.EnumToken.DeclarationNodeType) { let l = arena.lastToken[k]; - while (l != 0) { - if (arena.dataTypes[l] == exports.EnumToken.ImportantTokenType) { + while (l !== 0) { + if (arena.dataTypes[l] === exports.EnumToken.ImportantTokenType) { arena.detach(k); break; } - if (arena.dataTypes[l] == exports.EnumToken.WhitespaceTokenType || - arena.dataTypes[l] == exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[l] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[l] === exports.EnumToken.CommentTokenType) { l = arena.previousSibling[l]; continue; } @@ -24657,9 +26491,9 @@ k = next; } } - else if (nodeType == exports.EnumToken.AtRuleNodeType) { + else if (nodeType === exports.EnumToken.AtRuleNodeType) { const nam = arena.strings[arena.name[node]]; - const tokens = arena.firstToken[node] == 0 ? null : arena.tokens(node); + const tokens = arena.firstToken[node] === 0 ? null : arena.tokens(node); const renderPrelude = (acc, curr, index, arr) => acc + (arena.dataTypes[curr] === exports.EnumToken.CommentTokenType || (arena.dataTypes[curr] === exports.EnumToken.WhitespaceTokenType && @@ -24669,7 +26503,7 @@ (index + 3 < arr.length || arena.dataTypes[arr[index + 2]] === exports.EnumToken.WhitespaceTokenType)) ? "" : renderValue(arena, curr)); - if (nam == "media") { + if (nam === "media") { if (tokens != null) { const slice = tokens.slice(); minifyAtRuleMedia(arena, slice); @@ -24716,8 +26550,8 @@ arena.detach(node); continue; } - if (previousType == exports.EnumToken.AtRuleNodeType && - nam != "font-face" && + if (previousType === exports.EnumToken.AtRuleNodeType && + nam !== "font-face" && arena.name[previous] === arena.name[node] && arena.stringValue[previous] === arena.stringValue[node]) { if (arena.flags[node] & exports.EnumAstNodeStatus.HasChildren) { @@ -24744,7 +26578,7 @@ let wrapper = null; let match; if (options.nestingRules) { - if (previousType == exports.EnumToken.RuleNodeType) { + if (previousType === exports.EnumToken.RuleNodeType) { reduceRuleSelector(arena, previous); match = matchSelectors(arena.raw[previous], arena.raw[node]); if (match != null) { @@ -24754,7 +26588,7 @@ if (wrapper != null) { // wrap the following rules that match the wrapper selector let nextNode = arena.nextSibling[wrapper]; - while (nextNode != 0 && arena.dataTypes[nextNode] == exports.EnumToken.RuleNodeType) { + while (nextNode !== 0 && arena.dataTypes[nextNode] === exports.EnumToken.RuleNodeType) { reduceRuleSelector(arena, nextNode); match = matchSelectors(arena.raw[wrapper], arena.raw[nextNode]); if (match == null) { @@ -24798,7 +26632,7 @@ ")"; const sel2 = optimized.selector.reduce((acc, curr) => (acc.length > 0 ? acc + "," : "") + optimized.optimized[0] + curr.join(""), ""); // inlined: arena.setSelector(node, sel1.length < sel2.length ? sel1 : sel2) - arena.name[node] = arena.internString((sel1.length < sel2.length ? sel1 : sel2)); + arena.name[node] = arena.internString(sel1.length < sel2.length ? sel1 : sel2); // inlined: arena.setTokens(node) arena.setTokenList(node, []); } @@ -24817,8 +26651,8 @@ const optimizedSelector = arena.optimized[node]; let wrap = true; const selector = optimizedSelector.selector.reduce((acc, curr) => { - if (curr[0] == "&" && curr.length > 1) { - if (curr[1] == " ") { + if (curr[0] === "&" && curr.length > 1) { + if (curr[1] === " ") { curr.splice(0, 2); } else { @@ -24833,7 +26667,7 @@ return acc; }, []); if (!wrap) { - wrap = selector.some((s) => s[0] != "&"); + wrap = selector.some((s) => s[0] !== "&"); } let rule = null; const optimized = optimizedSelector.optimized.slice(); @@ -24855,9 +26689,9 @@ optimized.join("") + `:is(${selector .map((s) => { - const next = s[0] == "&" ? new Array(s.length) : new Array(s.length + 1); + const next = s[0] === "&" ? new Array(s.length) : new Array(s.length + 1); let write = 0; - if (s[0] == "&") { + if (s[0] === "&") { next[write++] = last; for (let read = 1; read < s.length; read++) { next[write++] = s[read]; @@ -24881,7 +26715,7 @@ if (rule == null) { rule = selector .map((s) => { - if (s[0] == "&") { + if (s[0] === "&") { const replacement = optimizedSelector.optimized; const all = new Array(Math.max(s.length - 1 + replacement.length, 0)); let write = 0; @@ -24915,7 +26749,7 @@ const sel1 = optimized.optimized[0] + ":is(" + optimized.selector.reduce(reducer, []).join(",") + ")"; const sel2 = optimized.selector.reduce((acc, curr) => (acc.length > 0 ? acc + "," : "") + optimized.optimized[0] + curr.join(""), ""); // inlined: arena.setSelector(node, sel1.length < sel2.length ? sel1 : sel2) - arena.name[node] = arena.internString((sel1.length < sel2.length ? sel1 : sel2)); + arena.name[node] = arena.internString(sel1.length < sel2.length ? sel1 : sel2); // inlined: arena.setTokens(node) arena.setTokenList(node, []); } @@ -24949,7 +26783,7 @@ if (previousType === nodeType) { let shouldMerge = true; let k = arena.lastChild[previous]; - while (k != 0) { + while (k !== 0) { if (arena.dataTypes[k] === exports.EnumToken.CommentNodeType) { k = arena.previousSibling[k]; continue; @@ -24961,7 +26795,7 @@ if (((nodeType === exports.EnumToken.RuleNodeType || nodeType === exports.EnumToken.KeyframesRuleNodeType) && arena.name[node] === arena.name[previous]) || - (nodeType == exports.EnumToken.AtRuleNodeType && + (nodeType === exports.EnumToken.AtRuleNodeType && arena.strings[arena.name[node]] !== "font-face" && arena.name[node] === arena.name[previous])) { arena.moveChildren(previous, node, arena.firstChild[node]); @@ -24972,14 +26806,14 @@ cursor = arena.nextSibling[node]; continue; } - else if (nodeType == previousType && + else if (nodeType === previousType && [exports.EnumToken.KeyframesRuleNodeType, exports.EnumToken.RuleNodeType].includes(nodeType)) { const intersect = diff(arena, previous, node, options, context); if (intersect != null) { // [result, node2] take the place of node1 (previous), node1 takes the place of node2 (node) const { node1, node2, result } = intersect; const after = arena.nextSibling[node2]; - const keep2 = arena.firstChild[node2] != 0; + const keep2 = arena.firstChild[node2] !== 0; if (result != null) { arena.insertBefore(node1, result); } @@ -24989,10 +26823,10 @@ else { arena.detach(node2); } - if (arena.firstChild[node1] == 0) { + if (arena.firstChild[node1] === 0) { arena.detach(node1); } - else if (after == 0) { + else if (after === 0) { arena.appendChild(ast, node1); } else { @@ -25001,13 +26835,13 @@ // next node to visit node = keep2 ? arena.nextSibling[result ?? node2] || null - : before(arena.parents[node1] == ast ? node1 : after, result == null ? 1 : 2); + : before(arena.parents[node1] === ast ? node1 : after, result == null ? 1 : 2); previous = result; } } } } - if (recursive && previous != null && previous != node) { + if (recursive && previous != null && previous !== node) { if (!hasDeclaration(arena, previous)) { doMinify(arena, previous, options, recursive, errors, nestingContent, context); } @@ -25016,7 +26850,7 @@ } if (!nestingContent && previous != null && - arena.dataTypes[previous] == exports.EnumToken.RuleNodeType && + arena.dataTypes[previous] === exports.EnumToken.RuleNodeType && arena.strings[arena.name[previous]].includes("&")) { fixSelector(arena, previous); } @@ -25024,16 +26858,16 @@ cursor = node == null ? arena.firstChild[ast] : arena.nextSibling[node]; } if (recursive && node != null && arena.flags[node] & exports.EnumAstNodeStatus.HasChildren) { - if (arena.dataTypes[node] == exports.EnumToken.KeyframesAtRuleNodeType || !hasDeclarationChild(arena, node)) { - if (!(arena.dataTypes[node] == exports.EnumToken.AtRuleNodeType && - arena.strings[arena.name[node]] != "font-face")) { + if (arena.dataTypes[node] === exports.EnumToken.KeyframesAtRuleNodeType || !hasDeclarationChild(arena, node)) { + if (!(arena.dataTypes[node] === exports.EnumToken.AtRuleNodeType && + arena.strings[arena.name[node]] !== "font-face")) { doMinify(arena, node, options, recursive, errors, nestingContent, context); } } } if (!nestingContent && node != null && - arena.dataTypes[node] == exports.EnumToken.RuleNodeType && + arena.dataTypes[node] === exports.EnumToken.RuleNodeType && arena.strings[arena.name[node]].includes("&")) { fixSelector(arena, node); } @@ -25048,11 +26882,11 @@ * @private */ function hasDeclaration(arena, node) { - for (let child = arena.firstChild[node]; child != 0; child = arena.nextSibling[child]) { - if (arena.dataTypes[child] == exports.EnumToken.CommentNodeType) { + for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) { + if (arena.dataTypes[child] === exports.EnumToken.CommentNodeType) { continue; } - return arena.dataTypes[child] == exports.EnumToken.DeclarationNodeType; + return arena.dataTypes[child] === exports.EnumToken.DeclarationNodeType; } return true; } @@ -25064,8 +26898,8 @@ * @private */ function hasDeclarationChild(arena, node) { - for (let child = arena.firstChild[node]; child != 0; child = arena.nextSibling[child]) { - if (arena.dataTypes[child] == exports.EnumToken.DeclarationNodeType) { + for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) { + if (arena.dataTypes[child] === exports.EnumToken.DeclarationNodeType) { return true; } } @@ -25078,6 +26912,30 @@ * @private */ function optimizeSelector(selector) { + if (selector.length === 0) { + return null; + } + if (selector.length === 1) { + const current = selector[0]; + const last = current.at(-1); + if (last == null || !last.startsWith(":is(")) { + let end = current.length; + while (end > 0 && (current[end - 1] === " " || combinators.includes(current[end - 1]))) { + end--; + } + const optimized = current.slice(0, end); + if (optimized[0] === "&" && optimized[1] === " ") { + optimized.splice(0, 2); + } + const remainder = current.slice(end); + return { + match: false, + optimized, + selector: [remainder[0] === "&" && remainder[1] === " " ? remainder.slice(2) : remainder], + reducible: false, + }; + } + } const map = new Set(); selector = selector .reduce((acc, curr) => { @@ -25085,8 +26943,8 @@ if (curr.length > 0 && curr.at(-1).startsWith(":is(")) { // @ts-ignore const rules = splitRule(curr.at(-1).slice(4, -1)).map((x) => { - if (x[0] == "&" && x.length > 1) { - return x.slice(x[1] == " " ? 2 : 1); + if (x[0] === "&" && x.length > 1) { + return x.slice(x[1] === " " ? 2 : 1); } return x; }); @@ -25108,7 +26966,7 @@ return true; }); const optimized = []; - const k = selector.reduce((acc, curr) => acc == 0 ? curr.length : curr.length == 0 ? acc : Math.min(acc, curr.length), 0); + const k = selector.reduce((acc, curr) => acc === 0 ? curr.length : curr.length === 0 ? acc : Math.min(acc, curr.length), 0); let i = 0; let j; let match; @@ -25116,7 +26974,7 @@ const item = selector[0][i]; match = true; for (j = 1; j < selector.length; j++) { - if (item != selector[j][i]) { + if (item !== selector[j][i]) { match = false; break; } @@ -25128,7 +26986,7 @@ } while (optimized.length > 0) { const last = optimized.at(-1); - if (last == " " || combinators.includes(last)) { + if (last === " " || combinators.includes(last)) { const all = new Array(Math.max(optimized.length - 1, 0)); let write = 0; for (let read = 0; read < optimized.length - 1; read++) { @@ -25153,9 +27011,9 @@ selector[i1][index] = all[index]; } } - let reducible = optimized.length == 1; - if (optimized[0] == "&") { - if (optimized[1] == " ") { + let reducible = optimized.length === 1; + if (optimized[0] === "&") { + if (optimized[1] === " ") { const all = new Array(Math.max(optimized.length - 2, 0)); let write = 0; for (let read = 2; read < optimized.length; read++) { @@ -25167,11 +27025,11 @@ } } } - if (optimized.length == 0 || optimized[0].charAt(0) == "&" || selector.length == 1) { + if (optimized.length === 0 || optimized[0].charAt(0) === "&" || selector.length === 1) { return { match: false, optimized, - selector: selector.map((selector) => selector[0] == "&" && selector[1] == " " ? selector.slice(2) : selector), + selector: selector.map((selector) => selector[0] === "&" && selector[1] === " " ? selector.slice(2) : selector), reducible: selector.length > 1 && selector.every((selector) => !combinators.includes(selector[0])), }; } @@ -25184,18 +27042,18 @@ hasCompound = !["&"].concat(combinators).includes(curr[0].charAt(0)); } // @ts-ignore - if (hasCompound && curr[0] == " ") { + if (hasCompound && curr[0] === " ") { hasCompound = false; curr.unshift("&"); } - if (curr.length == 0) { + if (curr.length === 0) { curr.push("&"); hasCompound = false; } if (reducible) { const chr = curr[0].charAt(0); // @ts-ignore - reducible = chr == "." || chr == ":" || isIdentStart(chr.charCodeAt(0)); + reducible = chr === "." || chr === ":" || isIdentStart(chr.charCodeAt(0)); } acc.push(hasCompound ? ["&"].concat(curr) : curr); return acc; @@ -25211,94 +27069,102 @@ */ function splitRule(buffer) { const result = [[]]; - let str = ""; - for (let i = 0; i < buffer.length; i++) { - let chr = buffer.charAt(i); - if (isWhiteSpace(chr.charCodeAt(0))) { - if (str !== "") { - // @ts-ignore - result.at(-1).push(str); - str = ""; + const length = buffer.length; + let group = result[0]; + // the start of the current part, -1 when it is empty: a part is a contiguous range of the buffer + let start = -1; + let code; + for (let i = 0; i < length; i++) { + code = buffer.charCodeAt(i); + if (isWhiteSpace(code)) { + if (start !== -1) { + group.push(buffer.slice(start, i)); + start = -1; } - // @ts-ignore - if (result.at(-1).length > 0) { - // @ts-ignore - result.at(-1).push(" "); + if (group.length > 0) { + group.push(" "); } - // i = k; continue; } - if (chr == ",") { - if (str !== "") { - result.at(-1).push(str); - str = ""; + // , + if (code === 0x2c) { + if (start !== -1) { + group.push(buffer.slice(start, i)); + start = -1; } - result.push([]); + group = []; + result.push(group); continue; } - if (chr == ".") { - if (str !== "") { - result.at(-1).push(str); - str = ""; + // . + if (code === 0x2e) { + if (start !== -1) { + group.push(buffer.slice(start, i)); } - str += chr; + start = i; continue; } - if (combinators.includes(chr)) { - if (str !== "") { - result.at(-1).push(str); - str = ""; + // the combinators: + > ~ | || + if (code === 0x2b || code === 0x3e || code === 0x7e || code === 0x7c) { + if (start !== -1) { + group.push(buffer.slice(start, i)); + start = -1; } - if (chr == "|" && buffer.charAt(i + 1) == "|") { - chr += buffer.charAt(++i); + if (code === 0x7c && buffer.charCodeAt(i + 1) === 0x7c) { + group.push("||"); + i++; + } + else { + group.push(code === 0x2b ? "+" : code === 0x3e ? ">" : code === 0x7e ? "~" : "|"); } - result.at(-1).push(chr); continue; } - if (chr == ":") { - if (str !== "") { - result.at(-1).push(str); - str = ""; + // : :: + if (code === 0x3a) { + if (start !== -1) { + group.push(buffer.slice(start, i)); } - if (buffer.charAt(i + 1) == ":") { - chr += buffer.charAt(++i); + start = i; + if (buffer.charCodeAt(i + 1) === 0x3a) { + i++; } - str += chr; continue; } - str += chr; - if (chr == "\\") { - str += buffer.charAt(++i); + if (start === -1) { + start = i; + } + // \: the escaped character + if (code === 0x5c) { + i++; continue; } - if (chr == "(" || chr == "[") { - const open = chr; - const close = chr == "(" ? ")" : "]"; - let inParens = 1; + // ( [: the part ends with the matching ) ] + if (code === 0x28 || code === 0x5b) { + const close = code === 0x28 ? 0x29 : 0x5d; + let depth = 1; let k = i; - while (++k < buffer.length) { - chr = buffer.charAt(k); - if (chr == "\\") { - str += buffer.slice(k, k + 2); + let c; + while (++k < length) { + c = buffer.charCodeAt(k); + if (c === 0x5c) { k++; continue; } - str += chr; - if (chr == open) { - inParens++; + if (c === code) { + depth++; } - else if (chr == close) { - inParens--; + else if (c === close) { + depth--; } - if (inParens == 0) { + if (depth === 0) { break; } } i = k; } } - if (str !== "") { - result.at(-1).push(str); + if (start !== -1) { + group.push(buffer.slice(start, length)); } return result; } @@ -25314,7 +27180,7 @@ // @ts-ignore curr = curr.slice(this.match[0].length); while (curr.length > 0) { - if (curr[0] == " ") { + if (curr[0] === " ") { hasCompoundSelector = false; curr.unshift("&"); continue; @@ -25324,16 +27190,16 @@ if (hasCompoundSelector && curr.length > 0) { hasCompoundSelector = !["&"].concat(combinators).includes(curr[0].charAt(0)); } - if (curr[0] == ":is(") { + if (curr[0] === ":is(") { let canReduce = true; const isCompound = curr.reduce((acc, token, index) => { - if (index == 0) { - canReduce = curr[1] == "&"; + if (index === 0) { + canReduce = curr[1] === "&"; } - else if (token == ")") ; - else if (token == ",") { + else if (token === ")") ; + else if (token === ",") { if (!canReduce) { - canReduce = curr[index + 1] == "&"; + canReduce = curr[index + 1] === "&"; } acc.push([]); } @@ -25357,7 +27223,7 @@ // @ts-ignore this.match.length == 0 ? ["&"] - : hasCompoundSelector && curr[0] != "&" && (curr.length == 0 || !combinators.includes(curr[0].charAt(0))) + : hasCompoundSelector && curr[0] !== "&" && (curr.length === 0 || !combinators.includes(curr[0].charAt(0))) ? ["&"].concat(curr) : curr); return acc; @@ -25412,7 +27278,7 @@ k = 0; token = selector1[0][i]; for (; k < selector1.length; k++) { - if (selector1[k][i] != token) { + if (selector1[k][i] !== token) { matching = false; break; } @@ -25420,7 +27286,7 @@ if (matching) { l = 0; for (; l < selector2.length; l++) { - if (selector2[l][i] != token) { + if (selector2[l][i] !== token) { matching = false; break; } @@ -25435,20 +27301,20 @@ match.at(-1).push(token); } // invalid function - if (matchFunction != 0 || inAttr != 0) { + if (matchFunction !== 0 || inAttr !== 0) { return null; } for (const part of match) { while (part.length > 0) { const token = part.at(-1); - if (token == " " || combinators.includes(token) || notEndingWith.includes(token.at(-1))) { + if (token === " " || combinators.includes(token) || notEndingWith.includes(token.at(-1))) { part.pop(); continue; } break; } } - if (match.every((t) => t.length == 0)) { + if (match.every((t) => t.length === 0)) { return null; } if (eq([["&"]], match)) { @@ -25481,12 +27347,12 @@ const attributes = parseString(arena, sel); // inlined: arena.walkValues(attributes) for (const attr of new ValueWalker(arena, attributes)) { - if (arena.dataTypes[attr] == exports.EnumToken.PseudoClassFuncTokenType && - arena.strings[arena.stringValue[attr]] == ":is") { + if (arena.dataTypes[attr] === exports.EnumToken.PseudoClassFuncTokenType && + arena.strings[arena.stringValue[attr]] === ":is") { let child = arena.lastToken[attr]; - while (child != 0) { + while (child !== 0) { const previous = arena.previousSibling[child]; - if (arena.dataTypes[child] == exports.EnumToken.NestingSelectorTokenType) { + if (arena.dataTypes[child] === exports.EnumToken.NestingSelectorTokenType) { arena.detach(child); } child = previous; @@ -25525,9 +27391,9 @@ const parent = arena.parents[node]; // the wrapper takes the place of node arena.insertBefore(node, wrapper); - if (pSel == "&" || pSel === "") { + if (pSel === "&" || pSel === "") { arena.moveChildren(previous, wrapper); - if (nSel == "&" || nSel === "") { + if (nSel === "&" || nSel === "") { arena.moveChildren(node, wrapper); } else { @@ -25539,21 +27405,21 @@ arena.appendChild(wrapper, node); } // the nodes whose children were moved into the wrapper are dropped - if (arena.parents[previous] == parent) { + if (arena.parents[previous] === parent) { arena.detach(previous); } - if (arena.parents[node] == parent) { + if (arena.parents[node] === parent) { arena.detach(node); } // update the selectors of the wrapped nodes - if (arena.parents[previous] == wrapper) { + if (arena.parents[previous] === wrapper) { // inlined: arena.setSelector(previous, pSel) arena.name[previous] = arena.internString(pSel); arena.raw[previous] = match.selector1; // inlined: arena.setTokens(previous) arena.setTokenList(previous, []); } - if (arena.parents[node] == wrapper) { + if (arena.parents[node] === wrapper) { // inlined: arena.setSelector(node, nSel) arena.name[node] = arena.internString(nSel); arena.raw[node] = match.selector2; @@ -25627,7 +27493,7 @@ break; } } - if (prefixes1.size != prefixes2.size) { + if (prefixes1.size !== prefixes2.size) { return null; } for (const prefix of prefixes1) { @@ -25638,16 +27504,16 @@ } // match the declarations of both rules, from the last to the first let matches = 0; - for (let child1 = arena.lastChild[node1]; child1 != 0; child1 = arena.previousSibling[child1]) { - if (arena.dataTypes[child1] == exports.EnumToken.CommentNodeType) { + for (let child1 = arena.lastChild[node1]; child1 !== 0; child1 = arena.previousSibling[child1]) { + if (arena.dataTypes[child1] === exports.EnumToken.CommentNodeType) { continue; } - for (let child2 = arena.lastChild[node2]; child2 != 0; child2 = arena.previousSibling[child2]) { - if (arena.dataTypes[child2] == exports.EnumToken.CommentNodeType || + for (let child2 = arena.lastChild[node2]; child2 !== 0; child2 = arena.previousSibling[child2]) { + if (arena.dataTypes[child2] === exports.EnumToken.CommentNodeType || arena.flags[child2] & exports.EnumAstNodeStatus.Matched) { continue; } - if (arena.name[child1] == arena.name[child2] && eqNode(arena, child1, child2)) { + if (arena.name[child1] === arena.name[child2] && eqNode(arena, child1, child2)) { arena.flags[child1] |= exports.EnumAstNodeStatus.Matched; arena.flags[child2] |= exports.EnumAstNodeStatus.Matched; matches++; @@ -25655,7 +27521,7 @@ } } } - if (matches == 0 && (arena.firstChild[node1] != 0 || arena.firstChild[node2] != 0)) { + if (matches === 0 && (arena.firstChild[node1] !== 0 || arena.firstChild[node2] !== 0)) { return null; } // the rules are rendered with the same options during the minification: the options are resolved once and @@ -25669,7 +27535,7 @@ options.cache.set(node, css); } } - return arena.firstChild[node] == 0 ? 0 : css.length; + return arena.firstChild[node] === 0 ? 0 : css.length; }; // size of the original nodes const size = renderedSize(n1, true) + renderedSize(n2, true); @@ -25686,7 +27552,7 @@ const moves = []; const moveMatched = (parent, target) => { let child = arena.firstChild[parent]; - while (child != 0) { + while (child !== 0) { const next = arena.nextSibling[child]; if (arena.flags[child] & exports.EnumAstNodeStatus.Matched) { arena.flags[child] &= ~exports.EnumAstNodeStatus.Matched; @@ -25707,11 +27573,11 @@ options.cache.delete(node1); options.cache.delete(node2); if (size <= renderedSize(node1, false) + renderedSize(node2, false) + renderedSize(result, false) && - arena.firstChild[node1] != 0 && - arena.firstChild[node2] != 0) { + arena.firstChild[node1] !== 0 && + arena.firstChild[node2] !== 0) { // restore the nodes: undo the moves in reverse order for (let k = moves.length - 3; k >= 0; k -= 3) { - if (moves[k + 2] == 0) { + if (moves[k + 2] === 0) { arena.appendChild(moves[k + 1], moves[k]); } else { @@ -25760,39 +27626,39 @@ * @private */ function eqNode(arena, a, b) { - if (a == b) { + if (a === b) { return true; } - if (arena.dataTypes[a] != arena.dataTypes[b] || - arena.name[a] != arena.name[b] || - arena.stringValue[a] != arena.stringValue[b]) { + if (arena.dataTypes[a] !== arena.dataTypes[b] || + arena.name[a] !== arena.name[b] || + arena.stringValue[a] !== arena.stringValue[b]) { return false; } if (arena.flags[a] & exports.EnumAstNodeStatus.HasValues) { let token1 = arena.firstToken[a]; let token2 = arena.firstToken[b]; - while (token1 != 0 && token2 != 0) { + while (token1 !== 0 && token2 !== 0) { if (!eqToken(arena, token1, token2)) { return false; } token1 = arena.nextSibling[token1]; token2 = arena.nextSibling[token2]; } - if (token1 != token2) { + if (token1 !== token2) { return false; } } if (arena.flags[a] & exports.EnumAstNodeStatus.HasChildren) { let child1 = arena.firstChild[a]; let child2 = arena.firstChild[b]; - while (child1 != 0 && child2 != 0) { + while (child1 !== 0 && child2 !== 0) { if (!eqNode(arena, child1, child2)) { return false; } child1 = arena.nextSibling[child1]; child2 = arena.nextSibling[child2]; } - return child1 == child2; + return child1 === child2; } return true; } @@ -25807,17 +27673,18 @@ if (arena.raw[node] == null) { arena.raw[node] = splitRule(arena.strings[arena.name[node]]); } - let optimized = optimizeSelector(arena.raw[node].reduce((acc, curr) => { - acc.push(curr.slice()); - return acc; - }, [])); + const raw = arena.raw[node]; + const singleSelectorWithoutIs = raw.length === 1 && (raw[0].at(-1) == null || !raw[0].at(-1).startsWith(":is(")); + let optimized = optimizeSelector(singleSelectorWithoutIs + ? raw + : raw.map((curr) => curr.slice())); if (optimized != null) { arena.optimized[node] = optimized; } if (optimized != null && optimized.match && optimized.reducible && optimized.selector.length > 1) { for (const selector of optimized.selector) { if (selector.length > 1 && - selector[0] == "&" && + selector[0] === "&" && (combinators.includes(selector[1]) || !/^[a-zA-Z:]/.test(selector[1]))) { const all = new Array(Math.max(selector.length - 1, 0)); let write = 0; @@ -25936,23 +27803,23 @@ fields = noFields; } else { - const single = typ == exports.EnumToken.BinaryExpressionTokenType || - typ == exports.EnumToken.IfElseConditionTokenType || - typ == exports.EnumToken.MatchExpressionTokenType || - typ == exports.EnumToken.NameSpaceAttributeTokenType; + const single = typ === exports.EnumToken.BinaryExpressionTokenType || + typ === exports.EnumToken.IfElseConditionTokenType || + typ === exports.EnumToken.MatchExpressionTokenType || + typ === exports.EnumToken.NameSpaceAttributeTokenType; const singleLeft = single || - typ == exports.EnumToken.MediaQueryConditionTokenType || - typ == exports.EnumToken.MediaQueryUnaryFeatureTokenType || - typ == exports.EnumToken.SupportsQueryUnaryConditionTokenType || - typ == exports.EnumToken.WhenElseUnaryConditionTokenType; - const singleRight = single || typ == exports.EnumToken.ComposesSelectorNodeType; + typ === exports.EnumToken.MediaQueryConditionTokenType || + typ === exports.EnumToken.MediaQueryUnaryFeatureTokenType || + typ === exports.EnumToken.SupportsQueryUnaryConditionTokenType || + typ === exports.EnumToken.WhenElseUnaryConditionTokenType; + const singleRight = single || typ === exports.EnumToken.ComposesSelectorNodeType; fields = [ ["l", exports.TokenField.L, singleLeft], ["r", exports.TokenField.R, singleRight], [ - typ == exports.EnumToken.MediaRangeQueryTokenType ? "op1" : "op", + typ === exports.EnumToken.MediaRangeQueryTokenType ? "op1" : "op", exports.TokenField.Op, - typ != exports.EnumToken.ContainerStyleRangeTokenType, + typ !== exports.EnumToken.ContainerStyleRangeTokenType, ], ["op2", exports.TokenField.Op2, true], ["val", exports.TokenField.Val, false], @@ -25964,7 +27831,7 @@ /** * little endian platform */ - const littleEndian = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1; + const littleEndian = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; /** * arena columns stored as typed arrays, in the order of the transferable buffers */ @@ -26041,10 +27908,6 @@ * 0 is never allocated: it means "no node" */ current = 1; - /** - * head of the list of recycled node ids. the list is linked through the `nextSibling` column, see {@link recycle} - */ - freeList = 0; /** * node EnumToken type array */ @@ -26105,17 +27968,27 @@ * token spans. 8 bits for source type. 28 bits for start position, 28 bits for end position. This allows us to store the start and end positions of tokens in a single 64-bit integer, which is more efficient than storing them separately. */ spans; + /** + * error cache + */ + errors = new Map(); + /** + * head of the list of recycled node ids. the list is linked through the `nextSibling` column, see {@link recycle} + */ + freeList = 0; + /** + * number of nodes the columns can hold: the length of the columns. the length of a typed array is a getter, + * allocate() reads the capacity of the arena for each node + */ + capacity = 0; /** * 32 bits view of the spans: the low word holds the end position and the 4 low bits of the start position, * the high word holds the 24 high bits of the start position and the source */ spans32; - /** - * error cache - */ - errors = new Map(); constructor(size = 4096) { this.dataTypes = new Uint8Array(size); + this.capacity = size; this.parents = new Uint32Array(size); this.nextSibling = new Uint32Array(size); this.previousSibling = new Uint32Array(size); @@ -26133,6 +28006,12 @@ this.spans32 = new Uint32Array(this.spans.buffer); this.dataTypes[this.root] = exports.EnumToken.StyleSheetNodeType; } + /** + * true when the column buffers have been transferred to another thread: the arena can no longer be used + */ + get transferred() { + return this.dataTypes.length === 0 && this.current > 0; + } /** * Export the arena as a structured-cloneable object and the list of its column buffers, to send an arena * to a worker (or back to the main thread) without copying the node data. @@ -26171,66 +28050,17 @@ arena.importProperties(properties, transferables); return arena; } - /** - * true when the column buffers have been transferred to another thread: the arena can no longer be used - */ - get transferred() { - return this.dataTypes.length == 0 && this.current > 0; - } - /** - * structured-cloneable properties of the arena - */ - exportProperties() { - return { - kind: "Arena", - current: this.current, - strings: this.strings, - errors: [...this.errors.entries()], - }; - } - /** - * column buffers, in the order of {@link arenaColumns}. the `spans` buffer is shared with the `spans32` view - */ - exportTransferables() { - const buffers = []; - for (const column of arenaColumns) { - const array = this[column]; - // the columns always own their buffer: no offset or partial view - buffers.push(array.buffer); - } - return buffers; - } - /** - * initialize the arena from exported properties and column buffers - * @param properties - * @param transferables - */ - importProperties(properties, transferables) { - if (transferables.length != arenaColumns.length) { - throw new TypeError(`expected ${arenaColumns.length} column buffers, got ${transferables.length}`); - } - for (let i = 0; i < arenaColumns.length; i++) { - const column = arenaColumns[i]; - // @ts-ignore - this[column] = new arenaColumnTypes[column](transferables[i]); - } - this.spans32 = new Uint32Array(this.spans.buffer); - this.current = properties.current; - this.strings = properties.strings.slice(); - this.stringIds = new Map(this.strings.map((str, index) => [str, index])); - this.errors = new Map(properties.errors); - } allocate() { let id = this.freeList; - if (id != 0) { + if (id !== 0) { // reuse a recycled node: its record is already zeroed, except the free list link this.freeList = this.nextSibling[id]; this.nextSibling[id] = 0; return id; } id = ++this.current; - if (id >= this.dataTypes.length) { - this.resize(this.dataTypes.length * 2); + if (id >= this.capacity) { + this.resize(this.capacity * 2); } return id; } @@ -26270,60 +28100,92 @@ return id; } /** - * set node data for a given id. The first argument is the id, the second is the type, the third is the string value, the fourth is the numeric value, and the fifth is the unit. + * * @param id - * @param args */ - set(id, ...args) { - this.dataTypes[id] = args[0]; - if (args.length > 1) { - // 0 is null string, so we can use it to indicate that there is no string value for this node. - this.stringValue[id] = args[1]; - } - if (args.length > 2) { - this.numericValue[id] = args[2]; - } - if (args.length > 3) { - this.unit[id] = args[3]; - } - } getType(id) { return this.dataTypes[id]; } /** - * type of a node or a token. null when the id is null + * type of node or a token. null when the id is null * @param id */ typeOf(id) { return id == null ? null : this.dataTypes[id]; } + /** + * + * @param id + * @param type + */ setType(id, type) { this.dataTypes[id] = type; } + /** + * + * @param id + * @param nameId + */ setName(id, nameId) { this.name[id] = nameId; } + /** + * + * @param id + */ getName(id) { return this.strings[this.name[id]] ?? null; } + /** + * + * @param id + * @param valueId + */ setValue(id, valueId) { this.stringValue[id] = valueId; } + /** + * + * @param id + */ getValue(id) { return this.strings[this.stringValue[id]] ?? null; } + /** + * + * @param id + * @param numericValue + */ setNumericValue(id, numericValue) { this.numericValue[id] = numericValue; } + /** + * + * @param id + * @param unit + */ setUnit(id, unit) { this.unit[id] = unit; } + /** + * + * @param id + */ getUnit(id) { return this.strings[this.unit[id]] ?? null; } + /** + * + * @param id + */ getNumericValue(id) { return this.numericValue[id]; } + /** + * + * @param id + * @param parentId + */ setParent(id, parentId) { this.parents[id] = parentId; } @@ -26388,11 +28250,11 @@ */ setFirstChild(id, firstChildId) { const firstChild = this.firstChild[id]; - if (firstChild == firstChildId) { + if (firstChild === firstChildId) { return; } this.detach(firstChildId); - if (firstChild != 0) { + if (firstChild !== 0) { this.#insertBefore(id, firstChild, firstChildId); this.detach(firstChild); } @@ -26401,6 +28263,10 @@ this.appendChildList(id, [firstChildId]); } } + /** + * + * @param id + */ getLastChild(id) { return this.lastChild[id]; } @@ -26411,11 +28277,11 @@ */ setLastChild(id, lastChildId) { const lastChild = this.lastChild[id]; - if (lastChild == lastChildId) { + if (lastChild === lastChildId) { return; } this.detach(lastChildId); - if (lastChild != 0) { + if (lastChild !== 0) { this.detach(lastChild); } // inlined: this.appendChildren(id, lastChildId) @@ -26427,7 +28293,7 @@ * @param nextSiblingId */ setNextSibling(id, nextSiblingId) { - if (id == nextSiblingId) { + if (id === nextSiblingId) { return; } this.detach(nextSiblingId); @@ -26437,13 +28303,13 @@ this.previousSibling[nextSiblingId] = id; this.nextSibling[id] = nextSiblingId; this.parents[nextSiblingId] = parent; - if (next != 0) { + if (next !== 0) { this.previousSibling[next] = nextSiblingId; } - else if (this.lastChild[parent] == id) { + else if (this.lastChild[parent] === id) { this.lastChild[parent] = nextSiblingId; } - else if (this.lastToken[parent] == id) { + else if (this.lastToken[parent] === id) { this.lastToken[parent] = nextSiblingId; } } @@ -26453,7 +28319,7 @@ * @param previousSiblingId */ setPreviousSibling(id, previousSiblingId) { - if (id == previousSiblingId) { + if (id === previousSiblingId) { return; } this.detach(previousSiblingId); @@ -26466,11 +28332,11 @@ */ setFirstToken(id, firstTokenId) { const firstToken = this.firstToken[id]; - if (firstToken == firstTokenId) { + if (firstToken === firstTokenId) { return; } this.detach(firstTokenId); - if (firstToken != 0) { + if (firstToken !== 0) { this.#insertBefore(id, firstToken, firstTokenId); this.detach(firstToken); } @@ -26479,28 +28345,56 @@ this.appendTokenList(id, [firstTokenId]); } } + /** + * + * @param id + * @param colorType + */ setColorType(id, colorType) { this.colorType[id] = colorType; } + /** + * + * @param id + */ getColorType(id) { return this.colorType[id]; } + /** + * + * @param id + * @param flags + */ setFlags(id, flags) { this.flags[id] = flags; } + /** + * + * @param id + */ getFlags(id) { return this.flags[id]; } + /** + * + * @param id + * @param flag + */ hasFlags(id, flag) { - return (this.flags[id] & flag) == flag; + return (this.flags[id] & flag) === flag; } + /** + * + * @param id + * @param index + */ getChildAt(id, index) { let child = this.firstChild[id]; - while (index > 0 && child != 0) { + while (index > 0 && child !== 0) { child = this.nextSibling[child]; index--; } - return child == 0 ? null : child; + return child === 0 ? null : child; } /** * token at the given position of the token list @@ -26509,11 +28403,11 @@ */ getTokenAt(id, index) { let token = this.firstToken[id]; - while (index > 0 && token != 0) { + while (index > 0 && token !== 0) { token = this.nextSibling[token]; index--; } - return token == 0 ? null : token; + return token === 0 ? null : token; } /** * replace the child at the given index. the node is appended when the index is out of range @@ -26523,7 +28417,7 @@ */ setChildAt(id, index, child) { const current = this.getChildAt(id, index); - if (current == child) { + if (current === child) { return; } this.detach(child); @@ -26535,29 +28429,6 @@ this.#insertBefore(id, current, child); this.detach(current); } - /** - * link a node before a reference node of the given parent - * @param parent - * @param reference - * @param node - */ - #insertBefore(parent, reference, node) { - const previous = this.previousSibling[reference]; - this.previousSibling[node] = previous; - this.nextSibling[node] = reference; - this.previousSibling[reference] = node; - this.parents[node] = parent; - if (previous != 0) { - this.nextSibling[previous] = node; - } - else if (this.firstChild[parent] == reference) { - this.firstChild[parent] = node; - } - else if (this.firstToken[parent] == reference) { - this.firstToken[parent] = node; - } - } - // ---- structured token fields --------------------------------------------------------- /** * list node holding the tokens of a structured token field. created when missing * @param id @@ -26567,13 +28438,13 @@ let child = this.firstChild[id]; let index = 0; while (index < field) { - if (child == 0) { + if (child === 0) { break; } child = this.nextSibling[child]; index++; } - if (child != 0) { + if (child !== 0) { return child; } // create the missing slots @@ -26594,7 +28465,7 @@ */ hasField(id, field) { const list = this.getChildAt(id, field); - return list != null && this.firstToken[list] != 0; + return list != null && this.firstToken[list] !== 0; } /** * first token of a structured token field (single token fields: `l` and `r` of binary expressions, `op`, ...) @@ -26614,6 +28485,7 @@ const list = this.getChildAt(id, field); return list == null ? [] : this.tokens(list); } + // ---- structured token fields --------------------------------------------------------- /** * set the tokens of a structured token field * @param id @@ -26632,35 +28504,77 @@ appendField(id, field, ...tokens) { this.appendTokenList(this.fieldList(id, field), tokens); } + /** + * + * @param id + * @param children + */ setLeft(id, ...children) { // inlined: this.setField(id, TokenField.L, ...children) this.setTokenList(this.fieldList(id, exports.TokenField.L), children); } + /** + * + * @param id + */ getLeft(id) { return this.getChildAt(id, exports.TokenField.L) == null ? null : this.fieldTokens(id, exports.TokenField.L); } + /** + * + * @param id + * @param rightId + */ setRight(id, ...rightId) { // inlined: this.setField(id, TokenField.R, ...(rightId == null || rightId[0] == null ? [] : (rightId as number[]))) - this.setTokenList(this.fieldList(id, exports.TokenField.R), (rightId == null || rightId[0] == null ? [] : rightId)); + this.setTokenList(this.fieldList(id, exports.TokenField.R), rightId == null || rightId[0] == null ? [] : rightId); } + /** + * + * @param id + */ getRight(id) { return this.getChildAt(id, exports.TokenField.R) == null ? null : this.fieldTokens(id, exports.TokenField.R); } + /** + * + * @param id + * @param opId + */ setOp(id, opId) { // inlined: this.setField(id, TokenField.Op, opId) this.setTokenList(this.fieldList(id, exports.TokenField.Op), [opId]); } + /** + * + * @param id + */ getOp(id) { return this.field(id, exports.TokenField.Op); } + /** + * + * @param id + * @param op2Id + */ setOp2(id, op2Id) { // inlined: this.setField(id, TokenField.Op2, op2Id) this.setTokenList(this.fieldList(id, exports.TokenField.Op2), [op2Id]); } + /** + * + * @param id + */ getOp2(id) { return this.field(id, exports.TokenField.Op2); } - // ---- spans --------------------------------------------------------------------- + /** + * + * @param id + * @param sourceId + * @param start + * @param end + */ setSpan(id, sourceId, start, end) { if (littleEndian) { const index = id << 1; @@ -26682,12 +28596,20 @@ this.spans32[t] = this.spans32[s]; this.spans32[t + 1] = this.spans32[s + 1]; } + /** + * + * @param id + */ getSourceId(id) { if (littleEndian) { return this.spans32[(id << 1) + 1] >>> 24; } return Number((this.spans[id] >> 56n) & 0xffn); } + /** + * + * @param id + */ getSpanStart(id) { if (littleEndian) { const index = id << 1; @@ -26695,21 +28617,44 @@ } return Number((this.spans[id] >> 28n) & 0xfffffffn); } + // ---- spans --------------------------------------------------------------------- + /** + * + * @param id + * @param start + */ setSpandStart(id, start) { this.setSpan(id, this.getSourceId(id), start, this.getSpanEnd(id)); } + /** + * + * @param id + */ getSpanEnd(id) { if (littleEndian) { return this.spans32[id << 1] & 0xfffffff; } return Number(this.spans[id] & 0xfffffffn); } + /** + * + * @param id + * @param end + */ setSpanEnd(id, end) { this.setSpan(id, this.getSourceId(id), this.getSpanStart(id), end); } + /** + * + * @param id + */ getParent(id) { return this.parents[id]; } + /** + * + * @param id + */ resolveString(id) { return this.strings[id]; } @@ -26718,28 +28663,28 @@ * @param id */ detach(id) { - if (id == 0 || this.parents[id] == 0) { + if (id === 0 || this.parents[id] === 0) { return; } const parent = this.parents[id]; const next = this.nextSibling[id]; const previous = this.previousSibling[id]; - if (previous != 0) { + if (previous !== 0) { this.nextSibling[previous] = next; } - else if (this.firstChild[parent] == id) { + else if (this.firstChild[parent] === id) { this.firstChild[parent] = next; } - else if (this.firstToken[parent] == id) { + else if (this.firstToken[parent] === id) { this.firstToken[parent] = next; } - if (next != 0) { + if (next !== 0) { this.previousSibling[next] = previous; } - else if (this.lastChild[parent] == id) { + else if (this.lastChild[parent] === id) { this.lastChild[parent] = previous; } - else if (this.lastToken[parent] == id) { + else if (this.lastToken[parent] === id) { this.lastToken[parent] = previous; } this.nextSibling[id] = 0; @@ -26839,16 +28784,16 @@ // the children, in reverse order const first = top; let token = this.firstToken[value]; - while (token != 0) { + while (token !== 0) { stack[top++] = token; token = this.nextSibling[token]; } - if ((this.flags[value] & exports.EnumAstNodeStatus.HasChildren) == 0) { + if ((this.flags[value] & exports.EnumAstNodeStatus.HasChildren) === 0) { let child = this.firstChild[value]; - while (child != 0) { - if (this.dataTypes[child] == exports.EnumToken.ListTokenType) { + while (child !== 0) { + if (this.dataTypes[child] === exports.EnumToken.ListTokenType) { token = this.firstToken[child]; - while (token != 0) { + while (token !== 0) { stack[top++] = token; token = this.nextSibling[token]; } @@ -26877,7 +28822,7 @@ */ getValueParent(id) { const parent = this.parents[id]; - return parent != 0 && this.dataTypes[parent] == exports.EnumToken.ListTokenType ? this.parents[parent] : parent; + return parent !== 0 && this.dataTypes[parent] === exports.EnumToken.ListTokenType ? this.parents[parent] : parent; } /** * node that owns a value token: the declaration, the rule or the at-rule. 0 when the token is detached @@ -26885,7 +28830,8 @@ */ getValueOwner(id) { let parent = this.parents[id]; - while (parent != 0 && (this.flags[parent] & (exports.EnumAstNodeStatus.HasChildren | exports.EnumAstNodeStatus.HasValues)) == 0) { + while (parent !== 0 && + (this.flags[parent] & (exports.EnumAstNodeStatus.HasChildren | exports.EnumAstNodeStatus.HasValues)) === 0) { parent = this.parents[parent]; } return parent; @@ -26972,7 +28918,7 @@ const walker = new NodeWalker(this, node); for (let r = walker.next(); !r.done; r = walker.next()) { const current = r.value; - if (this.firstToken[current] == 0) { + if (this.firstToken[current] === 0) { continue; } const values = new ValueWalker(this, this.tokens(current)); @@ -26994,10 +28940,10 @@ * @returns the token id or null */ findValue(node, matcher) { - if (node == null || node == 0) { + if (node == null || node === 0) { return null; } - if ((this.flags[node] & (exports.EnumAstNodeStatus.HasChildren | exports.EnumAstNodeStatus.HasValues)) == 0) { + if ((this.flags[node] & (exports.EnumAstNodeStatus.HasChildren | exports.EnumAstNodeStatus.HasValues)) === 0) { // token: the token itself is tested first if (matcher(this, node)) { return node; @@ -27021,7 +28967,7 @@ subTokens(id) { const result = []; let token = this.firstToken[id]; - while (token != 0) { + while (token !== 0) { result.push(token); token = this.nextSibling[token]; } @@ -27030,10 +28976,10 @@ return result; } let child = this.firstChild[id]; - while (child != 0) { - if (this.dataTypes[child] == exports.EnumToken.ListTokenType) { + while (child !== 0) { + if (this.dataTypes[child] === exports.EnumToken.ListTokenType) { token = this.firstToken[child]; - while (token != 0) { + while (token !== 0) { result.push(token); token = this.nextSibling[token]; } @@ -27045,9 +28991,14 @@ } return result; } + /** + * + * @param id + * @param predicate + */ findChild(id, predicate) { let child = this.firstChild[id]; - while (child != 0) { + while (child !== 0) { if (predicate(child)) { return child; } @@ -27062,7 +29013,7 @@ */ findToken(id, predicate) { let token = this.firstToken[id]; - while (token != 0) { + while (token !== 0) { if (predicate(this, token)) { return token; } @@ -27078,7 +29029,7 @@ siblings(id, filter) { let siblings = []; let child = this.firstChild[this.parents[id]]; - while (child != 0) { + while (child !== 0) { if (filter == null || filter(this, child)) { siblings.push(child); } @@ -27094,7 +29045,7 @@ children(id, filter) { let children = []; let child = this.firstChild[id]; - while (child != 0) { + while (child !== 0) { if (filter != null && !filter(this, child)) { child = this.nextSibling[child]; continue; @@ -27112,7 +29063,7 @@ tokens(id, filter) { let tokens = []; let token = this.firstToken[id]; - while (token != 0) { + while (token !== 0) { if (filter != null && !filter(this, token)) { token = this.nextSibling[token]; continue; @@ -27129,12 +29080,17 @@ tokenCount(id) { let count = 0; let token = this.firstToken[id]; - while (token != 0) { + while (token !== 0) { count++; token = this.nextSibling[token]; } return count; } + /** + * + * @param id + * @param children + */ setChildren(id, ...children) { this.setChildList(id, children); } @@ -27145,7 +29101,7 @@ */ setChildList(id, children) { let child = this.firstChild[id]; - while (child != 0) { + while (child !== 0) { const next = this.nextSibling[child]; this.nextSibling[child] = 0; this.previousSibling[child] = 0; @@ -27156,6 +29112,11 @@ this.lastChild[id] = 0; this.appendChildList(id, children); } + /** + * + * @param id + * @param children + */ setTokens(id, ...children) { this.setTokenList(id, children); } @@ -27166,7 +29127,7 @@ */ setTokenList(id, tokens) { let token = this.firstToken[id]; - while (token != 0) { + while (token !== 0) { const next = this.nextSibling[token]; this.nextSibling[token] = 0; this.previousSibling[token] = 0; @@ -27184,14 +29145,14 @@ * @param before the children are inserted before this child of `to`. they are appended when 0 */ moveChildren(from, to, before = 0) { - if (from == to) { + if (from === to) { return; } let child = this.firstChild[from]; - while (child != 0) { + while (child !== 0) { const next = this.nextSibling[child]; this.detach(child); - if (before == 0) { + if (before === 0) { this.appendChild(to, child); } else { @@ -27200,6 +29161,11 @@ child = next; } } + /** + * + * @param id + * @param children + */ appendChildren(id, ...children) { this.appendChildList(id, children); } @@ -27209,19 +29175,19 @@ * @param children */ appendChildList(id, children) { - if (children.length == 0) { + if (children.length === 0) { return; } let lastChild; for (let i = 0; i < children.length; i++) { const child = children[i]; - if (child == id || child == 0) { + if (child === id || child === 0) { continue; } // the child may already be the last child: detach before reading the last child this.detach(child); lastChild = this.lastChild[id]; - if (lastChild == 0) { + if (lastChild === 0) { this.firstChild[id] = child; } else { @@ -27233,6 +29199,11 @@ this.lastChild[id] = child; } } + /** + * + * @param id + * @param children + */ appendTokens(id, ...children) { this.appendTokenList(id, children); } @@ -27242,19 +29213,19 @@ * @param children */ appendTokenList(id, children) { - if (children.length == 0) { + if (children.length === 0) { return; } let lastToken; for (let i = 0; i < children.length; i++) { const token = children[i]; - if (token == id || token == 0) { + if (token === id || token === 0) { continue; } // the token may already be the last token: detach before reading the last token this.detach(token); lastToken = this.lastToken[id]; - if (lastToken == 0) { + if (lastToken === 0) { this.firstToken[id] = token; } else { @@ -27272,14 +29243,14 @@ * @param child */ appendChild(id, child) { - if (child == id || child == 0) { + if (child === id || child === 0) { return; } - if (this.parents[child] != 0) { + if (this.parents[child] !== 0) { this.detach(child); } const lastChild = this.lastChild[id]; - if (lastChild == 0) { + if (lastChild === 0) { this.firstChild[id] = child; } else { @@ -27296,14 +29267,14 @@ * @param token */ appendToken(id, token) { - if (token == id || token == 0) { + if (token === id || token === 0) { return; } - if (this.parents[token] != 0) { + if (this.parents[token] !== 0) { this.detach(token); } const lastToken = this.lastToken[id]; - if (lastToken == 0) { + if (lastToken === 0) { this.firstToken[id] = token; } else { @@ -27321,33 +29292,45 @@ */ prependTokens(id, ...tokens) { const first = this.firstToken[id]; - if (first == 0) { + if (first === 0) { this.appendTokenList(id, tokens); return; } for (const token of tokens) { - if (token == id || token == 0) { + if (token === id || token === 0) { continue; } this.setPreviousSibling(first, token); } } + /** + * + * @param node + * @param key + * @param string + */ equalsIgnoreCase(node, key, string) { - const id = key == "nam" ? this.name[node] : this.stringValue[node]; + const id = key === "nam" ? this.name[node] : this.stringValue[node]; const stringId = this.stringIds.get(string); - if (stringId != null && id == stringId) { + if (stringId != null && id === stringId) { return true; } const value = this.strings[id]; - if (value == null || string.length != value.length) { + if (value == null || string.length !== value.length) { return false; } return equalsIgnoreCase(value, string); } + /** + * + * @param node + * @param key + * @param string + */ startsWith(node, key, string) { - const id = key == "nam" ? this.name[node] : this.stringValue[node]; + const id = key === "nam" ? this.name[node] : this.stringValue[node]; const stringId = this.stringIds.get(string); - if (stringId != null && id == stringId) { + if (stringId != null && id === stringId) { return true; } const value = this.strings[id]; @@ -27356,6 +29339,10 @@ } return value.startsWith(string); } + /** + * + * @param newSize + */ resize(newSize) { if (newSize <= this.dataTypes.length) { return; @@ -27363,6 +29350,7 @@ const newDataTypes = new Uint8Array(newSize); newDataTypes.set(this.dataTypes); this.dataTypes = newDataTypes; + this.capacity = newSize; const newParents = new Uint32Array(newSize); newParents.set(this.parents); this.parents = newParents; @@ -27424,7 +29412,7 @@ for (let i = 0; i < used.length; i++) { count += used[i]; } - if (count == this.strings.length) { + if (count === this.strings.length) { return; } // remap the string ids @@ -27466,10 +29454,10 @@ const id = stack.pop(); order[next] = id; mapping[id] = next++; - for (let child = this.lastChild[id]; child != 0; child = this.previousSibling[child]) { + for (let child = this.lastChild[id]; child !== 0; child = this.previousSibling[child]) { stack.push(child); } - for (let token = this.lastToken[id]; token != 0; token = this.previousSibling[token]) { + for (let token = this.lastToken[id]; token !== 0; token = this.previousSibling[token]) { stack.push(token); } } @@ -27543,18 +29531,19 @@ this.stringIds = stringIds; } for (const [id, list] of this.errors) { - if (mapping[id] != 0) { + if (mapping[id] !== 0) { nodeErrors.set(mapping[id], list); } } if (errors != null) { for (const error of errors) { - if (typeof error.node == "number") { + if (typeof error.node === "number") { error.node = mapping[error.node] || null; } } } this.dataTypes = dataTypes; + this.capacity = dataTypes.length; this.parents = parents; this.nextSibling = nextSibling; this.previousSibling = previousSibling; @@ -27582,7 +29571,7 @@ */ mark(...ids) { for (const id of ids) { - if (id != 0 && id != this.root) { + if (id !== 0 && id !== this.root) { this.flags[id] |= exports.EnumAstNodeStatus.Marked; } } @@ -27592,7 +29581,7 @@ * @param id */ isMarked(id) { - return (this.flags[id] & exports.EnumAstNodeStatus.Marked) != 0; + return (this.flags[id] & exports.EnumAstNodeStatus.Marked) !== 0; } /** * release nodes: detach them and drop their data (interned strings, errors). node ids are never reused: @@ -27610,18 +29599,18 @@ } return; } - if (id == 0 || id == this.root) { + if (id === 0 || id === this.root) { return; } if (deep) { let child = this.firstChild[id]; - while (child != 0) { + while (child !== 0) { const next = this.nextSibling[child]; this.release(child, true); child = next; } let token = this.firstToken[id]; - while (token != 0) { + while (token !== 0) { const next = this.nextSibling[token]; this.release(token, true); token = next; @@ -27643,15 +29632,24 @@ this.release(); return this.compact(errors); } + /** + * + * @param id + * @param errors + */ setErrors(id, errors) { // empty error lists are not stored - if (errors == null || errors.length == 0) { + if (errors == null || errors.length === 0) { this.errors.delete(id); } else { this.errors.set(id, errors); } } + /** + * + * @param id + */ getErrors(id) { return this.errors.get(id) ?? null; } @@ -27662,12 +29660,78 @@ childCount(id) { let count = 0; let child = this.firstChild[id]; - while (child != 0) { + while (child !== 0) { count++; child = this.nextSibling[child]; } return count; } + /** + * structured-cloneable properties of the arena + */ + exportProperties() { + return { + kind: "Arena", + current: this.current, + strings: this.strings, + errors: [...this.errors.entries()], + }; + } + /** + * column buffers, in the order of {@link arenaColumns}. the `spans` buffer is shared with the `spans32` view + */ + exportTransferables() { + const buffers = []; + for (const column of arenaColumns) { + const array = this[column]; + // the columns always own their buffer: no offset or partial view + buffers.push(array.buffer); + } + return buffers; + } + /** + * initialize the arena from exported properties and column buffers + * @param properties + * @param transferables + */ + importProperties(properties, transferables) { + if (transferables.length !== arenaColumns.length) { + throw new TypeError(`expected ${arenaColumns.length} column buffers, got ${transferables.length}`); + } + for (let i = 0; i < arenaColumns.length; i++) { + const column = arenaColumns[i]; + // @ts-ignore + this[column] = new arenaColumnTypes[column](transferables[i]); + } + this.spans32 = new Uint32Array(this.spans.buffer); + this.capacity = this.dataTypes.length; + this.current = properties.current; + this.strings = properties.strings.slice(); + this.stringIds = new Map(this.strings.map((str, index) => [str, index])); + this.errors = new Map(properties.errors); + } + /** + * link a node before a reference node of the given parent + * @param parent + * @param reference + * @param node + */ + #insertBefore(parent, reference, node) { + const previous = this.previousSibling[reference]; + this.previousSibling[node] = previous; + this.nextSibling[node] = reference; + this.previousSibling[reference] = node; + this.parents[node] = parent; + if (previous !== 0) { + this.nextSibling[previous] = node; + } + else if (this.firstChild[parent] === reference) { + this.firstChild[parent] = node; + } + else if (this.firstToken[parent] === reference) { + this.firstToken[parent] = node; + } + } } /** * Css ast arena: ast nodes and value tokens. @@ -27688,33 +29752,16 @@ * source ids. `spans` store the index in this table (8 bits) */ sources = []; + /** + * + * @param size + */ constructor(size = 4096) { super(size); // string id 0 is the null / empty string this.internString(""); this.flags[this.root] = exports.EnumAstNodeStatus.HasChildren; } - /** - * @inheritDoc - */ - exportProperties() { - return { - ...super.exportProperties(), - kind: "AstArena", - sources: this.sources, - raw: this.raw, - optimized: this.optimized, - }; - } - /** - * @inheritDoc - */ - importProperties(properties, transferables) { - super.importProperties(properties, transferables); - this.sources = properties.sources?.slice() ?? []; - this.raw = properties.raw?.slice() ?? []; - this.optimized = properties.optimized?.slice() ?? []; - } /** * @inheritDoc */ @@ -27740,7 +29787,6 @@ this.optimized = []; return mapping; } - // ---- state --------------------------------------------------------------------- /** * validation state bits * @param id @@ -27756,21 +29802,21 @@ setState(id, state) { this.flags[id] = (this.flags[id] & ~exports.EnumAstNodeStatus.StateMask) | ((state ?? 0) & exports.EnumAstNodeStatus.StateMask); } + // ---- state --------------------------------------------------------------------- /** * true if the node is invalid * @param id */ isInvalid(id) { - return (this.flags[id] & exports.EnumAstNodeStatus.Invalid) != 0; + return (this.flags[id] & exports.EnumAstNodeStatus.Invalid) !== 0; } - // ---- location ------------------------------------------------------------------ /** * index of a source id in the sources table * @param srcId */ sourceIndex(srcId) { let index = this.sources.indexOf(srcId); - if (index == -1) { + if (index === -1) { index = this.sources.length; this.sources.push(srcId); } @@ -27793,6 +29839,7 @@ this.flags[id] |= exports.EnumAstNodeStatus.HasLocation; this.setSpan(id, this.sourceIndex(srcId ?? 0), sta ?? 0, end ?? 0); } + // ---- location ------------------------------------------------------------------ /** * set the location of a token from the tokenizer values. the source index is the index of the source id in the sources table * @param id @@ -27821,7 +29868,7 @@ * @param end */ spanLocation(id, start, end) { - if ((this.flags[start] & exports.EnumAstNodeStatus.HasLocation) == 0) { + if ((this.flags[start] & exports.EnumAstNodeStatus.HasLocation) === 0) { this.copyLocation(id, end); return; } @@ -27833,14 +29880,14 @@ * @param id */ hasLocation(id) { - return (this.flags[id] & exports.EnumAstNodeStatus.HasLocation) != 0; + return (this.flags[id] & exports.EnumAstNodeStatus.HasLocation) !== 0; } /** * source location * @param id */ getLocation(id) { - if ((this.flags[id] & exports.EnumAstNodeStatus.HasLocation) == 0) { + if ((this.flags[id] & exports.EnumAstNodeStatus.HasLocation) === 0) { return null; } return { @@ -27856,7 +29903,6 @@ getSource(id) { return this.sources[this.getSourceId(id)] ?? 0; } - // ---- ast nodes ------------------------------------------------------------------- /** * allocate a stylesheet node */ @@ -27887,6 +29933,7 @@ } return id; } + // ---- ast nodes ------------------------------------------------------------------- /** * allocate an at-rule node * @param typ @@ -27944,7 +29991,6 @@ this.flags[id] = 0; return id; } - // ---- tokens ---------------------------------------------------------------------- /** * allocate a token. string values are interned, numeric values are stored in the `numericValue` column * @param typ @@ -27954,10 +30000,10 @@ createToken(typ, val, unit) { const id = this.allocate(); this.dataTypes[id] = typ; - if (typeof val == "string") { + if (typeof val === "string") { this.stringValue[id] = this.internString(val); } - else if (typeof val == "number") { + else if (typeof val === "number") { this.numericValue[id] = val; } if (unit != null) { @@ -27982,6 +30028,7 @@ } return id; } + // ---- tokens ---------------------------------------------------------------------- /** * allocate a function token * @param typ function token type @@ -28044,7 +30091,7 @@ */ hasFraction(id) { const child = this.firstChild[id]; - return child != 0 && this.dataTypes[child] == exports.EnumToken.FractionTokenType; + return child !== 0 && this.dataTypes[child] === exports.EnumToken.FractionTokenType; } /** * fraction token of a numeric token @@ -28052,7 +30099,7 @@ */ getFraction(id) { const child = this.firstChild[id]; - return child != 0 && this.dataTypes[child] == exports.EnumToken.FractionTokenType ? child : 0; + return child !== 0 && this.dataTypes[child] === exports.EnumToken.FractionTokenType ? child : 0; } /** * set the fraction value of a numeric token. the numeric value is set to the fraction value @@ -28061,10 +30108,10 @@ */ setFraction(id, fraction) { const child = this.getFraction(id); - if (child != 0) { + if (child !== 0) { this.detach(child); } - if (fraction != null && fraction != 0) { + if (fraction != null && fraction !== 0) { // inlined: this.appendChildren(id, fraction) this.appendChildList(id, [fraction]); this.numericValue[id] = @@ -28121,11 +30168,11 @@ * @param tokens */ replaceToken(id, ...tokens) { - if (this.parents[id] == 0) { + if (this.parents[id] === 0) { return; } const index = tokens.indexOf(id); - if (index == -1) { + if (index === -1) { this.insertBefore(id, ...tokens); this.detach(id); return; @@ -28139,7 +30186,7 @@ * @param token */ take(token) { - return this.parents[token] == 0 ? token : this.clone(token, true); + return this.parents[token] === 0 ? token : this.clone(token, true); } /** * copy the data columns of a token (type, values, unit, color type, location) @@ -28170,10 +30217,10 @@ this.unit[id] = 0; this.colorType[id] = 0; this.name[id] = 0; - if (typeof val == "string") { + if (typeof val === "string") { this.stringValue[id] = this.internString(val); } - else if (typeof val == "number") { + else if (typeof val === "number") { this.numericValue[id] = val; } if (unit != null) { @@ -28184,7 +30231,6 @@ // inlined: this.setChildren(id) this.setChildList(id, []); } - // ---- plain objects ----------------------------------------------------------------- /** * Import an object: an {@link AstArenaNode} or a plain object ({@link PlainAstNode}, {@link PlainToken}). * @@ -28206,169 +30252,6 @@ ? this.nodeFromObject(node) : this.tokenFromObject(node); } - /** - * create an ast node from a plain object - * @param node - */ - nodeFromObject(node) { - const id = this.allocate(); - const typ = node.typ; - this.dataTypes[id] = typ; - switch (typ) { - case exports.EnumToken.StyleSheetNodeType: - this.flags[id] = exports.EnumAstNodeStatus.HasChildren; - break; - case exports.EnumToken.RuleNodeType: - case exports.EnumToken.KeyframesRuleNodeType: - this.name[id] = this.internString((node.sel ?? node.nam ?? "")); - this.flags[id] = exports.EnumAstNodeStatus.HasChildren; - if (node.raw != null) { - this.raw[id] = node.raw; - } - if (node.optimized != null) { - this.optimized[id] = node.optimized; - } - if (typeof node.val == "string") { - this.stringValue[id] = this.internString(node.val); - } - break; - case exports.EnumToken.AtRuleNodeType: - case exports.EnumToken.KeyframesAtRuleNodeType: - this.name[id] = this.internString(node.nam ?? ""); - this.stringValue[id] = this.internString(node.val ?? ""); - this.flags[id] = node.chi != null ? exports.EnumAstNodeStatus.HasChildren : 0; - break; - case exports.EnumToken.CommentNodeType: - case exports.EnumToken.CDOCOMMNodeType: - this.stringValue[id] = this.internString(node.val ?? ""); - this.flags[id] = 0; - break; - default: - // declaration like nodes - this.name[id] = this.internString(node.nam ?? ""); - this.flags[id] = exports.EnumAstNodeStatus.HasValues; - if (Array.isArray(node.val)) { - for (const token of node.val) { - this.appendToken(id, typeof token == "number" ? token : this.fromObject(token)); - } - } - break; - } - if (Array.isArray(node.tokens)) { - for (const token of node.tokens) { - this.appendToken(id, typeof token == "number" ? token : this.fromObject(token)); - } - } - // inlined: this.setState(id, node.state) - this.flags[id] = (this.flags[id] & ~exports.EnumAstNodeStatus.StateMask) | ((node.state ?? 0) & exports.EnumAstNodeStatus.StateMask); - const loc = node.loc; - if (loc != null) { - this.setLocation(id, loc.srcId, loc.sta, loc.end); - } - const errors = node.errors; - if (errors != null && errors.length > 0) { - this.errors.set(id, errors); - } - if (Array.isArray(node.chi) && this.flags[id] & exports.EnumAstNodeStatus.HasChildren) { - for (const child of node.chi) { - // inlined: this.appendChildren(id, typeof child == "number" ? child : this.fromObject(child)) - this.appendChildList(id, [(typeof child == "number" ? child : this.fromObject(child))]); - } - } - return id; - } - /** - * create a token from a plain object - * @param token - */ - tokenFromObject(token) { - const id = this.allocate(); - const typ = token.typ; - const plain = token; - this.dataTypes[id] = typ; - if (typeof plain.nam == "string") { - this.name[id] = this.internString(plain.nam); - } - if (typeof plain.unit == "string") { - this.unit[id] = this.internString(plain.unit); - } - if (typeof plain.kin == "number") { - // inlined: this.setColorType(id, plain.kin) - this.colorType[id] = plain.kin; - } - if (typeof plain.cal == "string") { - this.unit[id] = this.internString(plain.cal); - } - if (typeof plain.attr == "string") { - this.unit[id] = this.internString(plain.attr); - } - if (typ == exports.EnumToken.BinaryExpressionTokenType) { - this.numericValue[id] = plain.op; - } - else if (typ == exports.EnumToken.UnaryExpressionTokenType) { - this.numericValue[id] = plain.sign; - // inlined: this.appendChildren(id, typeof plain.val == "number" ? plain.val : this.fromObject(plain.val)) - this.appendChildList(id, [(typeof plain.val == "number" ? plain.val : this.fromObject(plain.val))]); - } - else if (typ == exports.EnumToken.FractionTokenType) { - // inlined: this.appendChildren(id, typeof plain.l == "number" ? plain.l : this.fromObject(plain.l), typeof plain.r == "number" ? plain.r : this.fromObject(plain.r)) - this.appendChildList(id, [(typeof plain.l == "number" ? plain.l : this.fromObject(plain.l)), (typeof plain.r == "number" ? plain.r : this.fromObject(plain.r))]); - } - else if (typeof plain.val == "string") { - if (numericTokenTypes.has(typ)) { - // numeric value as a string - this.numericValue[id] = +plain.val; - } - else { - this.stringValue[id] = this.internString(plain.val); - } - } - else if (typeof plain.val == "number") { - this.numericValue[id] = plain.val; - } - else if (plain.val != null && typeof plain.val == "object" && !Array.isArray(plain.val)) { - // fraction value - this.setFraction(id, this.fromObject(plain.val)); - } - else if (Array.isArray(plain.val) && typ != exports.EnumToken.MediaRangeQueryTokenType) { - // declaration like tokens - for (const child of plain.val) { - this.appendToken(id, typeof child == "number" ? child : this.fromObject(child)); - } - } - if (Array.isArray(plain.chi)) { - for (const child of plain.chi) { - this.appendToken(id, typeof child == "number" ? child : this.fromObject(child)); - } - } - if (structuredTokenTypes.has(typ)) { - const fields = [ - ["l", exports.TokenField.L], - ["r", exports.TokenField.R], - ["op", exports.TokenField.Op], - ["op1", exports.TokenField.Op], - ["op2", exports.TokenField.Op2], - ["val", exports.TokenField.Val], - ]; - for (const [key, field] of fields) { - if (plain[key] == null) { - continue; - } - const values = Array.isArray(plain[key]) ? plain[key] : [plain[key]]; - const fieldTokens = []; - for (const value of values) { - fieldTokens.push(typeof value == "number" ? value : this.fromObject(value)); - } - // inlined: this.setField(id, field, ...fieldTokens) - this.setTokenList(this.fieldList(id, field), fieldTokens); - } - } - const loc = plain.loc; - if (loc != null) { - this.setLocation(id, loc.srcId, loc.sta, loc.end); - } - return id; - } /** * Object view of a node or a token: an {@link AstArenaNode}. The view does not copy the node: its properties read * and write the arena. Importing the view in this arena ({@link fromObject}, visitor results, setters of the @@ -28388,6 +30271,7 @@ toObject(id) { return new AstArenaNode(this, id); } + // ---- plain objects ----------------------------------------------------------------- /** * export a node or a token as a plain object (deep copy). `JSON.stringify()` of an {@link AstArenaNode} returns * the plain object @@ -28436,7 +30320,7 @@ if (flags & exports.EnumAstNodeStatus.StateMask) { node.state = flags & exports.EnumAstNodeStatus.StateMask; } - if ((flags & exports.EnumAstNodeStatus.HasValues) == 0 && this.firstToken[id] != 0) { + if ((flags & exports.EnumAstNodeStatus.HasValues) === 0 && this.firstToken[id] !== 0) { node.tokens = []; for (const token of this.tokens(id)) { node.tokens.push(this.tokenToObject(token)); @@ -28460,49 +30344,49 @@ tokenToObject(id) { const typ = this.dataTypes[id]; const token = { typ }; - if (this.name[id] != 0) { + if (this.name[id] !== 0) { token.nam = this.strings[this.name[id]]; } - if (typ == exports.EnumToken.BinaryExpressionTokenType) { + if (typ === exports.EnumToken.BinaryExpressionTokenType) { token.op = this.numericValue[id]; } - else if (typ == exports.EnumToken.UnaryExpressionTokenType) { + else if (typ === exports.EnumToken.UnaryExpressionTokenType) { token.sign = this.numericValue[id]; - token.val = this.firstChild[id] == 0 ? null : this.tokenToObject(this.firstChild[id]); + token.val = this.firstChild[id] === 0 ? null : this.tokenToObject(this.firstChild[id]); } - else if (typ == exports.EnumToken.FractionTokenType) { + else if (typ === exports.EnumToken.FractionTokenType) { token.l = this.tokenToObject(this.firstChild[id]); token.r = this.tokenToObject(this.lastChild[id]); } else if (numericTokenTypes.has(typ)) { const fraction = this.getFraction(id); - token.val = fraction == 0 ? this.numericValue[id] : this.tokenToObject(fraction); + token.val = fraction === 0 ? this.numericValue[id] : this.tokenToObject(fraction); } - else if (this.stringValue[id] != 0 || typ == exports.EnumToken.IdenTokenType || typ == exports.EnumToken.StringTokenType) { + else if (this.stringValue[id] !== 0 || typ === exports.EnumToken.IdenTokenType || typ === exports.EnumToken.StringTokenType) { token.val = this.strings[this.stringValue[id]]; } - if (this.unit[id] != 0) { - if (typ == exports.EnumToken.ColorTokenType) { + if (this.unit[id] !== 0) { + if (typ === exports.EnumToken.ColorTokenType) { token.cal = this.strings[this.unit[id]]; } - else if (typ == exports.EnumToken.MatchExpressionTokenType) { + else if (typ === exports.EnumToken.MatchExpressionTokenType) { token.attr = this.strings[this.unit[id]]; } else { token.unit = this.strings[this.unit[id]]; } } - if (typ == exports.EnumToken.ColorTokenType && this.colorType[id] != exports.ColorType.NONE) { + if (typ === exports.EnumToken.ColorTokenType && this.colorType[id] !== exports.ColorType.NONE) { token.kin = this.colorType[id]; } - if (this.firstToken[id] != 0) { + if (this.firstToken[id] !== 0) { const tokens = []; for (const child of this.tokens(id)) { tokens.push(this.tokenToObject(child)); } - if (typ == exports.EnumToken.DeclarationNodeType || - typ == exports.EnumToken.CssVariableTokenType || - typ == exports.EnumToken.CssVariableImportTokenType) { + if (typ === exports.EnumToken.DeclarationNodeType || + typ === exports.EnumToken.CssVariableTokenType || + typ === exports.EnumToken.CssVariableImportTokenType) { token.val = tokens; } else { @@ -28527,7 +30411,6 @@ } return token; } - // ---- clone / import ---------------------------------------------------------------- /** * clone a node or a token. tokens are always cloned deeply * @param id @@ -28555,18 +30438,18 @@ if (this.errors.size > 0 && this.errors.has(id)) { this.errors.set(target, this.errors.get(id)); } - const isNode = (flags & (exports.EnumAstNodeStatus.HasChildren | exports.EnumAstNodeStatus.HasValues)) != 0; + const isNode = (flags & (exports.EnumAstNodeStatus.HasChildren | exports.EnumAstNodeStatus.HasValues)) !== 0; // declaration values are cloned only when requested - if (!isNode || deep || (flags & exports.EnumAstNodeStatus.HasValues) == 0) { + if (!isNode || deep || (flags & exports.EnumAstNodeStatus.HasValues) === 0) { let token = this.firstToken[id]; - while (token != 0) { + while (token !== 0) { this.appendToken(target, this.clone(token, true, cloneMap)); token = this.nextSibling[token]; } } if (!isNode || deep) { let child = this.firstChild[id]; - while (child != 0) { + while (child !== 0) { this.appendChild(target, this.clone(child, true, cloneMap)); child = this.nextSibling[child]; } @@ -28606,20 +30489,19 @@ this.errors.set(target, source.errors.get(id)); } let token = source.firstToken[id]; - while (token != 0) { + while (token !== 0) { this.appendToken(target, this.import(source, token)); token = source.nextSibling[token]; } - if (deep || (flags & exports.EnumAstNodeStatus.HasChildren) == 0) { + if (deep || (flags & exports.EnumAstNodeStatus.HasChildren) === 0) { let child = source.firstChild[id]; - while (child != 0) { + while (child !== 0) { this.appendChild(target, this.import(source, child)); child = source.nextSibling[child]; } } return target; } - // ---- tree helpers -------------------------------------------------------------- /** * index of a child in its parent's children (or tokens) list * @param id @@ -28627,10 +30509,10 @@ indexOf(id) { let index = 0; let child = this.previousSibling[id]; - if (this.parents[id] == 0) { + if (this.parents[id] === 0) { return -1; } - while (child != 0) { + while (child !== 0) { index++; child = this.previousSibling[child]; } @@ -28643,12 +30525,13 @@ */ insertBefore(reference, ...nodes) { for (const node of nodes) { - if (node == reference || node == 0) { + if (node === reference || node === 0) { continue; } this.setPreviousSibling(reference, node); } } + // ---- clone / import ---------------------------------------------------------------- /** * insert nodes after a child * @param reference @@ -28656,7 +30539,7 @@ */ insertAfter(reference, ...nodes) { for (const node of nodes) { - if (node == reference || node == 0) { + if (node === reference || node === 0) { continue; } this.setNextSibling(reference, node); @@ -28670,24 +30553,25 @@ */ prependChildren(id, ...nodes) { const first = this.firstChild[id]; - if (first == 0) { + if (first === 0) { this.appendChildList(id, nodes); } else { this.insertBefore(first, ...nodes); } } + // ---- tree helpers -------------------------------------------------------------- /** * replace a child with other nodes. the node itself may be part of the replacement * @param id * @param nodes */ replaceChild(id, ...nodes) { - if (this.parents[id] == 0) { + if (this.parents[id] === 0) { return; } const index = nodes.indexOf(id); - if (index == -1) { + if (index === -1) { this.insertBefore(id, ...nodes); this.detach(id); return; @@ -28700,7 +30584,7 @@ * @param id */ hasChildren(id) { - return (this.flags[id] & exports.EnumAstNodeStatus.HasChildren) != 0; + return (this.flags[id] & exports.EnumAstNodeStatus.HasChildren) !== 0; } /** * rule selector @@ -28733,7 +30617,6 @@ setValueString(id, val) { this.stringValue[id] = this.internString(val); } - // ---- nesting rules expansion --------------------------------------------------------------- /** * Expand the css nesting rules of a stylesheet, a rule or an at-rule. The tree is expanded in place: the nested rules * are moved into the parent of their rule and their selectors are resolved @@ -28753,17 +30636,18 @@ return ast; } let node = this.firstChild[ast]; - while (node != 0) { + while (node !== 0) { const next = this.nextSibling[node]; const typ = this.dataTypes[node]; if (typ === exports.EnumToken.RuleNodeType) { // the expanded rules are inserted after the rule this.expandRule(node, ast, next); } - else if (typ == exports.EnumToken.AtRuleNodeType && this.flags[node] & exports.EnumAstNodeStatus.HasChildren) { + else if (typ === exports.EnumToken.AtRuleNodeType && this.flags[node] & exports.EnumAstNodeStatus.HasChildren) { let j = this.lastChild[node]; - while (j != 0) { - if (this.dataTypes[j] == exports.EnumToken.RuleNodeType || this.dataTypes[j] == exports.EnumToken.AtRuleNodeType) { + while (j !== 0) { + if (this.dataTypes[j] === exports.EnumToken.RuleNodeType || + this.dataTypes[j] === exports.EnumToken.AtRuleNodeType) { this.expand(node); break; } @@ -28774,6 +30658,216 @@ } return ast; } + /** + * replace the nesting selector '&' of a selector + * @internal + * @param input + * @param replace + */ + replaceCompound(input, replace) { + const tokens = parseString(this, input); + // inlined: this.walkValues(tokens) + for (const t of new ValueWalker(this, tokens)) { + if (this.dataTypes[t] === exports.EnumToken.NestingSelectorTokenType) { + if (tokens.length === 2) { + this.resetToken(t, exports.EnumToken.LiteralTokenType, this.replaceCompoundLiteral(this.strings[this.stringValue[t]], replace)); + continue; + } + const rule = splitRule(replace); + this.resetToken(t, exports.EnumToken.LiteralTokenType, rule.length > 1 ? ":is(" + replace + ")" : replace); + } + } + return tokens.reduce((acc, curr) => acc + renderValue(this, curr), ""); + } + /** + * @inheritDoc + */ + exportProperties() { + return { + ...super.exportProperties(), + kind: "AstArena", + sources: this.sources, + raw: this.raw, + optimized: this.optimized, + }; + } + /** + * @inheritDoc + */ + importProperties(properties, transferables) { + super.importProperties(properties, transferables); + this.sources = properties.sources?.slice() ?? []; + this.raw = properties.raw?.slice() ?? []; + this.optimized = properties.optimized?.slice() ?? []; + } + // ---- nesting rules expansion --------------------------------------------------------------- + /** + * create an ast node from a plain object + * @param node + */ + nodeFromObject(node) { + const id = this.allocate(); + const typ = node.typ; + this.dataTypes[id] = typ; + switch (typ) { + case exports.EnumToken.StyleSheetNodeType: + this.flags[id] = exports.EnumAstNodeStatus.HasChildren; + break; + case exports.EnumToken.RuleNodeType: + case exports.EnumToken.KeyframesRuleNodeType: + this.name[id] = this.internString((node.sel ?? node.nam ?? "")); + this.flags[id] = exports.EnumAstNodeStatus.HasChildren; + if (node.raw != null) { + this.raw[id] = node.raw; + } + if (node.optimized != null) { + this.optimized[id] = node.optimized; + } + if (typeof node.val === "string") { + this.stringValue[id] = this.internString(node.val); + } + break; + case exports.EnumToken.AtRuleNodeType: + case exports.EnumToken.KeyframesAtRuleNodeType: + this.name[id] = this.internString(node.nam ?? ""); + this.stringValue[id] = this.internString(node.val ?? ""); + this.flags[id] = node.chi != null ? exports.EnumAstNodeStatus.HasChildren : 0; + break; + case exports.EnumToken.CommentNodeType: + case exports.EnumToken.CDOCOMMNodeType: + this.stringValue[id] = this.internString(node.val ?? ""); + this.flags[id] = 0; + break; + default: + // declaration like nodes + this.name[id] = this.internString(node.nam ?? ""); + this.flags[id] = exports.EnumAstNodeStatus.HasValues; + if (Array.isArray(node.val)) { + for (const token of node.val) { + this.appendToken(id, typeof token === "number" ? token : this.fromObject(token)); + } + } + break; + } + if (Array.isArray(node.tokens)) { + for (const token of node.tokens) { + this.appendToken(id, typeof token === "number" ? token : this.fromObject(token)); + } + } + // inlined: this.setState(id, node.state) + this.flags[id] = + (this.flags[id] & ~exports.EnumAstNodeStatus.StateMask) | ((node.state ?? 0) & exports.EnumAstNodeStatus.StateMask); + const loc = node.loc; + if (loc != null) { + this.setLocation(id, loc.srcId, loc.sta, loc.end); + } + const errors = node.errors; + if (errors != null && errors.length > 0) { + this.errors.set(id, errors); + } + if (Array.isArray(node.chi) && this.flags[id] & exports.EnumAstNodeStatus.HasChildren) { + for (const child of node.chi) { + // inlined: this.appendChildren(id, typeof child == "number" ? child : this.fromObject(child)) + this.appendChildList(id, [typeof child === "number" ? child : this.fromObject(child)]); + } + } + return id; + } + /** + * create a token from a plain object + * @param token + */ + tokenFromObject(token) { + const id = this.allocate(); + const typ = token.typ; + const plain = token; + this.dataTypes[id] = typ; + if (typeof plain.nam === "string") { + this.name[id] = this.internString(plain.nam); + } + if (typeof plain.unit === "string") { + this.unit[id] = this.internString(plain.unit); + } + if (typeof plain.kin === "number") { + // inlined: this.setColorType(id, plain.kin) + this.colorType[id] = plain.kin; + } + if (typeof plain.cal === "string") { + this.unit[id] = this.internString(plain.cal); + } + if (typeof plain.attr === "string") { + this.unit[id] = this.internString(plain.attr); + } + if (typ === exports.EnumToken.BinaryExpressionTokenType) { + this.numericValue[id] = plain.op; + } + else if (typ === exports.EnumToken.UnaryExpressionTokenType) { + this.numericValue[id] = plain.sign; + // inlined: this.appendChildren(id, typeof plain.val == "number" ? plain.val : this.fromObject(plain.val)) + this.appendChildList(id, [typeof plain.val === "number" ? plain.val : this.fromObject(plain.val)]); + } + else if (typ === exports.EnumToken.FractionTokenType) { + // inlined: this.appendChildren(id, typeof plain.l == "number" ? plain.l : this.fromObject(plain.l), typeof plain.r == "number" ? plain.r : this.fromObject(plain.r)) + this.appendChildList(id, [ + typeof plain.l === "number" ? plain.l : this.fromObject(plain.l), + typeof plain.r === "number" ? plain.r : this.fromObject(plain.r), + ]); + } + else if (typeof plain.val === "string") { + if (numericTokenTypes.has(typ)) { + // numeric value as a string + this.numericValue[id] = +plain.val; + } + else { + this.stringValue[id] = this.internString(plain.val); + } + } + else if (typeof plain.val === "number") { + this.numericValue[id] = plain.val; + } + else if (plain.val != null && typeof plain.val === "object" && !Array.isArray(plain.val)) { + // fraction value + this.setFraction(id, this.fromObject(plain.val)); + } + else if (Array.isArray(plain.val) && typ !== exports.EnumToken.MediaRangeQueryTokenType) { + // declaration like tokens + for (const child of plain.val) { + this.appendToken(id, typeof child === "number" ? child : this.fromObject(child)); + } + } + if (Array.isArray(plain.chi)) { + for (const child of plain.chi) { + this.appendToken(id, typeof child === "number" ? child : this.fromObject(child)); + } + } + if (structuredTokenTypes.has(typ)) { + const fields = [ + ["l", exports.TokenField.L], + ["r", exports.TokenField.R], + ["op", exports.TokenField.Op], + ["op1", exports.TokenField.Op], + ["op2", exports.TokenField.Op2], + ["val", exports.TokenField.Val], + ]; + for (const [key, field] of fields) { + if (plain[key] == null) { + continue; + } + const values = Array.isArray(plain[key]) ? plain[key] : [plain[key]]; + const fieldTokens = []; + for (const value of values) { + fieldTokens.push(typeof value === "number" ? value : this.fromObject(value)); + } + // inlined: this.setField(id, field, ...fieldTokens) + this.setTokenList(this.fieldList(id, field), fieldTokens); + } + } + const loc = plain.loc; + if (loc != null) { + this.setLocation(id, loc.srcId, loc.sta, loc.end); + } + return id; + } /** * expand a rule: the nested rules and at-rules are moved out of the rule, into `parent` before `before`. * the rule is detached when it has no children left @@ -28788,28 +30882,28 @@ const ast = node; const sel = this.strings[this.name[ast]]; const place = (child) => { - if (before == 0) { + if (before === 0) { this.appendChild(parent, child); } else { this.insertBefore(before, child); } }; - if (this.dataTypes[ast] == exports.EnumToken.RuleNodeType) { + if (this.dataTypes[ast] === exports.EnumToken.RuleNodeType) { let child = this.firstChild[ast]; - while (child != 0) { + while (child !== 0) { const next = this.nextSibling[child]; const typ = this.dataTypes[child]; - if (typ == exports.EnumToken.RuleNodeType) { + if (typ === exports.EnumToken.RuleNodeType) { const rule = child; const ruleSel = this.strings[this.name[rule]]; if (!ruleSel.includes("&")) { const selRule = splitRule(ruleSel); const arSelf = splitRule(sel) - .filter((r) => r.every((t) => t != ":before" && t != ":after" && !t.startsWith("::"))) + .filter((r) => r.every((t) => t !== ":before" && t !== ":after" && !t.startsWith("::"))) .reduce((acc, curr) => acc.concat([curr.join("")]), []) .join(","); - if (arSelf.length == 0) { + if (arSelf.length === 0) { this.detach(rule); child = next; continue; @@ -28832,9 +30926,9 @@ let withoutCompound = []; // pseudo elements cannot be used with '&' // https://www.w3.org/TR/css-nesting-1/#example-7145ff1e - const rules = splitRule(sel).filter((r) => r.every((t) => t != ":before" && t != ":after" && !t.startsWith("::"))); + const rules = splitRule(sel).filter((r) => r.every((t) => t !== ":before" && t !== ":after" && !t.startsWith("::"))); const parentSelector = !sel.includes("&"); - if (rules.length == 0) { + if (rules.length === 0) { this.detach(rule); child = next; continue; @@ -28842,13 +30936,13 @@ for (const sel of this.raw[rule] ?? splitRule(ruleSel)) { const s = sel.join(""); if (s.includes("&") || parentSelector) { - if (s.indexOf("&", 1) == -1) { - if (s.at(0) == "&") { - if (s.at(1) == " ") { + if (s.indexOf("&", 1) === -1) { + if (s.at(0) === "&") { + if (s.at(1) === " ") { childSelectorCompound.push(s.slice(2)); } else { - if (s == "&" || parentSelector) { + if (s === "&" || parentSelector) { withCompound.push(s); } } @@ -28863,9 +30957,11 @@ } } const selectors = []; - const selector = rules.length > 1 ? ":is(" + rules.map((a) => a.join("")).join(",") + ")" : rules[0].join(""); + const selector = rules.length > 1 + ? ":is(" + rules.map((a) => a.join("")).join(",") + ")" + : rules[0].join(""); if (childSelectorCompound.length > 0) { - if (childSelectorCompound.length == 1) { + if (childSelectorCompound.length === 1) { selectors.push(this.replaceCompound("& " + childSelectorCompound[0].trim(), selector)); } else { @@ -28875,20 +30971,20 @@ } } if (withCompound.length > 0) { - if (withCompound.every((t) => t[0] == "&" && t.indexOf("&", 1) == -1)) { + if (withCompound.every((t) => t[0] === "&" && t.indexOf("&", 1) === -1)) { withoutCompound.push(...withCompound.map((t) => t.slice(1))); withCompound.length = 0; } } if (withoutCompound.length > 0) { - if (withoutCompound.length == 1) { - const useIs = rules.length == 1 && + if (withoutCompound.length === 1) { + const useIs = rules.length === 1 && selector.match(/^[a-zA-Z.:]/) != null && selector.includes(" ") && - withoutCompound.length == 1 && + withoutCompound.length === 1 && withoutCompound[0].match(/^[a-zA-Z]+$/) != null; const compound = useIs ? ":is(&)" : "&"; - selectors.push(this.replaceCompound(rules.length == 1 + selectors.push(this.replaceCompound(rules.length === 1 ? useIs ? withoutCompound[0] + ":is(&)" : selector.match(/^[.:]/) && withoutCompound[0].match(/^[a-zA-Z]+$/) @@ -28908,17 +31004,17 @@ } } if (withCompound.length > 0) { - if (withCompound.length == 1) { + if (withCompound.length === 1) { selectors.push(this.replaceCompound(withCompound[0], selector)); } } // inlined: this.setSelector(rule, selectors.reduce((acc, curr) => (curr.length == 0 ? acc : acc + (acc.length > 0 ? "," : "") + curr), "")) - this.name[rule] = this.internString(selectors.reduce((acc, curr) => (curr.length == 0 ? acc : acc + (acc.length > 0 ? "," : "") + curr), "")); + this.name[rule] = this.internString(selectors.reduce((acc, curr) => (curr.length === 0 ? acc : acc + (acc.length > 0 ? "," : "") + curr), "")); } place(rule); this.expandRule(rule, parent, before); } - else if (typ == exports.EnumToken.AtRuleNodeType) { + else if (typ === exports.EnumToken.AtRuleNodeType) { const astAtRule = child; const atRuleName = this.strings[this.name[astAtRule]]; if (atRuleName === "scope") { @@ -28928,8 +31024,8 @@ this.stringValue[astAtRule] = this.internString(this.replaceCompound(atRuleValue, sel)); } let hasNesting = false; - for (let t = this.firstChild[astAtRule]; t != 0; t = this.nextSibling[t]) { - if (this.dataTypes[t] == exports.EnumToken.RuleNodeType && + for (let t = this.firstChild[astAtRule]; t !== 0; t = this.nextSibling[t]) { + if (this.dataTypes[t] === exports.EnumToken.RuleNodeType && this.strings[this.name[t]].includes("&")) { hasNesting = true; break; @@ -28950,9 +31046,9 @@ // the rules are expanded inside the at-rule: [clone, ...expanded nodes] this.moveChildren(astAtRule, clone); this.expandRule(clone, astAtRule, 0); - if (this.firstChild[clone] != 0) { + if (this.firstChild[clone] !== 0) { // the rule declarations are wrapped in the clone, before the expanded nodes - if (this.firstChild[astAtRule] == 0) { + if (this.firstChild[astAtRule] === 0) { this.appendChild(astAtRule, clone); } else { @@ -28962,9 +31058,9 @@ place(astAtRule); // the expanded at-rules are moved after the at-rule let r = this.firstChild[astAtRule]; - while (r != 0) { + while (r !== 0) { const nextRule = this.nextSibling[r]; - if (this.dataTypes[r] == exports.EnumToken.AtRuleNodeType) { + if (this.dataTypes[r] === exports.EnumToken.AtRuleNodeType) { if (this.flags[r] & exports.EnumAstNodeStatus.HasChildren) { const val = this.strings[this.stringValue[astAtRule]]; const rVal = this.strings[this.stringValue[r]]; @@ -28972,11 +31068,11 @@ const rName = this.strings[this.name[r]]; if (atRuleName === "media" && rName === "media") { // inlined: this.setValueString(r, val + " and " + rVal) - this.stringValue[r] = this.internString((val + " and " + rVal)); + this.stringValue[r] = this.internString(val + " and " + rVal); } - else if (atRuleName == "layer" && rName == "layer") { + else if (atRuleName === "layer" && rName === "layer") { // inlined: this.setValueString(r, val + "." + rVal) - this.stringValue[r] = this.internString((val + "." + rVal)); + this.stringValue[r] = this.internString(val + "." + rVal); } } place(r); @@ -28988,54 +31084,39 @@ r = nextRule; } } - if (this.firstChild[astAtRule] == 0) { + if (this.firstChild[astAtRule] === 0) { this.detach(astAtRule); } } child = next; } } - if (this.firstChild[ast] == 0) { + if (this.firstChild[ast] === 0) { this.detach(ast); } } /** - * replace the nesting selector '&' of a selector - * @internal - * @param input + * + * @param selector * @param replace + * @protected */ - replaceCompound(input, replace) { - const tokens = parseString(this, input); - // inlined: this.walkValues(tokens) - for (const t of new ValueWalker(this, tokens)) { - if (this.dataTypes[t] == exports.EnumToken.NestingSelectorTokenType) { - if (tokens.length == 2) { - this.resetToken(t, exports.EnumToken.LiteralTokenType, this.replaceCompoundLiteral(this.strings[this.stringValue[t]], replace)); - continue; - } - const rule = splitRule(replace); - this.resetToken(t, exports.EnumToken.LiteralTokenType, rule.length > 1 ? ":is(" + replace + ")" : replace); - } - } - return tokens.reduce((acc, curr) => acc + renderValue(this, curr), ""); - } replaceCompoundLiteral(selector, replace) { const tokens = [""]; let i = 0; for (; i < selector.length; i++) { - if (selector.charAt(i) == "&") { + if (selector.charAt(i) === "&") { tokens.push("&", ""); } } return tokens .sort((a, b) => { - if (a == "&") { + if (a === "&") { return 1; } - return b == "&" ? -1 : 0; + return b === "&" ? -1 : 0; }) - .reduce((acc, curr) => acc + (curr == "&" ? replace : curr), ""); + .reduce((acc, curr) => acc + (curr === "&" ? replace : curr), ""); } } @@ -29096,13 +31177,11 @@ /** * Return the color space of the color + * @param arena * @param color * @returns */ function getColorSpace(arena, color) { - // if (!("chi" in color)) { - // return "rgb"; - // } let name; const components = getColorComponents(arena, color); if (components == null || components.length < 3) { @@ -29127,7 +31206,7 @@ else { name = arena.strings[arena.stringValue[color]]; } - return name == "device-cmyk" + return name === "device-cmyk" ? "cmyk" : name.startsWith("xyz") ? "xyz" @@ -29146,7 +31225,6 @@ const angleUnits = ["rad", "turn", "deg", "grad"]; const resolutionUnits = ["dpi", "dpcm", "dppx", "x"]; const dimensionUnits = [ - "Q", "cap", "ch", "cm", @@ -29171,16 +31249,23 @@ "lvh", "lvi", "lvmax", + "lvmin", "lvw", "mm", "pc", "pt", "px", + "Q", + "rcap", + "rch", "rem", + "rex", + "ric", "rlh", "svb", "svh", "svi", + "svmax", "svmin", "svw", "vb", @@ -29617,52 +31702,69 @@ // "-moz-windows-glass", // "-moz-alt-content", // ]); - // renamed standard properties - const renamedStandardProperties = new Map([["color-adjust", "print-color-adjust"]]); + // renamed standard properties: the legacy name aliases of webref that are not vendor prefixed (see scripts/webref.ts), + // updated manually. the vendor prefixed aliases are not renamed: they use the syntax of the standard property (alias) + const renamedStandardProperties = new Map([ + ["color-adjust", "print-color-adjust"], + ["font-stretch", "font-width"], + ["grid-column-gap", "column-gap"], + ["grid-gap", "gap"], + ["grid-row-gap", "row-gap"], + ["word-wrap", "overflow-wrap"], + ]); + /** + * the units of each dimension, lower case: the units are case-insensitive (`Q`, `Hz`, `kHz`) + */ + const lengthUnitSet = new Set(dimensionUnits.map((unit) => unit.toLowerCase())); + const resolutionUnitSet = new Set(resolutionUnits.map((unit) => unit.toLowerCase())); + const angleUnitSet = new Set(angleUnits.map((unit) => unit.toLowerCase())); + const timeUnitSet = new Set(timeUnits.map((unit) => unit.toLowerCase())); + const frequencyUnitSet = new Set(frequencyUnits.map((unit) => unit.toLowerCase())); + const flexUnitSet = new Set(flexUnits.map((unit) => unit.toLowerCase())); /** * true if the unit is a length unit * @param unit */ function isLengthUnit(unit) { - return dimensionUnits.includes(unit.toLowerCase()); + return lengthUnitSet.has(unit.toLowerCase()); } /** * true if the unit is a resolution unit * @param unit */ function isResolutionUnit(unit) { - return resolutionUnits.includes(unit.toLowerCase()); + return resolutionUnitSet.has(unit.toLowerCase()); } /** * true if the unit is an angle unit * @param unit */ function isAngleUnit(unit) { - return angleUnits.includes(unit.toLowerCase()); + return angleUnitSet.has(unit.toLowerCase()); } /** * true if the unit is a time unit * @param unit */ function isTimeUnit(unit) { - return timeUnits.includes(unit.toLowerCase()); + return timeUnitSet.has(unit.toLowerCase()); } /** * true if the unit is a frequency unit * @param unit */ function isFrequencyUnit(unit) { - return frequencyUnits.includes(unit.toLowerCase()); + return frequencyUnitSet.has(unit.toLowerCase()); } /** * true if the unit is a flex unit * @param unit */ function isFlexUnit(unit) { - return "fr" == unit.toLowerCase(); + return flexUnitSet.has(unit.toLowerCase()); } function isLength(arena, dimension) { - return arena.unit[dimension] != 0 && isLengthUnit(arena.strings[arena.unit[dimension]]); + return arena.unit[dimension] !== 0 && isLengthUnit(arena.strings[arena.unit[dimension]]); } /** * Reduce color stops @@ -29672,18 +31774,18 @@ */ function reduceColorStops(arena, stops) { const parts = splitTokenList(arena, stops); - const n = parts.length == 1 ? 1 : parts.length - 1; + const n = parts.length === 1 ? 1 : parts.length - 1; let j; let i; let k = -1; let updated = false; for (i = 0; i < parts.length; i++) { k++; - if (parts[i].length != 3) { + if (parts[i].length !== 3) { continue; } if (i > 0 && isOkLabClose(arena, parts[i - 1][0], parts[i][0])) { - if (parts[i - 1].length == 1) { + if (parts[i - 1].length === 1) { parts[i - 1].push(arena.createToken(exports.EnumToken.WhitespaceTokenType), arena.createToken(exports.EnumToken.PercentageTokenType, ((k - 1) * 100) / n)); } for (let m = 1; m < parts[i].length; m++) { @@ -29695,9 +31797,9 @@ } for (j = 0; j < parts[i].length; j++) { const typ = arena.dataTypes[parts[i][j]]; - if ((typ == exports.EnumToken.LengthTokenType && 0 == arena.numericValue[parts[i][j]]) || - typ == exports.EnumToken.NumberTokenType || - typ == exports.EnumToken.PercentageTokenType) { + if ((typ === exports.EnumToken.LengthTokenType && 0 === arena.numericValue[parts[i][j]]) || + typ === exports.EnumToken.NumberTokenType || + typ === exports.EnumToken.PercentageTokenType) { if (arena.numericValue[parts[i][j]] === (k * 100) / n) { parts[i].length = j; trimArray(arena, parts[i]); @@ -29793,18 +31895,18 @@ */ function reduceConicColorStops(arena, stops) { const parts = splitTokenList(arena, stops); - const n = parts.length == 1 ? 1 : parts.length - 1; + const n = parts.length === 1 ? 1 : parts.length - 1; let j; let i; let k = -1; let updated = false; for (i = 0; i < parts.length; i++) { k++; - if (parts[i].length != 3) { + if (parts[i].length !== 3) { continue; } if (i > 0 && isOkLabClose(arena, parts[i - 1][0], parts[i][0])) { - if (parts[i - 1].length == 1) { + if (parts[i - 1].length === 1) { parts[i - 1].push(arena.createToken(exports.EnumToken.WhitespaceTokenType), arena.createToken(exports.EnumToken.AngleTokenType, ((k - 1) * 100) / n, "deg")); } for (let m = 1; m < parts[i].length; m++) { @@ -29816,8 +31918,8 @@ } for (j = 0; j < parts[i].length; j++) { const typ = arena.dataTypes[parts[i][j]]; - if ((typ == exports.EnumToken.NumberTokenType && 0 == arena.numericValue[parts[i][j]]) || - typ == exports.EnumToken.AngleTokenType) { + if ((typ === exports.EnumToken.NumberTokenType && 0 === arena.numericValue[parts[i][j]]) || + typ === exports.EnumToken.AngleTokenType) { if (arena.numericValue[toDegrees(arena, parts[i][j])] === (k * 360) / n) { parts[i].length = j; trimArray(arena, parts[i]); @@ -29867,8 +31969,8 @@ * @returns */ function isIdentColor(arena, token) { - return (arena.dataTypes[token] == exports.EnumToken.ColorTokenType && - arena.colorType[token] != exports.ColorType.NONE && + return (arena.dataTypes[token] === exports.EnumToken.ColorTokenType && + arena.colorType[token] !== exports.ColorType.NONE && [exports.ColorType.SYS, exports.ColorType.DPSYS, exports.ColorType.LIT].includes(arena.colorType[token]) && isIdent(arena.strings[arena.stringValue[token]])); } @@ -29880,7 +31982,7 @@ */ function filterChildren(arena, token, types) { const children = []; - for (let t = arena.firstToken[token]; t != 0; t = arena.nextSibling[t]) { + for (let t = arena.firstToken[token]; t !== 0; t = arena.nextSibling[t]) { if (types.includes(arena.dataTypes[t])) { children.push(t); } @@ -29900,15 +32002,15 @@ ]; function isColor(arena, token, errors) { const typ = arena.dataTypes[token]; - if (typ == exports.EnumToken.WildCardFunctionTokenType) { + if (typ === exports.EnumToken.WildCardFunctionTokenType) { return true; } - if (typ == exports.EnumToken.ColorTokenType) { - if (arena.colorType[token] != exports.ColorType.NONE && arena.firstToken[token] == 0) { + if (typ === exports.EnumToken.ColorTokenType) { + if (arena.colorType[token] !== exports.ColorType.NONE && arena.firstToken[token] === 0) { return true; } } - if (typ == exports.EnumToken.IdenTokenType) { + if (typ === exports.EnumToken.IdenTokenType) { const val = lowercase(arena.strings[arena.stringValue[token]]); if (systemColors.has(val) || deprecatedSystemColors.has(val) || nonStandardColors.has(val)) { return true; @@ -29917,7 +32019,7 @@ return val in COLORS_NAMES || "currentcolor" === val || "transparent" === val; } if (typ === exports.EnumToken.FunctionTokenType || typ === exports.EnumToken.ColorTokenType) { - if (arena.firstToken[token] != 0) { + if (arena.firstToken[token] !== 0) { const name = arena.strings[arena.stringValue[token]]; if (name === "light-dark") { const children = filterChildren(arena, token, [ @@ -29929,7 +32031,7 @@ exports.EnumToken.PercentageTokenType, exports.EnumToken.WildCardFunctionTokenType, ]); - if (children.length != 2) { + if (children.length !== 2) { errors?.push({ message: "light-dark function must have 2 arguments", node: token, @@ -30007,7 +32109,7 @@ tl = arena.field(value, exports.TokenField.R); } else if (parent != null && - parent != token && + parent !== token && arena.dataTypes[parent] === exports.EnumToken.MathFunctionTokenType && arena.strings[arena.stringValue[parent]] === "calc") { const children = arena.tokens(parent); @@ -30028,7 +32130,7 @@ tk = children[k]; tl = children[l]; } - if (tk != 0 && tl != 0 && tk != null && tl != null) { + if (tk !== 0 && tl !== 0 && tk != null && tl != null) { if ((arena.dataTypes[tk] === exports.EnumToken.PercentageTokenType || arena.dataTypes[tl] === exports.EnumToken.PercentageTokenType) && arena.dataTypes[tk] !== arena.dataTypes[tl]) { @@ -30041,7 +32143,7 @@ } } } - if (name == "color") { + if (name === "color") { const children = filterChildren(arena, token, [ exports.EnumToken.DashedIdenTokenType, exports.EnumToken.IdenTokenType, @@ -30052,13 +32154,13 @@ exports.EnumToken.MathFunctionTokenType, exports.EnumToken.PercentageTokenType, ]); - const isRelative = arena.dataTypes[children[0]] == exports.EnumToken.IdenTokenType && - arena.strings[arena.stringValue[children[0]]] == "from"; + const isRelative = arena.dataTypes[children[0]] === exports.EnumToken.IdenTokenType && + arena.strings[arena.stringValue[children[0]]] === "from"; let offset = 0; if (isRelative) { offset = 2; } - if (offset < children.length && arena.dataTypes[children[offset]] == exports.EnumToken.DashedIdenTokenType) { + if (offset < children.length && arena.dataTypes[children[offset]] === exports.EnumToken.DashedIdenTokenType) { if (children.length <= offset + 1) { errors?.push({ action: "drop", @@ -30069,14 +32171,14 @@ } for (let i = offset + 1; i < children.length; i++) { const childType = arena.dataTypes[children[i]]; - if (childType == exports.EnumToken.NumberTokenType || - childType == exports.EnumToken.LiteralTokenType || - childType == exports.EnumToken.ColorTokenType || - childType == exports.EnumToken.FunctionTokenType || - childType == exports.EnumToken.MathFunctionTokenType || - childType == exports.EnumToken.PercentageTokenType || + if (childType === exports.EnumToken.NumberTokenType || + childType === exports.EnumToken.LiteralTokenType || + childType === exports.EnumToken.ColorTokenType || + childType === exports.EnumToken.FunctionTokenType || + childType === exports.EnumToken.MathFunctionTokenType || + childType === exports.EnumToken.PercentageTokenType || isColor(arena, children[i]) || - (childType == exports.EnumToken.IdenTokenType && + (childType === exports.EnumToken.IdenTokenType && equalsIgnoreCase("none", arena.strings[arena.stringValue[children[i]]]))) { continue; } @@ -30084,15 +32186,15 @@ } return true; } - if (children.length == 4 || (isRelative && children.length == 6)) { + if (children.length === 4 || (isRelative && children.length === 6)) { return true; } return true; } - else if (name == "color-mix") { + else if (name === "color-mix") { const children = [[]]; - for (let t = arena.firstToken[token]; t != 0; t = arena.nextSibling[t]) { - if (arena.dataTypes[t] == exports.EnumToken.CommaTokenType) { + for (let t = arena.firstToken[token]; t !== 0; t = arena.nextSibling[t]) { + if (arena.dataTypes[t] === exports.EnumToken.CommaTokenType) { children.push([]); } else if (![exports.EnumToken.WhitespaceTokenType, exports.EnumToken.CommentTokenType].includes(arena.dataTypes[t])) { @@ -30108,7 +32210,7 @@ if (k < children[j].length && arena.dataTypes[children[j][k]] === exports.EnumToken.IdenTokenType) { if (!isRectangularOrthogonalColorspace(arena, children[j][k])) { if (isPolarColorspace(arena, children[j][k++])) { - if (k == children[j].length) ; + if (k === children[j].length) ; else if (arena.dataTypes[children[j][k]] !== exports.EnumToken.IdenTokenType) { return false; } @@ -30186,12 +32288,12 @@ } if (typ === exports.EnumToken.ColorTokenType) { const val = arena.strings[arena.stringValue[token]]; - if (arena.colorType[token] == exports.ColorType.NONE && arena.stringValue[token] != 0) { + if (arena.colorType[token] === exports.ColorType.NONE && arena.stringValue[token] !== 0) { // inlined: arena.setColorType(token, ColorType[val.replaceAll("-", "_").toUpperCase()] ?? 0) // @ts-expect-error arena.colorType[token] = (exports.ColorType[val.replaceAll("-", "_").toUpperCase()] ?? 0); } - if (arena.firstToken[token] != 0) { + if (arena.firstToken[token] !== 0) { const tk = arena.findToken(token, (arena, t) => arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[t] !== exports.EnumToken.CommentTokenType); if (tk != null && @@ -30200,12 +32302,12 @@ // inlined: arena.setUnitString(token, "rel") arena.unit[token] = arena.internString("rel"); } - else if (val == "color-mix" && tk != null && arena.strings[arena.stringValue[tk]] == "in") { + else if (val === "color-mix" && tk != null && arena.strings[arena.stringValue[tk]] === "in") { // inlined: arena.setUnitString(token, "mix") arena.unit[token] = arena.internString("mix"); } - if (val == "color") { - if (tk != null && exports.EnumToken.DashedIdenTokenType == arena.dataTypes[tk]) { + if (val === "color") { + if (tk != null && exports.EnumToken.DashedIdenTokenType === arena.dataTypes[tk]) { // inlined: arena.setColorType(token, ColorType.CUSTOM_COLOR) arena.colorType[token] = exports.ColorType.CUSTOM_COLOR; } @@ -30225,21 +32327,21 @@ } function isIdentStart(codepoint) { // _ - return codepoint == 0x5f || isLetter(codepoint) || isNonAscii(codepoint) || codepoint == REVERSE_SOLIDUS; + return codepoint === 0x5f || isLetter(codepoint) || isNonAscii(codepoint) || codepoint === REVERSE_SOLIDUS; } function isDigit(codepoint) { return codepoint >= 0x30 && codepoint <= 0x39; } function isIdentCodepoint(codepoint) { // - - return codepoint == 0x2d || isDigit(codepoint) || isIdentStart(codepoint); + return codepoint === 0x2d || isDigit(codepoint) || isIdentStart(codepoint); } const isIdent = memoize(function (name) { const j = name.length - 1; let i = 0; let codepoint = name.charCodeAt(0); // - - if (codepoint == 0x2d) { + if (codepoint === 0x2d) { const nextCodepoint = name.charCodeAt(1); if (Number.isNaN(nextCodepoint)) { return false; @@ -30256,7 +32358,7 @@ if (codepoint !== 0x2d && !isIdentStart(codepoint)) { return false; } - if (codepoint == REVERSE_SOLIDUS) { + if (codepoint === REVERSE_SOLIDUS) { if (i + 1 > j) { return false; } @@ -30275,7 +32377,7 @@ while (i < j) { i += codepoint < 0x80 ? 1 : String.fromCodePoint(codepoint).length; codepoint = name.charCodeAt(i); - if (codepoint == REVERSE_SOLIDUS) { + if (codepoint === REVERSE_SOLIDUS) { i += codepoint < 0x80 ? 1 : String.fromCodePoint(codepoint).length; codepoint = name.charCodeAt(i); i += codepoint < 0x80 ? 1 : String.fromCodePoint(codepoint).length; @@ -30291,9 +32393,9 @@ // null -> backspace return ((codepoint >= 0 && codepoint <= 0x8) || // tab - codepoint == 0xb || + codepoint === 0xb || // delete - codepoint == 0x7f || + codepoint === 0x7f || (codepoint >= 0xe && codepoint <= 0x1f)); } // export function isURLToken(str: string): boolean { @@ -30335,12 +32437,12 @@ // return i == str.length; // } function isPseudo(name) { - return (name.charAt(0) == ":" && - ((name.endsWith("(") && isIdent(name.charAt(1) == ":" ? name.slice(2, -1) : name.slice(1, -1))) || - isIdent(name.charAt(1) == ":" ? name.slice(2) : name.slice(1)))); + return (name.charAt(0) === ":" && + ((name.endsWith("(") && isIdent(name.charAt(1) === ":" ? name.slice(2, -1) : name.slice(1, -1))) || + isIdent(name.charAt(1) === ":" ? name.slice(2) : name.slice(1)))); } function isHash(name) { - return name.charAt(0) == "#" && isIdentStart(name.charCodeAt(1)); + return name.charAt(0) === "#" && isIdentStart(name.charCodeAt(1)); } function parseDimension(name) { let index = name.length; @@ -30413,23 +32515,23 @@ // } function isNewLine(codepoint) { // \n \r \f \v - return (codepoint == 0xa || - codepoint == 0xb || - codepoint == 0xc || - codepoint == 0xd || - codepoint == 0x2028 || - codepoint == 0x2029); + return (codepoint === 0xa || + codepoint === 0xb || + codepoint === 0xc || + codepoint === 0xd || + codepoint === 0x2028 || + codepoint === 0x2029); } function isWhiteSpace(codepoint) { - return (codepoint == 0x9 || - codepoint == 0x20 || + return (codepoint === 0x9 || + codepoint === 0x20 || // isNewLine - codepoint == 0xa || - codepoint == 0xb || - codepoint == 0xc || - codepoint == 0xd || - codepoint == 0x2028 || - codepoint == 0x2029); + codepoint === 0xa || + codepoint === 0xb || + codepoint === 0xc || + codepoint === 0xd || + codepoint === 0x2028 || + codepoint === 0x2029); } // export function isValue(token: Token) { // if (token == null) { @@ -30466,27 +32568,31 @@ function length2Px(arena, value) { let result = null; const val = arena.numericValue[value]; - if (arena.dataTypes[value] == exports.EnumToken.NumberTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.NumberTokenType) { result = val; } else { - switch (arena.strings[arena.unit[value]]) { + // the absolute length units: 1in = 2.54cm = 96px. the units are case-insensitive + switch (arena.strings[arena.unit[value]]?.toLowerCase()) { case "cm": - result = val * 37.8; + result = (val * 96) / 2.54; break; case "mm": - result = val * 3.78; + result = (val * 96) / 25.4; break; - case "Q": - result = (val * 37.8) / 40; + case "q": + // 1Q = 1/40cm + result = (val * 96) / 101.6; break; case "in": - result = val / 96; + result = val * 96; break; case "pc": - result = val / 16; + // 1pc = 1/6in + result = val * 16; break; case "pt": + // 1pt = 1/72in result = (val * 4) / 3; break; case "px": @@ -30501,7 +32607,7 @@ * @param val */ function minifyNumber(val) { - if (typeof val != "number") { + if (typeof val !== "number") { return minifyNumberValue(val); } // the same numbers are rendered many times (0, 1, .5, 100, ...): the result only depends on the number @@ -30538,13 +32644,13 @@ return "0"; } const chr = val.charAt(0); - if (chr == "-") { + if (chr === "-") { const slice = val.slice(0, 2); - if (slice == "-0") { - return val.length == 2 ? "0" : "-" + val.slice(2); + if (slice === "-0") { + return val.length === 2 ? "0" : "-" + val.slice(2); } } - if (chr == "0") { + if (chr === "0") { return val.slice(1); } return val; @@ -30566,6 +32672,68 @@ return angle; } + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + const nonAscii = /[^\x00-\x7f]/; + const empty = new Uint8Array(0); + /** + * true if the input is an ArrayBuffer or a view of an ArrayBuffer + * @param input + */ + function isBinaryInput(input) { + return input instanceof ArrayBuffer || ArrayBuffer.isView(input); + } + /** + * true if the input is css: a string, an ArrayBuffer or a view of an ArrayBuffer + * @param input + */ + function isCssInput(input) { + return typeof input === "string" || isBinaryInput(input); + } + /** + * the bytes of a binary input + * @param input + */ + function bytesOf(input) { + return input instanceof Uint8Array + ? input + : input instanceof ArrayBuffer + ? new Uint8Array(input) + : new Uint8Array(input.buffer, input.byteOffset, input.byteLength); + } + /** + * the utf-16 code units of a text + * @param text + */ + function codeUnitsOf(text) { + const codes = new Uint16Array(text.length); + for (let i = 0; i < text.length; i++) { + codes[i] = text.charCodeAt(i); + } + return codes; + } + /** + * convert the css input to code units: the tokenizer reads the code units. a string is encoded to an ArrayBuffer. + * an ascii input is read from its bytes: the code units are the bytes. the other inputs are decoded (utf-8) to + * utf-16 code units: the positions of the tokens are utf-16 positions, like the positions in a string + * @param input + */ + function toCodeUnits(input) { + if (input == null || input === "") { + return { codes: empty, text: "" }; + } + if (typeof input === "string") { + return { codes: nonAscii.test(input) ? codeUnitsOf(input) : encoder.encode(input), text: input }; + } + const bytes = bytesOf(input); + const text = decoder.decode(bytes); + // the text of an ascii input has a character for each byte. the byte order mark is removed by the decoder + if (text.length === bytes.length && !nonAscii.test(text)) { + return { codes: bytes, text }; + } + return { codes: codeUnitsOf(text), text }; + } + const SymbolsMapTokens = Object.create(null); const SymbolsMapTokensLower = Object.create(null); // Regex for escape sequence decoding - compile once, reuse many times @@ -30583,7 +32751,7 @@ return ""; } const codepoint = parseInt(sequence, 16); - if (codepoint == 0 || + if (codepoint === 0 || // leading surrogate (0xd800 <= codepoint && codepoint <= 0xdbff) || // trailing surrogate @@ -30595,7 +32763,18 @@ }); } /** - * hash table of ascii strings, looked up by a range of the css source without allocating a string. + * the code units of a string + * @param str + */ + function codesOf(str) { + const codes = new Uint16Array(str.length); + for (let i = 0; i < str.length; i++) { + codes[i] = str.charCodeAt(i); + } + return codes; + } + /** + * hash table of ascii strings, looked up by a range of the code units of the css source without allocating a string. * the keys are lowercase, the lookups ignore the case of ascii letters */ class RangeTable { @@ -30603,15 +32782,15 @@ values = []; slots = new Int32Array(1024).fill(-1); /** - * hash of a range of a string, ascii letters are lowercased. -1 when the range contains a non ascii character - * @param str + * hash of a range of code units, ascii letters are lowercased. -1 when the range contains a non ascii character + * @param codes * @param start * @param end */ - static hash(str, start, end) { + static hash(codes, start, end) { let hash = 0x811c9dc5; for (let i = start; i < end; i++) { - let code = str.charCodeAt(i); + let code = codes[i]; if (code > 0x7f) { return -1; } @@ -30622,82 +32801,97 @@ } return hash >>> 0; } + /** + * the value of a range of code units + * @param codes + * @param start + * @param end + */ + get(codes, start, end) { + const hash = RangeTable.hash(codes, start, end); + if (hash === -1) { + return undefined; + } + const index = this.slots[this.find(codes, start, end, hash)]; + return index === -1 ? undefined : this.values[index]; + } + /** + * the value of a key + * @param key + */ + getKey(key) { + return this.get(codesOf(key), 0, key.length); + } + set(key, value) { + const codes = codesOf(key); + const slot = this.find(codes, 0, codes.length, RangeTable.hash(codes, 0, codes.length)); + if (this.slots[slot] === -1) { + this.slots[slot] = this.keys.length; + this.keys.push(codes); + this.values.push(value); + } + else { + this.values[this.slots[slot]] = value; + } + } /** * slot of a key. the table is never full: it is sized for the static tables of the tokenizer - * @param str + * @param codes * @param start * @param end * @param hash */ - find(str, start, end, hash) { + find(codes, start, end, hash) { const mask = this.slots.length - 1; const length = end - start; let slot = hash & mask; for (;;) { const index = this.slots[slot]; - if (index == -1) { + if (index === -1) { return slot; } const key = this.keys[index]; - if (key.length == length) { + if (key.length === length) { let k = 0; while (k < length) { - let code = str.charCodeAt(start + k); + let code = codes[start + k]; if (code >= 65 && code <= 90) { code += 32; } - if (code != key.charCodeAt(k)) { + if (code !== key[k]) { break; } k++; } - if (k == length) { + if (k === length) { return slot; } } slot = (slot + 1) & mask; } } - get(str, start, end) { - const hash = RangeTable.hash(str, start, end); - if (hash == -1) { - return undefined; - } - const index = this.slots[this.find(str, start, end, hash)]; - return index == -1 ? undefined : this.values[index]; - } - set(key, value) { - const slot = this.find(key, 0, key.length, RangeTable.hash(key, 0, key.length)); - if (this.slots[slot] == -1) { - this.slots[slot] = this.keys.length; - this.keys.push(key); - this.values.push(value); - } - else { - this.values[this.slots[slot]] = value; - } - } } /** - * value of a number: the digits are read from the source without creating a string when the result is exact - * (at most 15 significant digits, no exponent), parseFloat() otherwise - * @param stream + * value of a number: the digits are read from the code units of the source without creating a string when the result + * is exact (at most 15 significant digits, no exponent), parseFloat() otherwise + * @param codes the code units of the source + * @param text the text of the source * @param start * @param end */ - function parseNumber(stream, start, end) { + function parseNumber(codes, text, start, end) { let i = start; - let code = stream.charCodeAt(i); + let code = codes[i]; let negative = false; - if (code == 0x2d || code == 0x2b) { - negative = code == 0x2d; - code = stream.charCodeAt(++i); + if (code === 0x2d || code === 0x2b) { + negative = code === 0x2d; + code = codes[++i]; } let mantissa = 0; let count = 0; let digits = 0; let decimals = -1; - for (; i < end; code = stream.charCodeAt(++i)) { + for (; i < end; code = codes[++i]) { if (code >= 0x30 && code <= 0x39) { mantissa = mantissa * 10 + (code - 0x30); count++; @@ -30708,7 +32902,7 @@ decimals++; } } - else if (code == 0x2e && decimals == -1) { + else if (code === 0x2e && decimals === -1) { decimals = 0; } else { @@ -30716,8 +32910,8 @@ } } // exponent, too many digits or not a number: the (correctly rounded) result of parseFloat() - if (i != end || count == 0 || digits > 15 || decimals > 22 || decimals == 0) { - return parseFloat(stream.slice(start, end)); + if (i !== end || count === 0 || digits > 15 || decimals > 22 || decimals === 0) { + return parseFloat(text.slice(start, end)); } // mantissa and 10^decimals are exact: the division is correctly rounded like parseFloat() const value = decimals > 0 ? mantissa / powersOf10[decimals] : mantissa; @@ -30740,7 +32934,7 @@ const key = (lowercase ? entry.toLowerCase() : entry) + suffix; SymbolsMapTokens[key] = tokenType; SymbolsMapTokensLower[key.toLowerCase()] = tokenType; - let items = itemTable.get(entry, 0, entry.length); + let items = itemTable.getKey(entry); if (items == null) { items = new Map(); itemTable.set(entry.toLowerCase(), items); @@ -30787,6 +32981,17 @@ assignTokenMap(angleUnits, exports.EnumToken.AngleTokenType); assignTokenMap(timeUnits, exports.EnumToken.TimeTokenType); assignTokenMap(frequencyUnits, exports.EnumToken.FrequencyTokenType); + // the units of the other dimensions are rendered in their canonical spelling: `6DB` is rendered `6dB` + for (const unit of validationUnits) { + let items = itemTable.getKey(unit); + if (items == null) { + items = new Map(); + itemTable.set(unit.toLowerCase(), items); + } + if (!items.has(exports.EnumToken.DimensionTokenType)) { + items.set(exports.EnumToken.DimensionTokenType, unit); + } + } assignTokenMap(pseudoElements, exports.EnumToken.PseudoElementTokenType); assignTokenMap(containerFunc, exports.EnumToken.ContainerFunctionTokenDefType, "("); assignTokenMap(urlFunc, exports.EnumToken.UrlFunctionTokenDefType, "("); @@ -30818,6 +33023,7 @@ var TokenMap; (function (TokenMap) { TokenMap[TokenMap["EXCLAMATION"] = 33] = "EXCLAMATION"; + TokenMap[TokenMap["QUESTION"] = 63] = "QUESTION"; TokenMap[TokenMap["SLASH"] = 47] = "SLASH"; TokenMap[TokenMap["LOWERTHAN"] = 60] = "LOWERTHAN"; TokenMap[TokenMap["HASH"] = 35] = "HASH"; @@ -30848,22 +33054,22 @@ TokenMap[TokenMap["PERCENTAGE"] = 37] = "PERCENTAGE"; })(TokenMap || (TokenMap = {})); function getSymbolHint(parseInfo, start, end) { - const stream = parseInfo.stream; - if (end > stream.length) { - end = stream.length; + const codes = parseInfo.codes; + if (end > parseInfo.length) { + end = parseInfo.length; } if (end - start <= 0) { return null; } // ascii names are looked up without allocating a string - const type = symbolTable.get(stream, start, end); + const type = symbolTable.get(codes, start, end); if (type !== undefined) { return type; } for (let i = start; i < end; i++) { // the unicode case mapping of toLowerCase() may produce ascii letters - if (stream.charCodeAt(i) > 0x7f) { - const value = stream.slice(start, end); + if (codes[i] > 0x7f) { + const value = parseInfo.stream.slice(start, end); return SymbolsMapTokens[value] ?? SymbolsMapTokensLower[value.toLowerCase()] ?? null; } } @@ -30880,23 +33086,69 @@ if (end - start <= 0) { return null; } - return itemTable.get(parseInfo.stream, start, end)?.get(type) ?? null; + return itemTable.get(parseInfo.codes, start, end)?.get(type) ?? null; + } + /** + * true if the character is a hexadecimal digit + * @param codepoint + */ + function isHexDigit(codepoint) { + return ((codepoint >= 0x30 && codepoint <= 0x39) || + (codepoint >= 0x41 && codepoint <= 0x46) || + (codepoint >= 0x61 && codepoint <= 0x66)); + } + /** + * true if the character may follow a numeric token: the end of the stream, a whitespace, `)`, `;`, `!` + * (`0!important`), `}`, `/`, `*`, `,`, and `+` after a dimension (`2n+1`) + * @param codepoint + * @param isDimension + */ + function isNumericTokenEnd(codepoint, isDimension) { + return ( + // eof + codepoint === undefined || + isWhiteSpace(codepoint) || + codepoint === 123 /* TokenMap.LEFT_BRACE */ || + codepoint === 41 /* TokenMap.RIGHT_PARENTHESIS */ || + codepoint === 59 /* TokenMap.SEMICOLON */ || + codepoint === 33 /* TokenMap.EXCLAMATION */ || + codepoint === 125 /* TokenMap.RIGHT_BRACE */ || + codepoint === 47 /* TokenMap.SLASH */ || + codepoint === 42 /* TokenMap.STAR */ || + codepoint === 44 /* TokenMap.COMMA */ || + (isDimension && codepoint === 43 /* TokenMap.PLUS */)); + } + /** + * the parse info of a css input: the input is converted to code units, see {@link Tokenizer.load}. a stream is read + * by {@link Tokenizer.tokenizeStream} + * @param input the css: a string, an ArrayBuffer, a view of an ArrayBuffer or a stream + * @param source the source file of the css + */ + function createParseInfo(input, source) { + const parseInfo = { + stream: "", + codes: new Uint8Array(0), + length: 0, + source, + offset: 0, + time: 0, + position: 0, + currentPosition: 0, + }; + if (!(input instanceof ReadableStream)) { + Tokenizer.load(parseInfo, input); + } + return parseInfo; } /** * tokenizer class */ class Tokenizer { - parseInfo; input; /** * token type */ typ = null; - /** - * the identifier read by the last call of consumeIdentToken() has non ascii characters: they may be new lines - * (U+2028, U+2029) - */ - identNonAscii = false; /** * token kind */ @@ -30941,11 +33193,49 @@ * source file */ source = null; + /** + * the identifier read by the last call of consumeIdentToken() has non ascii characters: they may be new lines + * (U+2028, U+2029) + */ + identNonAscii = false; /** * token hint */ hint = null; state = null; + parseInfo; + /** + * @param parseInfo the parse info, or the css: a string, an ArrayBuffer or a view of an ArrayBuffer + * @param input a stream of css + */ + constructor(parseInfo, input = null) { + this.input = input; + if (isCssInput(parseInfo)) { + this.parseInfo = createParseInfo(parseInfo, new SourceFile("", [], "")); + } + else { + // the parse info of a stream is loaded by tokenizeStream() + if (parseInfo.codes == null && input == null) { + Tokenizer.load(parseInfo, parseInfo.stream); + } + this.parseInfo = parseInfo; + } + } + /** + * set the css read by the tokenizer: the code units of the css (an ascii ArrayBuffer is read without copy) and its + * text, the content of the source file + * @param parseInfo + * @param input + */ + static load(parseInfo, input) { + const { codes, text } = toCodeUnits(input); + parseInfo.codes = codes; + parseInfo.length = codes.length; + parseInfo.stream = text; + if (parseInfo.source.content === "") { + parseInfo.source.content = text; + } + } /** * id of the source file being tokenized */ @@ -30953,26 +33243,10 @@ return this.parseInfo.source.id; } /** - * length of the css input. 0 when the input is a stream + * length of the css input, in code units. 0 when the input is a stream */ get streamLength() { - const stream = this.parseInfo.stream; - return typeof stream == "string" ? stream.length : 0; - } - constructor(parseInfo, input = null) { - this.parseInfo = parseInfo; - this.input = input; - this.parseInfo = - typeof parseInfo == "string" - ? { - stream: parseInfo, - source: new SourceFile(parseInfo, [], ""), - offset: 0, - time: 0, - position: 0, - currentPosition: 0, - } - : parseInfo; + return this.parseInfo.length; } /** * @@ -30983,20 +33257,20 @@ const quote = this.advanceCode(parseInfo); let charCode; let decodeSegments = false; - while ((charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset)) == charCode) { - if (charCode == 92 /* TokenMap.REVERSE_SOLIDUS */) { - if (charCode == parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset + 1)) { + while ((charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]) !== undefined) { + if (charCode === 92 /* TokenMap.REVERSE_SOLIDUS */) { + if (charCode === parseInfo.codes[parseInfo.currentPosition - parseInfo.offset + 1]) { this.advance(parseInfo, 2); continue; } - charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset + 1); + charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset + 1]; // \n \r \f \v - if (charCode == 0xa || - charCode == 0xb || - charCode == 0xc || - charCode == 0xd || - charCode == 0x2028 || - charCode == 0x2029) { + if (charCode === 0xa || + charCode === 0xb || + charCode === 0xc || + charCode === 0xd || + charCode === 0x2028 || + charCode === 0x2029) { this.advance(parseInfo, 2); decodeSegments = true; continue; @@ -31007,12 +33281,12 @@ let i; for (i = 1; i < sequence.length; i++) { codepoint = sequence.charCodeAt(i); - if (codepoint == 0x20 || + if (codepoint === 0x20 || (codepoint >= 0x61 && codepoint <= 0x66) || (codepoint >= 0x41 && codepoint <= 0x46) || (codepoint >= 0x30 && codepoint <= 0x39)) { escapeSequence += sequence[i]; - if (codepoint == 0x20) { + if (codepoint === 0x20) { break; } continue; @@ -31022,9 +33296,7 @@ if (escapeSequence.trimEnd().length > 0) { const length = escapeSequence.length + 1 + - (isWhiteSpace(parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset)) - ? 1 - : 0); + (isWhiteSpace(parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]) ? 1 : 0); decodeSegments = true; this.advance(parseInfo, length); continue; @@ -31032,7 +33304,7 @@ this.advance(parseInfo, 2); continue; } - if (charCode == quote) { + if (charCode === quote) { this.advanceCode(parseInfo); return this.makeToken(parseInfo, /* hasNewLine ? EnumToken.BadStringTokenType : */ exports.EnumToken.StringTokenType, null, decodeSegments); @@ -31056,9 +33328,9 @@ const quote = this.advanceCode(parseInfo); let charCode; let decodeSegments = false; - while ((charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset)) == charCode) { - if (charCode == 92 /* TokenMap.REVERSE_SOLIDUS */) { - if (charCode == parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset + 1)) { + while ((charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]) !== undefined) { + if (charCode === 92 /* TokenMap.REVERSE_SOLIDUS */) { + if (charCode === parseInfo.codes[parseInfo.currentPosition - parseInfo.offset + 1]) { this.advance(parseInfo, 2); continue; } @@ -31068,12 +33340,12 @@ let i; for (i = 1; i < sequence.length; i++) { codepoint = sequence.charCodeAt(i); - if (codepoint == 0x20 || + if (codepoint === 0x20 || (codepoint >= 0x61 && codepoint <= 0x66) || (codepoint >= 0x41 && codepoint <= 0x46) || (codepoint >= 0x30 && codepoint <= 0x39)) { escapeSequence += sequence[i]; - if (codepoint == 0x20) { + if (codepoint === 0x20) { break; } continue; @@ -31083,9 +33355,7 @@ if (escapeSequence.trimEnd().length > 0) { const length = escapeSequence.length + 1 + - (isWhiteSpace(parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset)) - ? 1 - : 0); + (isWhiteSpace(parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]) ? 1 : 0); decodeSegments = true; this.advance(parseInfo, length); continue; @@ -31093,15 +33363,15 @@ this.advance(parseInfo, 2); continue; } - if (charCode == quote) { + if (charCode === quote) { this.advanceCode(parseInfo); let k = 1; - let end = parseInfo.stream.length - parseInfo.offset; + let end = parseInfo.length - parseInfo.offset; let position = parseInfo.currentPosition - parseInfo.offset; while (position + k < end) { - charCode = parseInfo.stream.charCodeAt(position); - // NaN != NaN - if (charCode != charCode) { + charCode = parseInfo.codes[position]; + // the end of the stream + if (charCode === undefined) { this.advance(parseInfo, k); return this.makeToken(parseInfo, exports.EnumToken.BadUrlTokenType); } @@ -31110,7 +33380,7 @@ k++; continue; } - if (charCode != 41 /* TokenMap.RIGHT_PARENTHESIS */) { + if (charCode !== 41 /* TokenMap.RIGHT_PARENTHESIS */) { this.advance(parseInfo, k); return this.makeToken(parseInfo, exports.EnumToken.BadUrlTokenType); } @@ -31124,12 +33394,12 @@ if (isNewLine(charCode)) { // bad string this.advanceCode(parseInfo); - while ((charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset)) == charCode) { - if (charCode == 92 /* TokenMap.REVERSE_SOLIDUS */) { + while ((charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]) !== undefined) { + if (charCode === 92 /* TokenMap.REVERSE_SOLIDUS */) { this.advance(parseInfo, 2); continue; } - if (charCode == 41 /* TokenMap.RIGHT_PARENTHESIS */) { + if (charCode === 41 /* TokenMap.RIGHT_PARENTHESIS */) { return this.makeToken(parseInfo, exports.EnumToken.BadUrlTokenType); } this.advanceCode(parseInfo); @@ -31143,260 +33413,142 @@ // return result; } /** - * consume number, dimension, or percentage + * consume a unicode range: `U+` followed by one to six hexadecimal digits or `?` (the `?` are the last + * characters), optionally followed by `-` and one to six hexadecimal digits: `U+0025-00FF`, `U+4??`. + * the range is followed by the end of the stream, a whitespace, `,`, `;`, `}`, `)` or `!`: `u+a{` is a selector * @param parseInfo - * @returns + * @returns the length of the token, 0 if it is not a unicode range */ - consumeNumericToken(parseInfo) { - let position = parseInfo.currentPosition - parseInfo.offset; - let offset = position; - let hasDigits = false; - let hasLetter = false; - let hasPercent = false; - let codepoint = parseInfo.stream.charCodeAt(position); - this.slice = null; - this.hint = null; - // '+' '-' - if (codepoint == 0x2b || codepoint == 0x2d) { - position++; + consumeUnicodeRangeToken(parseInfo) { + const codes = parseInfo.codes; + const start = parseInfo.currentPosition - parseInfo.offset; + let position = start + 2; + let count = 0; + let wildcards = 0; + let codepoint; + if (codes[start + 1] !== 43 /* TokenMap.PLUS */) { + return 0; } - // consume digits - while (position < parseInfo.stream.length) { - codepoint = parseInfo.stream.charCodeAt(position); - if (isDigit(codepoint)) { - hasDigits = true; + while (count < 6) { + codepoint = codes[position]; + if (wildcards === 0 && isHexDigit(codepoint)) { + count++; position++; - continue; } - // '.' 'E' 'e' - if (codepoint == 0x2e || codepoint == 0x45 || codepoint == 0x65) { + else if (codepoint === 63 /* TokenMap.QUESTION */) { + wildcards++; + count++; position++; - break; - } - if (isWhiteSpace(codepoint) || - codepoint == 41 /* TokenMap.RIGHT_PARENTHESIS */ || - codepoint == 59 /* TokenMap.SEMICOLON */ || - codepoint == 125 /* TokenMap.RIGHT_BRACE */ || - codepoint == 47 /* TokenMap.SLASH */ || - codepoint == 42 /* TokenMap.STAR */ || - codepoint == 44 /* TokenMap.COMMA */) { - return !hasDigits ? 0 : position - offset; - } - if (codepoint == 37 /* TokenMap.PERCENTAGE */) { - hasPercent = true; - break; } - if (isLetter(codepoint)) { - hasLetter = true; - break; - } - // dashed ident as unit - if (codepoint == 0x2d && parseInfo.stream.charCodeAt(position + 1) == 0x2d) { - hasLetter = true; + else { break; } + } + if (count === 0) { return 0; } - if (!hasLetter && !hasPercent) { - // '.' - if (codepoint == 0x2e) { - codepoint = parseInfo.stream.charCodeAt(position); - if (codepoint != codepoint) { - return !hasDigits ? 0 : position - offset; - } - if (isWhiteSpace(codepoint) || - codepoint == 41 /* TokenMap.RIGHT_PARENTHESIS */ || - codepoint == 59 /* TokenMap.SEMICOLON */ || - codepoint == 125 /* TokenMap.RIGHT_BRACE */ || - codepoint == 47 /* TokenMap.SLASH */ || - codepoint == 42 /* TokenMap.STAR */ || - codepoint == 44 /* TokenMap.COMMA */) { - return !hasDigits ? 0 : position - offset; - } - if (!isDigit(codepoint)) { - if (!hasDigits) { - return 0; - } - if (codepoint == 37 /* TokenMap.PERCENTAGE */) { - hasPercent = true; - } - else if (isLetter(codepoint)) { - hasLetter = true; - } - // custom ident as unit - else if (codepoint == 0x2d && parseInfo.stream.charCodeAt(position + 1) == 0x2d) { - hasLetter = true; - } - else { - return 0; - } - } - else { - position++; - hasDigits = true; - } + // the end of the range + if (wildcards === 0 && codes[position] === 45 /* TokenMap.MINUS */ && isHexDigit(codes[position + 1])) { + position++; + count = 0; + while (count < 6 && isHexDigit(codes[position])) { + count++; + position++; } - if (!hasLetter && !hasPercent) { - while (position + 1 <= parseInfo.stream.length) { - codepoint = parseInfo.stream.charCodeAt(position); - if (isDigit(codepoint)) { - position++; - continue; - } - if (!hasDigits) { - return 0; - } - // 'E' 'e' - if (codepoint == 0x45 || codepoint == 0x65) { - position++; - break; - } - if (isWhiteSpace(codepoint) || - codepoint == 41 /* TokenMap.RIGHT_PARENTHESIS */ || - codepoint == 59 /* TokenMap.SEMICOLON */ || - codepoint == 125 /* TokenMap.RIGHT_BRACE */ || - codepoint == 47 /* TokenMap.SLASH */ || - codepoint == 42 /* TokenMap.STAR */ || - codepoint == 44 /* TokenMap.COMMA */) { - return position - offset; - } - if (isLetter(codepoint)) { - hasLetter = true; - break; - } - else if (codepoint == 0x2d && parseInfo.stream.charCodeAt(position + 1) == 0x2d) { - hasLetter = true; - break; - } - if (codepoint == 37 /* TokenMap.PERCENTAGE */) { - hasPercent = true; - break; - } - return 0; - } - // 'E' 'e' - 'em' - if ((codepoint == 0x45 || codepoint == 0x65) && hasDigits && !hasLetter && !hasPercent) { - if (isLetter(parseInfo.stream.charCodeAt(position))) { - hasLetter = true; - } - } - if (!hasLetter && !hasPercent) { - // 'E' 'e' - if (codepoint == 0x45 || codepoint == 0x65) { - codepoint = parseInfo.stream.charCodeAt(position + 1); - // '+' '-' - if (codepoint == 0x2b || codepoint == 0x2d) { - position++; - } - codepoint = position = parseInfo.stream.charCodeAt(position + 1); - if (!isDigit(codepoint)) { - if (!hasDigits) { - return 0; - } - if (isLetter(codepoint)) { - hasLetter = true; - } - else if (codepoint == 37 /* TokenMap.PERCENTAGE */) { - hasPercent = true; - } - else { - return 0; - } - } - } - if (!hasLetter && !hasPercent) { - while (++position < parseInfo.stream.length) { - codepoint = parseInfo.stream.charCodeAt(position); - // eof - if (codepoint != codepoint) { - break; - } - if (isDigit(codepoint)) { - position++; - continue; - } - if (!hasDigits) { - return 0; - } - if (isWhiteSpace(codepoint) || - codepoint == 41 /* TokenMap.RIGHT_PARENTHESIS */ || - codepoint == 59 /* TokenMap.SEMICOLON */ || - codepoint == 125 /* TokenMap.RIGHT_BRACE */ || - codepoint == 47 /* TokenMap.SLASH */ || - codepoint == 42 /* TokenMap.STAR */ || - codepoint == 44 /* TokenMap.COMMA */) { - return position - offset; - } - else if (isLetter(codepoint)) { - hasLetter = true; - break; - } - // custom ident as unit - else if (codepoint == 0x2d && parseInfo.stream.charCodeAt(position + 1) == 0x2d) { - hasLetter = true; - break; - } - else if (codepoint == 37 /* TokenMap.PERCENTAGE */) { - hasPercent = true; - break; - } - else { - return 0; - } - } - if (!hasLetter && !hasPercent) { - return position - offset; - } - } - } + } + codepoint = codes[position]; + if ( + // eof + codepoint === undefined || + isWhiteSpace(codepoint) || + codepoint === 44 /* TokenMap.COMMA */ || + codepoint === 59 /* TokenMap.SEMICOLON */ || + codepoint === 125 /* TokenMap.RIGHT_BRACE */ || + codepoint === 41 /* TokenMap.RIGHT_PARENTHESIS */ || + codepoint === 33 /* TokenMap.EXCLAMATION */) { + return position - start; + } + return 0; + } + /** + * consume number, dimension, or percentage. the number is `[+-]? digits? [. digits]? [(e|E) [+-]? digits]?`: + * `1.5e2`, `1e-3`, `.5e1`. the exponent requires a digit: `2em` is the number `2` and the unit `em`. + * the token is followed by the end of the stream, a whitespace, `)`, `;`, `!`, `}`, `/`, `*`, `,` (and `+` after + * a dimension: `2n+1`): otherwise it is not a numeric token + * @param parseInfo + * @returns the length of the token, 0 if it is not a numeric token + */ + consumeNumericToken(parseInfo) { + const codes = parseInfo.codes; + const offset = parseInfo.currentPosition - parseInfo.offset; + let position = offset; + let hasDigits = false; + let codepoint = codes[position]; + this.slice = null; + this.hint = null; + // '+' '-' + if (codepoint === 43 /* TokenMap.PLUS */ || codepoint === 45 /* TokenMap.MINUS */) { + position++; + } + // integer part + while (isDigit(codes[position])) { + position++; + hasDigits = true; + } + // decimal part + if (codes[position] === 46 /* TokenMap.DOT */ && isDigit(codes[position + 1])) { + position++; + while (isDigit(codes[position])) { + position++; } + hasDigits = true; } if (!hasDigits) { return 0; } - if (hasPercent) { + // exponent: 'E' 'e', followed by a digit or a sign and a digit + codepoint = codes[position]; + if (codepoint === 0x45 || codepoint === 0x65) { + let k = position + 1; + if (codes[k] === 43 /* TokenMap.PLUS */ || codes[k] === 45 /* TokenMap.MINUS */) { + k++; + } + if (isDigit(codes[k])) { + position = k; + while (isDigit(codes[position])) { + position++; + } + } + } + codepoint = codes[position]; + // percentage + if (codepoint === 37 /* TokenMap.PERCENTAGE */) { const slice = position; - codepoint = parseInfo.stream.charCodeAt(++position); - if (codepoint != codepoint || - isWhiteSpace(codepoint) || - codepoint == 41 /* TokenMap.RIGHT_PARENTHESIS */ || - codepoint == 59 /* TokenMap.SEMICOLON */ || - codepoint == 125 /* TokenMap.RIGHT_BRACE */ || - codepoint == 47 /* TokenMap.SLASH */ || - codepoint == 42 /* TokenMap.STAR */ || - codepoint == 44 /* TokenMap.COMMA */) { - this.slice = slice; - this.hint = exports.EnumToken.PercentageTokenType; - return position - offset; + if (!isNumericTokenEnd(codes[++position], false)) { + return 0; } - return 0; + this.slice = slice; + this.hint = exports.EnumToken.PercentageTokenType; + return position - offset; } - if (hasLetter) { - codepoint = parseInfo.stream.charCodeAt(position - 1); - // 'E' 'e' - const slice = codepoint == 0x45 || codepoint == 0x65 ? position - 1 : position; - while (position + 1 <= parseInfo.stream.length) { - codepoint = parseInfo.stream.charCodeAt(++position); - if (!isLetter(codepoint) && codepoint != 0x2d) { + // dimension: a unit, or a dashed ident (user defined unit) + if (isLetter(codepoint) || (codepoint === 45 /* TokenMap.MINUS */ && codes[position + 1] === 45 /* TokenMap.MINUS */)) { + const slice = position; + while (position < parseInfo.length) { + codepoint = codes[++position]; + if (!isLetter(codepoint) && codepoint !== 45 /* TokenMap.MINUS */) { break; } } - if (codepoint != codepoint || - isWhiteSpace(codepoint) || - codepoint == 41 /* TokenMap.RIGHT_PARENTHESIS */ || - codepoint == 59 /* TokenMap.SEMICOLON */ || - codepoint == 125 /* TokenMap.RIGHT_BRACE */ || - codepoint == 43 /* TokenMap.PLUS */ || - codepoint == 47 /* TokenMap.SLASH */ || - codepoint == 42 /* TokenMap.STAR */ || - codepoint == 44 /* TokenMap.COMMA */) { - this.slice = slice; - this.hint = getSymbolHint(parseInfo, slice, position) ?? exports.EnumToken.DimensionTokenType; - return position - offset; + if (!isNumericTokenEnd(codes[position], true)) { + return 0; } - return 0; + this.slice = slice; + this.hint = getSymbolHint(parseInfo, slice, position) ?? exports.EnumToken.DimensionTokenType; + return position - offset; } - return 0; + // number + return isNumericTokenEnd(codepoint, false) ? position - offset : 0; } /** * @@ -31407,36 +33559,36 @@ let position = parseInfo.currentPosition - parseInfo.offset; let offset = position; this.identNonAscii = false; - let codepoint = parseInfo.stream.charCodeAt(position); - if (!isIdentStart(codepoint) && codepoint != 45 /* TokenMap.MINUS */) { + let codepoint = parseInfo.codes[position]; + if (!isIdentStart(codepoint) && codepoint !== 45 /* TokenMap.MINUS */) { return 0; } - if (codepoint == 45 /* TokenMap.MINUS */) { + if (codepoint === 45 /* TokenMap.MINUS */) { position++; - codepoint = parseInfo.stream.charCodeAt(position); - if (!isIdentStart(codepoint) && codepoint != 45 /* TokenMap.MINUS */) { + codepoint = parseInfo.codes[position]; + if (!isIdentStart(codepoint) && codepoint !== 45 /* TokenMap.MINUS */) { return 0; } } - while ((codepoint = parseInfo.stream.charCodeAt(position)) == codepoint) { - if (codepoint == 92 /* TokenMap.REVERSE_SOLIDUS */) { + while ((codepoint = parseInfo.codes[position]) !== undefined) { + if (codepoint === 92 /* TokenMap.REVERSE_SOLIDUS */) { // eof - if ((codepoint = parseInfo.stream.charCodeAt(position + 1)) != codepoint) { + if ((codepoint = parseInfo.codes[position + 1]) === undefined) { return 0; } // \n \r \f \v - if (codepoint == 0xa || - codepoint == 0xb || - codepoint == 0xc || - codepoint == 0xd || - codepoint == 0x2028 || - codepoint == 0x2029) { + if (codepoint === 0xa || + codepoint === 0xb || + codepoint === 0xc || + codepoint === 0xd || + codepoint === 0x2028 || + codepoint === 0x2029) { return 0; } position += 2; continue; } - if (codepoint == 0x2d || isIdentCodepoint(codepoint)) { + if (codepoint === 0x2d || isIdentCodepoint(codepoint)) { if (codepoint > 0x7f) { this.identNonAscii = true; } @@ -31467,7 +33619,7 @@ case 43 /* TokenMap.PLUS */: return position - offset; } - if (codepoint != codepoint || isWhiteSpace(codepoint)) { + if (codepoint === undefined || isWhiteSpace(codepoint)) { return position - offset; } return 0; @@ -31483,14 +33635,14 @@ consumeColor(parseInfo) { let position = parseInfo.currentPosition - parseInfo.offset; let offset = position; - let codepoint = parseInfo.stream.charCodeAt(position); - if (codepoint != 35 /* TokenMap.HASH */) { + let codepoint = parseInfo.codes[position]; + if (codepoint !== 35 /* TokenMap.HASH */) { return 0; } position++; let count = 0; while (true) { - codepoint = parseInfo.stream.charCodeAt(position); + codepoint = parseInfo.codes[position]; // 'a-f0-9' 'A-F0-9' if ((codepoint >= 0x30 && codepoint <= 0x39) || (codepoint >= 0x61 && codepoint <= 0x66) || @@ -31501,16 +33653,16 @@ } break; } - if (count != 3 && count != 4 && count != 6 && count != 8) { + if (count !== 3 && count !== 4 && count !== 6 && count !== 8) { return 0; } - codepoint = parseInfo.stream.charCodeAt(position); - if (codepoint != codepoint || + codepoint = parseInfo.codes[position]; + if (codepoint === undefined || isWhiteSpace(codepoint) || - codepoint == 41 /* TokenMap.RIGHT_PARENTHESIS */ || - codepoint == 59 /* TokenMap.SEMICOLON */ || - codepoint == 125 /* TokenMap.RIGHT_BRACE */ || - codepoint == 44 /* TokenMap.COMMA */) { + codepoint === 41 /* TokenMap.RIGHT_PARENTHESIS */ || + codepoint === 59 /* TokenMap.SEMICOLON */ || + codepoint === 125 /* TokenMap.RIGHT_BRACE */ || + codepoint === 44 /* TokenMap.COMMA */) { return position - offset; } return 0; @@ -31519,18 +33671,18 @@ let charCode; // consume an // inlined: this.peekCharCode(parseInfo) - while (isWhiteSpace(parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset))) { + while (isWhiteSpace(parseInfo.codes[parseInfo.currentPosition - parseInfo.offset])) { this.advanceCode(parseInfo); } // inlined: this.peekCharCode(parseInfo) - charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset); - if (charCode == 34 /* TokenMap.DOUBLE_QUOTE */ || charCode == 39 /* TokenMap.SINGLE_QUOTE */) { + charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]; + if (charCode === 34 /* TokenMap.DOUBLE_QUOTE */ || charCode === 39 /* TokenMap.SINGLE_QUOTE */) { return this.consumeStringAsURLToken(parseInfo); } do { this.advanceCode(parseInfo); // inlined: this.peekCharCode(parseInfo) - charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset); + charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]; } while ( // !(value === "/" && this.match(parseInfo, "/*") && charCode !== 41 /* TokenMap.RIGHT_PARENTHESIS */ && @@ -31539,14 +33691,14 @@ if (charCode !== 41 /* TokenMap.RIGHT_PARENTHESIS */) { let k = 1; while (k < endPosition) { - charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset + k); + charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset + k]; if (isWhiteSpace(charCode)) { k++; continue; } break; } - if (charCode != charCode || (charCode != 41 /* TokenMap.RIGHT_PARENTHESIS */ && !isIdentStart(charCode))) { + if (charCode === undefined || (charCode !== 41 /* TokenMap.RIGHT_PARENTHESIS */ && !isIdentStart(charCode))) { this.advance(parseInfo, k); return this.makeToken(parseInfo, exports.EnumToken.BadUrlTokenType); } @@ -31554,7 +33706,8 @@ return this.makeToken(parseInfo, // parseInfo.position < parseInfo.currentPosition // inlined: this.peekCharCode(parseInfo) - (charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset)) != charCode || !this.isURLToken(parseInfo) + (charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]) === undefined || + !this.isURLToken(parseInfo) ? exports.EnumToken.BadUrlTokenType : exports.EnumToken.UrlTokenTokenType); } @@ -31562,7 +33715,8 @@ * * @param parseInfo * @param hint - * @param options + * @param slice + * @param decodeSegments * @returns */ makeToken(parseInfo, hint, slice, decodeSegments) { @@ -31657,9 +33811,14 @@ if (isList) { val = findItem(hint, parseInfo, hasUnit ? slice : parseInfo.position - parseInfo.offset, parseInfo.currentPosition - parseInfo.offset); } - else if (hint == exports.EnumToken.NumberTokenType || hint == exports.EnumToken.WhitespaceTokenType) ; + else if (hint === exports.EnumToken.NumberTokenType || hint === exports.EnumToken.WhitespaceTokenType) ; else if (!isHint) { - val = parseInfo.stream.slice(slice ?? parseInfo.position - parseInfo.offset, parseInfo.currentPosition - parseInfo.offset); + // the canonical spelling of a known unit: `6DB` is rendered `6dB` + val = + (hint === exports.EnumToken.DimensionTokenType + ? findItem(exports.EnumToken.DimensionTokenType, parseInfo, slice ?? parseInfo.position - parseInfo.offset, parseInfo.currentPosition - parseInfo.offset) + : null) ?? + parseInfo.stream.slice(slice ?? parseInfo.position - parseInfo.offset, parseInfo.currentPosition - parseInfo.offset); } if (this.decodeString) { val = decodeEscapeSequences(val); @@ -31669,24 +33828,24 @@ } else { this.typ = hint; - if (hasUnit || hint == exports.EnumToken.PercentageTokenType || hint == exports.EnumToken.DimensionTokenType) { - this.val = parseNumber(parseInfo.stream, parseInfo.position - parseInfo.offset, slice); - if (hint != exports.EnumToken.PercentageTokenType) { + if (hasUnit || hint === exports.EnumToken.PercentageTokenType || hint === exports.EnumToken.DimensionTokenType) { + this.val = parseNumber(parseInfo.codes, parseInfo.stream, parseInfo.position - parseInfo.offset, slice); + if (hint !== exports.EnumToken.PercentageTokenType) { this.unit = val; if (val.startsWith("--")) { this.typ = exports.EnumToken.UserDefinedDimensionTokenType; } } } - else if (hint == exports.EnumToken.NumberTokenType) { - this.val = parseNumber(parseInfo.stream, slice ?? parseInfo.position - parseInfo.offset, parseInfo.currentPosition - parseInfo.offset); + else if (hint === exports.EnumToken.NumberTokenType) { + this.val = parseNumber(parseInfo.codes, parseInfo.stream, slice ?? parseInfo.position - parseInfo.offset, parseInfo.currentPosition - parseInfo.offset); } - else if (hint == exports.EnumToken.AtRuleTokenType) { + else if (hint === exports.EnumToken.AtRuleTokenType) { this.nam = val; } else { this.val = val; - if (hint == exports.EnumToken.ColorTokenType) { + if (hint === exports.EnumToken.ColorTokenType) { this.kin = exports.ColorType.HEX; } } @@ -31714,24 +33873,28 @@ return this; } /** - * + * true if the text of the token being read equals the input, ignoring the case. the token text starts at + * parseInfo.position: `0!important` is the number `0` followed by `!important` * @param parseInfo * @param input * @returns */ equalsIgnoreCase(parseInfo, input) { - let position = parseInfo.currentPosition - parseInfo.offset; + let position = parseInfo.position - parseInfo.offset; + if (parseInfo.currentPosition - parseInfo.position !== input.length) { + return false; + } let ca; let cb; for (let i = 0; i < input.length; i++) { - ca = parseInfo.stream.charCodeAt(position + i); + ca = parseInfo.codes[position + i]; cb = input.charCodeAt(i); // Normalize A-Z to a-z if (ca >= 65 && ca <= 90) ca += 32; if (cb >= 65 && cb <= 90) cb += 32; - if (ca != cb) { + if (ca !== cb) { return false; } } @@ -31747,20 +33910,12 @@ let position = parseInfo.currentPosition - parseInfo.offset; // compare the character codes: no single character strings for (let i = 0; i < input.length; i++) { - if (parseInfo.stream.charCodeAt(position + i) != input.charCodeAt(i)) { + if (parseInfo.codes[position + i] !== input.charCodeAt(i)) { return false; } } return true; } - /** - * Get the current character code without creating a string - * @param parseInfo - * @returns charCode at current position - */ - peekCharCode(parseInfo) { - return parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset); - } /** * * @param parseInfo @@ -31768,36 +33923,36 @@ * @returns */ peek(parseInfo, count = 1) { - if (count == 1) { + if (count === 1) { return parseInfo.stream.charAt(parseInfo.currentPosition - parseInfo.offset); } const position = parseInfo.currentPosition - parseInfo.offset; return parseInfo.stream.slice(position, position + count); } /** - * move forward by count characters (at most to the end of the stream) and record the new lines. the characters - * are read from the stream: no string is created + * move forward by count characters (at most to the end of the stream) and record the new lines. the code units are + * read: no string is created * @param parseInfo * @param count */ advance(parseInfo, count = 1) { - const stream = parseInfo.stream; + const codes = parseInfo.codes; const position = parseInfo.currentPosition - parseInfo.offset; - const remaining = stream.length - position; + const remaining = parseInfo.length - position; const length = count < remaining ? (count > 0 ? count : 0) : remaining > 0 ? remaining : 0; const lineStarts = parseInfo.source.lineStarts.lineStarts; let codepoint; for (let i = 0; i < length; i++) { - codepoint = stream.charCodeAt(position + i); - if (codepoint == 0xa || // \n - codepoint == 0xb || // \v - codepoint == 0xc || // \f - codepoint == 0xd || // \r - codepoint == 0x2028 || // \u2028 - codepoint == 0x2029 // \u2029 + codepoint = codes[position + i]; + if (codepoint === 0xa || // \n + codepoint === 0xb || // \v + codepoint === 0xc || // \f + codepoint === 0xd || // \r + codepoint === 0x2028 || // \u2028 + codepoint === 0x2029 // \u2029 ) { // \r\n: a single line start - if (codepoint == 0xa && i > 0 && stream.charCodeAt(position + i - 1) == 0xd) ; + if (codepoint === 0xa && i > 0 && codes[position + i - 1] === 0xd) ; else { lineStarts.push(position + parseInfo.offset + i); } @@ -31812,7 +33967,7 @@ * @param count */ skip(parseInfo, count) { - const remaining = parseInfo.stream.length - (parseInfo.currentPosition - parseInfo.offset); + const remaining = parseInfo.length - (parseInfo.currentPosition - parseInfo.offset); parseInfo.currentPosition += count < remaining ? count : remaining > 0 ? remaining : 0; } /** @@ -31836,16 +33991,17 @@ */ advanceCode(parseInfo) { const position = parseInfo.currentPosition - parseInfo.offset; - const codepoint = parseInfo.stream.charCodeAt(position); - if (codepoint != codepoint) { - return codepoint; - } - if (codepoint == 0xa || // \n - codepoint == 0xb || // \v - codepoint == 0xc || // \f - codepoint == 0xd || // \r - codepoint == 0x2028 || - codepoint == 0x2029) { + const codepoint = parseInfo.codes[position]; + // the end of the stream: NaN + if (codepoint === undefined) { + return NaN; + } + if (codepoint === 0xa || // \n + codepoint === 0xb || // \v + codepoint === 0xc || // \f + codepoint === 0xd || // \r + codepoint === 0x2028 || + codepoint === 0x2029) { parseInfo.source.lineStarts.lineStarts.push(position + parseInfo.offset); } parseInfo.currentPosition++; @@ -31875,15 +34031,15 @@ // } // } j--; - let codepoint = parseInfo.stream.charCodeAt(i); + let codepoint = parseInfo.codes[i]; // - - if (codepoint == 0x2d) { + if (codepoint === 0x2d) { let nextCodepoint; - // NaN != NaN - if ((nextCodepoint = parseInfo.stream.charCodeAt(i + 1)) != nextCodepoint) { + // the end of the stream + if ((nextCodepoint = parseInfo.codes[i + 1]) === undefined) { return false; } - if (!isIdentStart(nextCodepoint) && nextCodepoint != 0x2d) { + if (!isIdentStart(nextCodepoint) && nextCodepoint !== 0x2d) { return false; } codepoint = nextCodepoint; @@ -31892,16 +34048,16 @@ if (codepoint !== 0x2d && !isIdentStart(codepoint)) { return false; } - if (codepoint == 92 /* TokenMap.REVERSE_SOLIDUS */) { - codepoint = parseInfo.stream.charCodeAt(i + 1); + if (codepoint === 92 /* TokenMap.REVERSE_SOLIDUS */) { + codepoint = parseInfo.codes[i + 1]; i += String.fromCodePoint(codepoint).length; } while (i < j) { i += codepoint < 0x80 ? 1 : String.fromCodePoint(codepoint).length; - codepoint = parseInfo.stream.charCodeAt(i); - if (codepoint == 92 /* TokenMap.REVERSE_SOLIDUS */) { + codepoint = parseInfo.codes[i]; + if (codepoint === 92 /* TokenMap.REVERSE_SOLIDUS */) { i += codepoint < 0x80 ? 1 : String.fromCodePoint(codepoint).length; - codepoint = parseInfo.stream.charCodeAt(i); + codepoint = parseInfo.codes[i]; i += codepoint < 0x80 ? 1 : String.fromCodePoint(codepoint).length; continue; } @@ -31922,7 +34078,7 @@ let j = input.length; // compare the character codes: no single character strings while (i < j) { - if (parseInfo.stream.charCodeAt(parseInfo.position - parseInfo.offset + i) != input.charCodeAt(i)) { + if (parseInfo.codes[parseInfo.position - parseInfo.offset + i] !== input.charCodeAt(i)) { return false; } i++; @@ -31938,30 +34094,30 @@ let i = parseInfo.position - parseInfo.offset; let c; while (++i < parseInfo.currentPosition) { - c = parseInfo.stream.charCodeAt(i); + c = parseInfo.codes[i]; // single quote or double quote or start parenthesis or close parenthesis - if (isNonPrintable(c) || c == 0x27 || c == 0x22 || c == 0x28 || c == 0x29) { + if (isNonPrintable(c) || c === 0x27 || c === 0x22 || c === 0x28 || c === 0x29) { return false; } // valid escape - if (c == 92 /* TokenMap.REVERSE_SOLIDUS */) { + if (c === 92 /* TokenMap.REVERSE_SOLIDUS */) { i++; if (i >= parseInfo.currentPosition) { return false; } - c = parseInfo.stream.charCodeAt(i); + c = parseInfo.codes[i]; // c is not '\n' or '\r' or '\f' - if (c == 0x6e || c == 0x72 || c == 0x66) { + if (c === 0x6e || c === 0x72 || c === 0x66) { return false; } continue; } // is white space - if (c == 0x20 || c == 0x09) { + if (c === 0x20 || c === 0x09) { break; } } - return i == parseInfo.currentPosition; + return i === parseInfo.currentPosition; } done() { return this.typ === exports.EnumToken.EOF; @@ -31976,19 +34132,26 @@ let nextCharCode; // const result: TokenizeResult[] = []; // allow 10 characters buffer for the streaming parser to avoid incomplete tokens - const endPosition = parseInfo.stream.length - 1; // yieldEOFToken ? parseInfo.stream.length - 1 : parseInfo.stream.length - 10; + const endPosition = parseInfo.length - 1; let tokensCount; - // NaN is not equal to NaN - // inlined: this.peekCharCode(parseInfo) - while ((charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset)) == charCode) { + // the code units are undefined after the end of the stream + while ((charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]) !== undefined) { if (this.state === exports.EnumToken.UrlFunctionTokenDefType) { this.state = null; return this.consumeURLToken(parseInfo, endPosition); } - if (parseInfo.position == parseInfo.currentPosition) { - if (charCode == 45 /* TokenMap.MINUS */ || - charCode == 43 /* TokenMap.PLUS */ || - charCode == 46 /* TokenMap.DOT */ || + if (parseInfo.position === parseInfo.currentPosition) { + // `U+0025-00FF` + if (charCode === 0x55 || charCode === 0x75) { + tokensCount = this.consumeUnicodeRangeToken(parseInfo); + if (tokensCount > 0) { + this.skip(parseInfo, tokensCount); + return this.makeToken(parseInfo, exports.EnumToken.UniCodeRange); + } + } + if (charCode === 45 /* TokenMap.MINUS */ || + charCode === 43 /* TokenMap.PLUS */ || + charCode === 46 /* TokenMap.DOT */ || isDigit(charCode)) { tokensCount = this.consumeNumericToken(parseInfo); if (tokensCount > 0) { @@ -31997,27 +34160,28 @@ return this.makeToken(parseInfo, this.hint ?? exports.EnumToken.NumberTokenType, this.slice); } } - if (isIdentStart(charCode) || charCode == 45 /* TokenMap.MINUS */) { + if (isIdentStart(charCode) || charCode === 45 /* TokenMap.MINUS */) { tokensCount = this.consumeIdentToken(parseInfo); if (tokensCount > 0) { this.skipIdent(parseInfo, tokensCount); // inlined: this.peekCharCode(parseInfo) - charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset); + charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]; // do not match function - if (40 /* TokenMap.LEFT_PARENTHESIS */ != charCode) { + if (40 /* TokenMap.LEFT_PARENTHESIS */ !== charCode) { return this.makeToken(parseInfo, this.startsWith(parseInfo, "--") ? exports.EnumToken.DashedIdenTokenType : exports.EnumToken.IdenTokenType); } } } - if (charCode == 64 /* TokenMap.AT */) { + if (charCode === 64 /* TokenMap.AT */) { this.skip(parseInfo, 1); // inlined: this.peekCharCode(parseInfo) - charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset); + charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]; // match at-rule // inlined: this.peekCharCode(parseInfo) - if (charCode == 45 /* TokenMap.MINUS */ || isIdentStart(parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset))) { + if (charCode === 45 /* TokenMap.MINUS */ || + isIdentStart(parseInfo.codes[parseInfo.currentPosition - parseInfo.offset])) { // consume '@' parseInfo.position = parseInfo.currentPosition; tokensCount = this.consumeIdentToken(parseInfo); @@ -32027,7 +34191,7 @@ } } } - if (charCode == 35 /* TokenMap.HASH */) { + if (charCode === 35 /* TokenMap.HASH */) { tokensCount = this.consumeColor(parseInfo); if (tokensCount > 0) { this.skip(parseInfo, tokensCount); @@ -32055,7 +34219,7 @@ // return this.makeToken(parseInfo); // } this.skip(parseInfo, 1); - charCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset); + charCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]; // if (isDigit(charCode)) { // tokensCount = this.consumeNumericToken(parseInfo); // if (tokensCount > 0) { @@ -32068,8 +34232,8 @@ // } return this.makeToken(parseInfo, exports.EnumToken.Plus); case 45 /* TokenMap.MINUS */: - if (parseInfo.position == parseInfo.currentPosition) { - nextCharCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset + 1); + if (parseInfo.position === parseInfo.currentPosition) { + nextCharCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset + 1]; // not a number if (isWhiteSpace(nextCharCode)) { this.skip(parseInfo, 1); @@ -32162,7 +34326,7 @@ // } this.skip(parseInfo, 1); // inlined: this.peekCharCode(parseInfo) - if (parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset) == 58 /* TokenMap.COLON */) { + if (parseInfo.codes[parseInfo.currentPosition - parseInfo.offset] === 58 /* TokenMap.COLON */) { this.skip(parseInfo, 1); return this.makeToken(parseInfo, exports.EnumToken.DoubleColonTokenType); } @@ -32181,14 +34345,14 @@ } this.advanceCode(parseInfo); // inlined: this.peekCharCode(parseInfo) - nextCharCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset); - while (nextCharCode == 0x20 || + nextCharCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]; + while (nextCharCode === 0x20 || (nextCharCode >= 0x9 && nextCharCode <= 0xd) || - nextCharCode == 0x2028 || - nextCharCode == 0x2029) { + nextCharCode === 0x2028 || + nextCharCode === 0x2029) { this.advanceCode(parseInfo); // inlined: this.peekCharCode(parseInfo) - nextCharCode = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset); + nextCharCode = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset]; } return this.makeToken(parseInfo, exports.EnumToken.WhitespaceTokenType); case 44 /* TokenMap.COMMA */: @@ -32278,8 +34442,8 @@ return this.makeToken(parseInfo, getSymbolHint(parseInfo, parseInfo.position - parseInfo.offset, parseInfo.currentPosition - parseInfo.offset)); } this.skip(parseInfo, 2); - while ((charCode = this.advanceCode(parseInfo)) == charCode) { - if (charCode == 42 /* TokenMap.STAR */) { + while ((charCode = this.advanceCode(parseInfo)) === charCode) { + if (charCode === 42 /* TokenMap.STAR */) { if (this.match(parseInfo, "/")) { this.skip(parseInfo, 1); return this.makeToken(parseInfo, exports.EnumToken.CommentTokenType); @@ -32311,8 +34475,8 @@ this.skip(parseInfo, 1); if (this.match(parseInfo, "!--")) { this.skip(parseInfo, 3); - while ((charCode = this.advanceCode(parseInfo)) == charCode) { - if (charCode == 45 /* TokenMap.MINUS */ && this.match(parseInfo, "->")) { + while ((charCode = this.advanceCode(parseInfo)) === charCode) { + if (charCode === 45 /* TokenMap.MINUS */ && this.match(parseInfo, "->")) { break; } } @@ -32327,13 +34491,13 @@ { const startPosition = parseInfo.position - parseInfo.offset; let offset = 1; - let charCode = parseInfo.stream.charCodeAt(startPosition + offset); + let charCode = parseInfo.codes[startPosition + offset]; if (isLetter(charCode)) { - charCode = parseInfo.stream.charCodeAt(++offset + startPosition); - while (offset < endPosition && (charCode == 45 /* TokenMap.MINUS */ || isLetter(charCode))) { - charCode = parseInfo.stream.charCodeAt(++offset + startPosition); + charCode = parseInfo.codes[++offset + startPosition]; + while (offset < endPosition && (charCode === 45 /* TokenMap.MINUS */ || isLetter(charCode))) { + charCode = parseInfo.codes[++offset + startPosition]; } - if (offset > 1 && charCode == 62 /* TokenMap.GREATERTHAN */) { + if (offset > 1 && charCode === 62 /* TokenMap.GREATERTHAN */) { this.skip(parseInfo, offset); return this.makeToken(parseInfo, exports.EnumToken.CssTypeTokenType); } @@ -32363,8 +34527,8 @@ } return this.consumeString(parseInfo); case 46 /* TokenMap.DOT */: - const codepoint = parseInfo.stream.charCodeAt(parseInfo.currentPosition - parseInfo.offset + 1); - if (isIdentStart(codepoint) || codepoint == 45 /* TokenMap.MINUS */) { + const codepoint = parseInfo.codes[parseInfo.currentPosition - parseInfo.offset + 1]; + if (isIdentStart(codepoint) || codepoint === 45 /* TokenMap.MINUS */) { // if (parseInfo.position < parseInfo.currentPosition) { // return this.makeToken(parseInfo); // } @@ -32412,12 +34576,34 @@ break; } } - // inlined: parseInfo.source.getContent() - parseInfo.stream = parseInfo.source.content; + Tokenizer.load(parseInfo, parseInfo.source.content); return this; // .next(); } } + /** + * response type + */ + exports.ResponseType = void 0; + (function (ResponseType) { + /** + * return text + */ + ResponseType[ResponseType["Text"] = 0] = "Text"; + /** + * return a readable stream + */ + ResponseType[ResponseType["ReadableStream"] = 1] = "ReadableStream"; + /** + * return an arraybuffer + */ + ResponseType[ResponseType["ArrayBuffer"] = 2] = "ArrayBuffer"; + /** + * return a json object + */ + ResponseType[ResponseType["JSON"] = 3] = "JSON"; + })(exports.ResponseType || (exports.ResponseType = {})); + // Alphabet: a-z, A-Z, 0-9, _, - const LOWER = "abcdefghijklmnopqrstuvwxyz"; const DIGITS = "0123456789"; @@ -32488,7 +34674,7 @@ case "base64url": case "base64": result = btoa(input); - if (algo == "base64url") { + if (algo === "base64url") { result = result.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } return result.slice(0, length); @@ -32518,7 +34704,7 @@ case "base64url": case "base64": result = btoa(input); - if (algo == "base64url") { + if (algo === "base64url") { result = result.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } return result.slice(0, length); @@ -32539,22 +34725,22 @@ const list = []; let index; for (index = 0; index < chi.length; index++) { - if (arena.dataTypes[chi[index]] == exports.EnumToken.CommentTokenType || - arena.dataTypes[chi[index]] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[chi[index]] === exports.EnumToken.CommentTokenType || + arena.dataTypes[chi[index]] === exports.EnumToken.WhitespaceTokenType) { continue; } - if (arena.dataTypes[chi[index]] == exports.EnumToken.IdenTokenType && + if (arena.dataTypes[chi[index]] === exports.EnumToken.IdenTokenType && equalsIgnoreCase("of", arena.strings[arena.stringValue[chi[index]]])) { index--; break; } list.push(chi[index]); } - if (list.length == 2) { - if (arena.dataTypes[list[1]] == exports.EnumToken.NumberTokenType) { - if (arena.numericValue[list[1]] == 0) { + if (list.length === 2) { + if (arena.dataTypes[list[1]] === exports.EnumToken.NumberTokenType) { + if (arena.numericValue[list[1]] === 0) { list.length = 1; - if (arena.dataTypes[list[0]] == exports.EnumToken.DimensionTokenType && arena.numericValue[list[0]] == -2) { + if (arena.dataTypes[list[0]] === exports.EnumToken.DimensionTokenType && arena.numericValue[list[0]] === -2) { arena.numericValue[list[0]] = 2; } } @@ -32564,16 +34750,16 @@ list.splice(1, 0, arena.createToken(exports.EnumToken.LiteralTokenType, sign > 0 ? "+" : "-")); } } - if (list.length == 3 && - arena.dataTypes[list[2]] == exports.EnumToken.NumberTokenType && - arena.dataTypes[list[0]] == exports.EnumToken.DimensionTokenType && - (arena.numericValue[list[0]] == 2 || arena.numericValue[list[0]] == -2)) { - if (1 == arena.numericValue[list[2]]) { + if (list.length === 3 && + arena.dataTypes[list[2]] === exports.EnumToken.NumberTokenType && + arena.dataTypes[list[0]] === exports.EnumToken.DimensionTokenType && + (arena.numericValue[list[0]] === 2 || arena.numericValue[list[0]] === -2)) { + if (1 === arena.numericValue[list[2]]) { const ident = arena.createToken(exports.EnumToken.IdenTokenType, "odd"); arena.copyLocation(ident, list[0]); list.splice(0, 3, ident); } - else if (0 == arena.numericValue[list[2]]) { + else if (0 === arena.numericValue[list[2]]) { const ident = arena.createToken(exports.EnumToken.IdenTokenType, "even"); arena.copyLocation(ident, list[0]); list.splice(0, 3, ident); @@ -32581,20 +34767,20 @@ } chi.splice(0, index, ...list); } - if (list.length == 1) { - if (arena.dataTypes[list[0]] == exports.EnumToken.IdenTokenType && + if (list.length === 1) { + if (arena.dataTypes[list[0]] === exports.EnumToken.IdenTokenType && equalsIgnoreCase("-n", arena.strings[arena.stringValue[list[0]]])) { // inlined: arena.setStr(list[0], "n") arena.stringValue[list[0]] = arena.internString("n"); } } - if (list.length == 3) { - if (arena.dataTypes[list[0]] == exports.EnumToken.IdenTokenType && - ("n" == arena.strings[arena.stringValue[list[0]]] || - "-n" == arena.strings[arena.stringValue[list[0]]] || - "+n" == arena.strings[arena.stringValue[list[0]]])) { - if (arena.dataTypes[list[1]] == exports.EnumToken.NextSiblingCombinatorTokenType) { - if (arena.dataTypes[list[2]] == exports.EnumToken.NumberTokenType && 0 == arena.numericValue[list[2]]) { + if (list.length === 3) { + if (arena.dataTypes[list[0]] === exports.EnumToken.IdenTokenType && + ("n" === arena.strings[arena.stringValue[list[0]]] || + "-n" === arena.strings[arena.stringValue[list[0]]] || + "+n" === arena.strings[arena.stringValue[list[0]]])) { + if (arena.dataTypes[list[1]] === exports.EnumToken.NextSiblingCombinatorTokenType) { + if (arena.dataTypes[list[2]] === exports.EnumToken.NumberTokenType && 0 === arena.numericValue[list[2]]) { // inlined: arena.setStr(list[0], "n") arena.stringValue[list[0]] = arena.internString("n"); chi.splice(0, index, list[0]); @@ -32604,12 +34790,13 @@ } } } - const token = chi.find((t) => arena.dataTypes[t] != exports.EnumToken.WhitespaceTokenType && arena.dataTypes[t] != exports.EnumToken.CommentTokenType); + const token = chi.find((t) => arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[t] !== exports.EnumToken.CommentTokenType); if (token != null) { - if (arena.dataTypes[token] == exports.EnumToken.IdenTokenType || arena.dataTypes[token] == exports.EnumToken.LiteralTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.IdenTokenType || + arena.dataTypes[token] === exports.EnumToken.LiteralTokenType) { const val = arena.strings[arena.stringValue[token]]; - if (arena.dataTypes[token] == exports.EnumToken.IdenTokenType && (val == "odd" || val == "even")) { - if (val == "even") { + if (arena.dataTypes[token] === exports.EnumToken.IdenTokenType && (val === "odd" || val === "even")) { + if (val === "even") { arena.resetToken(token, exports.EnumToken.DimensionTokenType, 2, "n"); } } @@ -32634,11 +34821,11 @@ let num = null; let i = index + 1; for (; i < chi.length; i++) { - if (arena.dataTypes[chi[i]] == exports.EnumToken.WhitespaceTokenType || - arena.dataTypes[chi[i]] == exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[chi[i]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[chi[i]] === exports.EnumToken.CommentTokenType) { continue; } - if (arena.dataTypes[chi[i]] == exports.EnumToken.NumberTokenType) { + if (arena.dataTypes[chi[i]] === exports.EnumToken.NumberTokenType) { num = chi[i]; break; } @@ -32659,6 +34846,41 @@ } arena.setTokenList(func, chi); } + /** + * split the unicode ranges of a selector: `u+a` is the element `u` followed by the element `a`, not a unicode range + * @param arena + * @param tokens + */ + function splitUnicodeRanges(arena, tokens) { + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (arena.dataTypes[token] === exports.EnumToken.UniCodeRange) { + const text = arena.strings[arena.stringValue[token]]; + const rest = text.slice(2); + const split = [ + arena.createToken(exports.EnumToken.IdenTokenType, text.charAt(0)), + arena.createToken(exports.EnumToken.Plus, "+"), + arena.createToken(isIdent(rest) ? exports.EnumToken.IdenTokenType : exports.EnumToken.LiteralTokenType, rest), + ]; + for (const t of split) { + arena.copyLocation(t, token); + } + tokens.splice(i, 1, ...split); + i += split.length - 1; + } + else if (arena.firstToken[token] !== 0) { + // `:is(u+a)` + const children = arena.tokens(token); + if (children.some((child) => arena.dataTypes[child] === exports.EnumToken.UniCodeRange || arena.firstToken[child] !== 0)) { + const length = children.length; + splitUnicodeRanges(arena, children); + if (children.length !== length) { + arena.setTokenList(token, children); + } + } + } + } + } /** * parse selector * @param arena @@ -32669,13 +34891,15 @@ */ function parseSelector(arena, tokens, context, options, errors) { const contextType = context == null ? null : arena.dataTypes[context]; + splitUnicodeRanges(arena, tokens); if (contextType === exports.EnumToken.KeyframesAtRuleNodeType) { const result = matchAllSyntaxes(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, "keyframe-selectors"), createValidationContext(arena, tokens), options); const parts = splitTokenList(arena, tokens); for (const part of parts) { trimArray(arena, part); if (options.minify) { - const filtered = part.filter((token) => arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== exports.EnumToken.CommentTokenType); + const filtered = part.filter((token) => arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[token] !== exports.EnumToken.CommentTokenType); if (filtered.length === 1) { if (arena.dataTypes[filtered[0]] === exports.EnumToken.IdenTokenType && "from" === arena.strings[arena.stringValue[filtered[0]]].toLowerCase()) { @@ -32740,7 +34964,7 @@ parent = arena.parents[parent]; continue; } - nested = arena.dataTypes[parent] == exports.EnumToken.RuleNodeType; + nested = arena.dataTypes[parent] === exports.EnumToken.RuleNodeType; if (nested) { break; } @@ -32750,18 +34974,18 @@ let write = 0; for (let read = 0; read < tokens.length; read++) { let token = tokens[read]; - if (arena.dataTypes[token] == exports.EnumToken.ColonTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.ColonTokenType) { const next = tokens[read + 1]; - if (arena.dataTypes[next] == exports.EnumToken.IdenTokenType) { + if (arena.dataTypes[next] === exports.EnumToken.IdenTokenType) { arena.dataTypes[token] = exports.EnumToken.PseudoElementTokenType; // inlined: arena.setStr(token, ":" + arena.strings[arena.stringValue[next]]) - arena.stringValue[token] = arena.internString((":" + arena.strings[arena.stringValue[next]])); + arena.stringValue[token] = arena.internString(":" + arena.strings[arena.stringValue[next]]); arena.spanLocation(token, token, next); all[write++] = token; read++; continue; } - if (arena.dataTypes[next] == exports.EnumToken.FunctionTokenDefType) { + if (arena.dataTypes[next] === exports.EnumToken.FunctionTokenDefType) { val = ":" + arena.strings[arena.stringValue[next]]; arena.dataTypes[token] = val + "()" in getSyntaxConfig().selectors @@ -32775,19 +34999,19 @@ continue; } } - if (arena.dataTypes[token] == exports.EnumToken.DoubleColonTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.DoubleColonTokenType) { const next = tokens[read + 1]; val = ":" + arena.strings[arena.stringValue[next]]; - if (arena.dataTypes[next] == exports.EnumToken.IdenTokenType) { + if (arena.dataTypes[next] === exports.EnumToken.IdenTokenType) { arena.dataTypes[token] = exports.EnumToken.PseudoClassTokenType; // inlined: arena.setStr(token, (pseudoElements.includes(val) ? "" : ":") + val) - arena.stringValue[token] = arena.internString(((pseudoElements.includes(val) ? "" : ":") + val)); + arena.stringValue[token] = arena.internString((pseudoElements.includes(val) ? "" : ":") + val); arena.spanLocation(token, token, next); all[write++] = token; read++; continue; } - if (arena.dataTypes[next] == exports.EnumToken.FunctionTokenDefType) { + if (arena.dataTypes[next] === exports.EnumToken.FunctionTokenDefType) { val = "::" + arena.strings[arena.stringValue[next]]; arena.dataTypes[token] = val + "()" in getSyntaxConfig().selectors @@ -32801,7 +35025,7 @@ continue; } } - if (arena.dataTypes[token] == exports.EnumToken.ColorTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.ColorTokenType) { if (isHash(arena.strings[arena.stringValue[token]])) { arena.dataTypes[token] = exports.EnumToken.HashTokenType; all[write++] = token; @@ -32837,7 +35061,7 @@ break; case exports.EnumToken.AttrEndTokenType: // inlined: arena.typeOf(stack.at(-1)) - if (arena.dataTypes[stack.at(-1)] == exports.EnumToken.AttrStartTokenType) { + if (arena.dataTypes[stack.at(-1)] === exports.EnumToken.AttrStartTokenType) { const attr = stack[stack.length - 1]; index = tokens.indexOf(attr); arena.spanLocation(attr, attr, token); @@ -32854,7 +35078,7 @@ break; case exports.EnumToken.EndParensTokenType: // inlined: arena.typeOf(stack.at(-1)) - if (arena.dataTypes[stack.at(-1)] == exports.EnumToken.PseudoClassFunctionTokenDefType) { + if (arena.dataTypes[stack.at(-1)] === exports.EnumToken.PseudoClassFunctionTokenDefType) { const func = stack[stack.length - 1]; index = tokens.indexOf(func); arena.spanLocation(func, func, token); @@ -32867,10 +35091,10 @@ // parse an+b // an+b produces an ident such as 'n-0', a literal such as '+2n-0' or a list of tokens such as[2n\s?[+-]\s?3] const name = arena.strings[arena.stringValue[func]]; - if (name == ":nth-child" || - name == ":nth-last-child" || - name == ":nth-of-type" || - name == ":nth-last-of-type") { + if (name === ":nth-child" || + name === ":nth-last-child" || + name === ":nth-of-type" || + name === ":nth-last-of-type") { minifyNthExpression(arena, func); } } @@ -32905,7 +35129,7 @@ let part = []; for (let index = 0; index < tokens.length; index++) { const curr = tokens[index]; - if (arena.dataTypes[curr] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[curr] === exports.EnumToken.WhitespaceTokenType) { if (trimWhiteSpace.includes(arena.dataTypes[tokens[index - 1]]) || trimWhiteSpace.includes(arena.dataTypes[tokens[index + 1]]) || // inlined: arena.str(tokens[index - 1]) @@ -32916,7 +35140,7 @@ } } const t = renderValue(arena, curr, selectorRenderOptions); - if (t == ",") { + if (t === ",") { addSelector(selectors, part); part = []; } @@ -32940,8 +35164,8 @@ */ function addSelector(selectors, curr) { for (let i = 0; i < curr.length; i++) { - if (i + 1 < curr.length && curr[i] == "*") { - const index = curr[i + 1] == " " ? 2 : 1; + if (i + 1 < curr.length && curr[i] === "*") { + const index = curr[i + 1] === " " ? 2 : 1; if (![">", "~", "+"].includes(curr[index])) { curr.splice(i, index); } @@ -32967,8 +35191,8 @@ result += buffer + " "; buffer = ""; } - else if (char == ".") { - while (i + 1 < template.length && template[i + 1] == ".") { + else if (char === ".") { + while (i + 1 < template.length && template[i + 1] === ".") { i++; } if (isWhiteSpace(result.at(-1)?.charCodeAt(0))) { @@ -33034,7 +35258,7 @@ let i; let nam = arena.strings[arena.stringValue[name]]; // parent at-rule name - const isAtRule = parent != null && typeof parent == "number" && arena.dataTypes[parent] === exports.EnumToken.AtRuleNodeType; + const isAtRule = parent != null && typeof parent === "number" && arena.dataTypes[parent] === exports.EnumToken.AtRuleNodeType; const parentNam = isAtRule ? arena.strings[arena.name[parent]] : null; let rules = null; let syntaxRules = null; @@ -33048,16 +35272,17 @@ } for (i = 0; i < tokens.length; i++) { const token = tokens[i]; - if (arena.dataTypes[token] == exports.EnumToken.WhitespaceTokenType || - arena.dataTypes[token] == exports.EnumToken.CommentTokenType || - arena.dataTypes[token] == exports.EnumToken.BadCdoTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[token] === exports.EnumToken.CommentTokenType || + arena.dataTypes[token] === exports.EnumToken.BadCdoTokenType) { continue; } break; } if ( // inlined: arena.typeOf(name) - (arena.dataTypes[name] !== exports.EnumToken.IdenTokenType && arena.dataTypes[name] !== exports.EnumToken.DashedIdenTokenType) || + (arena.dataTypes[name] !== exports.EnumToken.IdenTokenType && + arena.dataTypes[name] !== exports.EnumToken.DashedIdenTokenType) || arena.dataTypes[tokens[i]] !== exports.EnumToken.ColonTokenType) { if (tokens.length > 0) { arena.spanLocation(name, name, tokens[tokens.length - 1]); @@ -33079,7 +35304,7 @@ tokens = tokens.slice(start, end); // inlined: arena.typeOf(name) if (validate && arena.dataTypes[name] === exports.EnumToken.IdenTokenType) { - if (isAtRule && parentNam != "import" && parentNam != "supports" && parentNam != "media") { + if (isAtRule && parentNam !== "import" && parentNam !== "supports" && parentNam !== "media") { // check @at-rule description // pick up the syntax or reject immediately // else do this @@ -33100,13 +35325,14 @@ else { syntaxRules = getParsedSyntax(ValidationSyntaxGroupEnum.Declarations, lowercase(nam)); } - // or + // , or // else if (syntaxRules == null || (syntaxRules.length === 1 && syntaxRules[0].typ === ValidationTokenEnum.PropertyType && (syntaxRules[0].val === "declaration-list" || - syntaxRules[0].val === "declaration-rule-list"))) { + syntaxRules[0].val === "declaration-rule-list" || + syntaxRules[0].val === "block-contents"))) { if (isAtRule && (parentNam === "swash" || parentNam === "annotation" || @@ -33159,24 +35385,25 @@ for (i = 0; i < tokens.length; i++) { token = tokens[i]; if (tokensfuncDefMap.has(arena.dataTypes[token]) || - arena.dataTypes[token] == exports.EnumToken.StartParensTokenType || - arena.dataTypes[token] == exports.EnumToken.BlockStartTokenType) { + arena.dataTypes[token] === exports.EnumToken.StartParensTokenType || + arena.dataTypes[token] === exports.EnumToken.BlockStartTokenType) { stack.push(token); continue; } - if (arena.dataTypes[token] === exports.EnumToken.ColonTokenType && stack.length == 0) { + if (arena.dataTypes[token] === exports.EnumToken.ColonTokenType && stack.length === 0) { stack.push(token); continue; } switch (arena.dataTypes[token]) { case exports.EnumToken.Literal: // inlined: arena.typeOf(stack.at(-1)) - if (arena.strings[arena.stringValue[token]] === "/" && arena.dataTypes[stack.at(-1)] == exports.EnumToken.MathFunctionTokenDefType) { + if (arena.strings[arena.stringValue[token]] === "/" && + arena.dataTypes[stack.at(-1)] === exports.EnumToken.MathFunctionTokenDefType) { arena.dataTypes[token] = exports.EnumToken.Div; } else if (arena.strings[arena.stringValue[token]] === "-" && // inlined: arena.typeOf(stack.at(-1)) - arena.dataTypes[stack.at(-1)] == exports.EnumToken.MathFunctionTokenDefType) { + arena.dataTypes[stack.at(-1)] === exports.EnumToken.MathFunctionTokenDefType) { arena.dataTypes[token] = exports.EnumToken.Sub; } break; @@ -33210,7 +35437,7 @@ if (arena.dataTypes[tokens[index]] === exports.EnumToken.WildCardFunctionTokenType && equalsIgnoreCase(arena.strings[arena.stringValue[tokens[index]]], "if")) { const last = arena.lastToken[tokens[index]]; - if (last != 0 && arena.dataTypes[last] === exports.EnumToken.SemiColonTokenType) { + if (last !== 0 && arena.dataTypes[last] === exports.EnumToken.SemiColonTokenType) { arena.detach(last); } let foundElse = false; @@ -33224,7 +35451,7 @@ } let index = -1; while (++index < curr.length) { - if (arena.dataTypes[curr[index]] == exports.EnumToken.IdenTokenType && + if (arena.dataTypes[curr[index]] === exports.EnumToken.IdenTokenType && equalsIgnoreCase("else", arena.strings[arena.stringValue[curr[index]]])) { foundElse = true; } @@ -33260,7 +35487,8 @@ } else if (arena.dataTypes[tokens[index]] === exports.EnumToken.UrlFunctionTokenType) { const url = arena.findToken(tokens[index], (arena, t) => arena.dataTypes[t] === exports.EnumToken.StringTokenType); - if (url != null && /^[a-zA-Z0-0/_.-]+$/.test(arena.strings[arena.stringValue[url]].slice(1, -1))) { + if (url != null && + /^[a-zA-Z0-9/_.-]+$/.test(arena.strings[arena.stringValue[url]].slice(1, -1))) { arena.dataTypes[url] = exports.EnumToken.UrlTokenTokenType; // inlined: arena.setStr(url, arena.strings[arena.stringValue[url]].slice(1, -1)) arena.stringValue[url] = arena.internString(arena.strings[arena.stringValue[url]].slice(1, -1)); @@ -33284,7 +35512,10 @@ message: `invalid color`, node: tokens[index], // inlined: options.source!.getSourceLocation(arena.getSpanStart(tokens[index])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[index]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[index])), + ], }); } } @@ -33331,7 +35562,7 @@ i--; continue; } - if (arena.dataTypes[tokens[i - 1]] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[tokens[i - 1]] === exports.EnumToken.WhitespaceTokenType) { for (let index = i - 1; index < tokens.length - 1; index++) { tokens[index] = tokens[index + 1]; } @@ -33346,7 +35577,10 @@ message: "unbalanced token", node: stack[stack.length - 1], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stack[stack.length - 1])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stack[stack.length - 1]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stack[stack.length - 1])), + ], }); if (tokens.length > 0) { arena.spanLocation(name, name, tokens[tokens.length - 1]); @@ -33377,21 +35611,24 @@ if (tokens.length > 0) { arena.spanLocation(name, name, tokens[tokens.length - 1]); } - return createDeclarationNode(arena, name, tokens, hasImportantFlag ? exports.EnumAstNodeStatus.Unknown | exports.EnumAstNodeStatus.ImportantDeclaration : exports.EnumAstNodeStatus.Unknown, result?.errors ?? null); + return createDeclarationNode(arena, name, tokens, hasImportantFlag + ? exports.EnumAstNodeStatus.Unknown | exports.EnumAstNodeStatus.ImportantDeclaration + : exports.EnumAstNodeStatus.Unknown, result?.errors ?? null); } if (equalsIgnoreCase("composes", nam)) { let index = -1; for (let i = 0; i < tokens.length; i++) { - if (arena.dataTypes[tokens[i]] === exports.EnumToken.IdenTokenType && equalsIgnoreCase("from", arena.strings[arena.stringValue[tokens[i]]])) { + if (arena.dataTypes[tokens[i]] === exports.EnumToken.IdenTokenType && + equalsIgnoreCase("from", arena.strings[arena.stringValue[tokens[i]]])) { index = i; break; } } - const left = trimArray(arena, index == -1 ? tokens : tokens.slice(0, index)); - const right = index == -1 ? null : trimArray(arena, tokens.slice(index + 1)); + const left = trimArray(arena, index === -1 ? tokens : tokens.slice(0, index)); + const right = index === -1 ? null : trimArray(arena, tokens.slice(index + 1)); const composes = arena.createToken(exports.EnumToken.ComposesSelectorNodeType); const first = tokens[0]; - const last = index != -1 && right.length > 0 ? right[right.length - 1] : left[left.length - 1]; + const last = index !== -1 && right.length > 0 ? right[right.length - 1] : left[left.length - 1]; // inlined: arena.setField(composes, TokenField.L, ...left) arena.setTokenList(arena.fieldList(composes, exports.TokenField.L), left); if (right != null && right.length > 0) { @@ -33449,10 +35686,10 @@ const scopes = [currentScope]; const stack = []; const tokens = []; - let expectAndOrComma = false; i = 0; while (i < stream.length && - (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType)) { + (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType)) { tokens.push(stream[i]); i++; } @@ -33471,7 +35708,10 @@ message: `expecting ''`, node: stream[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], }); } } @@ -33482,22 +35722,21 @@ message: `expecting '('`, node: stream[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], }); } } for (; i < stream.length; i++) { tokens.push(stream[i]); - if (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType) { continue; } - if (expectAndOrComma) { - if (arena.dataTypes[stream[i]] === exports.EnumToken.IdenTokenType) { - arena.strings[arena.stringValue[stream[i]]].toLowerCase(); - } - expectAndOrComma = false; - } - if (arena.dataTypes[stream[i]] === exports.EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[stream[i]])) { + if (arena.dataTypes[stream[i]] === exports.EnumToken.StartParensTokenType || + tokensfuncDefMap.has(arena.dataTypes[stream[i]])) { scopes.push((currentScope = new Set())); stack.push(stream[i]); continue; @@ -33515,9 +35754,10 @@ { const val = arena.strings[arena.stringValue[stream[i]]].toLowerCase(); if (val === "and" || val === "or") { - arena.dataTypes[stream[i]] = val === "and" ? exports.EnumToken.AndTokenType : exports.EnumToken.OrTokenType; + arena.dataTypes[stream[i]] = + val === "and" ? exports.EnumToken.AndTokenType : exports.EnumToken.OrTokenType; if (val === "or" && - scopes.length == 1 && + scopes.length === 1 && scopes[0].size > 0 && !scopes[0].has(exports.EnumToken.OrTokenType)) { success = false; @@ -33526,7 +35766,10 @@ node: stream[i], message: ` is not allowed outside of parentheses`, // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], }); break; } @@ -33537,7 +35780,10 @@ node: stream[i], message: `cannot mix and at the same level`, // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], }); } currentScope.add(arena.dataTypes[stream[i]]); @@ -33580,19 +35826,20 @@ const left = trimArray(arena, tokens.slice(index3 + 1, index2)); const right = trimArray(arena, tokens.slice(index + 1, tokens.length - 1)); const names = trimArray(arena, tokens.slice(index2 + 1, index)); - const filteredNames = names.filter((n) => arena.dataTypes[n] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[n] !== exports.EnumToken.CommentTokenType); + const filteredNames = names.filter((n) => arena.dataTypes[n] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[n] !== exports.EnumToken.CommentTokenType); const name = arena.strings[arena.stringValue[filteredNames[0]]]; const mfInfo = getMFInfo(name); for (const val of [left, right]) { if (options.computeCalcExpression) { if (mfInfo == null || - (mfInfo.type != MediaFeatureType.KeywordType && - mfInfo.type != MediaFeatureType.StringType)) { + (mfInfo.type !== MediaFeatureType.KeywordType && + mfInfo.type !== MediaFeatureType.StringType)) { for (let l = 0; l < val.length; l++) { if (arena.dataTypes[val[l]] === exports.EnumToken.MathFunctionTokenType && arena.strings[arena.stringValue[val[l]]] === "calc") { const value = evaluate(arena, [val[l]]); - if (value.length == 1) { + if (value.length === 1) { arena.copyLocation(value[0], val[l]); val[l] = value[0]; } @@ -33627,7 +35874,9 @@ // inlined: arena.setField(rangeQuery, TokenField.Op, prevToken) arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.Op), [prevToken]); // inlined: arena.setField(rangeQuery, TokenField.Op2, stack[stack.length - 1]) - arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.Op2), [stack[stack.length - 1]]); + arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.Op2), [ + stack[stack.length - 1], + ]); // inlined: arena.setField(rangeQuery, TokenField.R, ...right) arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.R), right); if (left.length > 0 && right.length > 0) { @@ -33647,19 +35896,20 @@ const index3 = tokens.indexOf(stack.at(-2)); let names = trimArray(arena, tokens.slice(index3 + 1, index2)); let values = trimArray(arena, tokens.slice(index2 + 1, tokens.length - 1)); - const filteredNames = (names).filter((n) => arena.dataTypes[n] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[n] !== exports.EnumToken.CommentTokenType); + const filteredNames = (names).filter((n) => arena.dataTypes[n] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[n] !== exports.EnumToken.CommentTokenType); const name = arena.strings[arena.stringValue[filteredNames[0]]]; const mfInfo = getMFInfo(name); if (options.computeCalcExpression) { if (mfInfo == null || - (mfInfo.type != MediaFeatureType.KeywordType && - mfInfo.type != MediaFeatureType.StringType)) { + (mfInfo.type !== MediaFeatureType.KeywordType && + mfInfo.type !== MediaFeatureType.StringType)) { const val = values; for (let l = 0; l < val.length; l++) { if (arena.dataTypes[val[l]] === exports.EnumToken.MathFunctionTokenType && arena.strings[arena.stringValue[val[l]]] === "calc") { const value = evaluate(arena, [val[l]]); - if (value.length == 1) { + if (value.length === 1) { arena.copyLocation(value[0], val[l]); val[l] = value[0]; } @@ -33677,14 +35927,18 @@ action: "drop", node: arr[0], // inlined: options.source!.getSourceLocation(arena.getSpanStart(arr[0])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(arr[0]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(arr[0])), + ], message: `${mfValue.isValueAllowed === false ? "invalid " : "expected "}`, }); break; } if (mfInfo?.type === MediaFeatureType.RatioType) { const val = values; - const filteredValues = val.filter((n) => arena.dataTypes[n] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[n] !== exports.EnumToken.CommentTokenType); + const filteredValues = val.filter((n) => arena.dataTypes[n] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[n] !== exports.EnumToken.CommentTokenType); if (filteredValues.length === 3) { if (options.computeCalcExpression) { const div = gcd(arena.numericValue[filteredValues[0]], arena.numericValue[filteredValues[2]]); @@ -33729,7 +35983,10 @@ action: "drop", node: stream[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], message: `unmatched ')'`, }); break; @@ -33773,35 +36030,35 @@ // media range query if (options.minify && arena.dataTypes[op] === exports.EnumToken.AndTokenType) { const leftCondition = left.length === 1 && - arena.dataTypes[left[0]] == exports.EnumToken.ParensTokenType && - arena.tokenCount(left[0]) == 1 + arena.dataTypes[left[0]] === exports.EnumToken.ParensTokenType && + arena.tokenCount(left[0]) === 1 ? arena.firstToken[left[0]] : null; const rightCondition = right.length === 1 && - arena.dataTypes[right[0]] == exports.EnumToken.ParensTokenType && - arena.tokenCount(right[0]) == 1 + arena.dataTypes[right[0]] === exports.EnumToken.ParensTokenType && + arena.tokenCount(right[0]) === 1 ? arena.firstToken[right[0]] : null; if (leftCondition != null && rightCondition != null && - arena.dataTypes[leftCondition] == exports.EnumToken.MediaQueryConditionTokenType && - arena.dataTypes[rightCondition] == exports.EnumToken.MediaQueryConditionTokenType) { + arena.dataTypes[leftCondition] === exports.EnumToken.MediaQueryConditionTokenType && + arena.dataTypes[rightCondition] === exports.EnumToken.MediaQueryConditionTokenType) { const leftNames = arena.fieldTokens(leftCondition, exports.TokenField.L); const rightNames = arena.fieldTokens(rightCondition, exports.TokenField.L); const leftOp = arena.field(leftCondition, exports.TokenField.Op); const rightOp = arena.field(rightCondition, exports.TokenField.Op); - if (leftNames.length == 1 && - arena.dataTypes[leftNames[0]] == exports.EnumToken.IdenTokenType && - (arena.dataTypes[leftOp] == exports.EnumToken.GtTokenType || - arena.dataTypes[leftOp] == exports.EnumToken.GteTokenType) && - rightNames.length == 1 && - arena.dataTypes[rightNames[0]] == exports.EnumToken.IdenTokenType && - (arena.dataTypes[rightOp] == exports.EnumToken.LtTokenType || - arena.dataTypes[rightOp] == exports.EnumToken.LteTokenType) && + if (leftNames.length === 1 && + arena.dataTypes[leftNames[0]] === exports.EnumToken.IdenTokenType && + (arena.dataTypes[leftOp] === exports.EnumToken.GtTokenType || + arena.dataTypes[leftOp] === exports.EnumToken.GteTokenType) && + rightNames.length === 1 && + arena.dataTypes[rightNames[0]] === exports.EnumToken.IdenTokenType && + (arena.dataTypes[rightOp] === exports.EnumToken.LtTokenType || + arena.dataTypes[rightOp] === exports.EnumToken.LteTokenType) && equalsIgnoreCase(arena.strings[arena.stringValue[leftNames[0]]], arena.strings[arena.stringValue[rightNames[0]]])) { const rangeQuery = arena.createToken(exports.EnumToken.MediaRangeQueryTokenType); arena.dataTypes[leftOp] = - arena.dataTypes[leftOp] == exports.EnumToken.GteTokenType + arena.dataTypes[leftOp] === exports.EnumToken.GteTokenType ? exports.EnumToken.LteTokenType : exports.EnumToken.LtTokenType; // inlined: arena.setField(rangeQuery, TokenField.L, ...arena.fieldTokens(leftCondition, TokenField.R)) @@ -33823,7 +36080,6 @@ } } } - expectAndOrComma = true; } } break; @@ -33845,7 +36101,7 @@ stream.length = 0; let hasPart = false; for (const part of parts) { - if (part.length == 0) { + if (part.length === 0) { continue; } if (hasPart) { @@ -33885,20 +36141,20 @@ ]); for (; i < stream.length; i++) { tokens.push(stream[i]); - if (arena.dataTypes[stream[i]] == exports.EnumToken.ColonTokenType) { - if (arena.dataTypes[stream[i + 1]] == exports.EnumToken.IdenTokenType) { + if (arena.dataTypes[stream[i]] === exports.EnumToken.ColonTokenType) { + if (arena.dataTypes[stream[i + 1]] === exports.EnumToken.IdenTokenType) { const val = arena.strings[arena.stringValue[stream[i + 1]]]; arena.dataTypes[stream[i]] = pseudoElements.includes(val) ? exports.EnumToken.PseudoElementTokenType : exports.EnumToken.PseudoClassTokenType; // inlined: arena.setStr(stream[i], ":" + val) - arena.stringValue[stream[i]] = arena.internString((":" + val)); + arena.stringValue[stream[i]] = arena.internString(":" + val); // inlined: arena.setSpanEnd(stream[i], arena.getSpanEnd(stream[i + 1])) arena.setSpan(stream[i], arena.getSourceId(stream[i]), arena.getSpanStart(stream[i]), arena.getSpanEnd(stream[i + 1])); stream.splice(i + 1, 1); continue; } - if (arena.dataTypes[stream[i + 1]] == exports.EnumToken.FunctionTokenDefType) { + if (arena.dataTypes[stream[i + 1]] === exports.EnumToken.FunctionTokenDefType) { val = ":" + arena.strings[arena.stringValue[stream[i + 1]]]; arena.dataTypes[stream[i]] = val + "()" in getSyntaxConfig().selectors @@ -33926,13 +36182,15 @@ if (expectAndOr) { let k = i; while (k < stream.length && - (arena.dataTypes[stream[k]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[stream[k]] === exports.EnumToken.CommentTokenType)) { + (arena.dataTypes[stream[k]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[stream[k]] === exports.EnumToken.CommentTokenType)) { tokens.push(stream[k]); k++; } expectAndOr = false; } - if (arena.dataTypes[stream[i]] === exports.EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[stream[i]])) { + if (arena.dataTypes[stream[i]] === exports.EnumToken.StartParensTokenType || + tokensfuncDefMap.has(arena.dataTypes[stream[i]])) { scopes.push((scope = new Set())); stack.push(stream[i]); continue; @@ -34007,7 +36265,8 @@ stack.pop(); } // inlined: arena.typeOf(stack.at(-1)) - if (arena.dataTypes[stack.at(-1)] === exports.EnumToken.AndTokenType || arena.dataTypes[stack.at(-1)] === exports.EnumToken.OrTokenType) { + if (arena.dataTypes[stack.at(-1)] === exports.EnumToken.AndTokenType || + arena.dataTypes[stack.at(-1)] === exports.EnumToken.OrTokenType) { const index = tokens.indexOf(stack.at(-1)); const index2 = stack.length > 1 ? tokens.indexOf(stack.at(-2)) + 1 : 0; const op = stack[stack.length - 1]; @@ -34094,7 +36353,8 @@ if (arena.dataTypes[stream[k]] === exports.EnumToken.EndParensTokenType) { matchCount--; } - else if (arena.dataTypes[stream[k]] === exports.EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[stream[k]])) { + else if (arena.dataTypes[stream[k]] === exports.EnumToken.StartParensTokenType || + tokensfuncDefMap.has(arena.dataTypes[stream[k]])) { matchCount++; } if (matchCount === 0) { @@ -34118,13 +36378,17 @@ syntax: "@import", node: stream[0], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[0])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[0]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[0])), + ], }, ], }; } while (index + 1 < prelude.length && - (arena.dataTypes[stream[index]] == exports.EnumToken.WhitespaceTokenType || arena.dataTypes[stream[index]] == exports.EnumToken.CommentTokenType)) { + (arena.dataTypes[stream[index]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[stream[index]] === exports.EnumToken.CommentTokenType)) { tokens.push(stream[index++]); } // layer | layer() @@ -34148,14 +36412,17 @@ syntax: "@import", node: stream[index], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[index])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[index]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[index])), + ], }, ], }; } else if (arena.dataTypes[stream[index]] === exports.EnumToken.IdenTokenType) { tokens.push(stream[index++]); - while (arena.dataTypes[stream[index]] == exports.EnumToken.ClassSelectorTokenType) { + while (arena.dataTypes[stream[index]] === exports.EnumToken.ClassSelectorTokenType) { tokens.push(stream[index++]); } i = tokens.indexOf(stack[stack.length - 1]); @@ -34174,13 +36441,17 @@ syntax: "@import", node: stream[index], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[index])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[index]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[index])), + ], }, ], }; } } - while (arena.dataTypes[stream[index]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[stream[index]] === exports.EnumToken.CommentTokenType) { + while (arena.dataTypes[stream[index]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[stream[index]] === exports.EnumToken.CommentTokenType) { tokens.push(stream[index++]); } // supports([ | ]) @@ -34194,7 +36465,8 @@ // else { // match the next ')' while (index < stream.length && matchCount > 0) { - if (arena.dataTypes[stream[index]] === exports.EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[stream[index]])) { + if (arena.dataTypes[stream[index]] === exports.EnumToken.StartParensTokenType || + tokensfuncDefMap.has(arena.dataTypes[stream[index]])) { matchCount++; } else if (arena.dataTypes[stream[index]] === exports.EnumToken.EndParensTokenType) { @@ -34264,7 +36536,8 @@ if (expectAndOr) { let k = i; while (k < stream.length && - (arena.dataTypes[stream[k]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[stream[k]] === exports.EnumToken.CommentTokenType)) { + (arena.dataTypes[stream[k]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[stream[k]] === exports.EnumToken.CommentTokenType)) { tokens.push(stream[k]); k++; } @@ -34328,7 +36601,7 @@ } arena.spanLocation(stream[i], stream[i], stream[j]); const chi = isSupportsFunction - ? arena.firstToken[stream[i]] != 0 + ? arena.firstToken[stream[i]] !== 0 ? arena.tokens(stream[i]) : trimArray(arena, slice.slice(1, -1)) : arena.tokens(tokenList[0]); @@ -34463,13 +36736,15 @@ let expectAndOr = false; i = 0; while (i < stream.length && - (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType)) { + (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType)) { tokens.push(stream[i++]); } if (arena.dataTypes[stream[i]] === exports.EnumToken.IdenTokenType) { tokens.push(stream[i++]); } - while (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType) { + while (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType) { tokens.push(stream[i++]); } if (i < stream.length && @@ -34482,7 +36757,10 @@ action: "drop", node: stream[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], message: `expecting `, }, ], @@ -34490,7 +36768,8 @@ } for (; i < stream.length; i++) { tokens.push(stream[i]); - if (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[stream[i]] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[stream[i]] === exports.EnumToken.CommentTokenType) { continue; } if (expectAndOr) { @@ -34508,12 +36787,16 @@ node: stream[i], message: `expecting , or comma`, // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], }); break; } } - if (arena.dataTypes[stream[i]] === exports.EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[stream[i]])) { + if (arena.dataTypes[stream[i]] === exports.EnumToken.StartParensTokenType || + tokensfuncDefMap.has(arena.dataTypes[stream[i]])) { scopes.push((currentScope = new Set())); stack.push(stream[i]); continue; @@ -34535,14 +36818,18 @@ stack.push(stream[i]); } else if (val === "and" || val === "or") { - arena.dataTypes[stream[i]] = val === "and" ? exports.EnumToken.AndTokenType : exports.EnumToken.OrTokenType; + arena.dataTypes[stream[i]] = + val === "and" ? exports.EnumToken.AndTokenType : exports.EnumToken.OrTokenType; if (val === "or" && scopes.length <= 1) { success = false; errors.push({ action: "drop", node: stream[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], message: ` is not allowed outside of parentheses`, }); break; @@ -34597,13 +36884,19 @@ arena.dataTypes[tokens[index]] = tokensfuncDefMap.get(arena.dataTypes[tokens[index]]); arena.setTokenList(tokens[index], trimArray(arena, tokens.slice(index + 1, tokens.length - 1))); arena.spanLocation(tokens[index], tokens[index], stream[i]); - if (arena.tokens(tokens[index]).every((t) => arena.dataTypes[t] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[t] === exports.EnumToken.CommentTokenType)) { + if (arena + .tokens(tokens[index]) + .every((t) => arena.dataTypes[t] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[t] === exports.EnumToken.CommentTokenType)) { success = false; errors.push({ action: "drop", node: stream[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], message: `expecting '<${arena.strings[arena.stringValue[tokens[index]]]}-query>'`, }); break; @@ -34618,13 +36911,19 @@ arena.dataTypes[tokens[index]] = exports.EnumToken.ParensTokenType; arena.setTokenList(tokens[index], tokens.slice(index + 1, tokens.length - 1)); arena.spanLocation(tokens[index], tokens[index], stream[i]); - if (arena.tokens(tokens[index]).every((t) => arena.dataTypes[t] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[t] === exports.EnumToken.CommentTokenType)) { + if (arena + .tokens(tokens[index]) + .every((t) => arena.dataTypes[t] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[t] === exports.EnumToken.CommentTokenType)) { success = false; errors.push({ action: "drop", node: stream[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], message: `expecting ''`, }); break; @@ -34648,7 +36947,10 @@ action: "drop", node: tokens[k], // inlined: options.source!.getSourceLocation(arena.getSpanStart(tokens[k])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[k]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[k])), + ], message: `unexpected token 'not'`, }); break; @@ -34684,30 +36986,30 @@ tokens.length = l + 1; expectAndOr = true; if (arena.dataTypes[op] === exports.EnumToken.AndTokenType) { - const notNameOrSpace = (t) => arena.dataTypes[t] != exports.EnumToken.WhitespaceTokenType && - arena.dataTypes[t] != exports.EnumToken.IdenTokenType; + const notNameOrSpace = (t) => arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[t] !== exports.EnumToken.IdenTokenType; let leftCondition = left.find(notNameOrSpace); let rightCondition = right.find(notNameOrSpace); if (leftCondition != null && rightCondition != null && - arena.dataTypes[leftCondition] == exports.EnumToken.ParensTokenType && - arena.dataTypes[rightCondition] == exports.EnumToken.ParensTokenType) { + arena.dataTypes[leftCondition] === exports.EnumToken.ParensTokenType && + arena.dataTypes[rightCondition] === exports.EnumToken.ParensTokenType) { leftCondition = arena.tokens(leftCondition).find(notNameOrSpace); rightCondition = arena.tokens(rightCondition).find(notNameOrSpace); if (leftCondition != null && rightCondition != null && - arena.dataTypes[leftCondition] == exports.EnumToken.MediaQueryConditionTokenType && - arena.dataTypes[rightCondition] == exports.EnumToken.MediaQueryConditionTokenType) { + arena.dataTypes[leftCondition] === exports.EnumToken.MediaQueryConditionTokenType && + arena.dataTypes[rightCondition] === exports.EnumToken.MediaQueryConditionTokenType) { const leftOp = arena.field(leftCondition, exports.TokenField.Op); const rightOp = arena.field(rightCondition, exports.TokenField.Op); if ((mFLT.has(arena.dataTypes[leftOp]) || mFGT.has(arena.dataTypes[leftOp])) && (mFLT.has(arena.dataTypes[rightOp]) || mFGT.has(arena.dataTypes[rightOp]))) { const name = arena .fieldTokens(leftCondition, exports.TokenField.L) - .find((t) => arena.dataTypes[t] == exports.EnumToken.IdenTokenType); + .find((t) => arena.dataTypes[t] === exports.EnumToken.IdenTokenType); const name2 = arena .fieldTokens(rightCondition, exports.TokenField.L) - .find((t) => arena.dataTypes[t] == exports.EnumToken.IdenTokenType); + .find((t) => arena.dataTypes[t] === exports.EnumToken.IdenTokenType); if (name != null && name2 != null && equalsIgnoreCase(arena.strings[arena.stringValue[name]], arena.strings[arena.stringValue[name2]])) { @@ -34731,9 +37033,13 @@ // inlined: arena.setField(rangeQuery, TokenField.Val, name) arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.Val), [name]); // inlined: arena.setField(rangeQuery, TokenField.Op, leftOp) - arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.Op), [leftOp]); + arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.Op), [ + leftOp, + ]); // inlined: arena.setField(rangeQuery, TokenField.Op2, rightOp) - arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.Op2), [rightOp]); + arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.Op2), [ + rightOp, + ]); // inlined: arena.setField(rangeQuery, TokenField.R, ...arena.fieldTokens(rightCondition, TokenField.R)) arena.setTokenList(arena.fieldList(rangeQuery, exports.TokenField.R), arena.fieldTokens(rightCondition, exports.TokenField.R)); arena.spanLocation(rangeQuery, leftCondition, rightCondition); @@ -34768,7 +37074,7 @@ } stream.length = 0; for (const part of parts) { - if (part.length == 0) { + if (part.length === 0) { continue; } for (const token of part) { @@ -34810,7 +37116,8 @@ const scopes = [new Set()]; for (; i < stream.length; i++) { const token = stream[i]; - if (arena.dataTypes[token] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[token] === exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[token] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[token] === exports.EnumToken.CommentTokenType) { continue; } if (arena.dataTypes[token] === exports.EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[token])) { @@ -34828,7 +37135,10 @@ message: `unexpected token ${exports.EnumToken[arena.dataTypes[token]]}`, node: token, // inlined: options.source!.getSourceLocation(arena.getSpanStart(token)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(token))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(token)), + ], }); success = false; break; @@ -34837,14 +37147,18 @@ scopes.pop(); continue; } - if (arena.dataTypes[token] === exports.EnumToken.IdenTokenType && equalsIgnoreCase("and", arena.strings[arena.stringValue[token]])) { + if (arena.dataTypes[token] === exports.EnumToken.IdenTokenType && + equalsIgnoreCase("and", arena.strings[arena.stringValue[token]])) { if (!expectAndOr || scopes.at(-1)?.has(exports.EnumToken.OrTokenType)) { errors.push({ action: "drop", message: `unexpected token ${exports.EnumToken[arena.dataTypes[token]]}`, node: token, // inlined: options.source!.getSourceLocation(arena.getSpanStart(token)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(token))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(token)), + ], }); success = false; break; @@ -34854,14 +37168,18 @@ expectComma = false; continue; } - if (arena.dataTypes[token] === exports.EnumToken.IdenTokenType && equalsIgnoreCase("or", arena.strings[arena.stringValue[token]])) { + if (arena.dataTypes[token] === exports.EnumToken.IdenTokenType && + equalsIgnoreCase("or", arena.strings[arena.stringValue[token]])) { if (!expectAndOr || scopes.at(-1)?.has(exports.EnumToken.AndTokenType)) { errors.push({ action: "drop", message: `unexpected token ${exports.EnumToken[arena.dataTypes[token]]}`, node: token, // inlined: options.source!.getSourceLocation(arena.getSpanStart(token)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(token))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(token)), + ], }); success = false; break; @@ -34878,7 +37196,10 @@ message: `unexpected token ${exports.EnumToken[arena.dataTypes[token]]}`, node: token, // inlined: options.source!.getSourceLocation(arena.getSpanStart(token)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(token))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(token)), + ], }); success = false; break; @@ -34900,7 +37221,10 @@ message: `unexpected token ${exports.EnumToken[arena.dataTypes[stack[stack.length - 1]]]}`, node: stack[stack.length - 1], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stack[stack.length - 1])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stack[stack.length - 1]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stack[stack.length - 1])), + ], }); success = false; } @@ -34941,10 +37265,10 @@ if (Array.isArray(replacement)) { const result = []; for (const item of replacement) { - if (typeof item == "number") { + if (typeof item === "number") { result.push(item); } - else if (item != null && typeof item == "object") { + else if (item != null && typeof item === "object") { result.push(arena.fromObject(item)); } else { @@ -34953,10 +37277,10 @@ } return result; } - if (typeof replacement == "number") { + if (typeof replacement === "number") { return replacement; } - if (replacement != null && typeof replacement == "object") { + if (replacement != null && typeof replacement === "object") { return arena.fromObject(replacement); } return null; @@ -34980,7 +37304,7 @@ function arenaCapacity(tokenizer) { const length = tokenizer.streamLength; // small inputs (css modules, inline styles, ...) do not allocate a large arena, the arena grows when needed - return length == 0 ? 4096 : Math.min(1 << 25, Math.ceil(length / 4) + 1024); + return length === 0 ? 4096 : Math.min(1 << 25, Math.ceil(length / 4) + 1024); } /** * allocate the current tokenizer token in the arena @@ -35000,10 +37324,10 @@ arena.name[item] = arena.internString(tokenizer.nam); } else if (val !== null) { - if (typeof val == "number") { + if (typeof val === "number") { arena.numericValue[item] = val; } - else if (tokenizer.typ != exports.EnumToken.WhitespaceTokenType) { + else if (tokenizer.typ !== exports.EnumToken.WhitespaceTokenType) { // whitespace is always rendered as a single space: the text is not kept arena.stringValue[item] = arena.internString(val); } @@ -35031,13 +37355,13 @@ for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; // already recycled (a token can be recorded twice), attached or holding other tokens - if (arena.dataTypes[token] == 0 || - arena.parents[token] != 0 || - arena.firstChild[token] != 0 || - arena.firstToken[token] != 0) { + if (arena.dataTypes[token] === 0 || + arena.parents[token] !== 0 || + arena.firstChild[token] !== 0 || + arena.firstToken[token] !== 0) { continue; } - let referenced = invalidNodes.indexOf(token, invalidStart) != -1; + let referenced = invalidNodes.indexOf(token, invalidStart) !== -1; for (let j = errorStart; !referenced && j < errors.length; j++) { referenced = errors[j].node === token; } @@ -35059,11 +37383,12 @@ * @param type */ function isBadToken(type) { - return (type == exports.EnumToken.BadCommentTokenType || - type == exports.EnumToken.BadCdoTokenType || - type == exports.EnumToken.BadUrlTokenType || - type == exports.EnumToken.BadStringTokenType); + return (type === exports.EnumToken.BadCommentTokenType || + type === exports.EnumToken.BadCdoTokenType || + type === exports.EnumToken.BadUrlTokenType || + type === exports.EnumToken.BadStringTokenType); } + // new Map([["keyframes", EnumToken.KeyframesAtRuleNodeType]]); let keyNameCounter = 0; /** * Short-scoped name generator. @@ -35138,33 +37463,33 @@ // Compose final scoped name. Ensure the entire class doesn't start with a digit: for (const char of pattern) { position += char.length; - if (char == "[") { + if (char === "[") { inParens++; - if (inParens != 1) { + if (inParens !== 1) { throw new Error(`Unexpected character: '${char} at position ${position - 1}' in pattern '${pattern}'`); } continue; } - if (char == "]") { + if (char === "]") { inParens--; - if (inParens != 0) { + if (inParens !== 0) { throw new Error(`Unexpected character: '${char}:${position - 1}'`); } let hashAlgo = null; let length = null; if (key.includes(":")) { const parts = key.split(":"); - if (parts.length == 2) { + if (parts.length === 2) { // @ts-ignore [key, length] = parts; // @ts-ignore - if (key == "hash" && hashAlgorithms.includes(length)) { + if (key === "hash" && hashAlgorithms.includes(length)) { // @ts-ignore hashAlgo = length; length = null; } } - if (parts.length == 3) { + if (parts.length === 3) { // @ts-ignore [key, hashAlgo, length] = parts; } @@ -35172,7 +37497,7 @@ throw new Error(`Unsupported hash length: '${length}'. expecting format [hash:length] or [hash:hash-algo:length]`); } } - const slice = length != null && length != fileBase.length; + const slice = length != null && length !== fileBase.length; switch (key) { case "hash": result += await hash(hashString, length ?? hashLength, hashAlgo); @@ -35232,27 +37557,27 @@ // Compose final scoped name. Ensure the entire class doesn't start with a digit: for (const char of pattern) { position += char.length; - if (char == "[") { + if (char === "[") { inParens++; - if (inParens != 1) { + if (inParens !== 1) { throw new Error(`Unexpected character: '${char} at position ${position - 1}' in pattern '${pattern}'`); } continue; } - if (char == "]") { + if (char === "]") { inParens--; - if (inParens != 0) { + if (inParens !== 0) { throw new Error(`Unexpected character: '${char}:${position - 1}'`); } let hashAlgo = null; let length = null; if (key.includes(":")) { const parts = key.split(":"); - if (parts.length == 2) { + if (parts.length === 2) { // @ts-ignore [key, length] = parts; // @ts-ignore - if (key == "hash" && hashAlgorithms.includes(length)) { + if (key === "hash" && hashAlgorithms.includes(length)) { // @ts-ignore hashAlgo = length; length = null; @@ -35261,7 +37586,7 @@ } } } - if (parts.length == 3) { + if (parts.length === 3) { // @ts-ignore [key, hashAlgo, length] = parts; } @@ -35269,7 +37594,7 @@ throw new Error(`Unsupported hash length: '${length}'. expecting format [hash:length] or [hash:hash-algo:length]`); } } - const slice = length != null && length != fileBase.length; + const slice = length != null && length !== fileBase.length; switch (key) { case "hash": result += syncHash(hashString, length ?? hashLength, hashAlgo); @@ -35334,10 +37659,10 @@ key = visitors[i][0]; value = visitors[i][1]; if (Number.isInteger(+key)) { - if (typeof value == "function") { + if (typeof value === "function") { key = value.name; } - else if (value != null && typeof value == "object") { + else if (value != null && typeof value === "object") { // array of visitor maps: flatten. this used to depend on the array index being an EnumToken value for (const val of Object.entries(value)) { visitors.push(val); @@ -35346,13 +37671,13 @@ } } if (key in exports.EnumToken) { - if (typeof value == "function") { + if (typeof value === "function") { if (!valuesHandlers.has(exports.EnumToken[key])) { valuesHandlers.set(exports.EnumToken[key], []); } valuesHandlers.get(exports.EnumToken[key]).push(value); } - else if (typeof value == "object") { + else if (typeof value === "object") { if ("type" in value && "handler" in value && value.type in exports.WalkerEvent) { if (value.type == exports.WalkerEvent.Enter) { if (!preValuesHandlers.has(exports.EnumToken[key])) { @@ -35382,7 +37707,7 @@ } } else if (["Declaration", "Rule", "AtRule", "KeyframesRule", "KeyframesAtRule"].includes(key)) { - if (typeof value == "function") { + if (typeof value === "function") { if (!visitorsHandlersMap.has(key)) { visitorsHandlersMap.set(key, []); } @@ -35390,7 +37715,7 @@ .get(key) .push(value); } - else if (typeof value == "object") { + else if (typeof value === "object") { if ("type" in value && "handler" in value && value.type in exports.WalkerEvent) { if (value.type == exports.WalkerEvent.Enter) { if (!preVisitorsHandlersMap.has(key)) { @@ -35422,11 +37747,11 @@ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` }); } } - else if (key == "All" || key == "visitor") { - if (typeof value == "function") { + else if (key === "All" || key === "visitor") { + if (typeof value === "function") { allVisitorsHandlers.add(value); } - else if (typeof value == "object") { + else if (typeof value === "object") { if ("type" in value && "handler" in value && value.type in exports.WalkerEvent) { if (value.type == exports.WalkerEvent.Enter) { preAllVisitorsHandlers.add(value.handler); @@ -35545,7 +37870,7 @@ const statement = []; // nested parses share the arena of the parent const arena = options.arena ?? (options.arena = new AstArena(arenaCapacity(tokenizer))); - let ast = arena.current == 1 ? arena.root : arena.createStyleSheet(); + let ast = arena.current === 1 ? arena.root : arena.createStyleSheet(); let tokens = []; let context = ast; let item; @@ -35603,7 +37928,7 @@ context = node; } } - else if (itemType == exports.EnumToken.BlockStartTokenType) { + else if (itemType === exports.EnumToken.BlockStartTokenType) { let inBlock = 1; tokens.length = 0; tokens.push(item); @@ -35620,13 +37945,16 @@ inBlock--; } // inlined: tokenizer.done() - } while (inBlock != 0 && !(tokenizer.typ === exports.EnumToken.EOF)); + } while (inBlock !== 0 && !(tokenizer.typ === exports.EnumToken.EOF)); if (tokens.length > 0) { errors.push({ action: "drop", message: "invalid block", // inlined: options.source!.getSourceLocation(arena.getSpanStart(tokens[0])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[0]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[0])), + ], }); } } @@ -35644,8 +37972,8 @@ context = stack[stack.length - 1] ?? ast; if (options.removeEmpty && previousNode != null && - arena.firstChild[previousNode] == 0 && - arena.lastChild[context] == previousNode) { + arena.firstChild[previousNode] === 0 && + arena.lastChild[context] === previousNode) { arena.detach(previousNode); } recycleStatementTokens(arena, statement, errors, errorStart, invalidNodes, invalidStart); @@ -35662,7 +37990,7 @@ if (node != null) { if (arena.flags[node] & exports.EnumAstNodeStatus.HasChildren) { stack.push(node); - context = node; + // context = node; } } } @@ -35681,13 +38009,13 @@ // push the children of a node or the sub tokens of a value token onto the stack const enqueue = (node) => { if (arena.flags[node] & exports.EnumAstNodeStatus.HasChildren) { - for (let child = arena.lastChild[node]; child != 0; child = arena.previousSibling[child]) { + for (let child = arena.lastChild[node]; child !== 0; child = arena.previousSibling[child]) { nodes.push(child); } } if (visitors.includeTokens && - arena.dataTypes[node] != exports.EnumToken.RuleNodeType && - arena.dataTypes[node] != exports.EnumToken.KeyframesRuleNodeType) { + arena.dataTypes[node] !== exports.EnumToken.RuleNodeType && + arena.dataTypes[node] !== exports.EnumToken.KeyframesRuleNodeType) { // at-rule prelude, declaration values or token children. selector tokens are not visited const values = arena.subTokens(node); for (let i = values.length - 1; i >= 0; i--) { @@ -35704,20 +38032,20 @@ handlers.push(...visitors.preAllVisitorsHandlers); } genericKey = - nodeType == exports.EnumToken.DeclarationNodeType + nodeType === exports.EnumToken.DeclarationNodeType ? "Declaration" - : nodeType == exports.EnumToken.AtRuleNodeType + : nodeType === exports.EnumToken.AtRuleNodeType ? "AtRule" - : nodeType == exports.EnumToken.KeyframesAtRuleNodeType + : nodeType === exports.EnumToken.KeyframesAtRuleNodeType ? "KeyframesAtRule" : nodeType === exports.EnumToken.KeyframesRuleNodeType ? "KeyframesRule" - : nodeType == exports.EnumToken.RuleNodeType + : nodeType === exports.EnumToken.RuleNodeType ? "Rule" : null; - let keyName = nodeType == exports.EnumToken.DeclarationNodeType || nodeType == exports.EnumToken.AtRuleNodeType + let keyName = nodeType === exports.EnumToken.DeclarationNodeType || nodeType === exports.EnumToken.AtRuleNodeType ? camelize(arena.strings[arena.name[node]]) - : nodeType == exports.EnumToken.KeyframesAtRuleNodeType + : nodeType === exports.EnumToken.KeyframesAtRuleNodeType ? camelize(arena.strings[arena.stringValue[node]]) : null; if (visitors.allVisitorsHandlers?.size > 0) { @@ -35728,11 +38056,11 @@ if (genericKey != null && map.has(genericKey)) { // @ts-ignore for (const handler of map.get(genericKey)) { - if (typeof handler == "function") { + if (typeof handler === "function") { handlers.push(handler); } // @ts-ignore - else if (typeof handler[keyName] == "function") { + else if (typeof handler[keyName] === "function") { // @ts-ignore handlers.push(handler[keyName]); } @@ -35741,21 +38069,21 @@ if (map.has(nodeType)) { // @ts-ignore for (const handler of map.get(nodeType)) { - if (typeof handler == "function") { + if (typeof handler === "function") { handlers.push(handler); } else if (Array.isArray(handler)) { for (const h of handler) { - if (typeof h == "function") { + if (typeof h === "function") { handlers.push(h); } } } - else if (typeof handler.handler == "function") { + else if (typeof handler.handler === "function") { handlers.push(handler.handler); } // @ts-ignore - else if (typeof handler[keyName] == "function") { + else if (typeof handler[keyName] === "function") { // @ts-ignore handlers.push(handler[keyName]); } @@ -35834,7 +38162,7 @@ } } if (options.minifyAST) { - if (arena.firstChild[ast] != 0) { + if (arena.firstChild[ast] !== 0) { let passes = options.pass ?? 1; while (passes--) { minify(arena, ast, options, true, errors, false); @@ -35862,26 +38190,26 @@ naming: exports.ModuleCaseTransformEnum.IgnoreCase, pattern: "", generateScopedName: generateSyncScopedName, - ...(typeof options.module != "object" ? {} : options.module), + ...(typeof options.module !== "object" ? {} : options.module), }; const parseModuleTime = performance.now(); const namesMapping = {}; const global = new Set(); const processed = new Set(); - const pattern = typeof options.module == "boolean" ? null : moduleSettings.pattern; + const pattern = typeof options.module === "boolean" ? null : moduleSettings.pattern; const importMapping = {}; const cssVariablesMap = {}; const importedCssVariables = {}; let mapping = {}; let revMapping = {}; - let filePath = typeof options.module == "boolean" + let filePath = typeof options.module === "boolean" ? options.src : (moduleSettings.filePath ?? options.src); filePath = filePath === "" ? options.resolve(options.src, options.cwd).relative : options.resolve(filePath, options.dirname(options.src), options.cwd).relative; - if (typeof options.module == "number") { + if (typeof options.module === "number") { if (options.module & exports.ModuleCaseTransformEnum.CamelCase) { moduleSettings.naming = exports.ModuleCaseTransformEnum.CamelCase; } @@ -35910,7 +38238,7 @@ moduleSettings.scoped |= exports.ModuleScopeEnumOptions.ICSS; } } - if (typeof moduleSettings.scoped == "boolean") { + if (typeof moduleSettings.scoped === "boolean") { moduleSettings.scoped = moduleSettings.scoped ? exports.ModuleScopeEnumOptions.Local : exports.ModuleScopeEnumOptions.Global; @@ -35925,17 +38253,20 @@ for (const node of new NodeWalker(arena, ast)) { const parent = arena.parents[node]; const nodeType = arena.dataTypes[node]; - if (nodeType == exports.EnumToken.CssVariableImportTokenType) { + if (nodeType === exports.EnumToken.CssVariableImportTokenType) { throw new Error("css variable import not supported by parseSync() or transformSync(). use parse() or transform() instead.\nat " + // inlined: options.source!.getSourceLocation(arena.getSpanStart(node as AstNode)) - [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(node))].join(":")); + [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(node)), + ].join(":")); } // @ts-ignore - if (nodeType == exports.EnumToken.CssVariableDeclarationMapTokenType) { + if (nodeType === exports.EnumToken.CssVariableDeclarationMapTokenType) { // @ts-ignore const fromToken = arena .fieldTokens(node, exports.TokenField.L) - .find((t) => arena.dataTypes[t] == exports.EnumToken.IdenTokenType || isIdentColor(arena, t)); + .find((t) => arena.dataTypes[t] === exports.EnumToken.IdenTokenType || isIdentColor(arena, t)); const from = { val: arena.strings[arena.stringValue[fromToken]] }; if (!(from.val in cssVariablesMap)) { errors.push({ @@ -35947,7 +38278,7 @@ else { // @ts-ignore for (const token of arena.tokens(node)) { - if (arena.dataTypes[token] == exports.EnumToken.IdenTokenType || isIdentColor(arena, token)) { + if (arena.dataTypes[token] === exports.EnumToken.IdenTokenType || isIdentColor(arena, token)) { if (!(arena.strings[arena.stringValue[token]] in cssVariablesMap[from.val])) { errors.push({ node, @@ -35964,8 +38295,8 @@ arena.detach(node); continue; } - if (nodeType == exports.EnumToken.CssVariableTokenType) { - if (parent != null && arena.dataTypes[parent] == exports.EnumToken.StyleSheetNodeType) { + if (nodeType === exports.EnumToken.CssVariableTokenType) { + if (parent != null && arena.dataTypes[parent] === exports.EnumToken.StyleSheetNodeType) { if (result.cssModuleVariables == null) { result.cssModuleVariables = {}; } @@ -35976,7 +38307,7 @@ arena.detach(node); continue; } - if (nodeType == exports.EnumToken.DeclarationNodeType) { + if (nodeType === exports.EnumToken.DeclarationNodeType) { if (arena.strings[arena.name[node]].startsWith("--")) { if (!(arena.strings[arena.name[node]] in namesMapping)) { let value = moduleSettings.scoped & exports.ModuleScopeEnumOptions.Global @@ -35997,17 +38328,17 @@ if (equalsIgnoreCase("composes", arena.strings[arena.name[node]])) { const composeSelectors = []; // let isValid: boolean = true; - for (let token = arena.firstToken[node]; token != 0; token = arena.nextSibling[token]) { - if (arena.dataTypes[token] == exports.EnumToken.ComposesSelectorNodeType) { + for (let token = arena.firstToken[node]; token !== 0; token = arena.nextSibling[token]) { + if (arena.dataTypes[token] === exports.EnumToken.ComposesSelectorNodeType) { composeSelectors.push(token); } } // find parent rule let parentRule = parent ?? 0; - while (parentRule != 0 && arena.dataTypes[parentRule] != exports.EnumToken.RuleNodeType) { + while (parentRule !== 0 && arena.dataTypes[parentRule] !== exports.EnumToken.RuleNodeType) { parentRule = arena.parents[parentRule]; } - if ( /* !isValid || */composeSelectors.length == 0) { + if ( /* !isValid || */composeSelectors.length === 0) { errors.push({ action: "drop", message: `composes is empty`, @@ -36020,8 +38351,8 @@ // composes: a b c; if (!arena.hasField(token, exports.TokenField.R)) { for (const rule of arena.fieldTokens(token, exports.TokenField.L)) { - if (arena.dataTypes[rule] == exports.EnumToken.WhitespaceTokenType || - arena.dataTypes[rule] == exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[rule] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[rule] === exports.EnumToken.CommentTokenType) { continue; } if (!(arena.strings[arena.stringValue[rule]] in mapping)) { @@ -36029,7 +38360,7 @@ ? arena.strings[arena.stringValue[rule]] : moduleSettings.generateScopedName(arena.strings[arena.stringValue[rule]], moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength); mapping[arena.strings[arena.stringValue[rule]]] = - (arena.dataTypes[rule] == exports.EnumToken.DashedIdenTokenType ? "--" : "") + + (arena.dataTypes[rule] === exports.EnumToken.DashedIdenTokenType ? "--" : "") + (moduleSettings.naming & exports.ModuleCaseTransformEnum.DashCaseOnly || moduleSettings.naming & exports.ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(value, moduleSettings.naming) @@ -36037,9 +38368,9 @@ revMapping[mapping[arena.strings[arena.stringValue[rule]]]] = arena.strings[arena.stringValue[rule]]; } - if (parentRule != 0) { + if (parentRule !== 0) { for (const tk of arena.tokens(parentRule)) { - if (arena.dataTypes[tk] == exports.EnumToken.ClassSelectorTokenType) { + if (arena.dataTypes[tk] === exports.EnumToken.ClassSelectorTokenType) { const val = arena.strings[arena.stringValue[tk]].slice(1); if (val in revMapping) { const key = revMapping[val]; @@ -36056,32 +38387,29 @@ } } // composes: a b c from 'file.css'; - else if (arena.dataTypes[arena.field(token, exports.TokenField.R)] == exports.EnumToken.StringTokenType) { + else if (arena.dataTypes[arena.field(token, exports.TokenField.R)] === exports.EnumToken.StringTokenType) { throw new Error( // inlined: options.source!.getSourceLocation(arena.getSpanStart(node as AstNode)) `composes from file is not supported using parseSync() or transformSync(). Use parse() or transform() instead.\nat ${[options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(node))].join(":")}`); } // composes: a b c from global; - else if (arena.dataTypes[arena.field(token, exports.TokenField.R)] == exports.EnumToken.IdenTokenType) { + else if (arena.dataTypes[arena.field(token, exports.TokenField.R)] === exports.EnumToken.IdenTokenType) { // global - if (parentRule != 0) { + if (parentRule !== 0) { if (equalsIgnoreCase("global", arena.strings[arena.stringValue[arena.field(token, exports.TokenField.R)]])) { for (const tk of arena.tokens(parentRule)) { - if (arena.dataTypes[tk] == exports.EnumToken.ClassSelectorTokenType) { + if (arena.dataTypes[tk] === exports.EnumToken.ClassSelectorTokenType) { const val = arena.strings[arena.stringValue[tk]].slice(1); if (val in revMapping) { const key = revMapping[val]; const composedNames = []; for (const curr of arena.fieldTokens(token, exports.TokenField.L)) { - if (arena.dataTypes[curr] == exports.EnumToken.IdenTokenType) { + if (arena.dataTypes[curr] === exports.EnumToken.IdenTokenType) { composedNames.push(arena.strings[arena.stringValue[curr]]); } } mapping[key] = [ - ...new Set([ - ...mapping[key].split(" "), - ...composedNames, - ]), + ...new Set([...mapping[key].split(" "), ...composedNames]), ].join(" "); } } @@ -36112,7 +38440,7 @@ ].includes(arena.strings[arena.name[node]])) { // inlined: arena.walkValues(node as AstNode) for (const value of new ValueWalker(arena, node)) { - if (arena.dataTypes[value] != exports.EnumToken.IdenTokenType) { + if (arena.dataTypes[value] !== exports.EnumToken.IdenTokenType) { continue; } let idenToken = arena.strings[arena.stringValue[value]]; @@ -36143,16 +38471,16 @@ arena.stringValue[value] = arena.internString(mapping[idenToken]); } } - else if (arena.strings[arena.name[node]] == "grid-template-areas" || - arena.strings[arena.name[node]] == "grid-template") { - for (let token = arena.firstToken[node]; token != 0; token = arena.nextSibling[token]) { - if (arena.dataTypes[token] == exports.EnumToken.StringTokenType) { + else if (arena.strings[arena.name[node]] === "grid-template-areas" || + arena.strings[arena.name[node]] === "grid-template") { + for (let token = arena.firstToken[node]; token !== 0; token = arena.nextSibling[token]) { + if (arena.dataTypes[token] === exports.EnumToken.StringTokenType) { const str = arena.strings[arena.stringValue[token]]; const tokens = parseString(arena, str.slice(1, -1)); // inlined: arena.walkValues(tokens) for (const value of new ValueWalker(arena, tokens)) { - if (arena.dataTypes[value] == exports.EnumToken.IdenTokenType || - arena.dataTypes[value] == exports.EnumToken.DashedIdenTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.IdenTokenType || + arena.dataTypes[value] === exports.EnumToken.DashedIdenTokenType) { if (arena.strings[arena.stringValue[value]] in mapping) { // inlined: arena.setStr(value, mapping[arena.strings[arena.stringValue[value]]]) arena.stringValue[value] = arena.internString(mapping[arena.strings[arena.stringValue[value]]]); @@ -36169,15 +38497,15 @@ } } // inlined: arena.setStr(token, str.charAt(0) + renderTokens(arena, tokens) + str.charAt(str.length - 1)) - arena.stringValue[token] = arena.internString((str.charAt(0) + renderTokens(arena, tokens) + str.charAt(str.length - 1))); + arena.stringValue[token] = arena.internString(str.charAt(0) + renderTokens(arena, tokens) + str.charAt(str.length - 1)); } } } - else if (arena.strings[arena.name[node]] == "animation" || - arena.strings[arena.name[node]] == "animation-name") { + else if (arena.strings[arena.name[node]] === "animation" || + arena.strings[arena.name[node]] === "animation-name") { // inlined: arena.walkValues(node as AstNode) for (const value of new ValueWalker(arena, node)) { - if (arena.dataTypes[value] == exports.EnumToken.IdenTokenType && + if (arena.dataTypes[value] === exports.EnumToken.IdenTokenType && ![ "none", "infinite", @@ -36212,7 +38540,8 @@ moduleSettings.scoped & exports.ModuleScopeEnumOptions.Global ? arena.strings[arena.stringValue[value]] : moduleSettings.generateScopedName(arena.strings[arena.stringValue[value]], moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength); - revMapping[mapping[arena.strings[arena.stringValue[value]]]] = arena.strings[arena.stringValue[value]]; + revMapping[mapping[arena.strings[arena.stringValue[value]]]] = + arena.strings[arena.stringValue[value]]; } // inlined: arena.setStr(value, mapping[arena.strings[arena.stringValue[value]]]) arena.stringValue[value] = arena.internString(mapping[arena.strings[arena.stringValue[value]]]); @@ -36221,17 +38550,19 @@ } // inlined: arena.walkValues(node as AstNode) for (const value of new ValueWalker(arena, node)) { - if (arena.dataTypes[value] == exports.EnumToken.DashedIdenTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.DashedIdenTokenType) { // inlined: arena.setStr(value, mapping[arena.strings[arena.stringValue[value]]]) arena.stringValue[value] = arena.internString(mapping[arena.strings[arena.stringValue[value]]]); } - else if ((arena.dataTypes[value] == exports.EnumToken.IdenTokenType || isIdentColor(arena, value)) && + else if ((arena.dataTypes[value] === exports.EnumToken.IdenTokenType || isIdentColor(arena, value)) && arena.strings[arena.stringValue[value]] in importedCssVariables) { - arena.replaceToken(value, ...arena.tokens(importedCssVariables[arena.strings[arena.stringValue[value]]][ARENAID]).map((token) => arena.clone(token, true))); + arena.replaceToken(value, ...arena + .tokens(importedCssVariables[arena.strings[arena.stringValue[value]]][ARENAID]) + .map((token) => arena.clone(token, true))); } } } - else if (nodeType == exports.EnumToken.RuleNodeType) { + else if (nodeType === exports.EnumToken.RuleNodeType) { // if (node[TOKENS] == null) { const tokens = parseString(arena, arena.strings[arena.name[node]]); matchSelectorSyntax(arena, tokens, [], options); @@ -36239,8 +38570,8 @@ let hasIdOrClass = false; // inlined: arena.walkValues(node as AstNode, filter) for (const value of new ValueWalker(arena, node, (arena, value) => { - if (arena.dataTypes[value] == exports.EnumToken.PseudoClassTokenType || - arena.dataTypes[value] == exports.EnumToken.PseudoElementTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.PseudoClassTokenType || + arena.dataTypes[value] === exports.EnumToken.PseudoElementTokenType) { const val = arena.strings[arena.stringValue[value]].toLowerCase(); switch (val) { case ":local": @@ -36249,16 +38580,16 @@ // remove the pseudo class and the following whitespace const next = arena.nextSibling[value]; arena.detach(value); - if (next != 0 && - (arena.dataTypes[next] == exports.EnumToken.WhitespaceTokenType || - arena.dataTypes[next] == exports.EnumToken.DescendantCombinatorTokenType)) { + if (next !== 0 && + (arena.dataTypes[next] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[next] === exports.EnumToken.DescendantCombinatorTokenType)) { arena.detach(next); } } break; } } - else if (arena.dataTypes[value] == exports.EnumToken.PseudoClassFuncTokenType) { + else if (arena.dataTypes[value] === exports.EnumToken.PseudoClassFuncTokenType) { switch (arena.strings[arena.stringValue[value]].toLowerCase()) { case ":global": for (const token of arena.tokens(value)) { @@ -36274,20 +38605,22 @@ } return null; })) { - if (arena.dataTypes[value] == exports.EnumToken.HashTokenType || arena.dataTypes[value] == exports.EnumToken.ClassSelectorTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.HashTokenType || + arena.dataTypes[value] === exports.EnumToken.ClassSelectorTokenType) { hasIdOrClass = true; } if (processed.has(value)) { continue; } processed.add(value); - if (arena.dataTypes[value] == exports.EnumToken.PseudoClassTokenType || arena.dataTypes[value] == exports.EnumToken.PseudoElementTokenType) ; - else if (arena.dataTypes[value] == exports.EnumToken.PseudoClassFuncTokenType) ; + if (arena.dataTypes[value] === exports.EnumToken.PseudoClassTokenType || + arena.dataTypes[value] === exports.EnumToken.PseudoElementTokenType) ; + else if (arena.dataTypes[value] === exports.EnumToken.PseudoClassFuncTokenType) ; else { if (global.has(value)) { continue; } - if (arena.dataTypes[value] == exports.EnumToken.ClassSelectorTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.ClassSelectorTokenType) { const val = arena.strings[arena.stringValue[value]].slice(1); if (!(val in mapping)) { let value = moduleSettings.scoped & exports.ModuleScopeEnumOptions.Global @@ -36301,7 +38634,7 @@ revMapping[mapping[val]] = val; } // inlined: arena.setStr(value, "." + mapping[val]) - arena.stringValue[value] = arena.internString(("." + mapping[val])); + arena.stringValue[value] = arena.internString("." + mapping[val]); } } } @@ -36313,19 +38646,21 @@ } } // inlined: arena.setSelector(node as AstNode, arena.tokens(node as AstNode).reduce((acc: string, token: Token) => acc + renderValue(arena, token), "")) - arena.name[node] = arena.internString(arena.tokens(node).reduce((acc, token) => acc + renderValue(arena, token), "")); + arena.name[node] = arena.internString(arena + .tokens(node) + .reduce((acc, token) => acc + renderValue(arena, token), "")); } - else if (nodeType == exports.EnumToken.AtRuleNodeType || nodeType == exports.EnumToken.KeyframesAtRuleNodeType) { + else if (nodeType === exports.EnumToken.AtRuleNodeType || nodeType === exports.EnumToken.KeyframesAtRuleNodeType) { const val = arena.strings[arena.name[node]].toLowerCase(); - if (arena.firstToken[node] == 0) { + if (arena.firstToken[node] === 0) { // inlined: arena.setTokens(node as AstNode, ...parseString(arena, arena.strings[arena.stringValue[node as AstNode]])) arena.setTokenList(node, parseString(arena, arena.strings[arena.stringValue[node]])); } - if (val == "property" || val == "keyframes") { - const prefix = val == "property" ? "--" : ""; + if (val === "property" || val === "keyframes") { + const prefix = val === "property" ? "--" : ""; for (const value of arena.tokens(node)) { - if ((prefix == "--" && arena.dataTypes[value] == exports.EnumToken.DashedIdenTokenType) || - (prefix == "" && arena.dataTypes[value] == exports.EnumToken.IdenTokenType)) { + if ((prefix === "--" && arena.dataTypes[value] === exports.EnumToken.DashedIdenTokenType) || + (prefix === "" && arena.dataTypes[value] === exports.EnumToken.IdenTokenType)) { if (!(arena.strings[arena.stringValue[value]] in mapping)) { let val = moduleSettings.scoped & exports.ModuleScopeEnumOptions.Global ? arena.strings[arena.stringValue[value]] @@ -36336,7 +38671,8 @@ moduleSettings.naming & exports.ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(val, moduleSettings.naming) : val); - revMapping[mapping[arena.strings[arena.stringValue[value]]]] = arena.strings[arena.stringValue[value]]; + revMapping[mapping[arena.strings[arena.stringValue[value]]]] = + arena.strings[arena.stringValue[value]]; } // inlined: arena.setStr(value, mapping[arena.strings[arena.stringValue[value]]]) arena.stringValue[value] = arena.internString(mapping[arena.strings[arena.stringValue[value]]]); @@ -36347,7 +38683,7 @@ } } } - if (moduleSettings.naming != exports.ModuleCaseTransformEnum.IgnoreCase) { + if (moduleSettings.naming !== exports.ModuleCaseTransformEnum.IgnoreCase) { revMapping = {}; mapping = {}; let keyName; @@ -36441,7 +38777,7 @@ let tokenizer = iter instanceof Promise ? await iter : iter; // nested parses share the arena of the parent const arena = options.arena ?? (options.arena = new AstArena(arenaCapacity(tokenizer))); - let ast = arena.current == 1 ? arena.root : arena.createStyleSheet(); + let ast = arena.current === 1 ? arena.root : arena.createStyleSheet(); let tokens = []; let context = ast; const imports = []; @@ -36499,12 +38835,12 @@ stack.push(node); context = node; } - else if (arena.dataTypes[node] == exports.EnumToken.AtRuleNodeType && + else if (arena.dataTypes[node] === exports.EnumToken.AtRuleNodeType && arena.strings[arena.name[node]] === "import") { imports.push(node); } } - else if (itemType == exports.EnumToken.BlockStartTokenType) { + else if (itemType === exports.EnumToken.BlockStartTokenType) { let inBlock = 1; tokens.length = 0; tokens.push(item); @@ -36521,13 +38857,16 @@ inBlock--; } // inlined: tokenizer.done() - } while (inBlock != 0 && !(tokenizer.typ === exports.EnumToken.EOF)); + } while (inBlock !== 0 && !(tokenizer.typ === exports.EnumToken.EOF)); if (tokens.length > 0) { errors.push({ action: "drop", message: "invalid block", // inlined: options.source!.getSourceLocation(arena.getSpanStart(tokens[0])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[0]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[0])), + ], }); } } @@ -36545,8 +38884,8 @@ context = stack[stack.length - 1] ?? ast; if (options.removeEmpty && previousNode != null && - arena.firstChild[previousNode] == 0 && - arena.lastChild[context] == previousNode) { + arena.firstChild[previousNode] === 0 && + arena.lastChild[context] === previousNode) { arena.detach(previousNode); } recycleStatementTokens(arena, statement, errors, errorStart, invalidNodes, invalidStart); @@ -36557,18 +38896,17 @@ parensMatch = 0; curlyBracketMatch = 0; } - // } } if (tokens.length > 0) { node = parseNode(arena, tokens, context, options, errors, stats, invalidNodes, parensMatch); if (node != null) { - if (arena.dataTypes[node] == exports.EnumToken.AtRuleNodeType && + if (arena.dataTypes[node] === exports.EnumToken.AtRuleNodeType && "import" === arena.strings[arena.stringValue[node]]) { imports.push(node); } if (arena.flags[node] & exports.EnumAstNodeStatus.HasChildren) { stack.push(node); - context = node; + // context = node; } } } @@ -36578,25 +38916,19 @@ return; } const token = arena.firstToken[node]; - const url = arena.dataTypes[token] == exports.EnumToken.StringTokenType + const url = arena.dataTypes[token] === exports.EnumToken.StringTokenType ? arena.strings[arena.stringValue[token]].slice(1, -1) : arena.strings[arena.stringValue[token]]; try { const src = options.resolve(url, options.src ? dirname(options.src) : options.cwd); - const result = options.load(src); + // the imported file is loaded as an ArrayBuffer: the preferred input of the tokenizer + const result = options.load(src, ".", exports.ResponseType.ArrayBuffer); const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == "AsyncFunction" ? await result : result; const source = new SourceFile(typeof stream === "string" ? stream : "", [], src.relative); options.sourcesMap.set(source.id, source); - const parseInfo = { - stream, - offset: 0, - source, - position: 0, - currentPosition: 0, - time: 0, - }; + const parseInfo = createParseInfo(stream, source); const root = await doParse(stream instanceof ReadableStream ? new Tokenizer(parseInfo, stream).tokenizeStream() : new Tokenizer(parseInfo), Object.assign({}, options, { @@ -36609,7 +38941,7 @@ stats.tokensCount += root.stats.tokensCount; stats.imports.push(root.stats); // the imported stylesheet is allocated in the same arena: its children replace the @import rule - if (arena.parents[node] != 0) { + if (arena.parents[node] !== 0) { arena.moveChildren(root.ast, arena.parents[node], node); arena.detach(node); } @@ -36640,13 +38972,13 @@ // push the children of a node or the sub tokens of a value token onto the stack const enqueue = (node) => { if (arena.flags[node] & exports.EnumAstNodeStatus.HasChildren) { - for (let child = arena.lastChild[node]; child != 0; child = arena.previousSibling[child]) { + for (let child = arena.lastChild[node]; child !== 0; child = arena.previousSibling[child]) { nodes.push(child); } } if (visitors.includeTokens && - arena.dataTypes[node] != exports.EnumToken.RuleNodeType && - arena.dataTypes[node] != exports.EnumToken.KeyframesRuleNodeType) { + arena.dataTypes[node] !== exports.EnumToken.RuleNodeType && + arena.dataTypes[node] !== exports.EnumToken.KeyframesRuleNodeType) { // at-rule prelude, declaration values or token children. selector tokens are not visited const values = arena.subTokens(node); for (let i = values.length - 1; i >= 0; i--) { @@ -36663,20 +38995,20 @@ handlers.push(...visitors.preAllVisitorsHandlers); } genericKey = - nodeType == exports.EnumToken.DeclarationNodeType + nodeType === exports.EnumToken.DeclarationNodeType ? "Declaration" - : nodeType == exports.EnumToken.AtRuleNodeType + : nodeType === exports.EnumToken.AtRuleNodeType ? "AtRule" - : nodeType == exports.EnumToken.KeyframesAtRuleNodeType + : nodeType === exports.EnumToken.KeyframesAtRuleNodeType ? "KeyframesAtRule" : nodeType === exports.EnumToken.KeyframesRuleNodeType ? "KeyframesRule" - : nodeType == exports.EnumToken.RuleNodeType + : nodeType === exports.EnumToken.RuleNodeType ? "Rule" : null; - let keyName = nodeType == exports.EnumToken.DeclarationNodeType || nodeType == exports.EnumToken.AtRuleNodeType + let keyName = nodeType === exports.EnumToken.DeclarationNodeType || nodeType === exports.EnumToken.AtRuleNodeType ? camelize(arena.strings[arena.name[node]]) - : nodeType == exports.EnumToken.KeyframesAtRuleNodeType + : nodeType === exports.EnumToken.KeyframesAtRuleNodeType ? camelize(arena.strings[arena.stringValue[node]]) : null; if (visitors.allVisitorsHandlers?.size > 0) { @@ -36687,11 +39019,11 @@ if (genericKey != null && map.has(genericKey)) { // @ts-ignore for (const handler of map.get(genericKey)) { - if (typeof handler == "function") { + if (typeof handler === "function") { handlers.push(handler); } // @ts-ignore - else if (typeof handler[keyName] == "function") { + else if (typeof handler[keyName] === "function") { // @ts-ignore handlers.push(handler[keyName]); } @@ -36700,21 +39032,21 @@ if (map.has(nodeType)) { // @ts-ignore for (const handler of map.get(nodeType)) { - if (typeof handler == "function") { + if (typeof handler === "function") { handlers.push(handler); } else if (Array.isArray(handler)) { for (const h of handler) { - if (typeof h == "function") { + if (typeof h === "function") { handlers.push(h); } } } - else if (typeof handler.handler == "function") { + else if (typeof handler.handler === "function") { handlers.push(handler.handler); } // @ts-ignore - else if (typeof handler[keyName] == "function") { + else if (typeof handler[keyName] === "function") { // @ts-ignore handlers.push(handler[keyName]); } @@ -36796,7 +39128,7 @@ } } if (options.minifyAST) { - if (arena.firstChild[ast] != 0) { + if (arena.firstChild[ast] !== 0) { let passes = options.pass ?? 1; while (passes--) { minify(arena, ast, options, true, errors, false); @@ -36825,26 +39157,26 @@ naming: exports.ModuleCaseTransformEnum.IgnoreCase, pattern: "", generateScopedName, - ...(typeof options.module != "object" ? {} : options.module), + ...(typeof options.module !== "object" ? {} : options.module), }; const parseModuleTime = performance.now(); const namesMapping = {}; const global = new Set(); const processed = new Set(); - const pattern = typeof options.module == "boolean" ? null : moduleSettings.pattern; + const pattern = typeof options.module === "boolean" ? null : moduleSettings.pattern; const importMapping = {}; const cssVariablesMap = {}; const importedCssVariables = {}; let mapping = {}; let revMapping = {}; - let filePath = typeof options.module == "boolean" + let filePath = typeof options.module === "boolean" ? options.src : (moduleSettings.filePath ?? options.src); filePath = filePath === "" ? options.resolve(options.src, options.cwd).relative : options.resolve(filePath, options.dirname(options.src), options.cwd).relative; - if (typeof options.module == "number") { + if (typeof options.module === "number") { if (options.module & exports.ModuleCaseTransformEnum.CamelCase) { moduleSettings.naming = exports.ModuleCaseTransformEnum.CamelCase; } @@ -36873,7 +39205,7 @@ moduleSettings.scoped |= exports.ModuleScopeEnumOptions.ICSS; } } - if (typeof moduleSettings.scoped == "boolean") { + if (typeof moduleSettings.scoped === "boolean") { moduleSettings.scoped = moduleSettings.scoped ? exports.ModuleScopeEnumOptions.Local : exports.ModuleScopeEnumOptions.Global; @@ -36888,24 +39220,16 @@ for (const node of new NodeWalker(arena, ast)) { const parent = arena.parents[node]; const nodeType = arena.dataTypes[node]; - if (nodeType == exports.EnumToken.CssVariableImportTokenType) { - const url = arena.strings[arena.stringValue[arena.findToken(node, (arena, t) => arena.dataTypes[t] == exports.EnumToken.StringTokenType)]].slice(1, -1); + if (nodeType === exports.EnumToken.CssVariableImportTokenType) { + const url = arena.strings[arena.stringValue[arena.findToken(node, (arena, t) => arena.dataTypes[t] === exports.EnumToken.StringTokenType)]].slice(1, -1); const src = options.resolve(url, options.dirname(options.src), options.cwd); - const result = options.load(src, ""); + const result = options.load(src, "", exports.ResponseType.ArrayBuffer); const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == "AsyncFunction" ? await result : result; const source = new SourceFile(typeof stream === "string" ? stream : "", [], src.relative); options.sourcesMap.set(source.id, source); - const parseInfo = { - stream, - buffer: "", - offset: 0, - time: 0, - source, - position: 0, - currentPosition: 0, - }; + const parseInfo = createParseInfo(stream, source); const root = await doParse(stream instanceof ReadableStream ? new Tokenizer(parseInfo, stream).tokenizeStream() : new Tokenizer(parseInfo), Object.assign({}, options, { @@ -36920,11 +39244,11 @@ continue; } // @ts-ignore - if (nodeType == exports.EnumToken.CssVariableDeclarationMapTokenType) { + if (nodeType === exports.EnumToken.CssVariableDeclarationMapTokenType) { // @ts-ignore const fromToken = arena .fieldTokens(node, exports.TokenField.L) - .find((t) => arena.dataTypes[t] == exports.EnumToken.IdenTokenType || isIdentColor(arena, t)); + .find((t) => arena.dataTypes[t] === exports.EnumToken.IdenTokenType || isIdentColor(arena, t)); const from = { val: arena.strings[arena.stringValue[fromToken]] }; if (!(from.val in cssVariablesMap)) { errors.push({ @@ -36936,7 +39260,7 @@ else { // @ts-ignore for (const token of arena.tokens(node)) { - if (arena.dataTypes[token] == exports.EnumToken.IdenTokenType || isIdentColor(arena, token)) { + if (arena.dataTypes[token] === exports.EnumToken.IdenTokenType || isIdentColor(arena, token)) { if (!(arena.strings[arena.stringValue[token]] in cssVariablesMap[from.val])) { errors.push({ node, @@ -36953,8 +39277,8 @@ arena.detach(node); continue; } - if (nodeType == exports.EnumToken.CssVariableTokenType) { - if (parent != null && arena.dataTypes[parent] == exports.EnumToken.StyleSheetNodeType) { + if (nodeType === exports.EnumToken.CssVariableTokenType) { + if (parent != null && arena.dataTypes[parent] === exports.EnumToken.StyleSheetNodeType) { if (result.cssModuleVariables == null) { result.cssModuleVariables = {}; } @@ -36965,7 +39289,7 @@ arena.detach(node); continue; } - if (nodeType == exports.EnumToken.DeclarationNodeType) { + if (nodeType === exports.EnumToken.DeclarationNodeType) { if (arena.strings[arena.name[node]].startsWith("--")) { if (!(arena.strings[arena.name[node]] in namesMapping)) { let result = moduleSettings.scoped & exports.ModuleScopeEnumOptions.Global @@ -36988,17 +39312,17 @@ if (equalsIgnoreCase("composes", arena.strings[arena.name[node]])) { const composeSelectors = []; // let isValid: boolean = true; - for (let token = arena.firstToken[node]; token != 0; token = arena.nextSibling[token]) { - if (arena.dataTypes[token] == exports.EnumToken.ComposesSelectorNodeType) { + for (let token = arena.firstToken[node]; token !== 0; token = arena.nextSibling[token]) { + if (arena.dataTypes[token] === exports.EnumToken.ComposesSelectorNodeType) { composeSelectors.push(token); } } // find parent rule let parentRule = parent ?? 0; - while (parentRule != 0 && arena.dataTypes[parentRule] != exports.EnumToken.RuleNodeType) { + while (parentRule !== 0 && arena.dataTypes[parentRule] !== exports.EnumToken.RuleNodeType) { parentRule = arena.parents[parentRule]; } - if ( /* !isValid || */composeSelectors.length == 0) { + if ( /* !isValid || */composeSelectors.length === 0) { errors.push({ action: "drop", message: `composes is empty`, @@ -37012,8 +39336,8 @@ // composes: a b c; if (!arena.hasField(token, exports.TokenField.R)) { for (const rule of arena.fieldTokens(token, exports.TokenField.L)) { - if (arena.dataTypes[rule] == exports.EnumToken.WhitespaceTokenType || - arena.dataTypes[rule] == exports.EnumToken.CommentTokenType) { + if (arena.dataTypes[rule] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[rule] === exports.EnumToken.CommentTokenType) { continue; } if (!(arena.strings[arena.stringValue[rule]] in mapping)) { @@ -37023,7 +39347,7 @@ // @ts-expect-error let value = result instanceof Promise ? await result : result; mapping[arena.strings[arena.stringValue[rule]]] = - (arena.dataTypes[rule] == exports.EnumToken.DashedIdenTokenType ? "--" : "") + + (arena.dataTypes[rule] === exports.EnumToken.DashedIdenTokenType ? "--" : "") + (moduleSettings.naming & exports.ModuleCaseTransformEnum.DashCaseOnly || moduleSettings.naming & exports.ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(value, moduleSettings.naming) @@ -37031,9 +39355,9 @@ revMapping[mapping[arena.strings[arena.stringValue[rule]]]] = arena.strings[arena.stringValue[rule]]; } - if (parentRule != 0) { + if (parentRule !== 0) { for (const tk of arena.tokens(parentRule)) { - if (arena.dataTypes[tk] == exports.EnumToken.ClassSelectorTokenType) { + if (arena.dataTypes[tk] === exports.EnumToken.ClassSelectorTokenType) { const val = arena.strings[arena.stringValue[tk]].slice(1); if (val in revMapping) { const key = revMapping[val]; @@ -37050,28 +39374,17 @@ } } // composes: a b c from 'file.css'; - else if (arena.dataTypes[arena.field(token, exports.TokenField.R)] == exports.EnumToken.StringTokenType) { + else if (arena.dataTypes[arena.field(token, exports.TokenField.R)] === exports.EnumToken.StringTokenType) { const url = arena.strings[arena.stringValue[arena.field(token, exports.TokenField.R)]].slice(1, -1); const src = options.resolve(url, options.dirname(options.src), options.cwd); - const result = options.load(src, ""); + const result = options.load(src, "", exports.ResponseType.ArrayBuffer); const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == "AsyncFunction" ? await result : result; const root = await doParse(stream instanceof ReadableStream - ? new Tokenizer({ - offset: 0, - source: new SourceFile("", [], src.relative), - position: 0, - currentPosition: 0, - }, stream).tokenizeStream() - : new Tokenizer({ - stream, - offset: 0, - position: 0, - source: new SourceFile(stream, [], src.relative), - currentPosition: 0, - }), Object.assign({}, options, { + ? new Tokenizer(createParseInfo(stream, new SourceFile("", [], src.relative)), stream).tokenizeStream() + : new Tokenizer(createParseInfo(stream, new SourceFile("", [], src.relative))), Object.assign({}, options, { minify: false, setParent: false, src: src.relative, @@ -37083,16 +39396,16 @@ if (Object.keys(root.mapping).length > 0) { importMapping[srcIndex] = {}; } - if (parentRule != 0) { + if (parentRule !== 0) { for (const tk of arena.tokens(parentRule)) { - if (arena.dataTypes[tk] == exports.EnumToken.ClassSelectorTokenType) { + if (arena.dataTypes[tk] === exports.EnumToken.ClassSelectorTokenType) { const val = arena.strings[arena.stringValue[tk]].slice(1); if (val in revMapping) { const key = revMapping[val]; const values = []; for (const iden of arena.fieldTokens(token, exports.TokenField.L)) { - if (arena.dataTypes[iden] != exports.EnumToken.IdenTokenType && - arena.dataTypes[iden] != exports.EnumToken.DashedIdenTokenType) { + if (arena.dataTypes[iden] !== exports.EnumToken.IdenTokenType && + arena.dataTypes[iden] !== exports.EnumToken.DashedIdenTokenType) { continue; } if (!(arena.strings[arena.stringValue[iden]] in root.mapping)) { @@ -37120,26 +39433,23 @@ } } // composes: a b c from global; - else if (arena.dataTypes[arena.field(token, exports.TokenField.R)] == exports.EnumToken.IdenTokenType) { + else if (arena.dataTypes[arena.field(token, exports.TokenField.R)] === exports.EnumToken.IdenTokenType) { // global - if (parentRule != 0) { + if (parentRule !== 0) { if (equalsIgnoreCase("global", arena.strings[arena.stringValue[arena.field(token, exports.TokenField.R)]])) { for (const tk of arena.tokens(parentRule)) { - if (arena.dataTypes[tk] == exports.EnumToken.ClassSelectorTokenType) { + if (arena.dataTypes[tk] === exports.EnumToken.ClassSelectorTokenType) { const val = arena.strings[arena.stringValue[tk]].slice(1); if (val in revMapping) { const key = revMapping[val]; const composedNames = []; for (const curr of arena.fieldTokens(token, exports.TokenField.L)) { - if (arena.dataTypes[curr] == exports.EnumToken.IdenTokenType) { + if (arena.dataTypes[curr] === exports.EnumToken.IdenTokenType) { composedNames.push(arena.strings[arena.stringValue[curr]]); } } mapping[key] = [ - ...new Set([ - ...mapping[key].split(" "), - ...composedNames, - ]), + ...new Set([...mapping[key].split(" "), ...composedNames]), ].join(" "); } } @@ -37170,7 +39480,7 @@ ].includes(arena.strings[arena.name[node]])) { // inlined: arena.walkValues(node as AstNode) for (const value of new ValueWalker(arena, node)) { - if (arena.dataTypes[value] != exports.EnumToken.IdenTokenType) { + if (arena.dataTypes[value] !== exports.EnumToken.IdenTokenType) { continue; } let idenToken = arena.strings[arena.stringValue[value]]; @@ -37205,16 +39515,16 @@ arena.stringValue[value] = arena.internString(mapping[idenToken]); } } - else if (arena.strings[arena.name[node]] == "grid-template-areas" || - arena.strings[arena.name[node]] == "grid-template") { - for (let token = arena.firstToken[node]; token != 0; token = arena.nextSibling[token]) { - if (arena.dataTypes[token] == exports.EnumToken.StringTokenType) { + else if (arena.strings[arena.name[node]] === "grid-template-areas" || + arena.strings[arena.name[node]] === "grid-template") { + for (let token = arena.firstToken[node]; token !== 0; token = arena.nextSibling[token]) { + if (arena.dataTypes[token] === exports.EnumToken.StringTokenType) { const str = arena.strings[arena.stringValue[token]]; const tokens = parseString(arena, str.slice(1, -1)); // inlined: arena.walkValues(tokens) for (const value of new ValueWalker(arena, tokens)) { - if (arena.dataTypes[value] == exports.EnumToken.IdenTokenType || - arena.dataTypes[value] == exports.EnumToken.DashedIdenTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.IdenTokenType || + arena.dataTypes[value] === exports.EnumToken.DashedIdenTokenType) { if (arena.strings[arena.stringValue[value]] in mapping) { // inlined: arena.setStr(value, mapping[arena.strings[arena.stringValue[value]]]) arena.stringValue[value] = arena.internString(mapping[arena.strings[arena.stringValue[value]]]); @@ -37235,15 +39545,15 @@ } } // inlined: arena.setStr(token, str.charAt(0) + renderTokens(arena, tokens) + str.charAt(str.length - 1)) - arena.stringValue[token] = arena.internString((str.charAt(0) + renderTokens(arena, tokens) + str.charAt(str.length - 1))); + arena.stringValue[token] = arena.internString(str.charAt(0) + renderTokens(arena, tokens) + str.charAt(str.length - 1)); } } } - else if (arena.strings[arena.name[node]] == "animation" || - arena.strings[arena.name[node]] == "animation-name") { + else if (arena.strings[arena.name[node]] === "animation" || + arena.strings[arena.name[node]] === "animation-name") { // inlined: arena.walkValues(node as AstNode) for (const value of new ValueWalker(arena, node)) { - if (arena.dataTypes[value] == exports.EnumToken.IdenTokenType && + if (arena.dataTypes[value] === exports.EnumToken.IdenTokenType && ![ "none", "infinite", @@ -37277,9 +39587,11 @@ const result = moduleSettings.scoped & exports.ModuleScopeEnumOptions.Global ? arena.strings[arena.stringValue[value]] : moduleSettings.generateScopedName(arena.strings[arena.stringValue[value]], moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength); - // @ts-expect-error - mapping[arena.strings[arena.stringValue[value]]] = result instanceof Promise ? await result : result; - revMapping[mapping[arena.strings[arena.stringValue[value]]]] = arena.strings[arena.stringValue[value]]; + mapping[arena.strings[arena.stringValue[value]]] = + // @ts-expect-error + result instanceof Promise ? await result : result; + revMapping[mapping[arena.strings[arena.stringValue[value]]]] = + arena.strings[arena.stringValue[value]]; } // inlined: arena.setStr(value, mapping[arena.strings[arena.stringValue[value]]]) arena.stringValue[value] = arena.internString(mapping[arena.strings[arena.stringValue[value]]]); @@ -37288,17 +39600,19 @@ } // inlined: arena.walkValues(node as AstNode) for (const value of new ValueWalker(arena, node)) { - if (arena.dataTypes[value] == exports.EnumToken.DashedIdenTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.DashedIdenTokenType) { // inlined: arena.setStr(value, mapping[arena.strings[arena.stringValue[value]]]) arena.stringValue[value] = arena.internString(mapping[arena.strings[arena.stringValue[value]]]); } - else if ((arena.dataTypes[value] == exports.EnumToken.IdenTokenType || isIdentColor(arena, value)) && + else if ((arena.dataTypes[value] === exports.EnumToken.IdenTokenType || isIdentColor(arena, value)) && arena.strings[arena.stringValue[value]] in importedCssVariables) { - arena.replaceToken(value, ...arena.tokens(importedCssVariables[arena.strings[arena.stringValue[value]]][ARENAID]).map((token) => arena.clone(token, true))); + arena.replaceToken(value, ...arena + .tokens(importedCssVariables[arena.strings[arena.stringValue[value]]][ARENAID]) + .map((token) => arena.clone(token, true))); } } } - else if (nodeType == exports.EnumToken.RuleNodeType) { + else if (nodeType === exports.EnumToken.RuleNodeType) { // if (node[TOKENS] == null) { const tokens = parseString(arena, arena.strings[arena.name[node]]); matchSelectorSyntax(arena, tokens, [], options); @@ -37306,8 +39620,8 @@ let hasIdOrClass = false; // inlined: arena.walkValues(node as AstNode, filter) for (const value of new ValueWalker(arena, node, (arena, value) => { - if (arena.dataTypes[value] == exports.EnumToken.PseudoClassTokenType || - arena.dataTypes[value] == exports.EnumToken.PseudoElementTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.PseudoClassTokenType || + arena.dataTypes[value] === exports.EnumToken.PseudoElementTokenType) { const val = arena.strings[arena.stringValue[value]].toLowerCase(); switch (val) { case ":local": @@ -37316,16 +39630,16 @@ // remove the pseudo class and the following whitespace const next = arena.nextSibling[value]; arena.detach(value); - if (next != 0 && - (arena.dataTypes[next] == exports.EnumToken.WhitespaceTokenType || - arena.dataTypes[next] == exports.EnumToken.DescendantCombinatorTokenType)) { + if (next !== 0 && + (arena.dataTypes[next] === exports.EnumToken.WhitespaceTokenType || + arena.dataTypes[next] === exports.EnumToken.DescendantCombinatorTokenType)) { arena.detach(next); } } break; } } - else if (arena.dataTypes[value] == exports.EnumToken.PseudoClassFuncTokenType) { + else if (arena.dataTypes[value] === exports.EnumToken.PseudoClassFuncTokenType) { switch (arena.strings[arena.stringValue[value]].toLowerCase()) { case ":global": for (const token of arena.tokens(value)) { @@ -37341,20 +39655,22 @@ } return null; })) { - if (arena.dataTypes[value] == exports.EnumToken.HashTokenType || arena.dataTypes[value] == exports.EnumToken.ClassSelectorTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.HashTokenType || + arena.dataTypes[value] === exports.EnumToken.ClassSelectorTokenType) { hasIdOrClass = true; } if (processed.has(value)) { continue; } processed.add(value); - if (arena.dataTypes[value] == exports.EnumToken.PseudoClassTokenType || arena.dataTypes[value] == exports.EnumToken.PseudoElementTokenType) ; - else if (arena.dataTypes[value] == exports.EnumToken.PseudoClassFuncTokenType) ; + if (arena.dataTypes[value] === exports.EnumToken.PseudoClassTokenType || + arena.dataTypes[value] === exports.EnumToken.PseudoElementTokenType) ; + else if (arena.dataTypes[value] === exports.EnumToken.PseudoClassFuncTokenType) ; else { if (global.has(value)) { continue; } - if (arena.dataTypes[value] == exports.EnumToken.ClassSelectorTokenType) { + if (arena.dataTypes[value] === exports.EnumToken.ClassSelectorTokenType) { const val = arena.strings[arena.stringValue[value]].slice(1); if (!(val in mapping)) { const result = moduleSettings.scoped & exports.ModuleScopeEnumOptions.Global @@ -37370,7 +39686,7 @@ revMapping[mapping[val]] = val; } // inlined: arena.setStr(value, "." + mapping[val]) - arena.stringValue[value] = arena.internString(("." + mapping[val])); + arena.stringValue[value] = arena.internString("." + mapping[val]); } } } @@ -37382,19 +39698,21 @@ } } // inlined: arena.setSelector(node as AstNode, arena.tokens(node as AstNode).reduce((acc: string, token: Token) => acc + renderValue(arena, token), "")) - arena.name[node] = arena.internString(arena.tokens(node).reduce((acc, token) => acc + renderValue(arena, token), "")); + arena.name[node] = arena.internString(arena + .tokens(node) + .reduce((acc, token) => acc + renderValue(arena, token), "")); } - else if (nodeType == exports.EnumToken.AtRuleNodeType || nodeType == exports.EnumToken.KeyframesAtRuleNodeType) { + else if (nodeType === exports.EnumToken.AtRuleNodeType || nodeType === exports.EnumToken.KeyframesAtRuleNodeType) { const val = arena.strings[arena.name[node]].toLowerCase(); - if (arena.firstToken[node] == 0) { + if (arena.firstToken[node] === 0) { // inlined: arena.setTokens(node as AstNode, ...parseString(arena, arena.strings[arena.stringValue[node as AstNode]])) arena.setTokenList(node, parseString(arena, arena.strings[arena.stringValue[node]])); } - if (val == "property" || val == "keyframes") { - const prefix = val == "property" ? "--" : ""; + if (val === "property" || val === "keyframes") { + const prefix = val === "property" ? "--" : ""; for (const value of arena.tokens(node)) { - if ((prefix == "--" && arena.dataTypes[value] == exports.EnumToken.DashedIdenTokenType) || - (prefix == "" && arena.dataTypes[value] == exports.EnumToken.IdenTokenType)) { + if ((prefix === "--" && arena.dataTypes[value] === exports.EnumToken.DashedIdenTokenType) || + (prefix === "" && arena.dataTypes[value] === exports.EnumToken.IdenTokenType)) { if (!(arena.strings[arena.stringValue[value]] in mapping)) { const result = moduleSettings.scoped & exports.ModuleScopeEnumOptions.Global ? arena.strings[arena.stringValue[value]] @@ -37407,7 +39725,8 @@ moduleSettings.naming & exports.ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(val, moduleSettings.naming) : val); - revMapping[mapping[arena.strings[arena.stringValue[value]]]] = arena.strings[arena.stringValue[value]]; + revMapping[mapping[arena.strings[arena.stringValue[value]]]] = + arena.strings[arena.stringValue[value]]; } // inlined: arena.setStr(value, mapping[arena.strings[arena.stringValue[value]]]) arena.stringValue[value] = arena.internString(mapping[arena.strings[arena.stringValue[value]]]); @@ -37418,7 +39737,7 @@ } } } - if (moduleSettings.naming != exports.ModuleCaseTransformEnum.IgnoreCase) { + if (moduleSettings.naming !== exports.ModuleCaseTransformEnum.IgnoreCase) { revMapping = {}; mapping = Object.entries(mapping).reduce((acc, [key, value]) => { const keyName = getKeyName(key, moduleSettings.naming); @@ -37453,9 +39772,10 @@ if (matchCount > 0) { let k = tokens.length; while (k-- > 0 && - (dataTypes[tokens[k]] === exports.EnumToken.WhitespaceTokenType || dataTypes[tokens[k]] === exports.EnumToken.CommentTokenType)) + (dataTypes[tokens[k]] === exports.EnumToken.WhitespaceTokenType || + dataTypes[tokens[k]] === exports.EnumToken.CommentTokenType)) ; - if (dataTypes[tokens[k]] == exports.EnumToken.SemiColonTokenType) { + if (dataTypes[tokens[k]] === exports.EnumToken.SemiColonTokenType) { matchCount = 0; } while (matchCount > 0) { @@ -37475,7 +39795,10 @@ message: `CDOCOMM not allowed here ${JSON.stringify(tokens[i], null, 1)}`, node: tokens[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(tokens[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[i])), + ], }); // the misplaced CDO / CDC comment is rendered as an empty string arena.dataTypes[tokens[i]] = exports.EnumToken.BadCdoTokenType; @@ -37501,14 +39824,19 @@ i = 0; } for (; i < tokens.length; i++) { - if (arena.dataTypes[tokens[i]] == exports.EnumToken.CommentTokenType || arena.dataTypes[tokens[i]] == exports.EnumToken.CDOCOMMTokenType) { - if (arena.dataTypes[tokens[i]] == exports.EnumToken.CDOCOMMTokenType && contextType != exports.EnumToken.StyleSheetNodeType) { + if (arena.dataTypes[tokens[i]] === exports.EnumToken.CommentTokenType || + arena.dataTypes[tokens[i]] === exports.EnumToken.CDOCOMMTokenType) { + if (arena.dataTypes[tokens[i]] === exports.EnumToken.CDOCOMMTokenType && + contextType !== exports.EnumToken.StyleSheetNodeType) { errors.push({ action: "drop", message: `CDOCOMM not allowed here ${JSON.stringify(tokens[i], null, 1)}`, node: tokens[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(tokens[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(tokens[i])), + ], }); // the misplaced CDO / CDC comment is rendered as an empty string arena.dataTypes[tokens[i]] = exports.EnumToken.BadCdoTokenType; @@ -37518,34 +39846,34 @@ arena.appendChildList(context, [createCommentNode(arena, tokens[i])]); stats.nodesCount++; } - else if (arena.dataTypes[tokens[i]] != exports.EnumToken.WhitespaceTokenType) { + else if (arena.dataTypes[tokens[i]] !== exports.EnumToken.WhitespaceTokenType) { break; } } - if (tokens.length == 0) { + if (tokens.length === 0) { return null; } let delim = tokens[tokens.length - 1]; - if (arena.dataTypes[delim] == exports.EnumToken.SemiColonTokenType || - arena.dataTypes[delim] == exports.EnumToken.BlockStartTokenType || - arena.dataTypes[delim] == exports.EnumToken.BlockEndTokenType) { + if (arena.dataTypes[delim] === exports.EnumToken.SemiColonTokenType || + arena.dataTypes[delim] === exports.EnumToken.BlockStartTokenType || + arena.dataTypes[delim] === exports.EnumToken.BlockEndTokenType) { tokens.pop(); } - if (tokens.length == 0) { + if (tokens.length === 0) { return null; } - if (arena.dataTypes[tokens[0]] == exports.EnumToken.AtRuleTokenType) { + if (arena.dataTypes[tokens[0]] === exports.EnumToken.AtRuleTokenType) { let nestedRule = false; let parent = context; let node; - while (parent != 0) { - if (arena.dataTypes[parent] == exports.EnumToken.RuleNodeType) { + while (parent !== 0) { + if (arena.dataTypes[parent] === exports.EnumToken.RuleNodeType) { nestedRule = true; break; } parent = arena.parents[parent]; } - node = parseAtRule(arena, tokens, context, { ...options, nestedRule }, errors, arena.dataTypes[delim] == exports.EnumToken.BlockStartTokenType); + node = parseAtRule(arena, tokens, context, { ...options, nestedRule }, errors, arena.dataTypes[delim] === exports.EnumToken.BlockStartTokenType); if (node == null) { return null; } @@ -37565,7 +39893,7 @@ else { stats.nodesCount++; // rule - if (arena.dataTypes[delim] == exports.EnumToken.BlockStartTokenType) { + if (arena.dataTypes[delim] === exports.EnumToken.BlockStartTokenType) { const node = parseSelector(arena, tokens, context, options, errors); // inlined: arena.appendChildren(context, node) arena.appendChildList(context, [node]); @@ -37591,7 +39919,10 @@ action: "drop", node, // inlined: options.source!.getSourceLocation(arena.getSpanStart(node)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(node))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(node)), + ], }); } else if (options.lenient || arena.dataTypes[node] === exports.EnumToken.DeclarationNodeType) { @@ -37611,6 +39942,7 @@ return null; } /** + * @param arena * @param stream * @param context * @param options @@ -37664,7 +39996,8 @@ atRuleErrors = [errors[errors.length - 1]]; return createAtRuleNode(arena, atRule, exports.EnumToken.AtRuleNodeType, atRuleTokens, atRuleState, atRuleErrors, atRuleEnd, renderTokens(arena, trimArray(arena, stream), options), !!parseAsBlock); } - const token = stream.find((t) => arena.dataTypes[t] != exports.EnumToken.WhitespaceTokenType && arena.dataTypes[t] === exports.EnumToken.CommentTokenType) ?? null; + const token = stream.find((t) => arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[t] === exports.EnumToken.CommentTokenType) ?? null; if (token != null) { errors.push({ action: "drop", @@ -37703,14 +40036,18 @@ arena.dataTypes[stream[0]] !== exports.EnumToken.WhitespaceTokenType || arena.getSpanEnd(stream[0]) - arena.getSpanStart(stream[0]) !== 1 || // inlined: arena.getSource(stream[0]), options.sourcesMap?.get(...)?.getContent() - options.sourcesMap?.get(arena.sources[arena.getSourceId(stream[0])] ?? 0)?.content.charCodeAt(arena.getSpanStart(stream[0])) !== - 0x20) { + options.sourcesMap + ?.get(arena.sources[arena.getSourceId(stream[0])] ?? 0) + ?.content.charCodeAt(arena.getSpanStart(stream[0])) !== 0x20) { success = false; errors.push({ action: "drop", node: stream[0] ?? atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[0] ?? atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[0] ?? atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[0] ?? atRule)), + ], message: "expecting ", }); } @@ -37720,7 +40057,10 @@ action: "drop", node: stream[1] ?? atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[1] ?? atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[1] ?? atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[1] ?? atRule)), + ], message: "expecting ", }); } @@ -37730,7 +40070,10 @@ action: "drop", node: stream[1] ?? atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[1] ?? atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[1] ?? atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[1] ?? atRule)), + ], message: "expecting double-quoted string", }); } @@ -37775,19 +40118,26 @@ action: "drop", node: atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule)), + ], message: `unexpected at-rule ${nam}`, }); } if (success) { for (const token of stream) { - if (arena.dataTypes[token] !== exports.EnumToken.CommentTokenType && arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[token] !== exports.EnumToken.CommentTokenType && + arena.dataTypes[token] !== exports.EnumToken.WhitespaceTokenType) { success = false; errors.push({ action: "drop", node: token, // inlined: options.source!.getSourceLocation(arena.getSpanStart(token)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(token))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(token)), + ], message: `unexpected token`, }); } @@ -37830,8 +40180,9 @@ } case "keyframes": { const tokens = trimArray(arena, stream.slice(1)); - const filtered = stream.filter((t) => arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType && arena.dataTypes[t] !== exports.EnumToken.CommentTokenType); - if (filtered.length != 1 || + const filtered = stream.filter((t) => arena.dataTypes[t] !== exports.EnumToken.WhitespaceTokenType && + arena.dataTypes[t] !== exports.EnumToken.CommentTokenType); + if (filtered.length !== 1 || (arena.dataTypes[filtered[0]] !== exports.EnumToken.IdenTokenType && arena.dataTypes[filtered[0]] !== exports.EnumToken.StringTokenType && arena.dataTypes[filtered[0]] !== exports.EnumToken.DashedIdenTokenType)) { @@ -37839,7 +40190,10 @@ action: "drop", node: atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule)), + ], message: `expected `, }); success = false; @@ -37859,19 +40213,16 @@ errors.push(error); } } - // else { - // parseUrlToken(stream); - // } const valid = blockAllowed === parseAsBlock && result.success; if (valid) { let start = 0; let end = -1; let hasString = false; for (start = 0; start < stream.length; start++) { - if (arena.dataTypes[stream[start]] == exports.EnumToken.UrlFunctionTokenDefType) { + if (arena.dataTypes[stream[start]] === exports.EnumToken.UrlFunctionTokenDefType) { start++; for (end = start; end < stream.length; end++) { - if (arena.dataTypes[stream[end]] == exports.EnumToken.EndParensTokenType) { + if (arena.dataTypes[stream[end]] === exports.EnumToken.EndParensTokenType) { break; } if (arena.dataTypes[stream[end]] === exports.EnumToken.StringTokenType) { @@ -37894,7 +40245,8 @@ (arena.dataTypes[t] === exports.EnumToken.CommentTokenType || (arena.dataTypes[t] === exports.EnumToken.WhitespaceTokenType && arena.dataTypes[stream[index + 1]] === exports.EnumToken.CommentTokenType && - (stream.length < index + 3 || arena.dataTypes[stream[index + 2]] === exports.EnumToken.WhitespaceTokenType)) + (stream.length < index + 3 || + arena.dataTypes[stream[index + 2]] === exports.EnumToken.WhitespaceTokenType)) ? "" : renderValue(arena, t, options)), ""), !!parseAsBlock); } @@ -37906,8 +40258,11 @@ } } else { - if (arena.dataTypes[stream[0]] == exports.EnumToken.UrlFunctionTokenType && - arena.tokens(stream[0]).some((t) => arena.dataTypes[t] == exports.EnumToken.StringTokenType || arena.dataTypes[t] == exports.EnumToken.UrlTokenTokenType)) { + if (arena.dataTypes[stream[0]] === exports.EnumToken.UrlFunctionTokenType && + arena + .tokens(stream[0]) + .some((t) => arena.dataTypes[t] === exports.EnumToken.StringTokenType || + arena.dataTypes[t] === exports.EnumToken.UrlTokenTokenType)) { stream.splice(0, 1, ...arena.tokens(stream[0])); } } @@ -37919,7 +40274,8 @@ (arena.dataTypes[t] === exports.EnumToken.CommentTokenType || (arena.dataTypes[t] === exports.EnumToken.WhitespaceTokenType && arena.dataTypes[stream[index + 1]] === exports.EnumToken.CommentTokenType && - (stream.length < index + 3 || arena.dataTypes[stream[index + 2]] === exports.EnumToken.WhitespaceTokenType)) + (stream.length < index + 3 || + arena.dataTypes[stream[index + 2]] === exports.EnumToken.WhitespaceTokenType)) ? "" : renderValue(arena, t, options)), ""), false); } @@ -37938,7 +40294,7 @@ let success = result.success; if (nam === "else") { let sibling = arena.lastChild[context]; - while (sibling != 0) { + while (sibling !== 0) { if (arena.dataTypes[sibling] === exports.EnumToken.WhitespaceTokenType || arena.dataTypes[sibling] === exports.EnumToken.CommentTokenType || arena.dataTypes[sibling] === exports.EnumToken.CDOCOMMTokenType) { @@ -37949,7 +40305,7 @@ } let missingWhen = false; let definedAfterLastElse = false; - if (sibling == 0 || arena.dataTypes[sibling] !== exports.EnumToken.AtRuleNodeType) { + if (sibling === 0 || arena.dataTypes[sibling] !== exports.EnumToken.AtRuleNodeType) { missingWhen = true; } else if (arena.strings[arena.name[sibling]] !== "when") { @@ -37966,7 +40322,10 @@ action: "drop", node: atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule)), + ], message: "at-rule @when is required before @else block", }); } @@ -37976,7 +40335,10 @@ action: "drop", node: atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule)), + ], message: "at-rule @else block is defined after last @else block", }); } @@ -38013,7 +40375,10 @@ action: "drop", node: range[0] ?? atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(range[0] ?? atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(range[0] ?? atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(range[0] ?? atRule)), + ], message: "expected '(' at start of @scope block", }); success = false; @@ -38024,7 +40389,10 @@ action: "drop", node: range.at(-1) ?? atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(range.at(-1) ?? atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(range.at(-1) ?? atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(range.at(-1) ?? atRule)), + ], message: "expected ')' at end of @scope block", }); success = false; @@ -38051,7 +40419,10 @@ action: "drop", node: stream[index], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[index])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[index]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[index])), + ], message: "expected 'to' at end of @scope block", }); success = false; @@ -38065,7 +40436,10 @@ action: "drop", node: stream[index], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[index])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[index]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[index])), + ], message: "expected 'to' at end of @scope block", }); success = false; @@ -38080,7 +40454,10 @@ action: "drop", node: range.at(-1) ?? atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(range.at(-1) ?? atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(range.at(-1) ?? atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(range.at(-1) ?? atRule)), + ], message: "expected ')' at end of @scope block", }); success = false; @@ -38134,7 +40511,10 @@ action: "drop", node: atRule, // inlined: options.source!.getSourceLocation(arena.getSpanStart(atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule)), + ], message: "node is allowed only in @page rule", }); } @@ -38148,7 +40528,10 @@ action: "drop", node: stream[i], // inlined: options.source!.getSourceLocation(arena.getSpanStart(stream[i])) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i]))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(stream[i])), + ], message: "expected whitespace or comment", }); break; @@ -38165,7 +40548,7 @@ let index = 0; let isVarDeclaration = false; for (; index < stream.length; index++) { - if (arena.dataTypes[stream[index]] == exports.EnumToken.PseudoClassTokenType) { + if (arena.dataTypes[stream[index]] === exports.EnumToken.PseudoClassTokenType) { const colon = arena.createToken(exports.EnumToken.ColonTokenType); arena.copyLocation(colon, stream[index]); // inlined: arena.setStr(stream[index], arena.strings[arena.stringValue[stream[index]]].slice(1)) @@ -38175,11 +40558,11 @@ isVarDeclaration = true; break; } - else if (arena.dataTypes[stream[index]] == exports.EnumToken.ColonTokenType) { + else if (arena.dataTypes[stream[index]] === exports.EnumToken.ColonTokenType) { isVarDeclaration = true; break; } - else if (arena.dataTypes[stream[index]] == exports.EnumToken.IdenTokenType && + else if (arena.dataTypes[stream[index]] === exports.EnumToken.IdenTokenType && equalsIgnoreCase("from", arena.strings[arena.stringValue[stream[index]]])) { break; } @@ -38202,12 +40585,12 @@ return createAtRuleNode(arena, atRule, exports.EnumToken.AtRuleNodeType, atRuleTokens, atRuleState, atRuleErrors, atRuleEnd, renderTokens(arena, stream, options), false); } if (isVarDeclaration) { - const nam = stream.find((t) => arena.dataTypes[t] == exports.EnumToken.IdenTokenType); - const value = trimArray(arena, stream.slice(index + 1).filter((t) => arena.dataTypes[t] != exports.EnumToken.CommentTokenType)); + const nam = stream.find((t) => arena.dataTypes[t] === exports.EnumToken.IdenTokenType); + const value = trimArray(arena, stream.slice(index + 1).filter((t) => arena.dataTypes[t] !== exports.EnumToken.CommentTokenType)); // import from file as alias: @value : ; // variable declaration: @value : ; // the variable value is stored as the node values - const node = arena.createDeclaration(value.length == 1 && arena.dataTypes[value[0]] == exports.EnumToken.StringTokenType + const node = arena.createDeclaration(value.length === 1 && arena.dataTypes[value[0]] === exports.EnumToken.StringTokenType ? exports.EnumToken.CssVariableImportTokenType : exports.EnumToken.CssVariableTokenType, arena.strings[arena.stringValue[nam]], value, exports.EnumAstNodeStatus.Validated, []); arena.spanLocation(node, atRule, atRuleEnd); @@ -38249,7 +40632,8 @@ let i = 0; const stack = []; for (; i < stream.length; i++) { - if (arena.dataTypes[stream[i]] === exports.EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[stream[i]])) { + if (arena.dataTypes[stream[i]] === exports.EnumToken.StartParensTokenType || + tokensfuncDefMap.has(arena.dataTypes[stream[i]])) { stack.push(stream[i]); continue; } @@ -38273,22 +40657,25 @@ atRuleErrors = result.errors; switch (nam) { case "mixin": - if (contextType != exports.EnumToken.StyleSheetNodeType) { + if (contextType !== exports.EnumToken.StyleSheetNodeType) { atRuleState |= exports.EnumAstNodeStatus.Disallowed; atRuleErrors.push({ action: "drop", message: "mixin rule cannot be a nested group rule or rule style body", // inlined: options.source!.getSourceLocation(arena.getSpanStart(atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule)), + ], }); } break; case "contents": let parent = context; let valid = false; - while (parent != 0) { - if (arena.dataTypes[parent] == exports.EnumToken.AtRuleNodeType && - "mixin" == arena.strings[arena.name[parent]]) { + while (parent !== 0) { + if (arena.dataTypes[parent] === exports.EnumToken.AtRuleNodeType && + "mixin" === arena.strings[arena.name[parent]]) { valid = true; break; } @@ -38300,22 +40687,28 @@ action: "drop", message: "contents rule cannot be used outside mixin rule", // inlined: options.source!.getSourceLocation(arena.getSpanStart(atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule)), + ], }); } break; case "layer": - if (contextType != exports.EnumToken.StyleSheetNodeType) { + if (contextType !== exports.EnumToken.StyleSheetNodeType) { let parent = context; - while (parent != 0) { - if (arena.dataTypes[parent] == exports.EnumToken.AtRuleNodeType && - arena.strings[arena.name[parent]] == "mixin") { + while (parent !== 0) { + if (arena.dataTypes[parent] === exports.EnumToken.AtRuleNodeType && + arena.strings[arena.name[parent]] === "mixin") { atRuleState |= exports.EnumAstNodeStatus.Disallowed; atRuleErrors.push({ action: "drop", - message: "at-rule layeris not allowed inside mixin rule", + message: "at-rule layer is not allowed inside mixin rule", // inlined: options.source!.getSourceLocation(arena.getSpanStart(atRule)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(atRule)), + ], }); break; } @@ -38342,14 +40735,8 @@ */ function parseDeclarations(declaration, arena) { const stream = `.x{${declaration}}`; - const source = new SourceFile(stream, [], ""); - const result = doParseSync(new Tokenizer({ - stream, - offset: 0, - position: 0, - source, - currentPosition: 0, - }), { + const source = new SourceFile("", [], ""); + const result = doParseSync(new Tokenizer(createParseInfo(stream, source)), { setParent: false, minify: false, validation: false, @@ -38359,10 +40746,10 @@ }); const rule = result.arena.firstChild[result.ast]; const nodes = []; - for (let node = rule == 0 ? 0 : result.arena.firstChild[rule]; node != 0;) { + for (let node = rule === 0 ? 0 : result.arena.firstChild[rule]; node !== 0;) { const next = result.arena.nextSibling[node]; - if (result.arena.dataTypes[node] == exports.EnumToken.DeclarationNodeType || - result.arena.dataTypes[node] == exports.EnumToken.CommentNodeType) { + if (result.arena.dataTypes[node] === exports.EnumToken.DeclarationNodeType || + result.arena.dataTypes[node] === exports.EnumToken.CommentNodeType) { result.arena.detach(node); nodes.push(node); } @@ -38372,6 +40759,7 @@ } /** * Parse css string and return an array of tokens + * @param arena * @param src * @param options * - parseColor: parse identifiers as colors @@ -38394,16 +40782,7 @@ * ``` */ function parseString(arena, src, options = { parseColor: true }, errors) { - const tokenizer = new Tokenizer({ - stream: src, - buffer: "", - src: options?.src ?? "", - offset: 0, - time: 0, - source: new SourceFile(src, [], options?.src ?? ""), - position: 0, - currentPosition: 0, - }); + const tokenizer = new Tokenizer(createParseInfo(src, new SourceFile("", [], options?.src ?? ""))); const mapped = []; // inlined: tokenizer.done() while (!(tokenizer.typ === exports.EnumToken.EOF)) { @@ -38415,7 +40794,9 @@ // remove the EOF token and the whitespace before it: their ids are recycled const removed = result.splice(result.length - (arena.dataTypes[result[result.length - 2]] === exports.EnumToken.WhitespaceTokenType ? 2 : 1), 2); for (let i = 0; i < removed.length; i++) { - if (arena.parents[removed[i]] == 0 && arena.firstToken[removed[i]] == 0 && arena.firstChild[removed[i]] == 0) { + if (arena.parents[removed[i]] === 0 && + arena.firstToken[removed[i]] === 0 && + arena.firstChild[removed[i]] === 0) { arena.recycle(removed[i]); } } @@ -38423,6 +40804,7 @@ } /** * Parse function tokens in a token array + * @param arena * @param tokens * @param options * - parseColor: parse identifiers as colors @@ -38461,8 +40843,8 @@ // merge the colon and the function name into a pseudo class function const previous = tokens[i - 1]; // inlined: arena.setStr(previous, (arena.dataTypes[previous] === EnumToken.ColonTokenType ? ":" : "::") + arena.strings[arena.stringValue[t]]) - arena.stringValue[previous] = arena.internString(((arena.dataTypes[previous] === exports.EnumToken.ColonTokenType ? ":" : "::") + - arena.strings[arena.stringValue[t]])); + arena.stringValue[previous] = arena.internString((arena.dataTypes[previous] === exports.EnumToken.ColonTokenType ? ":" : "::") + + arena.strings[arena.stringValue[t]]); arena.dataTypes[previous] = exports.EnumToken.PseudoClassFunctionTokenDefType; // inlined: arena.setSpanEnd(previous, arena.getSpanEnd(t)) arena.setSpan(previous, arena.getSourceId(previous), arena.getSpanStart(previous), arena.getSpanEnd(t)); @@ -38488,7 +40870,10 @@ message: `Unbalanced token ')'`, node, // inlined: options.source!.getSourceLocation(arena.getSpanStart(node)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(node))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(node)), + ], }); // return []; continue; @@ -38519,7 +40904,10 @@ message: `Unbalanced token ']'`, node, // inlined: options.source!.getSourceLocation(arena.getSpanStart(node)) - location: [options.source.file, ...options.source.lineStarts.getOffsets(arena.getSpanStart(node))], + location: [ + options.source.file, + ...options.source.lineStarts.getOffsets(arena.getSpanStart(node)), + ], }); continue; } @@ -38534,8 +40922,8 @@ stack.pop(); continue; } - if (typ == exports.EnumToken.IdenTokenType) { - if (arena.strings[arena.stringValue[t]] == "from" && i > 0) { + if (typ === exports.EnumToken.IdenTokenType) { + if (arena.strings[arena.stringValue[t]] === "from" && i > 0) { const left = []; const right = []; let foundLeft = 0; @@ -38543,13 +40931,13 @@ let k = i; let l = i; while (k > 0) { - if (arena.dataTypes[tokens[k - 1]] == exports.EnumToken.CommentTokenType || - arena.dataTypes[tokens[k - 1]] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[tokens[k - 1]] === exports.EnumToken.CommentTokenType || + arena.dataTypes[tokens[k - 1]] === exports.EnumToken.WhitespaceTokenType) { left.push(tokens[--k]); continue; } - if (arena.dataTypes[tokens[k - 1]] == exports.EnumToken.IdenTokenType || - arena.dataTypes[tokens[k - 1]] == exports.EnumToken.DashedIdenTokenType) { + if (arena.dataTypes[tokens[k - 1]] === exports.EnumToken.IdenTokenType || + arena.dataTypes[tokens[k - 1]] === exports.EnumToken.DashedIdenTokenType) { foundLeft++; left.push(tokens[--k]); continue; @@ -38557,39 +40945,40 @@ break; } while (++l < tokens.length) { - if (arena.dataTypes[tokens[l]] == exports.EnumToken.CommentTokenType || - arena.dataTypes[tokens[l]] == exports.EnumToken.WhitespaceTokenType) { + if (arena.dataTypes[tokens[l]] === exports.EnumToken.CommentTokenType || + arena.dataTypes[tokens[l]] === exports.EnumToken.WhitespaceTokenType) { right.push(tokens[l]); continue; } - if (arena.dataTypes[tokens[l]] == exports.EnumToken.IdenTokenType || - arena.dataTypes[tokens[l]] == exports.EnumToken.StringTokenType) { + if (arena.dataTypes[tokens[l]] === exports.EnumToken.IdenTokenType || + arena.dataTypes[tokens[l]] === exports.EnumToken.StringTokenType) { foundRight++; right.push(tokens[l]); continue; } break; } - if (foundLeft > 0 && foundRight == 1) { - while (left.length > 0 && arena.dataTypes[left[0]] == exports.EnumToken.WhitespaceTokenType) { + if (foundLeft > 0 && foundRight === 1) { + while (left.length > 0 && arena.dataTypes[left[0]] === exports.EnumToken.WhitespaceTokenType) { left.shift(); } - while (left.length > 0 && arena.dataTypes[left[left.length - 1]] == exports.EnumToken.WhitespaceTokenType) { + while (left.length > 0 && + arena.dataTypes[left[left.length - 1]] === exports.EnumToken.WhitespaceTokenType) { left.pop(); } // composes selector: l = +, r = | | null const composes = arena.createToken(exports.EnumToken.ComposesSelectorNodeType); let from = 0; for (const b of right) { - if (from == 0 || - arena.dataTypes[b] == exports.EnumToken.IdenTokenType || - arena.dataTypes[b] == exports.EnumToken.StringTokenType) { + if (from === 0 || + arena.dataTypes[b] === exports.EnumToken.IdenTokenType || + arena.dataTypes[b] === exports.EnumToken.StringTokenType) { from = b; } } // inlined: arena.setField(composes, TokenField.L, ...left) arena.setTokenList(arena.fieldList(composes, exports.TokenField.L), left); - if (from != 0) { + if (from !== 0) { // inlined: arena.setField(composes, TokenField.R, from) arena.setTokenList(arena.fieldList(composes, exports.TokenField.R), [from]); } @@ -38602,9 +40991,9 @@ parseColor(arena, t); } } - if (typ == exports.EnumToken.WhitespaceTokenType && - (i == 0 || - i + 1 == tokens.length || + if (typ === exports.EnumToken.WhitespaceTokenType && + (i === 0 || + i + 1 === tokens.length || [ exports.EnumToken.CommaTokenType, exports.EnumToken.GteTokenType, @@ -38615,18 +41004,18 @@ tokens.splice(i--, 1); continue; } - if (typ == exports.EnumToken.ColonTokenType) { + if (typ === exports.EnumToken.ColonTokenType) { const next = i + 1 < tokens.length ? arena.dataTypes[tokens[i + 1]] : undefined; if (next != null) { - if (next == exports.EnumToken.FunctionTokenType) { + if (next === exports.EnumToken.FunctionTokenType) { arena.dataTypes[tokens[i + 1]] = exports.EnumToken.PseudoClassFuncTokenType; } - else if (next == exports.EnumToken.IdenTokenType) { + else if (next === exports.EnumToken.IdenTokenType) { // inlined: arena.setStr(tokens[i + 1], ":" + arena.strings[arena.stringValue[tokens[i + 1]]]) - arena.stringValue[tokens[i + 1]] = arena.internString((":" + arena.strings[arena.stringValue[tokens[i + 1]]])); + arena.stringValue[tokens[i + 1]] = arena.internString(":" + arena.strings[arena.stringValue[tokens[i + 1]]]); arena.dataTypes[tokens[i + 1]] = exports.EnumToken.PseudoClassTokenType; } - if (next == exports.EnumToken.FunctionTokenType || next == exports.EnumToken.IdenTokenType) { + if (next === exports.EnumToken.FunctionTokenType || next === exports.EnumToken.IdenTokenType) { tokens.splice(i, 1); i--; } @@ -38655,29 +41044,6 @@ return tokens; } - /** - * response type - */ - exports.ResponseType = void 0; - (function (ResponseType) { - /** - * return text - */ - ResponseType[ResponseType["Text"] = 0] = "Text"; - /** - * return a readable stream - */ - ResponseType[ResponseType["ReadableStream"] = 1] = "ReadableStream"; - /** - * return an arraybuffer - */ - ResponseType[ResponseType["ArrayBuffer"] = 2] = "ArrayBuffer"; - /** - * return a json object - */ - ResponseType[ResponseType["JSON"] = 3] = "JSON"; - })(exports.ResponseType || (exports.ResponseType = {})); - /** * parse result. process input sourcemap * @param result @@ -38694,8 +41060,8 @@ // extract inline source map from the input CSS const arena = result.arena; const token = arena.lastChild[result.ast]; - if (token != 0 && - arena.dataTypes[token] == exports.EnumToken.CommentTokenType && + if (token !== 0 && + arena.dataTypes[token] === exports.EnumToken.CommentTokenType && arena.startsWith(token, "val", "/*# sourceMappingURL=")) { let data = arena.strings[arena.stringValue[token]].slice(21, -2).trim(); if (data.endsWith(".map")) { @@ -38737,18 +41103,18 @@ let i; for (i = 0; i < args.length; i++) { const [key, value] = args[i]; - if (typeof value == "function") { + if (typeof value === "function") { if (value instanceof Promise || Object.getPrototypeOf(value).constructor.name == "AsyncFunction") { throw new Error(`[${prefix + key}]: Async functions are not supported in sync mode. Use parse() or transform() instead.`); } } - else if (value != null && typeof value == "object" && !(value instanceof AstArena)) { + else if (value != null && typeof value === "object" && !(value instanceof AstArena)) { validateSyncArguments(value, prefix + key + "."); } } } - var version = "2.0.1"; + var version = "2.1.0"; /** * Load file or url @@ -38763,11 +41129,11 @@ * ``` */ async function load(url, currentDirectory = ".", responseType = false) { - if (typeof responseType == "boolean") { + if (typeof responseType === "boolean") { responseType = responseType ? exports.ResponseType.ReadableStream : exports.ResponseType.Text; } let t; - if (typeof url == "object") { + if (typeof url === "object") { t = new URL(url.absolute, self.origin); } else if (matchUrl.test(url)) { @@ -38780,21 +41146,22 @@ const path = resolve(url, currentDirectory).absolute; t = new URL(path, self.origin); } - return fetch(t, t.origin != self.origin ? { mode: "cors" } : {}).then(async (response) => { + return fetch(t, t.origin !== self.origin ? { mode: "cors" } : {}).then(async (response) => { if (!response.ok) { throw new Error(`${response.status} ${response.statusText} ${response.url}`); } - if (responseType == exports.ResponseType.ArrayBuffer) { + if (responseType === exports.ResponseType.ArrayBuffer) { return response.arrayBuffer(); } - if (responseType == exports.ResponseType.JSON) { + if (responseType === exports.ResponseType.JSON) { return response.json(); } - return responseType == exports.ResponseType.ReadableStream ? response.body : response.text(); + return responseType === exports.ResponseType.ReadableStream ? response.body : response.text(); }); } /** * Render the ast tree + * @param arena * @param data * @param options * @param mapping @@ -38850,7 +41217,7 @@ function parseSync(...args) { let options; let stream; - if (typeof args[0] === "string") { + if (isCssInput(args[0])) { stream = args[0]; options = args[1]; } @@ -38874,20 +41241,11 @@ }); options.src = resolve(options.src, options.cwd).relative; if (options.source == null) { - const source = new SourceFile(typeof stream == "string" ? stream : "", [], options.src); + const source = new SourceFile(typeof stream === "string" ? stream : "", [], options.src); options.sourcesMap.set(source.id, source); options.source = source; } - options.parseInfo = { - stream, - buffer: "", - src: options.src ?? "", - offset: 0, - time: 0, - source: options.source, - position: 0, - currentPosition: 0, - }; + options.parseInfo = createParseInfo(stream, options.source); const result = doParseSync(new Tokenizer(options.parseInfo), options); return options.module == null && options.inputSourceMap == null && !options.sourcemap ? result @@ -38910,7 +41268,7 @@ function transformSync(...args) { let options; let stream; - if (typeof args[0] === "string") { + if (isCssInput(args[0])) { stream = args[0]; options = args[1]; } @@ -38926,9 +41284,9 @@ const parseResult = parseSync(stream, options); let mapping = null; let importMapping = null; - if ((typeof options.module == "number" && options.module & exports.ModuleScopeEnumOptions.ICSS) || - (typeof options.module == "object" && - typeof options.module.scoped == "number" && + if ((typeof options.module === "number" && options.module & exports.ModuleScopeEnumOptions.ICSS) || + (typeof options.module === "object" && + typeof options.module.scoped === "number" && options.module.scoped & exports.ModuleScopeEnumOptions.ICSS)) { mapping = parseResult.mapping; importMapping = parseResult.importMapping; @@ -38980,7 +41338,7 @@ async function parse(...args) { let options; let stream; - if (typeof args[0] === "string" || args[0] instanceof ReadableStream) { + if (isCssInput(args[0]) || args[0] instanceof ReadableStream) { stream = args[0]; options = args[1]; } @@ -38989,7 +41347,10 @@ const { file, input, ...opt } = args[0]; options = opt; if (file != null) { - return Promise.resolve((options.load ?? load)(file, "", options.asStream ?? false)).then((stream) => parse(stream, { src: options.file, ...options })); + return Promise.resolve((options.load != null + ? options.load(file, "", options.asStream ?? false) + : // the default loader loads the file as an ArrayBuffer: the preferred input of the tokenizer + load(file, "", options.asStream ? exports.ResponseType.ReadableStream : exports.ResponseType.ArrayBuffer))).then((stream) => parse(stream, { src: options.file, ...options })); } else { stream = input; @@ -38999,7 +41360,8 @@ options.src ??= ""; options.sourcesMap ??= new Map(); Object.assign(options, { - load, + // a custom loader is used to load the imported files + load: options.load ?? load, resolve, dirname, cwd: (options.cwd ?? self.location.pathname.endsWith("/")) @@ -39012,15 +41374,7 @@ options.sourcesMap.set(source.id, source); options.source = source; } - options.parseInfo = { - stream, - buffer: "", - offset: 0, - time: 0, - source: options.source, - position: 0, - currentPosition: 0, - }; + options.parseInfo = createParseInfo(stream, options.source); return doParse(stream instanceof ReadableStream ? new Tokenizer(options.parseInfo, stream).tokenizeStream() : new Tokenizer(options.parseInfo), options).then((result) => options.module == null && options.inputSourceMap == null && !options.sourcemap @@ -39051,7 +41405,7 @@ async function transform(...args) { let options; let stream; - if (typeof args[0] === "string" || args[0] instanceof ReadableStream) { + if (isCssInput(args[0]) || args[0] instanceof ReadableStream) { stream = args[0]; options = args[1]; } @@ -39060,7 +41414,10 @@ const { file, input, ...opt } = args[0]; options = opt; if (file != null) { - return Promise.resolve((options.load ?? load)(file, "", options.asStream ?? false)).then((stream) => transform(stream, { src: options.file, ...options })); + return Promise.resolve((options.load != null + ? options.load(file, "", options.asStream ?? false) + : // the default loader loads the file as an ArrayBuffer: the preferred input of the tokenizer + load(file, "", options.asStream ? exports.ResponseType.ReadableStream : exports.ResponseType.ArrayBuffer))).then((stream) => transform(stream, { src: options.file, ...options })); } else { stream = input; @@ -39071,9 +41428,9 @@ return parse(stream, options).then((parseResult) => { let mapping = null; let importMapping = null; - if ((typeof options.module == "number" && options.module & exports.ModuleScopeEnumOptions.ICSS) || - (typeof options.module == "object" && - typeof options.module.scoped == "number" && + if ((typeof options.module === "number" && options.module & exports.ModuleScopeEnumOptions.ICSS) || + (typeof options.module === "object" && + typeof options.module.scoped === "number" && options.module.scoped & exports.ModuleScopeEnumOptions.ICSS)) { mapping = parseResult.mapping; importMapping = parseResult.importMapping; @@ -39117,7 +41474,7 @@ exports.parseSync = parseSync; exports.parseSyntax = parseSyntax; exports.render = render; - exports.renderToken = renderValue; + exports.renderValue = renderValue; exports.resolve = resolve; exports.transform = transform; exports.transformSync = transformSync; diff --git a/dist/index.d.ts b/dist/index.d.ts index 3fc9bdbb9..2b2ec1874 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -1,14 +1,3 @@ -/** - * Syntax validation enum - */ -declare enum SyntaxValidationResult { - /** valid syntax */ - Valid = 0, - /** drop invalid syntax */ - Drop = 1, - /** preserve unknown at-rules, declarations and pseudo-classes */ - Lenient = 2 -} /** * Enum of node statuses */ @@ -646,6 +635,10 @@ declare enum EnumToken { * user defined dimension token type */ UserDefinedDimensionTokenType = 140, + /** + * unicode range token type: `U+0025-00FF`, `U+4??`. the token is rendered as it is + */ + UniCodeRange = 141, /** * alias for time token type */ @@ -1074,11 +1067,19 @@ declare class AstArenaNode { * at-rule / declaration name, token name. undefined for the other nodes */ get nam(): string | undefined; + /** + * + * @param nam + */ set nam(nam: string); /** * rule selector. undefined for the other nodes */ get sel(): string | undefined; + /** + * + * @param sel + */ set sel(sel: string); /** * value: @@ -1090,22 +1091,38 @@ declare class AstArenaNode { * - structured tokens with a value field: the field tokens */ get val(): string | number | AstArenaNode | readonly AstArenaNode[] | null | undefined; + /** + * + * @param val + */ set val(val: string | number | AstArenaNodeInput | readonly AstArenaNodeInput[] | null | undefined); /** * children: the child nodes of a stylesheet, a rule or an at-rule with a block, the tokens of a function token * (arguments), a parentheses token, ... undefined when the node has no children */ get chi(): readonly AstArenaNode[] | undefined; + /** + * + * @param chi + */ set chi(chi: readonly AstArenaNodeInput[] | null | undefined); /** * prelude tokens of an at-rule, selector tokens of a rule. null when the node has no prelude tokens */ get tokens(): readonly AstArenaNode[] | null; + /** + * + * @param tokens + */ set tokens(tokens: readonly AstArenaNodeInput[] | null | undefined); /** * unit of a dimension, calendar (`cal`) of a color, attribute (`attr`) of a match expression */ get unit(): string | undefined; + /** + * + * @param unit + */ set unit(unit: string | null | undefined); /** * color space of a color @@ -1126,46 +1143,82 @@ declare class AstArenaNode { * sign of a unary expression */ get sign(): EnumToken | undefined; + /** + * + * @param sign + */ set sign(sign: EnumToken); /** * operator: the operator of a binary expression, the operator tokens of a structured token */ get op(): EnumToken | AstArenaNode | readonly AstArenaNode[] | null | undefined; + /** + * + * @param op + */ set op(op: EnumToken | AstArenaNodeInput | readonly AstArenaNodeInput[] | null); /** * first operator of a media range query */ get op1(): AstArenaNode | readonly AstArenaNode[] | null | undefined; + /** + * + * @param op + */ set op1(op: AstArenaNodeInput | readonly AstArenaNodeInput[] | null); /** * second operator of a media range query */ get op2(): AstArenaNode | readonly AstArenaNode[] | null | undefined; + /** + * + * @param op + */ set op2(op: AstArenaNodeInput | readonly AstArenaNodeInput[] | null); /** * left hand side of a structured token, numerator of a fraction */ get l(): AstArenaNode | readonly AstArenaNode[] | null | undefined; + /** + * + * @param l + */ set l(l: AstArenaNodeInput | readonly AstArenaNodeInput[] | null); /** * right hand side of a structured token, denominator of a fraction */ get r(): AstArenaNode | readonly AstArenaNode[] | null | undefined; + /** + * + * @param r + */ set r(r: AstArenaNodeInput | readonly AstArenaNodeInput[] | null); /** * source location. null when the node has no location */ get loc(): Readonly | null; + /** + * + * @param loc + */ set loc(loc: SourceLocation | null | undefined); /** * validation state */ get state(): EnumAstNodeStatus; + /** + * + * @param state + */ set state(state: EnumAstNodeStatus | null | undefined); /** * validation errors. null when the node has no errors */ get errors(): readonly ErrorDescription[] | null; + /** + * + * @param errors + */ set errors(errors: readonly ErrorDescription[] | null | undefined); /** * parent node, or the token that owns the token (see {@link AstArena.getValueParent}). null when the node is @@ -1311,10 +1364,6 @@ declare class Arena { * 0 is never allocated: it means "no node" */ current: number; - /** - * head of the list of recycled node ids. the list is linked through the `nextSibling` column, see {@link recycle} - */ - protected freeList: number; /** * node EnumToken type array */ @@ -1375,16 +1424,29 @@ declare class Arena { * token spans. 8 bits for source type. 28 bits for start position, 28 bits for end position. This allows us to store the start and end positions of tokens in a single 64-bit integer, which is more efficient than storing them separately. */ spans: BigUint64Array; + /** + * error cache + */ + errors: Map; + /** + * head of the list of recycled node ids. the list is linked through the `nextSibling` column, see {@link recycle} + */ + protected freeList: number; + /** + * number of nodes the columns can hold: the length of the columns. the length of a typed array is a getter, + * allocate() reads the capacity of the arena for each node + */ + protected capacity: number; /** * 32 bits view of the spans: the low word holds the end position and the 4 low bits of the start position, * the high word holds the 24 high bits of the start position and the source */ protected spans32: Uint32Array; + constructor(size?: number); /** - * error cache + * true when the column buffers have been transferred to another thread: the arena can no longer be used */ - errors: Map; - constructor(size?: number); + get transferred(): boolean; /** * Export the arena as a structured-cloneable object and the list of its column buffers, to send an arena * to a worker (or back to the main thread) without copying the node data. @@ -1417,24 +1479,6 @@ declare class Arena { * @returns an `Arena` or an `AstArena` depending on the class the method is called on */ static fromTransferableArenaObjects(this: new (size?: number) => T, properties: ArenaProperties, transferables: ArenaTransferables): T; - /** - * true when the column buffers have been transferred to another thread: the arena can no longer be used - */ - get transferred(): boolean; - /** - * structured-cloneable properties of the arena - */ - protected exportProperties(): ArenaProperties; - /** - * column buffers, in the order of {@link arenaColumns}. the `spans` buffer is shared with the `spans32` view - */ - protected exportTransferables(): ArenaTransferables; - /** - * initialize the arena from exported properties and column buffers - * @param properties - * @param transferables - */ - protected importProperties(properties: ArenaProperties, transferables: ArenaTransferables): void; allocate(): number; /** * recycle a detached leaf node (no parent, no children, no tokens) that is no longer referenced: @@ -1449,51 +1493,70 @@ declare class Arena { */ internString(str: string): number; /** - * set node data for a given id. The first argument is the id, the second is the type, the third is the string value, the fourth is the numeric value, and the fifth is the unit. + * * @param id - * @param type - * @param stringValue */ - set(id: number, type: EnumToken): void; + getType(id: number): EnumToken; /** - * set node data for a given id. The first argument is the id, the second is the type, the third is the string value, the fourth is the numeric value, and the fifth is the unit. + * type of node or a token. null when the id is null * @param id - * @param type - * @param stringValue */ - set(id: number, type: EnumToken, stringValue: number): void; + typeOf(id: number | null | undefined): EnumToken | null; /** - * set node data for a given id. The first argument is the id, the second is the type, the third is the string value, and the fourth is the numeric value. + * * @param id * @param type - * @param stringValue - * @param numericValue */ - set(id: number, type: EnumToken, stringValue: number, numericValue: number): void; + setType(id: number, type: EnumToken): void; /** - * set node data for a given id. The first argument is the id, the second is the type, the third is the string value, the fourth is the numeric value, and the fifth is the unit. + * * @param id - * @param type - * @param stringValue - * @param numericValue - * @param unit + * @param nameId */ - set(id: number, type: EnumToken, stringValue: number, numericValue: number, unit: number): void; - getType(id: number): EnumToken; + setName(id: number, nameId: number): void; /** - * type of a node or a token. null when the id is null + * * @param id */ - typeOf(id: number | null | undefined): EnumToken | null; - setType(id: number, type: EnumToken): void; - setName(id: number, nameId: number): void; getName(id: number): string; + /** + * + * @param id + * @param valueId + */ setValue(id: number, valueId: number): void; + /** + * + * @param id + */ getValue(id: number): string; + /** + * + * @param id + * @param numericValue + */ setNumericValue(id: number, numericValue: number): void; + /** + * + * @param id + * @param unit + */ setUnit(id: number, unit: number): void; + /** + * + * @param id + */ getUnit(id: number): string; + /** + * + * @param id + */ getNumericValue(id: number): number; + /** + * + * @param id + * @param parentId + */ setParent(id: number, parentId: number): void; /** * first child of a node. 0 when the node has no children @@ -1539,6 +1602,10 @@ declare class Arena { * @param firstChildId */ setFirstChild(id: number, firstChildId: number): void; + /** + * + * @param id + */ getLastChild(id: number): number; /** * replace the last child @@ -1564,11 +1631,39 @@ declare class Arena { * @param firstTokenId */ setFirstToken(id: number, firstTokenId: number): void; + /** + * + * @param id + * @param colorType + */ setColorType(id: number, colorType: number): void; + /** + * + * @param id + */ getColorType(id: number): number; + /** + * + * @param id + * @param flags + */ setFlags(id: number, flags: number): void; + /** + * + * @param id + */ getFlags(id: number): number; + /** + * + * @param id + * @param flag + */ hasFlags(id: number, flag: number): boolean; + /** + * + * @param id + * @param index + */ getChildAt(id: number, index: number): number | null; /** * token at the given position of the token list @@ -1621,15 +1716,63 @@ declare class Arena { * @param tokens */ appendField(id: number, field: TokenField, ...tokens: number[]): void; + /** + * + * @param id + * @param children + */ setLeft(id: number, ...children: number[]): void; + /** + * + * @param id + */ getLeft(id: number): number[] | null; + /** + * + * @param id + * @param rightId + */ setRight(id: number, rightId: null): void; + /** + * + * @param id + * @param rightId + */ setRight(id: number, ...rightId: number[]): void; + /** + * + * @param id + */ getRight(id: number): number[] | null; + /** + * + * @param id + * @param opId + */ setOp(id: number, opId: number): void; + /** + * + * @param id + */ getOp(id: number): number; + /** + * + * @param id + * @param op2Id + */ setOp2(id: number, op2Id: number): void; + /** + * + * @param id + */ getOp2(id: number): number; + /** + * + * @param id + * @param sourceId + * @param start + * @param end + */ setSpan(id: number, sourceId: number, start: number, end: number): void; /** * copy the packed location of a node @@ -1637,12 +1780,42 @@ declare class Arena { * @param source */ copySpan(target: number, source: number): void; + /** + * + * @param id + */ getSourceId(id: number): number; + /** + * + * @param id + */ getSpanStart(id: number): number; + /** + * + * @param id + * @param start + */ setSpandStart(id: number, start: number): void; + /** + * + * @param id + */ getSpanEnd(id: number): number; + /** + * + * @param id + * @param end + */ setSpanEnd(id: number, end: number): void; + /** + * + * @param id + */ getParent(id: number): number; + /** + * + * @param id + */ resolveString(id: number): string; /** * detach a node from its parent @@ -1804,6 +1977,11 @@ declare class Arena { * @param id */ subTokens(id: number): number[]; + /** + * + * @param id + * @param predicate + */ findChild(id: number, predicate: (id: number) => boolean): number | null; /** * find a token in the token list @@ -1834,6 +2012,11 @@ declare class Arena { * @param id */ tokenCount(id: number): number; + /** + * + * @param id + * @param children + */ setChildren(id: number, ...children: number[]): void; /** * replace the children. same as {@link setChildren} with an array @@ -1841,6 +2024,11 @@ declare class Arena { * @param children */ setChildList(id: number, children: number[]): void; + /** + * + * @param id + * @param children + */ setTokens(id: number, ...children: number[]): void; /** * replace the token list. same as {@link setTokens} with an array @@ -1855,6 +2043,11 @@ declare class Arena { * @param before the children are inserted before this child of `to`. they are appended when 0 */ moveChildren(from: number, to: number, before?: number): void; + /** + * + * @param id + * @param children + */ appendChildren(id: number, ...children: number[]): void; /** * append children. same as {@link appendChildren} with an array @@ -1862,6 +2055,11 @@ declare class Arena { * @param children */ appendChildList(id: number, children: number[]): void; + /** + * + * @param id + * @param children + */ appendTokens(id: number, ...children: number[]): void; /** * append tokens. same as {@link appendTokens} with an array @@ -1887,8 +2085,24 @@ declare class Arena { * @param tokens */ prependTokens(id: number, ...tokens: number[]): void; + /** + * + * @param node + * @param key + * @param string + */ equalsIgnoreCase(node: number, key: "nam" | "val", string: string): boolean; + /** + * + * @param node + * @param key + * @param string + */ startsWith(node: number, key: "nam" | "val", string: string): boolean; + /** + * + * @param newSize + */ resize(newSize: number): void; /** * drop the interned strings that are no longer referenced by any node @@ -1927,13 +2141,36 @@ declare class Arena { * @returns mapping of the old ids to the new ids (0 when the node was dropped) */ trim(errors?: ErrorDescription[] | null): Uint32Array; + /** + * + * @param id + * @param errors + */ setErrors(id: number, errors: ErrorDescription[] | null): void; + /** + * + * @param id + */ getErrors(id: number): ErrorDescription[] | null; /** * number of children * @param id */ childCount(id: number): number; + /** + * structured-cloneable properties of the arena + */ + protected exportProperties(): ArenaProperties; + /** + * column buffers, in the order of {@link arenaColumns}. the `spans` buffer is shared with the `spans32` view + */ + protected exportTransferables(): ArenaTransferables; + /** + * initialize the arena from exported properties and column buffers + * @param properties + * @param transferables + */ + protected importProperties(properties: ArenaProperties, transferables: ArenaTransferables): void; } /** * Css ast arena: ast nodes and value tokens. @@ -1954,15 +2191,11 @@ declare class AstArena extends Arena { * source ids. `spans` store the index in this table (8 bits) */ sources: number[]; - constructor(size?: number); /** - * @inheritDoc - */ - protected exportProperties(): ArenaProperties; - /** - * @inheritDoc + * + * @param size */ - protected importProperties(properties: ArenaProperties, transferables: ArenaTransferables): void; + constructor(size?: number); /** * @inheritDoc */ @@ -2201,16 +2434,6 @@ declare class AstArena extends Arena { * @returns the node id */ fromObject(node: AstArenaNode | PlainAstNode | PlainToken): number; - /** - * create an ast node from a plain object - * @param node - */ - protected nodeFromObject(node: PlainAstNode): number; - /** - * create a token from a plain object - * @param token - */ - protected tokenFromObject(token: PlainToken): number; /** * Object view of a node or a token: an {@link AstArenaNode}. The view does not copy the node: its properties read * and write the arena. Importing the view in this arena ({@link fromObject}, visitor results, setters of the @@ -2325,6 +2548,31 @@ declare class AstArena extends Arena { * @returns the node id */ expand(ast: AstStyleSheet | AstAtRule | AstRule): AstNode; + /** + * replace the nesting selector '&' of a selector + * @internal + * @param input + * @param replace + */ + replaceCompound(input: string, replace: string): string; + /** + * @inheritDoc + */ + protected exportProperties(): ArenaProperties; + /** + * @inheritDoc + */ + protected importProperties(properties: ArenaProperties, transferables: ArenaTransferables): void; + /** + * create an ast node from a plain object + * @param node + */ + protected nodeFromObject(node: PlainAstNode): number; + /** + * create a token from a plain object + * @param token + */ + protected tokenFromObject(token: PlainToken): number; /** * expand a rule: the nested rules and at-rules are moved out of the rule, into `parent` before `before`. * the rule is detached when it has no children left @@ -2334,12 +2582,11 @@ declare class AstArena extends Arena { */ protected expandRule(node: AstRule, parent: AstNode, before: AstNode): void; /** - * replace the nesting selector '&' of a selector - * @internal - * @param input + * + * @param selector * @param replace + * @protected */ - replaceCompound(input: string, replace: string): string; protected replaceCompoundLiteral(selector: string, replace: string): string; } @@ -2539,6 +2786,14 @@ type AstValueMatcher = (arena: AstArena, token: Token) => boolean; */ type AstNodeMatcher = (arena: AstArena, node: AstNode) => boolean; +/** + * Unicode range token: `U+0025-00FF`, `U+4??` + */ +export declare interface UniCodeRangeToken extends BaseToken { + typ: EnumToken.UniCodeRange; + val: string; +} + /** * Literal token */ @@ -4128,6 +4383,7 @@ export declare type Token = number; */ export declare type PlainToken = | LiteralToken + | UniCodeRangeToken | IdentToken | IdentListToken | DashedIdentToken @@ -5017,15 +5273,6 @@ declare class LineMap { * @returns */ search(offset: number): number; - /** - * get line starts - * @returns - */ - getLineStarts(): number[]; - /** - * add line start - */ - addLineStart(lineStart: number): void; } /** @@ -5061,45 +5308,6 @@ declare class SourceFile { * @param content */ append(content: string): void; - /** - * get file name - * @returns - */ - getFileName(): string | null; - /** - * get content - * @returns - */ - getContent(): string; - /** - * get text - * @param start - * @param length - * @returns - */ - getText(start: number, length: number): string; - /** - * Compute line and column of the offset - * @param offset - * @returns - */ - getOffsets(offset: number): [number, number]; - /** - * get source location - * @param offset - * @returns - */ - getSourceLocation(offset: number): [string | null, number, number]; - /** - * get line starts - * @returns - */ - getLineStarts(): number[]; - /** - * add line start - * @param lineStart - */ - addLineStart(lineStart: number): void; /** * set input source map * @param inputSourceMap @@ -5131,10 +5339,21 @@ export declare interface PropertyListOptions { */ export declare interface ParseInfo$1 { /** - * stream + * the text of the css. the css input (a string, an ArrayBuffer or a view of an ArrayBuffer) is converted by the + * tokenizer */ stream: string; + /** + * the utf-16 code units of the css, read by the tokenizer. the code units of an ascii ArrayBuffer are its bytes + */ + codes: Uint8Array | Uint16Array; + + /** + * the number of code units: the length of a typed array is a getter + */ + length: number; + /** * Source file */ @@ -5264,6 +5483,10 @@ declare enum ValidationSyntaxGroupEnum { Declarations = "declarations", Functions = "functions", Syntaxes = "syntaxes", + /** + * value types, keyed by their name without the angle brackets (`color` for ``). referenced as {@link Syntaxes} + */ + Types = "types", Selectors = "selectors", AtRules = "atRules", Units = "units", @@ -5291,12 +5514,18 @@ interface Position { } interface ValidationValueRangeMatch { - min: ValidationNumberToken; + /** + * lower bound. null: -∞ + */ + min: ValidationNumberToken | null; max: ValidationNumberToken | null; } interface ValidationDimensionRangeMatch { - min: ValidationDimensionToken; + /** + * lower bound. null: -∞ + */ + min: ValidationDimensionToken | null; max: ValidationDimensionToken | null; } @@ -5382,6 +5611,12 @@ interface ValidationDimensionToken extends ValidationToken$1 { unit: keyof EnumToken; } +/** + * css input: the utf-8 encoded css in an ArrayBuffer or in a view of an ArrayBuffer (Uint8Array, Buffer), the preferred + * input, or a string + */ +type CssInput = string | ArrayBuffer | ArrayBufferView; + /** * response type */ @@ -6402,8 +6637,8 @@ interface MinifyOptions { export declare type LoadResult = | Promise> | ReadableStream - | string - | Promise + | CssInput + | Promise | object; /** @@ -6631,18 +6866,18 @@ export declare interface ParseInputFileOptions { */ export declare interface ParseInputOptions { /** - * Input string or stream + * Input css: an ArrayBuffer or a view of an ArrayBuffer (utf-8, the preferred input), or a string */ - input: string; + input: CssInput; } /** * Input options for string or stream */ export declare interface ParseInputStreamOptions { /** - * Input string or stream + * Input css: an ArrayBuffer or a view of an ArrayBuffer (utf-8, the preferred input), a string or a stream */ - input: string | ReadableStream; + input: CssInput | ReadableStream; } /** @@ -7314,9 +7549,14 @@ declare const resolve: (url: string, currentDirectory?: string, cwd?: string) => */ export declare interface ValidationSyntaxNode { /** - * mdn data syntax + * webref syntax */ syntax: string; + /** + * name of the standard property whose syntax is used: the vendor prefixed legacy name aliases of webref + * (`-webkit-align-content` is an alias of `align-content`). an alias has no other key + */ + alias?: string; /** * validation tokens */ @@ -7378,7 +7618,7 @@ interface ValidationResult { /** * validation result */ - valid: SyntaxValidationResult; + valid: boolean; /** * node */ @@ -7444,6 +7684,7 @@ declare function parseDeclarations(declaration: string, arena?: AstArena): { }; /** * Parse css string and return an array of tokens + * @param arena * @param src * @param options * - parseColor: parse identifiers as colors @@ -7473,6 +7714,7 @@ declare function parseString(arena: AstArena, src: string, options?: { /** * render ast token. identical constructs (colors and tokens with sub tokens: functions, parentheses, binary * expressions, ...) are rendered once per render, see {@link RenderMemo} + * @param arena * @param token * @param options * @param cache @@ -7486,6 +7728,7 @@ declare function renderValue(arena: AstArena, token: Token, options?: RenderOpti /** * Converts a color to another color space + * @param arena * @param token * @param to * @@ -7520,7 +7763,7 @@ declare function okLabDistance(arena: AstArena, color1: Token, color2: Token): n declare function isOkLabClose(arena: AstArena, color1: Token, color2: Token, threshold?: number): boolean; /** - * parse mdn data syntax + * parse a css value definition syntax (webref) * @param syntax * @returns */ @@ -7546,6 +7789,7 @@ declare function load(url: string | { }, currentDirectory?: string, responseType?: boolean | ResponseType): Promise>>; /** * Render the ast tree + * @param arena * @param data * @param options * @param mapping @@ -7594,7 +7838,7 @@ declare function render(arena: AstArena, data: AstNode, options?: RenderOptions, * ``` * */ -declare function parseSync(stream: string, options?: ParserSyncOptions): ParseResult; +declare function parseSync(stream: CssInput, options?: ParserSyncOptions): ParseResult; /** * Parse CSS string * @param options @@ -7628,7 +7872,7 @@ declare function parseSync(options: ParseInputOptions & ParserSyncOptions): Pars * ``` * */ -declare function transformSync(css: string, options?: TransformSyncOptions): TransformResult; +declare function transformSync(css: CssInput, options?: TransformSyncOptions): TransformResult; /** * Transform CSS * @param options @@ -7687,7 +7931,7 @@ declare function transformSync(options: ParseInputOptions & TransformSyncOptions * console.log(result.ast); * ``` */ -declare function parse(stream: string | ReadableStream, options?: ParserOptions): Promise; +declare function parse(stream: CssInput | ReadableStream, options?: ParserOptions): Promise; /** * Parse CSS * @param options @@ -7804,7 +8048,7 @@ declare function parse(options: ParseInputStreamOptions & ParserOptions): Promis * console.log(result.code); * ``` */ -declare function transform(css: string | ReadableStream, options?: TransformOptions): Promise; +declare function transform(css: CssInput | ReadableStream, options?: TransformOptions): Promise; /** * Transform CSS * @param options @@ -7864,5 +8108,5 @@ declare function transform(options: ParseInputStreamOptions & TransformOptions): */ declare function transform(options: ParseInputFileOptions & TransformOptions): Promise; -export { ARENA, ARENAID, Arena, AstArena, AstArenaNode, ColorType$1 as ColorType, EnumAstNodeStatus, EnumToken, FeatureWalkMode, ModuleCaseTransformEnum, ModuleScopeEnumOptions, ResponseType, SourceMap, TokenField, WalkerEvent, WalkerOptionEnum, arenaColumns, convertColor, dirname, isOkLabClose, load, minify, okLabDistance, parse, parseDeclarations, parseString, parseSync, parseSyntax, render, renderValue as renderToken, resolve, transform, transformSync, version }; -export type { AddToken, AndToken, AngleToken, ArenaProperties, ArenaTransferables, AstArenaNodeInput, AstAtRule, AstComment, AstDeclaration, AstKeyframesAtRule, AstKeyframesRule, AstNode, AstNodeMatcher, AstRule, AstRuleList, AstStyleSheet, AstValueMatcher, AtRuleToken, AtRuleVisitorHandler, AttrEndToken, AttrStartToken, AttrToken, Background, BackgroundAttachmentMapping, BackgroundPosition, BackgroundPositionClass, BackgroundPositionConstraints, BackgroundPositionMapping, BackgroundProperties, BackgroundRepeat, BackgroundRepeatMapping, BackgroundSize, BackgroundSizeMapping, BadCDOCommentToken, BadCommentToken, BadStringToken, BadUrlToken, BaseToken, BinaryExpressionNode, BinaryExpressionToken, BlockEndToken, BlockStartToken, Border, BorderColor, BorderColorClass, BorderProperties, BorderRadius, CDOCommentToken, ChildCombinatorToken, ClassSelectorToken, ColonToken, ColorToken, ColumnCombinatorToken, CommaToken, CommentToken, ComposesSelectorToken, ConstraintsMapping, ContainMatchToken, ContainerStyleRangeToken, CssTypeTokenType, CssVariableImportTokenType, CssVariableMapTokenType, CssVariableToken, DashMatchToken, DashedIdentToken, DeclarationToken, DeclarationVisitorHandler, DelimToken, DescendantCombinatorToken, DimensionToken, DivToken, DoubleColonToken, EOFToken, EndMatchToken, EqualMatchToken, ErrorDescription, FlexToken, Font, FontFamily, FontProperties, FontWeight, FontWeightConstraints, FontWeightMapping, FractionToken, FrequencyToken, FunctionDefToken, FunctionImageToken, FunctionToken, FunctionURLToken, GenericVisitorAstNodeHandlerMap, GenericVisitorAstNodeSyncHandlerMap, GenericVisitorAsyncResult, GenericVisitorHandler, GenericVisitorResult, GenericVisitorSyncHandler, GenericVisitorSyncResult, GreaterThanOrEqualToken, GreaterThanToken, GridTemplateFuncToken, HashToken, IdentListToken, IdentToken, IfConditionToken, IfElseConditionToken, ImportantToken, IncludeMatchToken, InfinityToken, LengthToken, LessThanOrEqualToken, LessThanToken, LineHeight, ListToken, LiteralToken, LoadResult, Map$1 as Map, MatchExpressionToken, MatchedSelector, MediaFeatureOnlyToken, MediaFeatureToken, MediaQueryConditionToken, MediaQueryUnaryFeatureToken, MediaRangeQueryToken, MinifyFeature, MinifyFeatureOptions, MinifyOptions, ModuleAsyncOptions, ModuleSyncOptions, MulToken, NaNToken, NameSpaceAttributeToken, NegativeInfinityToken, NestingSelectorToken, NextSiblingCombinatorToken, NotToken, NumberToken, OptimizedSelector, OptimizedSelectorToken, OrToken, Outline, OutlineProperties, ParensEndToken, ParensStartToken, ParensToken, ParseInfo$1 as ParseInfo, ParseInputFileOptions, ParseInputOptions, ParseInputStreamOptions, ParseResult, ParseResultStats, ParseSourceOptions, ParseTokenOptions, ParsedVisitorHandlers, ParserOptions, ParserSourceMapOptions, ParserSyncOptions, PercentageToken, PlainAstNode, PlainToken, Prefix, PropertiesConfig, PropertiesConfigProperties, PropertyListOptions, PropertyMapType, PropertySetType, PropertyType, PseudoClassFunctionToken, PseudoClassToken, PseudoElementToken, PseudoPageToken, PurpleBackgroundAttachment, RawNodeToken, RawSelectorTokens, RenderOptions, RenderResult, ResolutionToken, ResolvedPath, RuleVisitorHandler, SemiColonToken, Separator, ShorthandDef, ShorthandMapType, ShorthandProperties, ShorthandPropertyType, ShorthandType, SinglePropertyType, SinglePropertyTypeMapping, SourceLocation, SourceMapObject, StartMatchToken, StringToken, SubToken, SubsequentCombinatorToken, SupportsQueryConditionToken, SupportsQueryUnaryConditionToken, TimeToken, TimelineFunctionToken, TimingFunctionToken, Token, TokenizeResult, TransformOptions, TransformResult, TransformSyncOptions, UnaryExpression, UnaryExpressionNode, UnclosedStringToken, UniversalSelectorToken, UrlToken, ValidationConfiguration, ValidationMediaFeature, ValidationOptions, ValidationResult, ValidationSelectorOptions, ValidationSyntaxNode, ValidationSyntaxResult, ValidationToken$1 as ValidationToken, Value, ValueVisitorHandler, ValueVisitorSyncHandler, VariableScopeInfo, VisitorNodeMap, VisitorSyncNodeMap, WalkerFilter, WalkerOption, WalkerOptions, WalkerValueFilter, WalkerValueOptions, WhenElseQueryConditionToken, WhenElseUnaryConditionToken, WhitespaceToken, WrappedValuesToken }; +export { ARENA, ARENAID, Arena, AstArena, AstArenaNode, ColorType$1 as ColorType, EnumAstNodeStatus, EnumToken, FeatureWalkMode, ModuleCaseTransformEnum, ModuleScopeEnumOptions, ResponseType, SourceMap, TokenField, WalkerEvent, WalkerOptionEnum, arenaColumns, convertColor, dirname, isOkLabClose, load, minify, okLabDistance, parse, parseDeclarations, parseString, parseSync, parseSyntax, render, renderValue, resolve, transform, transformSync, version }; +export type { AddToken, AndToken, AngleToken, ArenaProperties, ArenaTransferables, AstArenaNodeInput, AstAtRule, AstComment, AstDeclaration, AstKeyframesAtRule, AstKeyframesRule, AstNode, AstNodeMatcher, AstRule, AstRuleList, AstStyleSheet, AstValueMatcher, AtRuleToken, AtRuleVisitorHandler, AttrEndToken, AttrStartToken, AttrToken, Background, BackgroundAttachmentMapping, BackgroundPosition, BackgroundPositionClass, BackgroundPositionConstraints, BackgroundPositionMapping, BackgroundProperties, BackgroundRepeat, BackgroundRepeatMapping, BackgroundSize, BackgroundSizeMapping, BadCDOCommentToken, BadCommentToken, BadStringToken, BadUrlToken, BaseToken, BinaryExpressionNode, BinaryExpressionToken, BlockEndToken, BlockStartToken, Border, BorderColor, BorderColorClass, BorderProperties, BorderRadius, CDOCommentToken, ChildCombinatorToken, ClassSelectorToken, ColonToken, ColorToken, ColumnCombinatorToken, CommaToken, CommentToken, ComposesSelectorToken, ConstraintsMapping, ContainMatchToken, ContainerStyleRangeToken, CssInput, CssTypeTokenType, CssVariableImportTokenType, CssVariableMapTokenType, CssVariableToken, DashMatchToken, DashedIdentToken, DeclarationToken, DeclarationVisitorHandler, DelimToken, DescendantCombinatorToken, DimensionToken, DivToken, DoubleColonToken, EOFToken, EndMatchToken, EqualMatchToken, ErrorDescription, FlexToken, Font, FontFamily, FontProperties, FontWeight, FontWeightConstraints, FontWeightMapping, FractionToken, FrequencyToken, FunctionDefToken, FunctionImageToken, FunctionToken, FunctionURLToken, GenericVisitorAstNodeHandlerMap, GenericVisitorAstNodeSyncHandlerMap, GenericVisitorAsyncResult, GenericVisitorHandler, GenericVisitorResult, GenericVisitorSyncHandler, GenericVisitorSyncResult, GreaterThanOrEqualToken, GreaterThanToken, GridTemplateFuncToken, HashToken, IdentListToken, IdentToken, IfConditionToken, IfElseConditionToken, ImportantToken, IncludeMatchToken, InfinityToken, LengthToken, LessThanOrEqualToken, LessThanToken, LineHeight, ListToken, LiteralToken, LoadResult, Map$1 as Map, MatchExpressionToken, MatchedSelector, MediaFeatureOnlyToken, MediaFeatureToken, MediaQueryConditionToken, MediaQueryUnaryFeatureToken, MediaRangeQueryToken, MinifyFeature, MinifyFeatureOptions, MinifyOptions, ModuleAsyncOptions, ModuleSyncOptions, MulToken, NaNToken, NameSpaceAttributeToken, NegativeInfinityToken, NestingSelectorToken, NextSiblingCombinatorToken, NotToken, NumberToken, OptimizedSelector, OptimizedSelectorToken, OrToken, Outline, OutlineProperties, ParensEndToken, ParensStartToken, ParensToken, ParseInfo$1 as ParseInfo, ParseInputFileOptions, ParseInputOptions, ParseInputStreamOptions, ParseResult, ParseResultStats, ParseSourceOptions, ParseTokenOptions, ParsedVisitorHandlers, ParserOptions, ParserSourceMapOptions, ParserSyncOptions, PercentageToken, PlainAstNode, PlainToken, Prefix, PropertiesConfig, PropertiesConfigProperties, PropertyListOptions, PropertyMapType, PropertySetType, PropertyType, PseudoClassFunctionToken, PseudoClassToken, PseudoElementToken, PseudoPageToken, PurpleBackgroundAttachment, RawNodeToken, RawSelectorTokens, RenderOptions, RenderResult, ResolutionToken, ResolvedPath, RuleVisitorHandler, SemiColonToken, Separator, ShorthandDef, ShorthandMapType, ShorthandProperties, ShorthandPropertyType, ShorthandType, SinglePropertyType, SinglePropertyTypeMapping, SourceLocation, SourceMapObject, StartMatchToken, StringToken, SubToken, SubsequentCombinatorToken, SupportsQueryConditionToken, SupportsQueryUnaryConditionToken, TimeToken, TimelineFunctionToken, TimingFunctionToken, Token, TokenizeResult, TransformOptions, TransformResult, TransformSyncOptions, UnaryExpression, UnaryExpressionNode, UnclosedStringToken, UniCodeRangeToken, UniversalSelectorToken, UrlToken, ValidationConfiguration, ValidationMediaFeature, ValidationOptions, ValidationResult, ValidationSelectorOptions, ValidationSyntaxNode, ValidationSyntaxResult, ValidationToken$1 as ValidationToken, Value, ValueVisitorHandler, ValueVisitorSyncHandler, VariableScopeInfo, VisitorNodeMap, VisitorSyncNodeMap, WalkerFilter, WalkerOption, WalkerOptions, WalkerValueFilter, WalkerValueOptions, WhenElseQueryConditionToken, WhenElseUnaryConditionToken, WhitespaceToken, WrappedValuesToken }; diff --git a/dist/package.json.js b/dist/package.json.js index 8dd9e1ca6..763841984 100644 --- a/dist/package.json.js +++ b/dist/package.json.js @@ -2,9 +2,9 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ -var version = "2.0.1"; +var version = "2.1.0"; export { version }; diff --git a/dist/src/data/properties.json.js b/dist/src/data/properties.json.js index f04b1dc18..36c918076 100644 --- a/dist/src/data/properties.json.js +++ b/dist/src/data/properties.json.js @@ -2,7 +2,7 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ var properties = { diff --git a/dist/src/data/validation.json.js b/dist/src/data/validation.json.js index 25c63a346..28209b532 100644 --- a/dist/src/data/validation.json.js +++ b/dist/src/data/validation.json.js @@ -2,157 +2,310 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ -var declarations = { - "-ms-accelerator": { - syntax: "false | true" +var atRules = { + "@annotation": { + syntax: "@annotation { }" }, - "-ms-block-progression": { - syntax: "tb | rl | bt | lr" + "@apply": { + syntax: " @apply [ | ] [ { } ]?;" }, - "-ms-content-zoom-chaining": { - syntax: "none | chained" + "@bottom-center": { + syntax: "@bottom-center { };" }, - "-ms-content-zoom-limit": { - syntax: "<'-ms-content-zoom-limit-min'> <'-ms-content-zoom-limit-max'>" + "@bottom-left": { + syntax: " @bottom-left { }" }, - "-ms-content-zoom-limit-max": { - syntax: "" + "@bottom-left-corner": { + syntax: " @bottom-left-corner { }" }, - "-ms-content-zoom-limit-min": { - syntax: "" + "@bottom-right": { + syntax: " @bottom-right { }" }, - "-ms-content-zoom-snap": { - syntax: "<'-ms-content-zoom-snap-type'> || <'-ms-content-zoom-snap-points'>" + "@bottom-right-corner": { + syntax: " @bottom-right-corner { }" }, - "-ms-content-zoom-snap-points": { - syntax: "snapInterval( , ) | snapList( # )" + "@character-variant": { + syntax: "@character-variant { }" }, - "-ms-content-zoom-snap-type": { - syntax: "none | proximity | mandatory" + "@charset": { + syntax: "@charset \"\";" }, - "-ms-content-zooming": { - syntax: "none | zoom" + "@color-profile": { + syntax: "@color-profile [ | device-cmyk] { }", + descriptors: { + components: "#", + "rendering-intent": "relative-colorimetric | absolute-colorimetric | perceptual | saturation", + src: "" + } }, - "-ms-filter": { - syntax: "" + "@container": { + syntax: "@container # { }", + descriptors: { + "aspect-ratio": "", + "block-size": "", + fallback: "none | [ [ || ] | ]", + height: "", + "inline-size": "", + orientation: "portrait | landscape", + scrollable: "none | top | right | bottom | left | block-start | inline-start | block-end | inline-end | x | y | block | inline", + scrolled: "none | top | right | bottom | left | block-start | inline-start | block-end | inline-end | x | y | block | inline", + snapped: "none | x | y | block | inline | both", + stuck: "none | top | right | bottom | left | block-start | inline-start | block-end | inline-end", + width: "" + } }, - "-ms-flow-from": { - syntax: "[ none | ]#" + "@contents": { + syntax: " @contents [ { } ]?;" }, - "-ms-flow-into": { - syntax: "[ none | ]#" + "@counter-style": { + syntax: "@counter-style { }", + descriptors: { + "additive-symbols": "[ && ]#", + fallback: "", + negative: " ?", + pad: " && ", + prefix: "", + range: "[ [ | infinite ]{2} ]# | auto", + "speak-as": "auto | bullets | numbers | words | spell-out | ", + suffix: "", + symbols: "+", + system: "cyclic | numeric | alphabetic | symbolic | additive | [fixed ?] | [ extends ]" + } }, - "-ms-grid-columns": { - syntax: "none | | " + "@custom-media": { + syntax: " @custom-media [ | true | false ];" }, - "-ms-grid-rows": { - syntax: "none | | " + "@custom-selector": { + syntax: "@custom-selector ;" }, - "-ms-high-contrast-adjust": { - syntax: "auto | none" + "@document": { + syntax: "@document [ | url-prefix() | domain() | media-document() | regexp() ]# {\n \n}" }, - "-ms-hyphenate-limit-chars": { - syntax: "auto | {1,3}" + "@else": { + syntax: " @else ? {\n \n}" }, - "-ms-hyphenate-limit-lines": { - syntax: "no-limit | " + "@font-face": { + syntax: "@font-face { }", + descriptors: { + "ascent-override": "[ normal | ]{1,2}", + "descent-override": "[ normal | ]{1,2}", + "font-display": "auto | block | swap | fallback | optional", + "font-family": "", + "font-feature-settings": "normal | #", + "font-language-override": "normal | ", + "font-named-instance": "auto | ", + "font-size": "auto | []{1,2}", + "font-style": "auto | normal | italic | left | right | oblique [ {1,2} ]?", + "font-variation-settings": "normal | [ ]#", + "font-weight": "auto | {1,2}", + "font-width": "auto | <'font-width'>{1,2}", + "line-gap-override": "[ normal | ]{1,2}", + "size-adjust": "", + src: "", + "subscript-position-override": "[ normal | from-font | ]{1,2}", + "subscript-size-override": "[ normal | from-font | ]{1,2}", + "superscript-position-override": "[ normal | from-font | ]{1,2}", + "superscript-size-override": "[ normal | from-font | ]{1,2}", + "unicode-range": "#" + } }, - "-ms-hyphenate-limit-zone": { - syntax: " | " + "@font-feature-values": { + syntax: " @font-feature-values # { <@historical-forms> | <@styleset> | <@character-variant> | <@swash> | <@ornaments> | <@annotation> } ", + descriptors: { + "font-display": { + syntax: "auto | block | swap | fallback | optional" + } + } }, - "-ms-ime-align": { - syntax: "auto | after" + "@font-features-values": { + descriptors: { + "font-display": "auto | block | swap | fallback | optional" + } }, - "-ms-overflow-style": { - syntax: " auto | none | scrollbar | -ms-autohiding-scrollbar" + "@font-palette-values": { + syntax: "@font-palette-values { }", + descriptors: { + "base-palette": "light | dark | ", + "font-family": "#", + "override-colors": "[ ]#" + } }, - "-ms-scroll-chaining": { - syntax: "chained | none" + "@function": { + syntax: "@function #? ) [ returns ]? { }", + descriptors: { + result: "?" + } }, - "-ms-scroll-limit": { - syntax: "<'-ms-scroll-limit-x-min'> <'-ms-scroll-limit-y-min'> <'-ms-scroll-limit-x-max'> <'-ms-scroll-limit-y-max'>" + "@historical-forms": { + syntax: " @historical-forms { }" }, - "-ms-scroll-limit-x-max": { - syntax: "auto | " + "@import": { + syntax: "@import [ | ] [[ layer | layer( ) ] || [ scope | scope( | ) ] || ]? ;" }, - "-ms-scroll-limit-x-min": { - syntax: "" + "@keyframes": { + syntax: "@keyframes { }" }, - "-ms-scroll-limit-y-max": { - syntax: "auto | " + "@layer": { + syntax: "@layer [ # | ? {\n \n} ]" }, - "-ms-scroll-limit-y-min": { - syntax: "" + "@left-bottom": { + syntax: " @left-bottom { }" }, - "-ms-scroll-rails": { - syntax: "none | railed" + "@left-middle": { + syntax: " @left-middle { }" }, - "-ms-scroll-snap-points-x": { - syntax: "snapInterval( , ) | snapList( # )" + "@left-top": { + syntax: " @left-top { }" }, - "-ms-scroll-snap-points-y": { - syntax: "snapInterval( , ) | snapList( # )" + "@location": { + syntax: "" }, - "-ms-scroll-snap-type": { - syntax: "none | proximity | mandatory" + "@media": { + syntax: "@media { }" }, - "-ms-scroll-snap-x": { - syntax: "<'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-x'>" + "@mixin": { + syntax: "@mixin [ #? ) | ] { }" }, - "-ms-scroll-snap-y": { - syntax: "<'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-y'>" + "@namespace": { + syntax: "@namespace ? [ | ] ;" }, - "-ms-scroll-translation": { - syntax: "none | vertical-to-horizontal" + "@navigation": { + syntax: "@navigation { }" }, - "-ms-scrollbar-3dlight-color": { - syntax: "" + "@ornaments": { + syntax: "@ornaments { }" }, - "-ms-scrollbar-arrow-color": { - syntax: "" + "@page": { + syntax: "@page ? { }", + descriptors: { + bleed: "auto | ", + marks: "none | [ crop || cross ]", + "page-margin-safety": "none | clamp | add", + "page-orientation": "upright | rotate-left | rotate-right", + size: "{1,2} | auto | [ || [ portrait | landscape ] ]" + } }, - "-ms-scrollbar-base-color": { - syntax: "" + "@position-try": { + syntax: " @position-try { } ", + descriptors: { + "align-self": "<'align-self'> | anchor-center", + "block-size": "<'block-size'>", + bottom: "<'bottom'>", + height: "<'height'>", + "inline-size": "<'inline-size'>", + inset: "<'inset'>", + "inset-block": "<'inset-block'>", + "inset-block-end": "<'inset-block-end'>", + "inset-block-start": "<'inset-block-start'>", + "inset-inline": "<'inset-inline'>", + "inset-inline-end": "<'inset-inline-end'>", + "inset-inline-start": "<'inset-inline-start'>", + "justify-self": "<'justify-self'> | anchor-center", + left: "<'left'>", + margin: "<'margin'>", + "margin-block": "<'margin-block'>", + "margin-block-end": "<'margin-block-end'>", + "margin-block-start": "<'margin-block-start'>", + "margin-bottom": "<'margin-bottom'>", + "margin-inline": "<'margin-inline'>", + "margin-inline-end": "<'margin-inline-end'>", + "margin-inline-start": "<'margin-inline-start'>", + "margin-left": "<'margin-left'>", + "margin-right": "<'margin-right'>", + "margin-top": "<'margin-top'>", + "max-block-size": "<'max-block-size'>", + "max-height": "<'max-height'>", + "max-inline-size": "<'max-inline-size'>", + "max-width": "<'max-width'>", + "min-block-size": "<'min-block-size'>", + "min-height": "<'min-height'>", + "min-inline-size": "<'min-inline-size'>", + "min-width": "<'min-width'>", + right: "<'right'>", + top: "<'top'>", + width: "<'width'>" + } }, - "-ms-scrollbar-darkshadow-color": { - syntax: "" + "@private": { + syntax: "@private { }" }, - "-ms-scrollbar-face-color": { - syntax: "" + "@property": { + syntax: "@property # { }", + descriptors: { + syntax: "", + inherits: "true | false", + "initial-value": "?" + } }, - "-ms-scrollbar-highlight-color": { - syntax: "" + "@right-bottom": { + syntax: " @right-bottom { }" }, - "-ms-scrollbar-shadow-color": { - syntax: "" + "@right-middle": { + syntax: " @right-middle { }" }, - "-ms-scrollbar-track-color": { - syntax: "" + "@right-top": { + syntax: " @right-top { }" }, - "-ms-text-autospace": { - syntax: "none | ideograph-alpha | ideograph-numeric | ideograph-parenthesis | ideograph-space" + "@scope": { + syntax: "@scope ? { }" }, - "-ms-touch-select": { - syntax: "grippers | none" + "@starting-style": { + syntax: "@starting-style {\n | \n}" }, - "-ms-user-select": { - syntax: "none | element | text" + "@styleset": { + syntax: "@styleset { }" }, - "-ms-wrap-flow": { - syntax: "auto | both | start | end | maximum | clear" + "@stylistic": { + syntax: "@stylistic { }" }, - "-ms-wrap-margin": { - syntax: "" + "@supports": { + syntax: "@supports { }" }, - "-ms-wrap-through": { - syntax: "wrap | none" + "@supports-condition": { + syntax: "@supports-condition { }" }, + "@swash": { + syntax: "@swash { }" + }, + "@top-center": { + syntax: " @top-center { }" + }, + "@top-left": { + syntax: " @top-left { }" + }, + "@top-left-corner": { + syntax: " @top-left-corner { }" + }, + "@top-right": { + syntax: " @top-right { }" + }, + "@top-right-corner": { + syntax: " @top-right-corner { }" + }, + "@value": { + syntax: "@value [ | [ # from ] ]" + }, + "@view-transition": { + syntax: "@view-transition { }", + descriptors: { + navigation: "auto | none", + types: "none | +" + } + }, + "@when": { + syntax: " @when {\n \n}" + } +}; +var declarations = { "-moz-appearance": { syntax: "none | button | button-arrow-down | button-arrow-next | button-arrow-previous | button-arrow-up | button-bevel | button-focus | caret | checkbox | checkbox-container | checkbox-label | checkmenuitem | dualbutton | groupbox | listbox | listitem | menuarrow | menubar | menucheckbox | menuimage | menuitem | menuitemtext | menulist | menulist-button | menulist-text | menulist-textfield | menupopup | menuradio | menuseparator | meterbar | meterchunk | progressbar | progressbar-vertical | progresschunk | progresschunk-vertical | radio | radio-container | radio-label | radiomenuitem | range | range-thumb | resizer | resizerpanel | scale-horizontal | scalethumbend | scalethumb-horizontal | scalethumbstart | scalethumbtick | scalethumb-vertical | scale-vertical | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | separator | sheet | spinner | spinner-downbutton | spinner-textfield | spinner-upbutton | splitter | statusbar | statusbarpanel | tab | tabpanel | tabpanels | tab-scroll-arrow-back | tab-scroll-arrow-forward | textfield | textfield-multiline | toolbar | toolbarbutton | toolbarbutton-dropdown | toolbargripper | toolbox | tooltip | treeheader | treeheadercell | treeheadersortarrow | treeitem | treeline | treetwisty | treetwistyopen | treeview | -moz-mac-unified-toolbar | -moz-win-borderless-glass | -moz-win-browsertabbar-toolbox | -moz-win-communicationstext | -moz-win-communications-toolbox | -moz-win-exclude-glass | -moz-win-glass | -moz-win-mediatext | -moz-win-media-toolbox | -moz-window-button-box | -moz-window-button-box-maximized | -moz-window-button-close | -moz-window-button-maximize | -moz-window-button-minimize | -moz-window-button-restore | -moz-window-frame-bottom | -moz-window-frame-left | -moz-window-frame-right | -moz-window-titlebar | -moz-window-titlebar-maximized" }, + "-moz-background-clip": { + syntax: "padding | border" + }, "-moz-binding": { syntax: " | none" }, @@ -162,6 +315,18 @@ var declarations = { "-moz-border-left-colors": { syntax: "+ | none" }, + "-moz-border-radius-bottomleft": { + syntax: "<'border-bottom-left-radius'>" + }, + "-moz-border-radius-bottomright": { + syntax: "<'border-bottom-right-radius'>" + }, + "-moz-border-radius-topleft": { + syntax: "<'border-top-left-radius'>" + }, + "-moz-border-radius-topright": { + syntax: "<'border-bottom-right-radius'>" + }, "-moz-border-right-colors": { syntax: "+ | none" }, @@ -171,6 +336,9 @@ var declarations = { "-moz-context-properties": { syntax: "none | [ fill | fill-opacity | stroke | stroke-opacity ]#" }, + "-moz-control-character-visibility": { + syntax: "visible | hidden" + }, "-moz-float-edge": { syntax: "border-box | content-box | margin-box | padding-box" }, @@ -180,6 +348,9 @@ var declarations = { "-moz-orient": { syntax: "inline | block | horizontal | vertical" }, + "-moz-osx-font-smoothing": { + syntax: "auto | grayscale" + }, "-moz-outline-radius": { syntax: "{1,4} [ / {1,4} ]?" }, @@ -195,6 +366,9 @@ var declarations = { "-moz-outline-radius-topright": { syntax: "" }, + "-moz-padding-start": { + syntax: "<'padding-top'>" + }, "-moz-stack-sizing": { syntax: "ignore | stretch-to-fit" }, @@ -210,14 +384,245 @@ var declarations = { "-moz-user-modify": { syntax: "read-only | read-write | write-only" }, + "-moz-user-select": { + syntax: "none | text | all | -moz-none | auto" + }, "-moz-window-dragging": { syntax: "drag | no-drag" }, "-moz-window-shadow": { syntax: "default | menu | tooltip | sheet | none" }, + "-ms-accelerator": { + syntax: "false | true" + }, + "-ms-block-progression": { + syntax: "tb | rl | bt | lr" + }, + "-ms-content-zoom-chaining": { + syntax: "none | chained" + }, + "-ms-content-zoom-limit": { + syntax: "<'-ms-content-zoom-limit-min'> <'-ms-content-zoom-limit-max'>" + }, + "-ms-content-zoom-limit-max": { + syntax: "" + }, + "-ms-content-zoom-limit-min": { + syntax: "" + }, + "-ms-content-zoom-snap": { + syntax: "<'-ms-content-zoom-snap-type'> || <'-ms-content-zoom-snap-points'>" + }, + "-ms-content-zoom-snap-points": { + syntax: "snapInterval( , ) | snapList( # )" + }, + "-ms-content-zoom-snap-type": { + syntax: "none | proximity | mandatory" + }, + "-ms-content-zooming": { + syntax: "none | zoom" + }, + "-ms-filter": { + syntax: " " + }, + "-ms-flex-align": { + syntax: "start | end | center | baseline | stretch" + }, + "-ms-flex-item-align": { + syntax: "auto | start | end | center | baseline | stretch" + }, + "-ms-flex-line-pack": { + syntax: "start | end | center | justify | distribute | stretch" + }, + "-ms-flex-negative": { + syntax: "<'flex-shrink'>" + }, + "-ms-flex-order": { + syntax: "" + }, + "-ms-flex-pack": { + syntax: "start | end | center | justify | distribute" + }, + "-ms-flex-positive": { + syntax: "<'flex-grow'>" + }, + "-ms-flex-preferred-size": { + syntax: "<'flex-basis'>" + }, + "-ms-flow-from": { + syntax: "[ none | ]#" + }, + "-ms-flow-into": { + syntax: "[ none | ]#" + }, + "-ms-grid-column-align": { + syntax: "start | end | center | stretch" + }, + "-ms-grid-columns": { + syntax: "none | | " + }, + "-ms-grid-row-align": { + syntax: "start | end | center | stretch" + }, + "-ms-grid-rows": { + syntax: "none | | " + }, + "-ms-high-contrast-adjust": { + syntax: "auto | none" + }, + "-ms-hyphenate-limit-chars": { + syntax: "auto | {1,3}" + }, + "-ms-hyphenate-limit-last": { + syntax: "none | always | column | page | spread" + }, + "-ms-hyphenate-limit-lines": { + syntax: "no-limit | " + }, + "-ms-hyphenate-limit-zone": { + syntax: " | " + }, + "-ms-ime-align": { + syntax: "auto | after" + }, + "-ms-interpolation-mode": { + syntax: "nearest-neighbor | bicubic" + }, + "-ms-overflow-style": { + syntax: " auto | none | scrollbar | -ms-autohiding-scrollbar" + }, + "-ms-scroll-chaining": { + syntax: "chained | none" + }, + "-ms-scroll-limit": { + syntax: "<'-ms-scroll-limit-x-min'> <'-ms-scroll-limit-y-min'> <'-ms-scroll-limit-x-max'> <'-ms-scroll-limit-y-max'>" + }, + "-ms-scroll-limit-x-max": { + syntax: "auto | " + }, + "-ms-scroll-limit-x-min": { + syntax: "" + }, + "-ms-scroll-limit-y-max": { + syntax: "auto | " + }, + "-ms-scroll-limit-y-min": { + syntax: "" + }, + "-ms-scroll-rails": { + syntax: "none | railed" + }, + "-ms-scroll-snap-points-x": { + syntax: "snapInterval( , ) | snapList( # )" + }, + "-ms-scroll-snap-points-y": { + syntax: "snapInterval( , ) | snapList( # )" + }, + "-ms-scroll-snap-type": { + syntax: "none | proximity | mandatory" + }, + "-ms-scroll-snap-x": { + syntax: "<'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-x'>" + }, + "-ms-scroll-snap-y": { + syntax: "<'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-y'>" + }, + "-ms-scroll-translation": { + syntax: "none | vertical-to-horizontal" + }, + "-ms-scrollbar-3dlight-color": { + syntax: "" + }, + "-ms-scrollbar-arrow-color": { + syntax: "" + }, + "-ms-scrollbar-base-color": { + syntax: "" + }, + "-ms-scrollbar-darkshadow-color": { + syntax: "" + }, + "-ms-scrollbar-face-color": { + syntax: "" + }, + "-ms-scrollbar-highlight-color": { + syntax: "" + }, + "-ms-scrollbar-shadow-color": { + syntax: "" + }, + "-ms-scrollbar-track-color": { + syntax: "" + }, + "-ms-text-autospace": { + syntax: "none | ideograph-alpha | ideograph-numeric | ideograph-parenthesis | ideograph-space" + }, + "-ms-touch-select": { + syntax: "grippers | none" + }, + "-ms-user-select": { + syntax: "none | element | text" + }, + "-ms-wrap-flow": { + syntax: "auto | both | start | end | maximum | clear" + }, + "-ms-wrap-margin": { + syntax: "" + }, + "-ms-wrap-through": { + syntax: "wrap | none" + }, + "-webkit-align-content": { + alias: "align-content" + }, + "-webkit-align-items": { + alias: "align-items" + }, + "-webkit-align-self": { + alias: "align-self" + }, + "-webkit-animation": { + alias: "animation" + }, + "-webkit-animation-delay": { + alias: "animation-delay" + }, + "-webkit-animation-direction": { + alias: "animation-direction" + }, + "-webkit-animation-duration": { + alias: "animation-duration" + }, + "-webkit-animation-fill-mode": { + alias: "animation-fill-mode" + }, + "-webkit-animation-iteration-count": { + alias: "animation-iteration-count" + }, + "-webkit-animation-name": { + alias: "animation-name" + }, + "-webkit-animation-play-state": { + alias: "animation-play-state" + }, + "-webkit-animation-timing-function": { + alias: "animation-timing-function" + }, "-webkit-appearance": { - syntax: " none | button | button-bevel | caps-lock-indicator | caret | checkbox | default-button | inner-spin-button | listbox | listitem | media-controls-background | media-controls-fullscreen-background | media-current-time-display | media-enter-fullscreen-button | media-exit-fullscreen-button | media-fullscreen-button | media-mute-button | media-overlay-play-button | media-play-button | media-seek-back-button | media-seek-forward-button | media-slider | media-sliderthumb | media-time-remaining-display | media-toggle-closed-captions-button | media-volume-slider | media-volume-slider-container | media-volume-sliderthumb | menulist | menulist-button | menulist-text | menulist-textfield | meter | progress-bar | progress-bar-value | push-button | radio | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbargripper-horizontal | scrollbargripper-vertical | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | searchfield-cancel-button | searchfield-decoration | searchfield-results-button | searchfield-results-decoration | slider-horizontal | slider-vertical | sliderthumb-horizontal | sliderthumb-vertical | square-button | textarea | textfield | -apple-pay-button" + syntax: "<'appearance'> | none | button | button-bevel | caps-lock-indicator | caret | checkbox | default-button | inner-spin-button | listbox | listitem | media-controls-background | media-controls-fullscreen-background | media-current-time-display | media-enter-fullscreen-button | media-exit-fullscreen-button | media-fullscreen-button | media-mute-button | media-overlay-play-button | media-play-button | media-seek-back-button | media-seek-forward-button | media-slider | media-sliderthumb | media-time-remaining-display | media-toggle-closed-captions-button | media-volume-slider | media-volume-slider-container | media-volume-sliderthumb | menulist | menulist-button | menulist-text | menulist-textfield | meter | progress-bar | progress-bar-value | push-button | radio | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbargripper-horizontal | scrollbargripper-vertical | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | searchfield-cancel-button | searchfield-decoration | searchfield-results-button | searchfield-results-decoration | slider-horizontal | slider-vertical | sliderthumb-horizontal | sliderthumb-vertical | square-button | textarea | textfield | -apple-pay-button" + }, + "-webkit-backface-visibility": { + alias: "backface-visibility" + }, + "-webkit-background-clip": { + syntax: "<'background-clip'> | [ | border | padding | content | text ]#" + }, + "-webkit-background-origin": { + alias: "background-origin" + }, + "-webkit-background-size": { + alias: "background-size" }, "-webkit-border-after": { syntax: "<'border-top'>" @@ -243,6 +648,12 @@ var declarations = { "-webkit-border-before-width": { syntax: "<'border-top-width'>" }, + "-webkit-border-bottom-left-radius": { + alias: "border-bottom-left-radius" + }, + "-webkit-border-bottom-right-radius": { + alias: "border-bottom-right-radius" + }, "-webkit-border-end": { syntax: "<'border-top'>" }, @@ -255,6 +666,9 @@ var declarations = { "-webkit-border-end-width": { syntax: "<'border-top-width'>" }, + "-webkit-border-radius": { + alias: "border-radius" + }, "-webkit-border-start": { syntax: "<'border-top'>" }, @@ -267,77 +681,194 @@ var declarations = { "-webkit-border-start-width": { syntax: "<'border-top-width'>" }, + "-webkit-border-top-left-radius": { + alias: "border-top-left-radius" + }, + "-webkit-border-top-right-radius": { + alias: "border-top-right-radius" + }, "-webkit-box-reflect": { syntax: "[ above | below | right | left ]? ? ?" }, - "-webkit-line-clamp": { - syntax: "none | " + "-webkit-box-shadow": { + alias: "box-shadow" }, - "-webkit-mask": { - syntax: "[ || [ / ]? || || [ | border | padding | content | text ] || [ | border | padding | content ] ]#" + "-webkit-box-sizing": { + alias: "box-sizing" }, - "-webkit-mask-attachment": { - syntax: "#" + "-webkit-column-break-after": { + syntax: "always | auto | avoid" }, - "-webkit-mask-clip": { - syntax: "[ | no-clip | border | padding | content | text ]#" + "-webkit-column-break-before": { + syntax: "always | auto | avoid" }, - "-webkit-mask-composite": { - syntax: "#" + "-webkit-column-break-inside": { + syntax: "always | auto | avoid" }, - "-webkit-mask-image": { - syntax: "#" + "-webkit-filter": { + alias: "filter" }, - "-webkit-mask-origin": { - syntax: "[ | border | padding | content ]#" + "-webkit-flex": { + alias: "flex" }, - "-webkit-mask-position": { - syntax: "#" + "-webkit-flex-basis": { + alias: "flex-basis" }, - "-webkit-mask-position-x": { - syntax: "[ | left | center | right ]#" + "-webkit-flex-direction": { + alias: "flex-direction" }, - "-webkit-mask-position-y": { - syntax: "[ | top | center | bottom ]#" + "-webkit-flex-flow": { + alias: "flex-flow" }, - "-webkit-mask-repeat": { - syntax: "#" + "-webkit-flex-grow": { + alias: "flex-grow" }, - "-webkit-mask-repeat-x": { - syntax: "repeat | no-repeat | space | round" + "-webkit-flex-shrink": { + alias: "flex-shrink" }, - "-webkit-mask-repeat-y": { - syntax: "repeat | no-repeat | space | round" + "-webkit-flex-wrap": { + alias: "flex-wrap" }, - "-webkit-mask-size": { - syntax: "#" + "-webkit-font-smoothing": { + syntax: "auto | none | antialiased | subpixel-antialiased" + }, + "-webkit-justify-content": { + alias: "justify-content" + }, + "-webkit-line-clamp": { + syntax: "none | " + }, + "-webkit-margin-end": { + syntax: "<'margin-block-end'>" + }, + "-webkit-mask": { + syntax: "<'mask'> | [ || [ / ]? || || [ | border | padding | content | text ] || [ | no-clip | border | padding | content | text ] || [ | ] || ]#" + }, + "-webkit-mask-attachment": { + syntax: "#" + }, + "-webkit-mask-box-image": { + syntax: "<'mask-border'> | [ | | none ] [ {4} <-webkit-mask-box-repeat>{2} ]?" + }, + "-webkit-mask-box-image-outset": { + alias: "mask-border-outset" + }, + "-webkit-mask-box-image-repeat": { + alias: "mask-border-repeat" + }, + "-webkit-mask-box-image-slice": { + alias: "mask-border-slice" + }, + "-webkit-mask-box-image-source": { + alias: "mask-border-source" + }, + "-webkit-mask-box-image-width": { + alias: "mask-border-width" + }, + "-webkit-mask-clip": { + syntax: "<'mask-clip'> | [ | no-clip | border | padding | content | text ]#" + }, + "-webkit-mask-composite": { + syntax: "<'mask-composite'> | [ | ]#" + }, + "-webkit-mask-image": { + alias: "mask-image" + }, + "-webkit-mask-origin": { + syntax: "<'mask-origin'> | [ | border | padding | content ]#" + }, + "-webkit-mask-position": { + alias: "mask-position" + }, + "-webkit-mask-position-x": { + syntax: "[ | left | center | right ]#" + }, + "-webkit-mask-position-y": { + syntax: "[ | top | center | bottom ]#" + }, + "-webkit-mask-repeat": { + alias: "mask-repeat" + }, + "-webkit-mask-repeat-x": { + syntax: "repeat | no-repeat | space | round" + }, + "-webkit-mask-repeat-y": { + syntax: "repeat | no-repeat | space | round" + }, + "-webkit-mask-size": { + alias: "mask-size" + }, + "-webkit-order": { + alias: "order" }, "-webkit-overflow-scrolling": { syntax: "auto | touch" }, + "-webkit-perspective": { + alias: "perspective" + }, + "-webkit-perspective-origin": { + alias: "perspective-origin" + }, + "-webkit-print-color-adjust": { + syntax: "economy | exact" + }, "-webkit-tap-highlight-color": { syntax: "" }, "-webkit-text-fill-color": { syntax: "" }, + "-webkit-text-security": { + syntax: "none | circle | disc | square" + }, + "-webkit-text-size-adjust": { + alias: "text-size-adjust" + }, "-webkit-text-stroke": { - syntax: " || " + syntax: " || " }, "-webkit-text-stroke-color": { syntax: "" }, "-webkit-text-stroke-width": { - syntax: "" + syntax: "" }, "-webkit-touch-callout": { syntax: "default | none" }, + "-webkit-transform": { + alias: "transform" + }, + "-webkit-transform-origin": { + alias: "transform-origin" + }, + "-webkit-transform-style": { + alias: "transform-style" + }, + "-webkit-transition": { + alias: "transition" + }, + "-webkit-transition-delay": { + alias: "transition-delay" + }, + "-webkit-transition-duration": { + alias: "transition-duration" + }, + "-webkit-transition-property": { + alias: "transition-property" + }, + "-webkit-transition-timing-function": { + alias: "transition-timing-function" + }, + "-webkit-user-drag": { + syntax: "none | element | auto" + }, "-webkit-user-modify": { syntax: "read-only | read-write | read-write-plaintext-only" }, "-webkit-user-select": { - syntax: " auto | none | text | all" + syntax: "auto | text | none | contain | all" }, "accent-color": { syntax: "auto | " @@ -346,25 +877,25 @@ var declarations = { syntax: "normal | | | ? " }, "align-items": { - syntax: "normal | stretch | | [ ? ] | anchor-center" + syntax: "normal | stretch | | ? " }, "align-self": { - syntax: "auto | normal | stretch | | ? | anchor-center" + syntax: "auto | ? [ normal | ]| stretch | | anchor-center" }, "align-tracks": { syntax: "[ normal | | | ? ]#" }, "alignment-baseline": { - syntax: " auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical" + syntax: "baseline | " }, all: { - syntax: "initial | inherit | unset | revert | revert-layer" + syntax: "initial | inherit | unset | revert | revert-layer | revert-rule" }, "anchor-name": { - syntax: "none | #" + syntax: "none | #" }, "anchor-scope": { - syntax: "none | all | #" + syntax: "none | all | #" }, animation: { syntax: "#" @@ -373,6 +904,12 @@ var declarations = { syntax: "#" }, "animation-delay": { + syntax: "[ <'animation-delay-start'> <'animation-delay-end'>? ]#" + }, + "animation-delay-end": { + syntax: "?`, `*`, `[ ? ? ]`, `[ [ and ]* | [ or ]* ]` + * @param syntax + */ +function isNullable(syntax) { + if (syntax.typ === ValidationTokenEnum.Whitespace) { + return true; + } + // `[ ? ? ]!`: at least one token + if (syntax.isMandatatoryGroup) { + return false; + } + if (syntax.isOptional || syntax.isRepeatable || syntax.match?.min?.val === 0) { + return true; + } + let nullable = nullableSyntaxes.get(syntax); + if (nullable == null) { + switch (syntax.typ) { + case ValidationTokenEnum.Bracket: + nullable = syntax.chi.every(isNullable); + break; + case ValidationTokenEnum.PipeToken: + nullable = syntax.chi.some((syntaxes) => syntaxes.every(isNullable)); + break; + case ValidationTokenEnum.AmpersandToken: + nullable = + syntax.l.every(isNullable) && + syntax.r.every(isNullable); + break; + default: + nullable = false; + } + nullableSyntaxes.set(syntax, nullable); + } + return nullable; +} +/** + * index of the first syntax that must be matched, starting at index. -1 if the remaining syntaxes may match no token + * @param syntaxes + * @param index + */ +function findMandatorySyntax(syntaxes, index) { + for (let i = index; i < syntaxes.length; i++) { + if (!isNullable(syntaxes[i])) { + return i; + } + } + return -1; +} +/** + * true if a numeric token is in the range of the syntax: `` + * @param arena + * @param token + * @param syntax + */ +function isInRange(arena, token, syntax) { + if (syntax.range == null || + arena.dataTypes[token] === EnumToken.MathFunctionTokenType || + arena.dataTypes[token] === EnumToken.MathFunctionTokenDefType || + arena.dataTypes[token] === EnumToken.WildCardFunctionTokenType || + arena.dataTypes[token] === EnumToken.WildCardFunctionTokenDefType) { + return true; + } + const range = syntax.range; + // a null lower bound is -∞ + let success = !arena.hasFraction(token) && (range.min == null || arena.numericValue[token] >= range.min.val); + if (range.min?.typ === ValidationTokenEnum.Dimension) { + success = + arena.dataTypes[token] === + EnumToken[ + // @ts-expect-error + range.min.unit]; + } + if (success && range.max != null) { + success = arena.numericValue[token] <= range.max.val; + } + return success; +} +/** + * the wildcard functions being matched with a syntax, see {@link matchWildCardFunction} + */ +const wildCardProbes = new Map(); +/** + * var(), env() and if() may be substituted by any number of values. the function is matched: + * - as a part of the syntax at index: `var(--color) 65%` is matched by `` (`` is the function) + * - as the syntax at index, or as all the remaining syntaxes when it is the last token + * + * the next syntaxes must match the tokens that follow. otherwise, the syntax at index is skipped if it is optional and + * the function is matched with the next syntax + * @param arena + * @param syntaxes + * @param index index of the syntax matched by the function + * @param context + * @param token the function token + * @param end last token of the function + * @param options + * @param out + * @returns the result, null if the syntax at index is skipped + */ +function matchWildCardFunction(arena, syntaxes, index, context, token, end, options, out) { + let errors = noErrors; + const candidates = []; + // the function is a part of the syntax. a keyword, a comma, ... is matched by the function + if (syntaxes[index].typ !== ValidationTokenEnum.Keyword && + syntaxes[index].typ !== ValidationTokenEnum.Comma && + syntaxes[index].typ !== ValidationTokenEnum.Separator && + syntaxes[index].typ !== ValidationTokenEnum.StringToken && + syntaxes[index].typ !== ValidationTokenEnum.OpenParenthesis && + syntaxes[index].typ !== ValidationTokenEnum.CloseParenthesis) { + const previous = wildCardProbes.get(token); + let probe; + wildCardProbes.set(token, syntaxes[index]); + try { + probe = matchSyntax(arena, [syntaxes[index]], context.slice(), options); + } + finally { + if (previous == null) { + wildCardProbes.delete(token); + } + else { + wildCardProbes.set(token, previous); + } + } + if (probe.success) { + if (probe.context.done()) { + // the syntax matched all the tokens: the remaining syntaxes must be optional + if (findMandatorySyntax(syntaxes, index + 1) === -1) { + context.end(); + return setMatch(out, true, probe.valid, null, context, null, probe.errors); + } + } + else if (probe.context.current() != null) { + // the syntax matched some tokens + candidates.push(probe.context); + } + } + } + // the function is the syntax + const next = context.slice(); + next.update(end); + if (next.done()) { + // all the remaining syntaxes + context.end(); + return setMatch(out, true, true, null, context, null, noErrors); + } + candidates.push(next); + for (const candidate of candidates) { + const rest = matchSyntax(arena, syntaxes.slice(index + 1), candidate.slice(), options); + if (rest.success) { + if (rest.context.done()) { + context.end(); + } + else { + context.update(rest.context.current() ?? candidate.current()); + } + return setMatch(out, true, rest.valid, rest.token, context, null, rest.errors); + } + errors = rest.errors; + } + if (isNullable(syntaxes[index])) { + return null; + } + return setMatch(out, false, true, token, context, syntaxes[index], errors); +} +/** + * the tokens are consumed: the match succeeds if the remaining syntaxes, starting at index, are optional. + * `[ , ]` does not match `.2` + * @param out + * @param syntaxes + * @param index index of the next syntax + * @param valid + * @param token + * @param context + * @param errors + */ +function setDoneMatch(out, syntaxes, index, valid, token, context, errors) { + const mandatory = findMandatorySyntax(syntaxes, index); + if (mandatory !== -1) { + return setMatch(out, false, valid, token, context, syntaxes[mandatory], noErrors); + } + return setMatch(out, true, valid, token, context, syntaxes[index] ?? null, errors); +} +/** + * matches a list of syntaxes + * @param arena + * @param syntaxes + * @param context + * @param options + * @param out + * @returns + */ function matchSyntax(arena, syntaxes, context, options, out = createMatch()) { if (syntaxes == null) { return setMatch(out, true, false, context.peek(), context, null, noErrors); @@ -1193,14 +1492,14 @@ function matchSyntax(arena, syntaxes, context, options, out = createMatch()) { let token = null; let result = null; let isOptional; - if (context.tokens.length == 1 && - arena.dataTypes[context.tokens[0]] == EnumToken.IdenTokenType && + if (context.tokens.length === 1 && + arena.dataTypes[context.tokens[0]] === EnumToken.IdenTokenType && isCssWideKeyword(arena.strings[arena.stringValue[context.tokens[0]]])) { context.end(); return setMatch(out, true, true, context.peek(), context, null, noErrors); } while (++i < syntaxes.length) { - if (syntaxes[i].typ == ValidationTokenEnum.Whitespace) { + if (syntaxes[i].typ === ValidationTokenEnum.Whitespace) { continue; } isOptional = @@ -1210,36 +1509,44 @@ function matchSyntax(arena, syntaxes, context, options, out = createMatch()) { !syntaxes[i].isMandatatoryGroup; token = context.peek(); if (token == null) { - if (!isOptional) { - return setMatch(out, false, true, null, context, syntaxes[i], [ + // the remaining syntaxes must be optional: `? ` + const mandatory = findMandatorySyntax(syntaxes, isOptional ? i + 1 : i); + if (mandatory !== -1) { + return setMatch(out, false, true, null, context, syntaxes[mandatory], [ { action: "drop", message: "could not match syntax", node: null, - syntax: syntaxes[i], + syntax: syntaxes[mandatory], }, ]); } break; } - if (arena.dataTypes[token] === EnumToken.WildCardFunctionTokenType && arena.strings[arena.stringValue[token]] === "var") { + if (arena.dataTypes[token] === EnumToken.WildCardFunctionTokenType && + arena.strings[arena.stringValue[token]] === "var" && + wildCardProbes.get(token) !== syntaxes[i]) { result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, arena.strings[arena.stringValue[token]] + "()")?.[0]?.chi, createValidationContext(arena, arena.tokens(token)), options, out); if (result.success && result.context.done()) { - context.next(); - continue; + const wildCardResult = matchWildCardFunction(arena, syntaxes, i, context, token, token, options, out); + if (wildCardResult == null) { + continue; + } + return wildCardResult; } } if ( // @ts-ignore - arena.dataTypes[token] === EnumToken.WildCardFunctionTokenDefType) { + arena.dataTypes[token] === EnumToken.WildCardFunctionTokenDefType && + wildCardProbes.get(token) !== syntaxes[i]) { const range = trimArray(arena, context.peekRange()); result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, arena.strings[arena.stringValue[token]] + "()")?.[0]?.chi, createValidationContext(arena, range.slice(1, -1)), options, out); if (result.success) { - context.update(range.at(-1)); - if (context.done()) { - return setMatch(out, result.success, result.valid, result.token, context, syntaxes[i + 1], result.errors); + const wildCardResult = matchWildCardFunction(arena, syntaxes, i, context, token, range.at(-1), options, out); + if (wildCardResult == null) { + continue; } - continue; + return wildCardResult; } } if (syntaxes[i].isRepeatableAtLeastOnce || syntaxes[i].isRepeatable) { @@ -1247,7 +1554,7 @@ function matchSyntax(arena, syntaxes, context, options, out = createMatch()) { if (result.success) { if (result.context.done()) { context.end(); - return setMatch(out, result.success, result.valid, result.token, result.context, syntaxes[i + 1], result.errors); + return setDoneMatch(out, syntaxes, i + 1, result.valid, result.token, result.context, result.errors); } context.update(result.context.current()); continue; @@ -1263,7 +1570,7 @@ function matchSyntax(arena, syntaxes, context, options, out = createMatch()) { options.visited.get(token)?.delete?.(syntaxes[i]); if (result.context.done()) { context.end(); - return setMatch(out, true, true, null, context, syntaxes[i + 1], result.errors); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, result.errors); } context.update(result.context.current()); continue; @@ -1279,7 +1586,7 @@ function matchSyntax(arena, syntaxes, context, options, out = createMatch()) { options.visited.get(token).delete(syntaxes[i]); if (result.context.done()) { context.end(); - return setMatch(out, result.success, result.valid, result.token, context, syntaxes[++i], result.errors); + return setDoneMatch(out, syntaxes, i + 1, result.valid, result.token, context, result.errors); } context.update(result.context.current()); continue; @@ -1298,240 +1605,250 @@ function matchSyntax(arena, syntaxes, context, options, out = createMatch()) { } options.visited.get(token).add(syntaxes[i]); success = false; - switch (syntaxes[i].typ) { - case ValidationTokenEnum.Comma: - if (arena.dataTypes[token] == EnumToken.CommaTokenType) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.Keyword: - if (arena.dataTypes[token] == EnumToken.IdenTokenType && - lowercase(arena.strings[arena.stringValue[token]]) === - lowercase(syntaxes[i].val)) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - if (isOptional) { - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.DeclarationType: - result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Declarations, syntaxes[i].val), context, options, out); - if (result.success) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - if (result.context.done()) { - context.end(); - return setMatch(out, result.success, result.valid, token, context, syntaxes[1 + i], result.errors); + try { + switch (syntaxes[i].typ) { + case ValidationTokenEnum.Colon: + // ` : ?` + if (arena.dataTypes[token] === EnumToken.ColonTokenType) { + success = true; + context.next(); + break; } - else { - if (result.context.current() != null) { - context.update(result.context.current()); - } + if (isOptional) { + break; } - } - if (success || isOptional) { - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], result.errors); - case ValidationTokenEnum.OptionalGroupToken: { - // - const tokens = context.split(); - let j = 0; - for (; j < tokens.length; j++) { - result = matchSyntax(arena, syntaxes[i].chi, context.slice(), options, out); - if (result.success) { - context.update(tokens[j].at(-1)); + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.Comma: + if (arena.dataTypes[token] === EnumToken.CommaTokenType) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.Keyword: + if (arena.dataTypes[token] === EnumToken.IdenTokenType && + lowercase(arena.strings[arena.stringValue[token]]) === + lowercase(syntaxes[i].val)) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; } - break; - } - if (result?.context?.done?.()) { - return result; - } - break; - } - case ValidationTokenEnum.StringToken: - if (arena.dataTypes[token] === EnumToken.Add) { - success = syntaxes[i].val.slice(1, -1) === "+"; - } - else if (arena.dataTypes[token] === EnumToken.Sub) { - success = syntaxes[i].val.slice(1, -1) === "-"; - } - else if (arena.dataTypes[token] === EnumToken.LiteralTokenType) { - success = arena.strings[arena.stringValue[token]] === syntaxes[i].val.slice(1, -1); - } - else if (arena.dataTypes[token] == EnumToken.Plus) { - success = true; - } - if (success) { - context.next(); - break; - } - if (isOptional) { - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.PropertyType: - result = matchProperty(arena, syntaxes[i], context, options); - if (!result.success) { if (isOptional) { break; } - return setMatch(out, false, true, context.current() ?? token, context, syntaxes[i], noErrors); - } - success = true; - options.visited.get(token).delete(syntaxes[i]); - if (result.context.done()) { - context.end(); - return setMatch(out, success, true, null, context, syntaxes[i + 1], noErrors); - } - else { - context.update(result.context.current()); - } - break; - case ValidationTokenEnum.PipeToken: - { - // each alternative is matched in the same scratch result, the best match is copied - const scratch = createMatch(); - let best = null; - let tmp = null; - for (const syntax of syntaxes[i].chi) { - tmp = matchSyntax(arena, syntax, context.slice(), options, scratch); - if (tmp.success) { - if (best == null || tmp.context.index >= best.context.index) { - best = copyMatch(best ?? createMatch(), tmp); + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.DeclarationType: + result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Declarations, syntaxes[i].val), context, options, out); + if (result.success) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, result.valid, token, context, result.errors); + } + else { + if (result.context.current() != null) { + context.update(result.context.current()); + } + } + } + if (success || isOptional) { + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], result.errors); + case ValidationTokenEnum.OptionalGroupToken: { + const chi = syntaxes[i].chi; + // `#? , ` (the group of the optional list, the comma is the list separator) is + // matched as `[ , ]* `: the last item is left to the next syntax + if (chi.length === 1 && chi[0].isList) { + const { isList, isOptional, match, ...item } = chi[0]; + const group = [ + item, + { typ: ValidationTokenEnum.Comma }, + ]; + while (context.peek() != null) { + const tmp = matchSyntax(arena, group, context.slice(), options); + if (!tmp.success || tmp.context.current() == null) { + break; } + context.update(tmp.context.current()); if (tmp.context.done()) { - context.end(); - return setMatch(out, tmp.success, tmp.valid, tmp.token, context, syntaxes[i + 1], tmp.errors); + break; } } - } - result = best; - if (result?.success) { success = true; - options.visited.get(token).delete(syntaxes[i]); - context.update(result.context.current()); break; } - } - return setMatch(out, false, true, token, context, syntaxes[i], [ - { - action: "drop", - message: "could not match syntax", - node: token, - // @ts-ignore - // location: options.source!.getSourceLocation(token[LOC]?.sta), - syntax: syntaxes[i], - }, - ]); - case ValidationTokenEnum.Bracket: - result = matchSyntax(arena, syntaxes[i].chi, context.slice(), options, out); - if (result.success) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - if (result.context.done()) { - context.end(); - return setMatch(out, success, true, null, context, syntaxes[1 + i], noErrors); - } - else { + // the group is optional: it is skipped if it does not match + result = matchSyntax(arena, chi, context.slice(), options); + if (result.success) { + success = true; + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, result.errors); + } context.update(result.context.current()); } break; } - if (isOptional) { - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.ColumnToken: - result = matchColumnSyntax(arena, syntaxes[i], context.slice(), options); - if (result.success) { + case ValidationTokenEnum.StringToken: + if (arena.dataTypes[token] === EnumToken.Add) { + success = syntaxes[i].val.slice(1, -1) === "+"; + } + else if (arena.dataTypes[token] === EnumToken.Sub) { + success = syntaxes[i].val.slice(1, -1) === "-"; + } + else if (arena.dataTypes[token] === EnumToken.LiteralTokenType) { + success = + arena.strings[arena.stringValue[token]] === + syntaxes[i].val.slice(1, -1); + } + else if (arena.dataTypes[token] === EnumToken.Plus) { + success = true; + } + if (success) { + context.next(); + break; + } + if (isOptional) { + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.PropertyType: + result = matchProperty(arena, syntaxes[i], context, options); + if (!result.success) { + if (isOptional) { + break; + } + return setMatch(out, false, true, context.current() ?? token, context, syntaxes[i], noErrors); + } success = true; options.visited.get(token).delete(syntaxes[i]); if (result.context.done()) { + if (!isInRange(arena, token, syntaxes[i])) { + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + } context.end(); - return setMatch(out, success, true, null, context, syntaxes[1 + i], noErrors); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, noErrors); } else { context.update(result.context.current()); } break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.AmpersandToken: - result = matchAmpersandSyntax(arena, syntaxes[i], context.slice(), options); - if (result.success) { - success = true; - options.visited.get(token).delete(syntaxes[i]); - if (result.context.done()) { - context.end(); - return setMatch(out, success, true, null, context, syntaxes[1 + i], noErrors); - } - else { - context.update(result.context.current()); + case ValidationTokenEnum.PipeToken: + { + // each alternative is matched in the same scratch result, the best match is copied + const scratch = createMatch(); + let best = null; + let tmp = null; + for (const syntax of syntaxes[i].chi) { + tmp = matchSyntax(arena, syntax, context.slice(), options, scratch); + if (tmp.success) { + // an alternative that consumes the tokens is skipped if mandatory syntaxes remain + if (tmp.context.done() && findMandatorySyntax(syntaxes, i + 1) !== -1) { + continue; + } + if (best == null || tmp.context.index >= best.context.index) { + best = copyMatch(best ?? createMatch(), tmp); + } + if (tmp.context.done()) { + context.end(); + return setMatch(out, tmp.success, tmp.valid, tmp.token, context, syntaxes[i + 1], tmp.errors); + } + } + } + result = best; + if (result?.success) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.update(result.context.current()); + break; + } } - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.Function: - if ((!tokensfuncDefMap.has(arena.dataTypes[token]) && - !funcLike.includes(arena.dataTypes[token]) && - !funcTypes.includes(arena.dataTypes[token])) || - !equalsIgnoreCase(syntaxes[i].val, arena.strings[arena.stringValue[token]].toLowerCase())) { return setMatch(out, false, true, token, context, syntaxes[i], [ { action: "drop", - message: `Expecting a function ${EnumToken[arena.dataTypes[token]]}`, + message: "could not match syntax", node: token, + // @ts-ignore + // location: options.source!.getSourceLocation(token[LOC]?.sta), + syntax: syntaxes[i], }, ]); - } - if (tokensfuncDefMap.has(arena.dataTypes[token])) { - const range = context.peekRange(); - result = matchSyntax(arena, syntaxes[i].chi, createValidationContext(arena, range.slice(1, -1)), options, out); - if (result.success && result.context.done()) { - context.update(range.at(-1)); + case ValidationTokenEnum.Bracket: + result = matchSyntax(arena, syntaxes[i].chi, context.slice(), options, out); + if (result.success) { + success = true; options.visited.get(token).delete(syntaxes[i]); + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, noErrors); + } + else { + context.update(result.context.current()); + } break; } - } - else { - result = matchSyntax(arena, syntaxes[i].chi, createValidationContext(arena, arena.tokens(token)), options, out); - if (result.success && result.context.done()) { + if (isOptional) { + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.ColumnToken: + result = matchColumnSyntax(arena, syntaxes[i], context.slice(), options); + if (result.success) { success = true; options.visited.get(token).delete(syntaxes[i]); - context.next(); + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, noErrors); + } + else { + context.update(result.context.current()); + } break; } - } - return setMatch(out, false, true, token, context, syntaxes[i], result.errors); - case ValidationTokenEnum.Separator: - if (arena.dataTypes[token] === EnumToken.LiteralTokenType && arena.strings[arena.stringValue[token]] === "/") { - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.FunctionDefinition: - if (arena.strings[arena.stringValue[token]] && - equalsIgnoreCase(arena.strings[arena.stringValue[token]], syntaxes[i].val)) { + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.AmpersandToken: + result = matchAmpersandSyntax(arena, syntaxes[i], context.slice(), options); + if (result.success) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + if (result.context.done()) { + context.end(); + return setDoneMatch(out, syntaxes, i + 1, true, null, context, noErrors); + } + else { + context.update(result.context.current()); + } + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.Function: + if ((!tokensfuncDefMap.has(arena.dataTypes[token]) && + !funcLike.includes(arena.dataTypes[token]) && + !funcTypes.includes(arena.dataTypes[token])) || + !equalsIgnoreCase(syntaxes[i].val, arena.strings[arena.stringValue[token]].toLowerCase())) { + return setMatch(out, false, true, token, context, syntaxes[i], [ + { + action: "drop", + message: `Expecting a function ${EnumToken[arena.dataTypes[token]]}`, + node: token, + }, + ]); + } if (tokensfuncDefMap.has(arena.dataTypes[token])) { - const children = trimArray(arena, context.peekRange()); - result = matchSyntax(arena, (getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, syntaxes[i].val + "()")?.[0]).chi ?? [], createValidationContext(arena, children.slice(1, -1)), options, out); + const range = context.peekRange(); + result = matchSyntax(arena, syntaxes[i].chi, createValidationContext(arena, range.slice(1, -1)), options, out); if (result.success && result.context.done()) { - success = true; + context.update(range.at(-1)); options.visited.get(token).delete(syntaxes[i]); - context.update(children.at(-1)); break; } } - else if (tokensfuncSet.has(arena.dataTypes[token])) { - result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, syntaxes[i].val + "()") ?? [], createValidationContext(arena, [token]), options, out); + else { + result = matchSyntax(arena, syntaxes[i].chi, createValidationContext(arena, arena.tokens(token)), options, out); if (result.success && result.context.done()) { success = true; options.visited.get(token).delete(syntaxes[i]); @@ -1539,99 +1856,112 @@ function matchSyntax(arena, syntaxes, context, options, out = createMatch()) { break; } } - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.OpenParenthesis: - if (arena.dataTypes[token] === EnumToken.StartParensTokenType) { - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.OpenCurlyBrace: - if (arena.dataTypes[token] === EnumToken.BlockStartTokenType) { - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - case ValidationTokenEnum.CloseParenthesis: - if (arena.dataTypes[token] === EnumToken.EndParensTokenType) { - options.visited.get(token).delete(syntaxes[i]); - context.next(); - break; - } - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); - default: - throw new Error(`Unexpected syntax ${ValidationTokenEnum[syntaxes[i].typ]}`); - } - if (success && - "range" in syntaxes[i] && - !(arena.dataTypes[token] === EnumToken.MathFunctionTokenType || - arena.dataTypes[token] === EnumToken.MathFunctionTokenDefType || - arena.dataTypes[token] === EnumToken.WildCardFunctionTokenDefType)) { - let success = false; - success = - !arena.hasFraction(token) && - arena.numericValue[token] >= - syntaxes[i].range.min.val; - if (syntaxes[i].range.min.typ === ValidationTokenEnum.Dimension) { - success = - arena.dataTypes[token] === - EnumToken[ - // @ts-expect-error - syntaxes[i].range.min - .unit]; - } - if (success && - syntaxes[i].range.max != null) { - success = - arena.numericValue[token] <= - syntaxes[i].range.max.val; - } - if (!success) { - return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + return setMatch(out, false, true, token, context, syntaxes[i], result.errors); + case ValidationTokenEnum.Separator: + if (arena.dataTypes[token] === EnumToken.LiteralTokenType && + arena.strings[arena.stringValue[token]] === "/") { + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.FunctionDefinition: + if (arena.strings[arena.stringValue[token]] && + equalsIgnoreCase(arena.strings[arena.stringValue[token]], syntaxes[i].val)) { + if (tokensfuncDefMap.has(arena.dataTypes[token])) { + const children = trimArray(arena, context.peekRange()); + result = matchSyntax(arena, (getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, syntaxes[i].val + "()")?.[0]).chi ?? [], createValidationContext(arena, children.slice(1, -1)), options, out); + if (result.success && result.context.done()) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.update(children.at(-1)); + break; + } + } + else if (tokensfuncSet.has(arena.dataTypes[token])) { + result = matchSyntax(arena, getParsedSyntax(ValidationSyntaxGroupEnum.Syntaxes, syntaxes[i].val + "()") ?? [], createValidationContext(arena, [token]), options, out); + if (result.success && result.context.done()) { + success = true; + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + } + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.OpenParenthesis: + if (arena.dataTypes[token] === EnumToken.StartParensTokenType) { + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.OpenCurlyBrace: + if (arena.dataTypes[token] === EnumToken.BlockStartTokenType) { + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + case ValidationTokenEnum.CloseParenthesis: + if (arena.dataTypes[token] === EnumToken.EndParensTokenType) { + options.visited.get(token).delete(syntaxes[i]); + context.next(); + break; + } + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + default: + throw new Error(`Unexpected syntax ${ValidationTokenEnum[syntaxes[i].typ]}`); } } + finally { + // the syntax is no longer being matched: a token may be matched again with the same syntax (the + // alternatives of an optional group, ...). only the syntaxes being matched detect a cyclic definition + options.visited.get(token)?.delete(syntaxes[i]); + } + if (success && !isInRange(arena, token, syntaxes[i])) { + return setMatch(out, false, true, token, context, syntaxes[i], noErrors); + } } - return result?.success ? result : setMatch(out, true, true, token, context, syntaxes[i] ?? null, noErrors); + // the context of this list of syntaxes: the last result may not include the tokens matched after it (`,`, ...) + return setMatch(out, true, result?.success ? result.valid : true, token, context, syntaxes[i] ?? null, result?.success ? result.errors : noErrors); } /** - * matches a column of syntaxes + * matches a column of syntaxes: ` || || `, one or more syntaxes in any order. the syntaxes are matched in + * the order that matches the most tokens: `[ none | ] || ? && ?` matches no token + success: best != null || + (all && syntaxes.every((syntaxes) => findMandatorySyntax(syntaxes, 0) === -1)), valid: true, token: context.current(), context, @@ -1640,32 +1970,134 @@ function matchColumnSyntax(arena, syntax, context, options) { }; } /** - * matches an ampersand of syntaxes + * position of a context in the tokens of the unordered syntaxes, see {@link searchUnorderedSyntaxes} + * @param base + * @param context + */ +function unorderedPosition(base, context) { + return context.done() ? Number.POSITIVE_INFINITY : base.tokens.indexOf(context.current()); +} +/** + * the context after the unordered syntaxes that match the most tokens. null if the syntaxes do not match + * @param arena + * @param syntaxes the unordered syntaxes + * @param remaining the indexes of the syntaxes that are not matched + * @param all all the syntaxes must be matched, except the syntaxes that match no token + * @param base the context of the syntaxes + * @param context + * @param options + * @param cache the context after a syntax, by syntax index and position + */ +function searchUnorderedSyntaxes(arena, syntaxes, remaining, all, base, context, options, cache) { + const position = unorderedPosition(base, context); + let best = null; + for (let k = 0; k < remaining.length; k++) { + const key = remaining[k] + ":" + position; + let next = cache.get(key); + if (next === undefined) { + const result = matchSyntax(arena, syntaxes[remaining[k]], context.slice(), options); + next = null; + // the syntax matched some tokens + if (result.success && (result.context.done() || result.context.current() !== context.current())) { + next = context.slice(); + if (result.context.done()) { + next.end(); + } + else { + next.update(result.context.current()); + } + } + cache.set(key, next); + } + if (next == null) { + continue; + } + const rest = remaining.slice(0, k).concat(remaining.slice(k + 1)); + // the match may stop after this syntax + const complete = !all || rest.every((index) => findMandatorySyntax(syntaxes[index], 0) === -1); + const candidates = []; + if (!next.done() && rest.length > 0) { + const deeper = searchUnorderedSyntaxes(arena, syntaxes, rest, all, base, next, options, cache); + if (deeper != null) { + candidates.push(deeper); + } + } + if (complete) { + candidates.push(next); + } + for (const candidate of candidates) { + if (candidate.done()) { + return candidate; + } + if (best == null || unorderedPosition(base, candidate) > unorderedPosition(base, best)) { + best = candidate; + } + } + } + return best; +} +/** + * the operands of chained ampersands: ` && && ` is parsed as `[ && ] && ` + * @param syntax + * @param operands + */ +function ampersandOperands(syntax, operands = []) { + for (const side of [syntax.l, syntax.r]) { + const tokens = side.filter((token) => token.typ !== ValidationTokenEnum.Whitespace); + if (tokens.length === 1 && + tokens[0].typ === ValidationTokenEnum.AmpersandToken && + !tokens[0].isOptional && + !tokens[0].isRepeatable && + !tokens[0].isRepeatableAtLeastOnce && + !tokens[0].isList && + tokens[0].match == null) { + ampersandOperands(tokens[0], operands); + } + else { + operands.push(side); + } + } + return operands; +} +/** + * matches an ampersand of syntaxes: ` && && `, all the syntaxes in any order, except the optional syntaxes + * that match no token. `[ && ]` matches `thin 10px` and `10px thin` + * @param arena * @param syntax * @param context * @param options * @returns */ function matchAmpersandSyntax(arena, syntax, context, options) { - const syntaxes = [syntax.l, syntax.r]; - let result; - let i; - for (i = 0; i < syntaxes.length; i++) { - result = matchSyntax(arena, syntaxes[i], context.slice(), options); - if (result.success) { - if (result.context.done()) { - context.end(); - break; - } - context.update(result.context.current()); - syntaxes.splice(i, 1); - i = -1; + return matchUnorderedSyntaxes(arena, syntax, ampersandOperands(syntax), true, context, options); +} +/** + * the tokens of a media / container feature: the tokens before the closing parenthesis, `width >= 700px` in + * `(width >= 700px)`. the whitespace and the comments are skipped + * @param arena + * @param context + */ +function peekFeatureTokens(arena, context) { + const tokens = []; + let depth = 0; + for (let index = context.index + 1; index < context.tokens.length; index++) { + const token = context.tokens[index]; + if (arena.dataTypes[token] === EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[token])) { + depth++; + } + else if (arena.dataTypes[token] === EnumToken.EndParensTokenType && depth-- === 0) { + break; + } + if (arena.dataTypes[token] !== EnumToken.WhitespaceTokenType && + arena.dataTypes[token] !== EnumToken.CommentTokenType) { + tokens.push(token); } } - return result; + return tokens; } /** * matches a property + * @param arena * @param property * @param context * @param options @@ -1676,7 +2108,7 @@ function matchProperty(arena, property, context, options) { const token = context.peek(); // inlined: arena.typeOf(token) let t = (token == null ? null : arena.dataTypes[token]); - let checkCalc = (t == EnumToken.MathFunctionTokenDefType || t == EnumToken.MathFunctionTokenType) && + let checkCalc = (t === EnumToken.MathFunctionTokenDefType || t === EnumToken.MathFunctionTokenType) && [ "number", "zero", @@ -1734,7 +2166,6 @@ function matchProperty(arena, property, context, options) { }; } switch (property.val) { - case "function-parameter": case "declaration-value": { // consume a declaration value @@ -1744,21 +2175,24 @@ function matchProperty(arena, property, context, options) { // if semicolon or end curly brace is encountered, stop let expectToken = true; let token; + // one or more tokens + let consumed = 0; const stack = []; token = context.peek(); if (token != null) { success = false; while ((token = context.peek()) != null) { - if (arena.dataTypes[token] == EnumToken.StartParensTokenType || tokensfuncDefMap.has(arena.dataTypes[token])) { + if (arena.dataTypes[token] === EnumToken.StartParensTokenType || + tokensfuncDefMap.has(arena.dataTypes[token])) { stack.push(token); } if (expectToken) { expectToken = false; } - if (arena.dataTypes[token] == EnumToken.CommaTokenType) { + if (arena.dataTypes[token] === EnumToken.CommaTokenType) { expectToken = true; } - if (arena.dataTypes[token] == EnumToken.EndParensTokenType) { + if (arena.dataTypes[token] === EnumToken.EndParensTokenType) { if (stack.length > 0) { stack.pop(); } @@ -1768,9 +2202,10 @@ function matchProperty(arena, property, context, options) { } } context.next(); + consumed++; } } - success = !expectToken; + success = consumed > 0 && !expectToken; if (success) { return { success, @@ -1833,26 +2268,20 @@ function matchProperty(arena, property, context, options) { break; } // inlined: arena.typeOf(token) - if (arena.dataTypes[token] === EnumToken.LiteralTokenType || arena.dataTypes[token] === EnumToken.IdenTokenType) { + if (arena.dataTypes[token] === EnumToken.LiteralTokenType || + arena.dataTypes[token] === EnumToken.IdenTokenType) { let match = /^(([+-]?[0-9]*)?n)?([+-]?[0-9]+)?$/.exec(arena.strings[arena.stringValue[token]]); success = match != null; - if (match?.[3] == null) { - token = context.peek(1); - if ( - // inlined: arena.typeOf(token) - arena.dataTypes[token] === EnumToken.Add || - // inlined: arena.typeOf(token) - arena.dataTypes[token] === EnumToken.NextSiblingCombinatorTokenType || - // inlined: arena.typeOf(token) - arena.dataTypes[token] === EnumToken.Sub) { - token = context.peek(2); - success = - // inlined: arena.typeOf(token) - arena.dataTypes[token] === EnumToken.NumberTokenType && - Number.isInteger(arena.numericValue[token]); - } - if (success) { - context.update(token); + // `n + 1`: the sign and the number follow the ident + if (success && match?.[3] == null) { + const sign = context.peek(1); + // `n+1`: the sign is a part of the number + if (arena.dataTypes[sign] === EnumToken.NumberTokenType) { + if (!Number.isInteger(arena.numericValue[sign])) { + success = false; + break; + } + context.update(sign); return { success: true, valid: true, @@ -1862,6 +2291,30 @@ function matchProperty(arena, property, context, options) { errors: [], }; } + if ( + // inlined: arena.typeOf(sign) + arena.dataTypes[sign] === EnumToken.Add || + // inlined: arena.typeOf(sign) + arena.dataTypes[sign] === EnumToken.NextSiblingCombinatorTokenType || + // inlined: arena.typeOf(sign) + arena.dataTypes[sign] === EnumToken.Sub) { + token = context.peek(2); + success = + // inlined: arena.typeOf(token) + arena.dataTypes[token] === EnumToken.NumberTokenType && + Number.isInteger(arena.numericValue[token]); + if (success) { + context.update(token); + return { + success: true, + valid: true, + token: null, + context, + syntaxToken: property, + errors: [], + }; + } + } } break; } @@ -1875,7 +2328,13 @@ function matchProperty(arena, property, context, options) { break; } if (arena.dataTypes[token] === EnumToken.NumberTokenType) { - // the sign of the number is not tracked by the tokenizer + // `2n+1`, `-2n -0`: the sign is a part of the number + if (Number.isInteger(arena.numericValue[token])) { + context.next(); + } + else { + success = false; + } break; } if (arena.dataTypes[token] === EnumToken.NextSiblingCombinatorTokenType) { @@ -1903,11 +2362,13 @@ function matchProperty(arena, property, context, options) { case "content-position": { let values = propertyKeywordValues.get(property.val); if (values == null) { - values = new Set(config.syntaxes[property.val].syntax.split(/[\s|]+/)); + values = new Set((getSyntax(property.val) ?? "").split(/[\s|]+/)); propertyKeywordValues.set(property.val, values); } // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == EnumToken.IdenTokenType && values.has(arena.strings[arena.stringValue[token]].toLowerCase()); + success = + arena.dataTypes[token] === EnumToken.IdenTokenType && + values.has(arena.strings[arena.stringValue[token]].toLowerCase()); break; } case "mf-name": @@ -1923,7 +2384,7 @@ function matchProperty(arena, property, context, options) { case "extension-name": case "custom-property-name": // inlined: arena.typeOf(context.peek()) - success = arena.dataTypes[context.peek()] == EnumToken.DashedIdenTokenType; + success = arena.dataTypes[context.peek()] === EnumToken.DashedIdenTokenType; break; case "namespace-prefix": case "ident": @@ -1932,7 +2393,9 @@ function matchProperty(arena, property, context, options) { case "counter-name": case "counter-style-name": // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == EnumToken.IdenTokenType || arena.dataTypes[token] == EnumToken.DashedIdenTokenType; + success = + arena.dataTypes[token] === EnumToken.IdenTokenType || + arena.dataTypes[token] === EnumToken.DashedIdenTokenType; // inlined: arena.typeOf(token) if (success && arena.dataTypes[token] === EnumToken.IdenTokenType) { const val = arena.strings[arena.stringValue[token]].toLowerCase(); @@ -1958,6 +2421,21 @@ function matchProperty(arena, property, context, options) { ].includes(arena.dataTypes[token]); break; } + case "unicode-range-token": + // `U+0025-00FF` + // inlined: arena.typeOf(context.peek()) + success = arena.dataTypes[context.peek()] === EnumToken.UniCodeRange; + break; + case "hash-token": { + // : `#foo`. a valid hex color such as `#fade` is tokenized as a color + const token = context.peek(); + success = + // inlined: arena.typeOf(token) + arena.dataTypes[token] === EnumToken.HashTokenType || + (arena.dataTypes[token] === EnumToken.ColorTokenType && + arena.colorType[token] === ColorType.HEX); + break; + } case "string": { const token = context.peek(); // inlined: arena.typeOf(token) @@ -1966,7 +2444,7 @@ function matchProperty(arena, property, context, options) { } case "wq-name": { // inlined: arena.typeOf(context.peek()) - const success = arena.dataTypes[context.peek()] == EnumToken.IdenTokenType; + const success = arena.dataTypes[context.peek()] === EnumToken.IdenTokenType; return { success, valid: true, @@ -1980,13 +2458,15 @@ function matchProperty(arena, property, context, options) { { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == EnumToken.NumberTokenType; + success = arena.dataTypes[token] === EnumToken.NumberTokenType; } break; case "zero": { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == EnumToken.NumberTokenType && arena.numericValue[token] === 0; + success = + arena.dataTypes[token] === EnumToken.NumberTokenType && + arena.numericValue[token] === 0; break; } case "integer": @@ -1994,44 +2474,50 @@ function matchProperty(arena, property, context, options) { const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.NumberTokenType && Number.isInteger(Number(arena.numericValue[token])); + arena.dataTypes[token] === EnumToken.NumberTokenType && + Number.isInteger(Number(arena.numericValue[token])); } break; case "dimension": { const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.DimensionTokenType || + arena.dataTypes[token] === EnumToken.DimensionTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.AngleTokenType || + arena.dataTypes[token] === EnumToken.AngleTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.LengthTokenType || + arena.dataTypes[token] === EnumToken.LengthTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.PercentageTokenType || + arena.dataTypes[token] === EnumToken.PercentageTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.ResolutionTokenType || + arena.dataTypes[token] === EnumToken.ResolutionTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.TimeTokenType || + arena.dataTypes[token] === EnumToken.TimeTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.FrequencyTokenType || + arena.dataTypes[token] === EnumToken.FrequencyTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.UserDefinedDimensionTokenType || + arena.dataTypes[token] === EnumToken.UserDefinedDimensionTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.FlexTokenType; + arena.dataTypes[token] === EnumToken.FlexTokenType; break; } case "angle": { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] === EnumToken.AngleTokenType || arena.dataTypes[token] === EnumToken.UserDefinedDimensionTokenType; + success = + arena.dataTypes[token] === EnumToken.AngleTokenType || + arena.dataTypes[token] === EnumToken.UserDefinedDimensionTokenType; } break; case "angle-percentage": { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] === EnumToken.AngleTokenType || arena.dataTypes[token] === EnumToken.UserDefinedDimensionTokenType || arena.dataTypes[token] === EnumToken.PercentageTokenType; + success = + arena.dataTypes[token] === EnumToken.AngleTokenType || + arena.dataTypes[token] === EnumToken.UserDefinedDimensionTokenType || + arena.dataTypes[token] === EnumToken.PercentageTokenType; } break; case "percentage": @@ -2048,28 +2534,49 @@ function matchProperty(arena, property, context, options) { const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.PercentageTokenType || + arena.dataTypes[token] === EnumToken.PercentageTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.LengthTokenType || + arena.dataTypes[token] === EnumToken.LengthTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.UserDefinedDimensionTokenType || + arena.dataTypes[token] === EnumToken.UserDefinedDimensionTokenType || // inlined: arena.typeOf(token) - (arena.dataTypes[token] == EnumToken.NumberTokenType && arena.numericValue[token] === 0); + (arena.dataTypes[token] === EnumToken.NumberTokenType && + arena.numericValue[token] === 0); } break; case "flex": // inlined: arena.typeOf(context.peek()) - success = arena.dataTypes[context.peek()] == EnumToken.FlexTokenType || arena.dataTypes[context.peek()] == EnumToken.UserDefinedDimensionTokenType; + success = + arena.dataTypes[context.peek()] === EnumToken.FlexTokenType || + arena.dataTypes[context.peek()] === EnumToken.UserDefinedDimensionTokenType; break; case "length": { const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.LengthTokenType || + arena.dataTypes[token] === EnumToken.LengthTokenType || // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.UserDefinedDimensionTokenType || + arena.dataTypes[token] === EnumToken.UserDefinedDimensionTokenType || // inlined: arena.typeOf(token) - (arena.dataTypes[token] == EnumToken.NumberTokenType && arena.numericValue[token] === 0); + (arena.dataTypes[token] === EnumToken.NumberTokenType && + arena.numericValue[token] === 0); + break; + } + case "resolution": + // inlined: arena.typeOf(context.peek()) + success = arena.dataTypes[context.peek()] === EnumToken.ResolutionTokenType; + break; + case "frequency": + // inlined: arena.typeOf(context.peek()) + success = arena.dataTypes[context.peek()] === EnumToken.FrequencyTokenType; + break; + case "decibel": + case "semitones": { + // `6dB`, `2st` + const token = context.peek(); + success = + arena.dataTypes[token] === EnumToken.DimensionTokenType && + equalsIgnoreCase(arena.strings[arena.unit[token]], property.val === "decibel" ? "dB" : "st"); break; } case "time": @@ -2078,7 +2585,9 @@ function matchProperty(arena, property, context, options) { if (token == null) { break; } - success = arena.dataTypes[token] == EnumToken.TimeTokenType || arena.dataTypes[token] == EnumToken.UserDefinedDimensionTokenType; + success = + arena.dataTypes[token] === EnumToken.TimeTokenType || + arena.dataTypes[token] === EnumToken.UserDefinedDimensionTokenType; } break; case "color": @@ -2091,7 +2600,7 @@ function matchProperty(arena, property, context, options) { const range = context.peekRange(); const newRange = range.map((t) => arena.clone(t, true)); parseTokens(arena, newRange, { parseColor: true }, errors); - success = newRange.length == 1 && isColor(arena, newRange[0], errors); + success = newRange.length === 1 && isColor(arena, newRange[0], errors); if (success) { context.update(range.at(-1)); return { @@ -2136,11 +2645,11 @@ function matchProperty(arena, property, context, options) { case "complex-selector-list": { const tokens = context.getRemainingTokens(); const result = matchSelectorSyntax(arena, tokens, [], options, property.val.startsWith("forgiving-relative-selector-list")); - if (result.success || property.val == "forgiving-relative-selector-list") { + if (result.success || property.val === "forgiving-relative-selector-list") { context.update(tokens.at(-1)); } return { - success: result.success || property.val == "forgiving-relative-selector-list", + success: result.success || property.val === "forgiving-relative-selector-list", valid: true, token: context.peek(), context, @@ -2151,8 +2660,8 @@ function matchProperty(arena, property, context, options) { case "function-token": // inlined: arena.typeOf(context.peek()). the type of a null id is undefined: not a key of the map either if (tokensfuncDefMap.has(arena.dataTypes[context.peek()])) { + // the token is consumed below success = true; - context.next(); break; } return { @@ -2167,68 +2676,54 @@ function matchProperty(arena, property, context, options) { const token = context.peek(); success = // inlined: arena.typeOf(token) - arena.dataTypes[token] == EnumToken.IdenTokenType && + arena.dataTypes[token] === EnumToken.IdenTokenType && // @ts-expect-error - config.languages.some((t) => t === arena.strings[arena.stringValue[token]] || arena.strings[arena.stringValue[token]].startsWith(t + "-")); + config.languages.some((t) => t === arena.strings[arena.stringValue[token]] || + arena.strings[arena.stringValue[token]].startsWith(t + "-")); break; } case "size-feature": { - const range = context.peekRange(); - const filteredRange = range.filter((token) => arena.dataTypes[token] !== EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== EnumToken.CommentTokenType); - if (filteredRange.length === 1) { - success = - arena.dataTypes[filteredRange[0]] === EnumToken.IdenTokenType || - arena.dataTypes[filteredRange[0]] === EnumToken.DashedIdenTokenType; - context.update(filteredRange[0]); - return { - success, - valid: true, - token: filteredRange[0], - context, - syntaxToken: property, - errors: [], - }; - } - if (!mFLT.has(arena.dataTypes[filteredRange[1]]) && - !mFGT.has(arena.dataTypes[filteredRange[1]]) && - arena.dataTypes[filteredRange[1]] !== EnumToken.ColonTokenType && - arena.dataTypes[filteredRange[1]] !== EnumToken.DelimTokenType) { - return { - success: false, - valid: true, - token: filteredRange[1], - context, - syntaxToken: property, - errors: [], - }; + // | : | . the feature is validated by the at-rule parser + const filteredRange = peekFeatureTokens(arena, context); + success = + filteredRange.length === 1 + ? arena.dataTypes[filteredRange[0]] === EnumToken.IdenTokenType || + arena.dataTypes[filteredRange[0]] === EnumToken.DashedIdenTokenType + : filteredRange.length > 2 && + (mFLT.has(arena.dataTypes[filteredRange[1]]) || + mFGT.has(arena.dataTypes[filteredRange[1]]) || + arena.dataTypes[filteredRange[1]] === EnumToken.ColonTokenType || + arena.dataTypes[filteredRange[1]] === EnumToken.DelimTokenType); + if (success) { + context.update(filteredRange.at(-1)); } - break; + return { + success, + valid: true, + token: success ? null : (filteredRange[1] ?? context.peek()), + context, + syntaxToken: property, + errors: [], + }; } case "style-feature": { - // case 'style-feature-value': - // match - // match - // match - const range = context.peekRange(); - const filteredRange = range.filter((token) => arena.dataTypes[token] !== EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== EnumToken.CommentTokenType); - if (filteredRange.length === 1) { - success = - arena.dataTypes[filteredRange[0]] === EnumToken.IdenTokenType || - arena.dataTypes[filteredRange[0]] === EnumToken.DashedIdenTokenType; - context.update(filteredRange[0]); - return { - success, - valid: true, - token: filteredRange[0], - context, - syntaxToken: property, - errors: [], - }; + // | | + const filteredRange = peekFeatureTokens(arena, context); + success = + filteredRange.length === 1 + ? arena.dataTypes[filteredRange[0]] === EnumToken.IdenTokenType || + arena.dataTypes[filteredRange[0]] === EnumToken.DashedIdenTokenType + : filteredRange.length > 2 && + (mFLT.has(arena.dataTypes[filteredRange[1]]) || + mFGT.has(arena.dataTypes[filteredRange[1]]) || + arena.dataTypes[filteredRange[1]] === EnumToken.ColonTokenType); + if (success) { + context.update(filteredRange.at(-1)); } return { - success: false, - valid: false, - token: context.peek(), + success, + valid: success, + token: success ? null : context.peek(), context, syntaxToken: property, errors: [], @@ -2238,25 +2733,27 @@ function matchProperty(arena, property, context, options) { const token = context.peek(); let l; // inlined: arena.typeOf(token) - if (arena.dataTypes[token] == EnumToken.UrlFunctionTokenDefType) { + if (arena.dataTypes[token] === EnumToken.UrlFunctionTokenDefType) { l = 0; let token; while ((token = context.peek(++l))) { - if (arena.dataTypes[token] !== EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== EnumToken.CommentTokenType) { + if (arena.dataTypes[token] !== EnumToken.WhitespaceTokenType && + arena.dataTypes[token] !== EnumToken.CommentTokenType) { break; } } if (token != null && - (arena.dataTypes[token] == EnumToken.StringTokenType || - arena.dataTypes[token] == EnumToken.IdenTokenType || - arena.dataTypes[token] == EnumToken.UrlTokenTokenType)) { + (arena.dataTypes[token] === EnumToken.StringTokenType || + arena.dataTypes[token] === EnumToken.IdenTokenType || + arena.dataTypes[token] === EnumToken.UrlTokenTokenType)) { while ((token = context.peek(++l))) { - if (arena.dataTypes[token] !== EnumToken.WhitespaceTokenType && arena.dataTypes[token] !== EnumToken.CommentTokenType) { + if (arena.dataTypes[token] !== EnumToken.WhitespaceTokenType && + arena.dataTypes[token] !== EnumToken.CommentTokenType) { break; } } // inlined: arena.typeOf(token) - if (arena.dataTypes[token] == EnumToken.EndParensTokenType) { + if (arena.dataTypes[token] === EnumToken.EndParensTokenType) { success = true; context.update(token); return { @@ -2272,7 +2769,7 @@ function matchProperty(arena, property, context, options) { break; } // inlined: arena.typeOf(token) - if (arena.dataTypes[token] != EnumToken.UrlFunctionTokenType) { + if (arena.dataTypes[token] !== EnumToken.UrlFunctionTokenType) { success = false; break; } @@ -2286,9 +2783,9 @@ function matchProperty(arena, property, context, options) { } if (l < urlTokens.length) { success = - arena.dataTypes[urlTokens[l]] == EnumToken.StringTokenType || - arena.dataTypes[urlTokens[l]] == EnumToken.IdenTokenType || - arena.dataTypes[urlTokens[l]] == EnumToken.UrlTokenTokenType; + arena.dataTypes[urlTokens[l]] === EnumToken.StringTokenType || + arena.dataTypes[urlTokens[l]] === EnumToken.IdenTokenType || + arena.dataTypes[urlTokens[l]] === EnumToken.UrlTokenTokenType; context.next(); return { success: true, @@ -2302,10 +2799,38 @@ function matchProperty(arena, property, context, options) { break; } case "css-type": { - // inlined: arena.typeOf(context.peek()) - success = arena.dataTypes[context.peek()] == EnumToken.CssTypeTokenType; + const token = context.peek(); + // `type( | )`: the css type syntax + if ((arena.dataTypes[token] === EnumToken.FunctionTokenDefType || + arena.dataTypes[token] === EnumToken.FunctionTokenType) && + equalsIgnoreCase(arena.strings[arena.stringValue[token]], "type")) { + if (arena.dataTypes[token] === EnumToken.FunctionTokenDefType) { + context.update(context.peekRange().at(-1)); + } + else { + context.next(); + } + return { + success: true, + valid: true, + token: null, + context, + syntaxToken: null, + errors: [], + }; + } + // inlined: arena.typeOf(token) + success = arena.dataTypes[token] === EnumToken.CssTypeTokenType; if (success) { context.next(); + // the multiplier follows the type: `#`, `+` + const multiplier = context.tokens[context.index + 1]; + if (multiplier != null && + (arena.dataTypes[multiplier] === EnumToken.Plus || + (arena.dataTypes[multiplier] === EnumToken.LiteralTokenType && + arena.strings[arena.stringValue[multiplier]] === "#"))) { + context.next(); + } return { success: true, valid: true, @@ -2320,9 +2845,17 @@ function matchProperty(arena, property, context, options) { case "dashed-function": { const token = context.peek(); // inlined: arena.typeOf(token) - success = arena.dataTypes[token] == EnumToken.CustomFunctionTokenDefType; + success = + arena.dataTypes[token] === EnumToken.CustomFunctionTokenDefType || + arena.dataTypes[token] === EnumToken.CustomFunctionTokenType; if (success) { - context.next(); + // `--name()`: the function and its arguments + if (arena.dataTypes[token] === EnumToken.CustomFunctionTokenDefType) { + context.update(context.peekRange().at(-1)); + } + else { + context.next(); + } return { success: true, valid: true, @@ -2336,7 +2869,7 @@ function matchProperty(arena, property, context, options) { } case "block-contents": // inlined: arena.typeOf(context.peek()) - success = arena.dataTypes[context.peek()] == EnumToken.StartParensTokenType; + success = arena.dataTypes[context.peek()] === EnumToken.StartParensTokenType; if (success) { context.next(); return { @@ -2357,7 +2890,7 @@ function matchProperty(arena, property, context, options) { errors: [], }; default: - if (!(property.val in config.syntaxes)) { + if (!hasSyntax(property.val)) { console.debug("Unknown syntax", context.peek(), property); throw new Error(`Unexpected validation property ${property.val}`); } @@ -2365,7 +2898,7 @@ function matchProperty(arena, property, context, options) { } if (!success && // inlined: arena.typeOf(context.peek()) - arena.dataTypes[context.peek()] == EnumToken.IdenTokenType && + arena.dataTypes[context.peek()] === EnumToken.IdenTokenType && allValues.includes(arena.strings[arena.stringValue[context.peek()]])) { success = true; } @@ -2391,6 +2924,7 @@ function matchProperty(arena, property, context, options) { } /** * matches a repeatable syntax + * @param arena * @param syntax * @param context * @param options @@ -2410,7 +2944,8 @@ function matchRepeatableSyntax(arena, syntax, context, options) { context.end(); break; } - if (tmpResult.context.index === context.index) { + // no token matched. the indexes of the contexts are not comparable: the result context is a slice + if (tmpResult.context.current() === context.current()) { break; } context.update(result.context.current()); diff --git a/dist/src/lib/validation/parser/parse.js b/dist/src/lib/validation/parser/parse.js index f54c7e9f6..e407a5bd5 100644 --- a/dist/src/lib/validation/parser/parse.js +++ b/dist/src/lib/validation/parser/parse.js @@ -2,13 +2,13 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ import { EnumToken } from '../../ast/types.js'; import { LOC } from '../../syntax/constants.js'; import { ValidationTokenEnum } from './typedef.js'; -import { isIdentStart, isIdent, parseDimension, isPseudo } from '../../syntax/syntax.js'; +import { isIdentStart, parseDimension, isPseudo, isIdent } from '../../syntax/syntax.js'; const SymbolsMapTokens = { "&&": ValidationTokenEnum.Ampersand, @@ -48,7 +48,7 @@ const makeBinaryOp = new Map([ */ const symbolTypes = new Map(); for (const [key, type] of Object.entries(SymbolsMapTokens)) { - if (key.length == 1) { + if (key.length === 1) { symbolTypes.set(key.charCodeAt(0), type); } } @@ -57,7 +57,7 @@ for (const [key, type] of Object.entries(SymbolsMapTokens)) { */ const pairSymbols = new Map(); for (const [key, type] of Object.entries(SymbolsMapTokens)) { - if (key.length == 2) { + if (key.length === 2) { const list = pairSymbols.get(key.charCodeAt(0)) ?? []; list.push([key.charCodeAt(1), type]); pairSymbols.set(key.charCodeAt(0), list); @@ -76,7 +76,7 @@ function pairSymbolType(syntax, index) { if (list != null) { const next = syntax.charCodeAt(index + 1); for (let k = 0; k < list.length; k++) { - if (list[k][0] == next) { + if (list[k][0] === next) { return list[k][1]; } } @@ -109,7 +109,7 @@ function codePoints(str, start, end) { * @param str */ function isDigits(str) { - if (str.length == 0) { + if (str.length === 0) { return false; } for (let k = 0; k < str.length; k++) { @@ -135,14 +135,15 @@ function getTokenType(token, loc) { } const first = token.charCodeAt(0); // " or ' - if (first == 34 || first == 39) { + if (first === 34 || first === 39) { return { typ: ValidationTokenEnum.StringToken, val: token, [LOC]: loc, }; } - if (isDigits(token)) { + // integer, optionally negative: range bounds such as `` + if (isDigits(token) || (first === 45 && isDigits(token.slice(1)))) { return { typ: ValidationTokenEnum.Number, val: Number(token), @@ -168,7 +169,7 @@ function getTokenType(token, loc) { }; } // @ - if (first == 64 && isIdent(token.slice(1))) { + if (first === 64 && isIdent(token.slice(1))) { return { typ: ValidationTokenEnum.AtRule, val: token.slice(1), @@ -234,9 +235,9 @@ function tokenizeSyntax(syntax, position = { let code; let type; const bufferLength = () => prefix.length + bufferEnd - bufferStart; - const buffer = () => prefix.length == 0 ? syntax.slice(bufferStart, bufferEnd) : prefix + syntax.slice(bufferStart, bufferEnd); + const buffer = () => prefix.length === 0 ? syntax.slice(bufferStart, bufferEnd) : prefix + syntax.slice(bufferStart, bufferEnd); const append = (index) => { - if (bufferEnd == bufferStart) { + if (bufferEnd === bufferStart) { bufferStart = index; } bufferEnd = index + 1; @@ -258,7 +259,7 @@ function tokenizeSyntax(syntax, position = { curCol++; curInd++; // - if (code == 60 && syntax.startsWith("an+b>", i + 1)) { + if (code === 60 && syntax.startsWith("an+b>", i + 1)) { if (bufferLength() > 0) { prefix = buffer(); bufferStart = bufferEnd = 0; @@ -288,17 +289,17 @@ function tokenizeSyntax(syntax, position = { continue; } // : - if (code == 58) { - if (syntax.charCodeAt(i + 1) == 58) { + if (code === 58) { + if (syntax.charCodeAt(i + 1) === 58) { if (isIdentStart(syntax.charCodeAt(i + 2)) || - (syntax.charCodeAt(i + 2) == 45 && isIdentStart(syntax.charCodeAt(i + 3)))) { + (syntax.charCodeAt(i + 2) === 45 && isIdentStart(syntax.charCodeAt(i + 3)))) { append(i); append(++i); continue; } } if (isIdentStart(syntax.charCodeAt(i + 1)) || - (syntax.charCodeAt(i + 1) == 45 && isIdentStart(syntax.charCodeAt(i + 2)))) { + (syntax.charCodeAt(i + 1) === 45 && isIdentStart(syntax.charCodeAt(i + 2)))) { append(i); continue; } @@ -310,7 +311,7 @@ function tokenizeSyntax(syntax, position = { while (k + 1 < length && symbolTypes.get(syntax.charCodeAt(k + 1)) === ValidationTokenEnum.Whitespace) { k++; } - if (k != i) { + if (k !== i) { curCol += k - i; curInd += k - i; i = k; @@ -329,20 +330,19 @@ function tokenizeSyntax(syntax, position = { } switch (code) { // : - case 58: - if (isIdent(buffer())) { - tokens.push({ - typ: ValidationTokenEnum.DeclarationNameToken, - val: buffer(), - [LOC]: { ind: posInd, lin: posLin, col: posCol }, - }); + case 58: { + // ` : ?`, `name: `: the colon is a token + const loc = startToken(); + if (bufferLength() > 0) { + tokens.push(getTokenType(buffer(), startToken())); clear(); - curCol++; - curInd++; - break; } - append(i); + tokens.push({ + typ: ValidationTokenEnum.Colon, + [LOC]: loc, + }); break; + } // " and ' case 34: case 39: @@ -351,7 +351,7 @@ function tokenizeSyntax(syntax, position = { append(i); while (i + 1 < length) { append(++i); - if (syntax.charCodeAt(i) == quote) { + if (syntax.charCodeAt(i) === quote) { break; } } @@ -383,7 +383,7 @@ function tokenizeSyntax(syntax, position = { return tokens; } /** - * parse mdn data syntax + * parse a css value definition syntax (webref) * @param syntax * @returns */ @@ -398,17 +398,17 @@ function parseSyntax(syntax) { tokens.push(token); switch (token.typ) { case ValidationTokenEnum.EOF: - if (stack.at(-1)?.typ == ValidationTokenEnum.PipeToken) { + if (stack.at(-1)?.typ === ValidationTokenEnum.PipeToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).chi.push(trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))); stack.pop(); } - else if (stack.at(-1)?.typ == ValidationTokenEnum.AmpersandToken) { + else if (stack.at(-1)?.typ === ValidationTokenEnum.AmpersandToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).r = trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2)); stack.pop(); } - else if (stack.at(-1)?.typ == ValidationTokenEnum.ColumnToken) { + else if (stack.at(-1)?.typ === ValidationTokenEnum.ColumnToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).chi.push(trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))); stack.pop(); @@ -417,10 +417,10 @@ function parseSyntax(syntax) { break; case ValidationTokenEnum.Pipe: { - while (stack.at(-1)?.typ == ValidationTokenEnum.AmpersandToken || - stack.at(-1)?.typ == ValidationTokenEnum.ColumnToken) { + while (stack.at(-1)?.typ === ValidationTokenEnum.AmpersandToken || + stack.at(-1)?.typ === ValidationTokenEnum.ColumnToken) { let index = tokens.lastIndexOf(stack.at(-1)); - if (stack.at(-1)?.typ == ValidationTokenEnum.AmpersandToken) { + if (stack.at(-1)?.typ === ValidationTokenEnum.AmpersandToken) { stack.at(-1).r = trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2)); } else { @@ -428,8 +428,8 @@ function parseSyntax(syntax) { } stack.pop(); } - let index = stack.length == 0 ? -1 : tokens.lastIndexOf(stack.at(-1)); - if (stack.at(-1)?.typ != ValidationTokenEnum.PipeToken) { + let index = stack.length === 0 ? -1 : tokens.lastIndexOf(stack.at(-1)); + if (stack.at(-1)?.typ !== ValidationTokenEnum.PipeToken) { stack.push(Object.assign(token, { typ: ValidationTokenEnum.PipeToken, chi: [trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))], @@ -442,7 +442,7 @@ function parseSyntax(syntax) { break; case ValidationTokenEnum.Ampersand: { - let index = stack.length == 0 ? -1 : tokens.lastIndexOf(stack.at(-1)); + let index = stack.length === 0 ? -1 : tokens.lastIndexOf(stack.at(-1)); if (stack.at(-1)?.typ === makeBinaryOp.get(token.typ)) { if (token.typ === ValidationTokenEnum.Ampersand) { stack.at(-1).r = trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2)); @@ -478,13 +478,13 @@ function parseSyntax(syntax) { break; case ValidationTokenEnum.Column: { - let index = stack.length == 0 ? -1 : tokens.lastIndexOf(stack.at(-1)); + let index = stack.length === 0 ? -1 : tokens.lastIndexOf(stack.at(-1)); if (stack.at(-1)?.typ === makeBinaryOp.get(token.typ)) { stack.at(-1).chi.push(trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))); tokens.pop(); } else { - if (index != -1) { + if (index !== -1) { stack.push(Object.assign(token, { typ: makeBinaryOp.get(token.typ), chi: [trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))], @@ -500,7 +500,7 @@ function parseSyntax(syntax) { } break; case ValidationTokenEnum.OpenParenthesis: - if (tokens.at(-2)?.typ == ValidationTokenEnum.Keyword) { + if (tokens.at(-2)?.typ === ValidationTokenEnum.Keyword) { stack.push(Object.assign(tokens.at(-2), { typ: ValidationTokenEnum.Function, chi: [], @@ -508,7 +508,7 @@ function parseSyntax(syntax) { tokens.pop(); break; } - if (tokens.at(-2)?.typ == ValidationTokenEnum.PseudoClassToken) { + if (tokens.at(-2)?.typ === ValidationTokenEnum.PseudoClassToken) { stack.push(Object.assign(tokens.at(-2), { typ: ValidationTokenEnum.PseudoClassFunctionToken, chi: [], @@ -519,13 +519,13 @@ function parseSyntax(syntax) { stack.push(token); break; case ValidationTokenEnum.CloseParenthesis: - if (stack.at(-1)?.typ == ValidationTokenEnum.PipeToken) { + if (stack.at(-1)?.typ === ValidationTokenEnum.PipeToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).chi.push(trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))); stack.pop(); } - if (stack.at(-1)?.typ == ValidationTokenEnum.OpenParenthesis || - (stack.at(-1)?.typ == ValidationTokenEnum.PropertyType && + if (stack.at(-1)?.typ === ValidationTokenEnum.OpenParenthesis || + (stack.at(-1)?.typ === ValidationTokenEnum.PropertyType && stack.at(-1).val === "function-token")) { stack.pop(); } @@ -561,7 +561,7 @@ function parseSyntax(syntax) { tokens[tokens.length - 3].range = tokens[tokens.length - 2].range; } tokens.splice(tokens.length - 2, 2); - if (tokens.at(-1).val == "function-token") { + if (tokens.at(-1).val === "function-token") { // consume the closing ')' stack.push(tokens.at(-1)); } @@ -587,19 +587,19 @@ function parseSyntax(syntax) { break; case ValidationTokenEnum.CloseBracket: while (true) { - if (stack.at(-1).typ == ValidationTokenEnum.AmpersandToken) { + if (stack.at(-1).typ === ValidationTokenEnum.AmpersandToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).r = trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2)); stack.pop(); continue; } - else if (stack.at(-1).typ == ValidationTokenEnum.ColumnToken) { + else if (stack.at(-1).typ === ValidationTokenEnum.ColumnToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).chi.push(trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))); stack.pop(); continue; } - if (stack.at(-1).typ == ValidationTokenEnum.PipeToken) { + if (stack.at(-1).typ === ValidationTokenEnum.PipeToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).chi.push(trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))); stack.pop(); @@ -614,6 +614,32 @@ function parseSyntax(syntax) { // } { let index = tokens.lastIndexOf(stack.at(-1)); + // the lower bound of a range may be '-∞': + const isNegativeInfinity = tokens[index + 1]?.typ === ValidationTokenEnum.Keyword && + tokens[index + 1].val === "-" && + tokens[index + 2]?.typ === ValidationTokenEnum.InfinityToken; + if (isNegativeInfinity && + (tokens[index - 2]?.typ === ValidationTokenEnum.Keyword || + tokens[index - 2]?.typ === ValidationTokenEnum.StringToken) && + tokens[index - 1]?.typ === ValidationTokenEnum.Whitespace && + tokens[index + 3]?.typ === ValidationTokenEnum.Comma && + (tokens[index + 4]?.typ === ValidationTokenEnum.Number || + tokens[index + 4]?.typ === ValidationTokenEnum.Dimension || + tokens[index + 4]?.typ === ValidationTokenEnum.InfinityToken) && + tokens[index + 5]?.typ === ValidationTokenEnum.CloseBracket) { + stack.pop(); + // a null bound is unbounded + Object.assign(tokens[index - 2], { + range: { + min: null, + max: tokens[index + 4]?.typ === ValidationTokenEnum.InfinityToken + ? null + : tokens[index + 4], + }, + }); + tokens.splice(index - 1, 8); + break; + } if ((tokens[index - 2]?.typ === ValidationTokenEnum.Keyword || tokens[index - 2]?.typ === ValidationTokenEnum.StringToken) && tokens[index - 1]?.typ === ValidationTokenEnum.Whitespace && @@ -672,13 +698,13 @@ function parseSyntax(syntax) { // stack.pop(); // continue; // } else - if (stack.at(-1).typ == ValidationTokenEnum.ColumnToken) { + if (stack.at(-1).typ === ValidationTokenEnum.ColumnToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).chi.push(trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))); stack.pop(); continue; } - if (stack.at(-1)?.typ == ValidationTokenEnum.PipeToken) { + if (stack.at(-1)?.typ === ValidationTokenEnum.PipeToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).chi.push(trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 2))); stack.pop(); @@ -693,7 +719,7 @@ function parseSyntax(syntax) { let index = tokens.lastIndexOf(stack.at(-1)); const slice = tokens.slice(index + 1, -1); if (slice.length === 1 || slice.length === 3) { - if (slice[0].typ == ValidationTokenEnum.Number) { + if (slice[0].typ === ValidationTokenEnum.Number) { Object.assign(tokens[index - 1], { match: { min: slice[0], @@ -715,7 +741,7 @@ function parseSyntax(syntax) { Object.assign(tokens[index - 1], { match: { min: slice[0], - max: slice[2].typ == ValidationTokenEnum.InfinityToken + max: slice[2].typ === ValidationTokenEnum.InfinityToken ? Number.POSITIVE_INFINITY : slice[2], }, @@ -743,7 +769,7 @@ function parseSyntax(syntax) { // sliceIndex = tokens.length - 2; // } else // { - isGroup = tokens.at(-3)?.typ == ValidationTokenEnum.Comma; + isGroup = tokens.at(-3)?.typ === ValidationTokenEnum.Comma; if (isGroup) { sliceIndex = tokens.length - 3; } @@ -766,12 +792,12 @@ function parseSyntax(syntax) { // if (tokens.at(-2)?.isOptional && tokens.at(-2)!.typ !== ValidationTokenEnum.OptionalGroupToken) { // sliceIndex = tokens.length - 2; // } else - if (tokens.at(-2).typ == ValidationTokenEnum.Whitespace && + if (tokens.at(-2).typ === ValidationTokenEnum.Whitespace && tokens.at(-3)?.isOptional && tokens.at(-3).typ !== ValidationTokenEnum.OptionalGroupToken) { sliceIndex = tokens.length - 3; } - if (sliceIndex != -1) { + if (sliceIndex !== -1) { if (tokens[sliceIndex].isList) { tokens.pop(); } @@ -801,7 +827,7 @@ function parseSyntax(syntax) { } } if (stack.length > 0) { - if (stack.at(-1)?.typ == ValidationTokenEnum.PipeToken) { + if (stack.at(-1)?.typ === ValidationTokenEnum.PipeToken) { let index = tokens.lastIndexOf(stack.at(-1)); stack.at(-1).chi.push(trimSyntaxArray(tokens.splice(index + 1, tokens.length - index - 1))); stack.pop(); diff --git a/dist/src/lib/validation/parser/typedef.js b/dist/src/lib/validation/parser/typedef.js index 4476ce3e4..056416e62 100644 --- a/dist/src/lib/validation/parser/typedef.js +++ b/dist/src/lib/validation/parser/typedef.js @@ -2,7 +2,7 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ var ValidationTokenEnum; @@ -89,6 +89,10 @@ var ValidationSyntaxGroupEnum; ValidationSyntaxGroupEnum["Declarations"] = "declarations"; ValidationSyntaxGroupEnum["Functions"] = "functions"; ValidationSyntaxGroupEnum["Syntaxes"] = "syntaxes"; + /** + * value types, keyed by their name without the angle brackets (`color` for ``). referenced as {@link Syntaxes} + */ + ValidationSyntaxGroupEnum["Types"] = "types"; ValidationSyntaxGroupEnum["Selectors"] = "selectors"; ValidationSyntaxGroupEnum["AtRules"] = "atRules"; ValidationSyntaxGroupEnum["Units"] = "units"; diff --git a/dist/src/lib/validation/utils/list.js b/dist/src/lib/validation/utils/list.js index 0ac53683b..c9d161c9c 100644 --- a/dist/src/lib/validation/utils/list.js +++ b/dist/src/lib/validation/utils/list.js @@ -2,7 +2,7 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ import { EnumToken } from '../../ast/types.js'; @@ -16,7 +16,7 @@ function stripCommaToken(arena, tokenList) { let result = []; for (let i = 0; i < tokenList.length; i++) { const typ = arena.dataTypes[tokenList[i]]; - if (typ == EnumToken.CommentTokenType || typ == EnumToken.CommaTokenType) { + if (typ === EnumToken.CommentTokenType || typ === EnumToken.CommaTokenType) { continue; } result.push(tokenList[i]); diff --git a/dist/src/node.js b/dist/src/node.js index d1fb1ac49..e0cd0cebc 100644 --- a/dist/src/node.js +++ b/dist/src/node.js @@ -2,7 +2,7 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ import { Readable } from 'node:stream'; @@ -11,10 +11,11 @@ import { lstat, readFile } from 'node:fs/promises'; import { doParse, doParseSync } from './lib/parser/parse.js'; export { parseDeclarations, parseString } from './lib/parser/parse.js'; import { doRender } from './lib/printer/render.js'; -export { renderValue as renderToken } from './lib/printer/render.js'; +export { renderValue } from './lib/printer/render.js'; import { ModuleScopeEnumOptions } from './lib/ast/types.js'; export { ColorType, EnumAstNodeStatus, EnumToken, ModuleCaseTransformEnum, WalkerEvent, WalkerOptionEnum } from './lib/ast/types.js'; -import { Tokenizer } from './lib/parser/tokenize.js'; +import { createParseInfo, Tokenizer } from './lib/parser/tokenize.js'; +import { isCssInput } from './lib/parser/input.js'; import { resolve, matchUrl, dirname } from './lib/fs/resolve.js'; import { ResponseType } from './types.js'; import { resolve as resolve$1 } from 'node:path'; @@ -44,8 +45,8 @@ export { version } from '../package.json.js'; * ``` */ async function load(url, currentDirectory = ".", responseType = false) { - const resolved = typeof url == "string" ? resolve(url, currentDirectory) : url; - if (typeof responseType == "boolean") { + const resolved = typeof url === "string" ? resolve(url, currentDirectory) : url; + if (typeof responseType === "boolean") { responseType = responseType ? ResponseType.ReadableStream : ResponseType.Text; } if (matchUrl.test(resolved.absolute)) { @@ -53,13 +54,13 @@ async function load(url, currentDirectory = ".", responseType = false) { if (!response.ok) { throw new Error(`${response.status} ${response.statusText} ${response.url}`); } - if (responseType == ResponseType.ArrayBuffer) { + if (responseType === ResponseType.ArrayBuffer) { return response.arrayBuffer(); } - if (responseType == ResponseType.JSON) { + if (responseType === ResponseType.JSON) { return response.json(); } - return responseType == ResponseType.ReadableStream + return responseType === ResponseType.ReadableStream ? response.body : response.text(); }); @@ -67,11 +68,14 @@ async function load(url, currentDirectory = ".", responseType = false) { try { const stats = await lstat(resolved.absolute); if (stats.isFile()) { - if (responseType == ResponseType.Text || responseType == ResponseType.JSON) { - return readFile(resolved.absolute, "utf-8").then((buffer) => responseType == ResponseType.JSON ? JSON.parse(buffer) : buffer); + if (responseType === ResponseType.Text || responseType === ResponseType.JSON) { + return readFile(resolved.absolute, "utf-8").then((buffer) => responseType === ResponseType.JSON ? JSON.parse(buffer) : buffer); } - if (responseType == ResponseType.ArrayBuffer) { - return readFile(resolved.absolute).then((buffer) => buffer.buffer); + if (responseType === ResponseType.ArrayBuffer) { + // the buffer of the file, without copy. a buffer that is a part of a larger buffer is copied + return readFile(resolved.absolute).then((buffer) => buffer.byteOffset === 0 && buffer.byteLength === buffer.buffer.byteLength + ? buffer.buffer + : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)); } return Readable.toWeb(createReadStream(resolved.absolute, { encoding: "utf-8", @@ -84,6 +88,7 @@ async function load(url, currentDirectory = ".", responseType = false) { } /** * Render the ast tree + * @param arena * @param data * @param options * @param mapping @@ -133,7 +138,7 @@ function render(arena, data, options = {}, mapping) { function parseSync(...args) { let options; let stream; - if (typeof args[0] === "string") { + if (isCssInput(args[0])) { stream = args[0]; options = args[1]; } @@ -155,20 +160,11 @@ function parseSync(...args) { }); options.src = resolve(options.src, options.cwd).relative; if (options.source == null) { - const source = new SourceFile(typeof stream == "string" ? stream : "", [], options.src); + const source = new SourceFile(typeof stream === "string" ? stream : "", [], options.src); options.sourcesMap.set(source.id, source); options.source = source; } - options.parseInfo = { - stream, - buffer: "", - src: options.src ?? "", - offset: 0, - time: 0, - source: options.source, - position: 0, - currentPosition: 0, - }; + options.parseInfo = createParseInfo(stream, options.source); const result = doParseSync(new Tokenizer(options.parseInfo), options); return options.module == null && options.inputSourceMap == null && !options.sourcemap ? result @@ -191,7 +187,7 @@ function parseSync(...args) { function transformSync(...args) { let options; let stream; - if (typeof args[0] === "string") { + if (isCssInput(args[0])) { stream = args[0]; options = args[1]; } @@ -215,9 +211,9 @@ function transformSync(...args) { const parseResult = parseSync(stream, options); let mapping = null; let importMapping = null; - if ((typeof options.module == "number" && options.module & ModuleScopeEnumOptions.ICSS) || - (typeof options.module == "object" && - typeof options.module.scoped == "number" && + if ((typeof options.module === "number" && options.module & ModuleScopeEnumOptions.ICSS) || + (typeof options.module === "object" && + typeof options.module.scoped === "number" && options.module.scoped & ModuleScopeEnumOptions.ICSS)) { mapping = parseResult.mapping; importMapping = parseResult.importMapping; @@ -286,7 +282,7 @@ function transformSync(...args) { async function parse(...args) { let options; let stream; - if (typeof args[0] === "string" || args[0] instanceof ReadableStream) { + if (isCssInput(args[0]) || args[0] instanceof ReadableStream) { stream = args[0]; options = args[1]; } @@ -295,7 +291,10 @@ async function parse(...args) { const { file, input, ...opt } = args[0]; options = opt; if (file != null) { - return Promise.resolve((options.load ?? load)(file, "", options.asStream ?? false)).then((stream) => parse(stream, { src: file, ...options })); + return Promise.resolve((options.load != null + ? options.load(file, "", options.asStream ?? false) + : // the default loader loads the file as an ArrayBuffer: the preferred input of the tokenizer + load(file, "", options.asStream ? ResponseType.ReadableStream : ResponseType.ArrayBuffer))).then((stream) => parse(stream, { src: file, ...options })); } else { stream = input; @@ -305,27 +304,19 @@ async function parse(...args) { options.src ??= ""; options.sourcesMap ??= new Map(); Object.assign(options, { - load, + // a custom loader is used to load the imported files + load: options.load ?? load, resolve, dirname, cwd: options.cwd ?? cwd(), }); options.src = resolve(options.src, options.cwd).relative; if (options.source == null) { - const source = new SourceFile(typeof stream == "string" ? stream : "", [], options.src); + const source = new SourceFile(typeof stream === "string" ? stream : "", [], options.src); options.sourcesMap.set(source.id, source); options.source = source; } - options.parseInfo = { - stream, - buffer: "", - src: options.src ?? "", - offset: 0, - time: 0, - source: options.source, - position: 0, - currentPosition: 0, - }; + options.parseInfo = createParseInfo(stream, options.source); return doParse(stream instanceof ReadableStream ? new Tokenizer(options.parseInfo, stream).tokenizeStream() : new Tokenizer(options.parseInfo), options).then((result) => options.module == null && options.inputSourceMap == null && !options.sourcemap @@ -377,7 +368,7 @@ async function parse(...args) { async function transform(...args) { let options; let stream; - if (typeof args[0] === "string" || args[0] instanceof ReadableStream) { + if (isCssInput(args[0]) || args[0] instanceof ReadableStream) { stream = args[0]; options = args[1]; } @@ -386,7 +377,10 @@ async function transform(...args) { const { file, input, ...opt } = args[0]; options = opt; if (file != null) { - return Promise.resolve((options.load ?? load)(file, "", options.asStream ?? false)).then((stream) => transform(stream, { src: file, ...options })); + return Promise.resolve((options.load != null + ? options.load(file, "", options.asStream ?? false) + : // the default loader loads the file as an ArrayBuffer: the preferred input of the tokenizer + load(file, "", options.asStream ? ResponseType.ReadableStream : ResponseType.ArrayBuffer))).then((stream) => transform(stream, { src: file, ...options })); } else { stream = input; @@ -406,9 +400,9 @@ async function transform(...args) { return parse(stream, options).then((parseResult) => { let mapping = null; let importMapping = null; - if ((typeof options.module == "number" && options.module & ModuleScopeEnumOptions.ICSS) || - (typeof options.module == "object" && - typeof options.module.scoped == "number" && + if ((typeof options.module === "number" && options.module & ModuleScopeEnumOptions.ICSS) || + (typeof options.module === "object" && + typeof options.module.scoped === "number" && options.module.scoped & ModuleScopeEnumOptions.ICSS)) { mapping = parseResult.mapping; importMapping = parseResult.importMapping; diff --git a/dist/src/types.js b/dist/src/types.js index 87cc1cc1c..0465a6b6f 100644 --- a/dist/src/types.js +++ b/dist/src/types.js @@ -2,7 +2,7 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ /** diff --git a/dist/src/utils/sync.js b/dist/src/utils/sync.js index 7d5177ab4..6a8d1d024 100644 --- a/dist/src/utils/sync.js +++ b/dist/src/utils/sync.js @@ -2,7 +2,7 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ import { EnumToken } from '../lib/ast/types.js'; @@ -26,8 +26,8 @@ function parseResult(result, options) { // extract inline source map from the input CSS const arena = result.arena; const token = arena.lastChild[result.ast]; - if (token != 0 && - arena.dataTypes[token] == EnumToken.CommentTokenType && + if (token !== 0 && + arena.dataTypes[token] === EnumToken.CommentTokenType && arena.startsWith(token, "val", "/*# sourceMappingURL=")) { let data = arena.strings[arena.stringValue[token]].slice(21, -2).trim(); if (data.endsWith(".map")) { @@ -69,12 +69,12 @@ function validateSyncArguments(options, prefix = "options.") { let i; for (i = 0; i < args.length; i++) { const [key, value] = args[i]; - if (typeof value == "function") { + if (typeof value === "function") { if (value instanceof Promise || Object.getPrototypeOf(value).constructor.name == "AsyncFunction") { throw new Error(`[${prefix + key}]: Async functions are not supported in sync mode. Use parse() or transform() instead.`); } } - else if (value != null && typeof value == "object" && !(value instanceof AstArena)) { + else if (value != null && typeof value === "object" && !(value instanceof AstArena)) { validateSyncArguments(value, prefix + key + "."); } } diff --git a/dist/src/web.js b/dist/src/web.js index bb33a22be..470cf6672 100644 --- a/dist/src/web.js +++ b/dist/src/web.js @@ -2,16 +2,17 @@ CSS parser, minifier and validator for node and the browser Author(s): Thierry Bela - Version: 2.0.1 + Version: 2.1.0 License: MIT */ import { doParse, doParseSync } from './lib/parser/parse.js'; export { parseDeclarations, parseString } from './lib/parser/parse.js'; import { doRender } from './lib/printer/render.js'; -export { renderValue as renderToken } from './lib/printer/render.js'; +export { renderValue } from './lib/printer/render.js'; import { ModuleScopeEnumOptions } from './lib/ast/types.js'; export { ColorType, EnumAstNodeStatus, EnumToken, ModuleCaseTransformEnum, WalkerEvent, WalkerOptionEnum } from './lib/ast/types.js'; -import { Tokenizer } from './lib/parser/tokenize.js'; +import { createParseInfo, Tokenizer } from './lib/parser/tokenize.js'; +import { isCssInput } from './lib/parser/input.js'; import { matchUrl, resolve, dirname } from './lib/fs/resolve.js'; import { ResponseType } from './types.js'; import { SourceFile } from './lib/parser/source.js'; @@ -40,11 +41,11 @@ export { version } from '../package.json.js'; * ``` */ async function load(url, currentDirectory = ".", responseType = false) { - if (typeof responseType == "boolean") { + if (typeof responseType === "boolean") { responseType = responseType ? ResponseType.ReadableStream : ResponseType.Text; } let t; - if (typeof url == "object") { + if (typeof url === "object") { t = new URL(url.absolute, self.origin); } else if (matchUrl.test(url)) { @@ -57,21 +58,22 @@ async function load(url, currentDirectory = ".", responseType = false) { const path = resolve(url, currentDirectory).absolute; t = new URL(path, self.origin); } - return fetch(t, t.origin != self.origin ? { mode: "cors" } : {}).then(async (response) => { + return fetch(t, t.origin !== self.origin ? { mode: "cors" } : {}).then(async (response) => { if (!response.ok) { throw new Error(`${response.status} ${response.statusText} ${response.url}`); } - if (responseType == ResponseType.ArrayBuffer) { + if (responseType === ResponseType.ArrayBuffer) { return response.arrayBuffer(); } - if (responseType == ResponseType.JSON) { + if (responseType === ResponseType.JSON) { return response.json(); } - return responseType == ResponseType.ReadableStream ? response.body : response.text(); + return responseType === ResponseType.ReadableStream ? response.body : response.text(); }); } /** * Render the ast tree + * @param arena * @param data * @param options * @param mapping @@ -127,7 +129,7 @@ function render(arena, data, options = {}, mapping) { function parseSync(...args) { let options; let stream; - if (typeof args[0] === "string") { + if (isCssInput(args[0])) { stream = args[0]; options = args[1]; } @@ -151,20 +153,11 @@ function parseSync(...args) { }); options.src = resolve(options.src, options.cwd).relative; if (options.source == null) { - const source = new SourceFile(typeof stream == "string" ? stream : "", [], options.src); + const source = new SourceFile(typeof stream === "string" ? stream : "", [], options.src); options.sourcesMap.set(source.id, source); options.source = source; } - options.parseInfo = { - stream, - buffer: "", - src: options.src ?? "", - offset: 0, - time: 0, - source: options.source, - position: 0, - currentPosition: 0, - }; + options.parseInfo = createParseInfo(stream, options.source); const result = doParseSync(new Tokenizer(options.parseInfo), options); return options.module == null && options.inputSourceMap == null && !options.sourcemap ? result @@ -187,7 +180,7 @@ function parseSync(...args) { function transformSync(...args) { let options; let stream; - if (typeof args[0] === "string") { + if (isCssInput(args[0])) { stream = args[0]; options = args[1]; } @@ -203,9 +196,9 @@ function transformSync(...args) { const parseResult = parseSync(stream, options); let mapping = null; let importMapping = null; - if ((typeof options.module == "number" && options.module & ModuleScopeEnumOptions.ICSS) || - (typeof options.module == "object" && - typeof options.module.scoped == "number" && + if ((typeof options.module === "number" && options.module & ModuleScopeEnumOptions.ICSS) || + (typeof options.module === "object" && + typeof options.module.scoped === "number" && options.module.scoped & ModuleScopeEnumOptions.ICSS)) { mapping = parseResult.mapping; importMapping = parseResult.importMapping; @@ -257,7 +250,7 @@ function transformSync(...args) { async function parse(...args) { let options; let stream; - if (typeof args[0] === "string" || args[0] instanceof ReadableStream) { + if (isCssInput(args[0]) || args[0] instanceof ReadableStream) { stream = args[0]; options = args[1]; } @@ -266,7 +259,10 @@ async function parse(...args) { const { file, input, ...opt } = args[0]; options = opt; if (file != null) { - return Promise.resolve((options.load ?? load)(file, "", options.asStream ?? false)).then((stream) => parse(stream, { src: options.file, ...options })); + return Promise.resolve((options.load != null + ? options.load(file, "", options.asStream ?? false) + : // the default loader loads the file as an ArrayBuffer: the preferred input of the tokenizer + load(file, "", options.asStream ? ResponseType.ReadableStream : ResponseType.ArrayBuffer))).then((stream) => parse(stream, { src: options.file, ...options })); } else { stream = input; @@ -276,7 +272,8 @@ async function parse(...args) { options.src ??= ""; options.sourcesMap ??= new Map(); Object.assign(options, { - load, + // a custom loader is used to load the imported files + load: options.load ?? load, resolve, dirname, cwd: (options.cwd ?? self.location.pathname.endsWith("/")) @@ -289,15 +286,7 @@ async function parse(...args) { options.sourcesMap.set(source.id, source); options.source = source; } - options.parseInfo = { - stream, - buffer: "", - offset: 0, - time: 0, - source: options.source, - position: 0, - currentPosition: 0, - }; + options.parseInfo = createParseInfo(stream, options.source); return doParse(stream instanceof ReadableStream ? new Tokenizer(options.parseInfo, stream).tokenizeStream() : new Tokenizer(options.parseInfo), options).then((result) => options.module == null && options.inputSourceMap == null && !options.sourcemap @@ -328,7 +317,7 @@ async function parse(...args) { async function transform(...args) { let options; let stream; - if (typeof args[0] === "string" || args[0] instanceof ReadableStream) { + if (isCssInput(args[0]) || args[0] instanceof ReadableStream) { stream = args[0]; options = args[1]; } @@ -337,7 +326,10 @@ async function transform(...args) { const { file, input, ...opt } = args[0]; options = opt; if (file != null) { - return Promise.resolve((options.load ?? load)(file, "", options.asStream ?? false)).then((stream) => transform(stream, { src: options.file, ...options })); + return Promise.resolve((options.load != null + ? options.load(file, "", options.asStream ?? false) + : // the default loader loads the file as an ArrayBuffer: the preferred input of the tokenizer + load(file, "", options.asStream ? ResponseType.ReadableStream : ResponseType.ArrayBuffer))).then((stream) => transform(stream, { src: options.file, ...options })); } else { stream = input; @@ -348,9 +340,9 @@ async function transform(...args) { return parse(stream, options).then((parseResult) => { let mapping = null; let importMapping = null; - if ((typeof options.module == "number" && options.module & ModuleScopeEnumOptions.ICSS) || - (typeof options.module == "object" && - typeof options.module.scoped == "number" && + if ((typeof options.module === "number" && options.module & ModuleScopeEnumOptions.ICSS) || + (typeof options.module === "object" && + typeof options.module.scoped === "number" && options.module.scoped & ModuleScopeEnumOptions.ICSS)) { mapping = parseResult.mapping; importMapping = parseResult.importMapping; diff --git a/files/getting-started.md b/files/getting-started.md index eae78d90f..e028d1951 100644 --- a/files/getting-started.md +++ b/files/getting-started.md @@ -62,7 +62,7 @@ It can be imported as an umd module. ```html + +