diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 977a43c1..83688086 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -16,7 +16,10 @@ jobs: node-version: 20 cache: 'npm' - name: install - run: npm install + run: npm ci + - run: npm audit --omit=dev + - run: npm run build + - run: npm run test:bundles - run: npm run test - uses: JS-DevTools/npm-publish@v1 with: diff --git a/.github/workflows/npm-run-test.yml b/.github/workflows/npm-run-test.yml index 3e771750..96bd53ec 100644 --- a/.github/workflows/npm-run-test.yml +++ b/.github/workflows/npm-run-test.yml @@ -5,9 +5,9 @@ name: "CI/CD: build & test & lint" on: push: - branches: [ "main" ] + branches: [ "main", "v5" ] pull_request: - branches: [ "main" ] + branches: [ "main", "v5" ] jobs: build: @@ -27,6 +27,8 @@ jobs: with: node-version: ${{ matrix.node-version }} cache: 'npm' - - run: npm install + - run: npm ci + - run: npm audit --omit=dev - run: npm run build + - run: npm run test:bundles - run: npm run test diff --git a/.gitignore b/.gitignore index 1d451ceb..5e5db5ca 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ node_modules dist yarn-error.log -.rollup.cache \ No newline at end of file +.rollup.cache +.compatibility-css/ \ No newline at end of file diff --git a/README.md b/README.md index 13053ccd..3db5eda5 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,24 @@ Parse CSS into an Abstract Syntax Tree (AST) and convert it back to CSS with configurable formatting. Built with TypeScript for type safety and modern JavaScript features. +## V5: Final Compatibility Release + +V5 will be the **final release of `@adobe/css-tools`**. We recommend moving to +[PostCSS](https://postcss.org/) directly whenever possible, especially for new projects. + +V5 retains **V4's public API and css-tools AST**. It replaces the parser +internals with PostCSS and adds compatibility shims for existing options and +default output. The returned AST remains a css-tools AST rather than a native +PostCSS AST. The V4 parser is not used at runtime. + +Compatibility is verified for the tested corpus, not every CSS input. The +[upstream parser limitations](#known-issues-in-v5) are accepted for this final +release and **will not be fixed** in css-tools. + +Using PostCSS directly is a separate migration: its API and AST differ from +css-tools. V5 lets existing applications upgrade without that migration while +keeping a path open to using PostCSS directly. + ## Install ```bash @@ -43,8 +61,9 @@ Parses CSS code and returns an Abstract Syntax Tree (AST). **Parameters:** - `code` (string) - The CSS code to parse - `options` (object, optional) - Parsing options - - `silent` (boolean) - Silently fail on parse errors instead of throwing + - `silent` (boolean) - Collect recoverable parse errors instead of throwing. Recovery can still throw for some malformed inputs; see [known issues](#known-issues-in-v5). - `source` (string) - File path for better error reporting + - `stripCommentsInValues` (boolean) - Remove comment-like text from declaration values, including inside quoted strings, for V4 compatibility (default: `true`). Set to `false` to preserve leading, embedded, and trailing value comments. **Returns:** `CssStylesheetAST` - The parsed CSS as an AST @@ -67,7 +86,7 @@ Converts a CSS AST back to CSS string with configurable formatting. - **Error Handling**: Configurable error handling with detailed position information - **Formatting Options**: Pretty print, minify, or custom formatting - **Performance Optimized**: Efficient parsing and stringification for large CSS files -- **Source Maps**: Track original source positions for debugging and tooling +- **Source Positions**: Track original source positions for debugging and tooling ### Supported CSS Features @@ -124,11 +143,152 @@ console.log(rule.position?.start) // { line: 1, column: 1 } console.log(rule.position?.end) // { line: 1, column: 20 } ``` +Positions and parse errors refer to the supplied CSS. As in V4, input source maps +are not loaded or resolved; `sourceMappingURL` comments remain ordinary CSS comments. + For more examples, see the [Examples documentation](docs/EXAMPLES.md). ## Performance -The library is optimized for performance and can handle large CSS files efficiently. For benchmarking information, see the `benchmark/` directory in the source code. +V5's PostCSS-based parser was faster than the published V4.5.0 parser on these +samples. Measurements used Benchmark.js with repeated warm, steady-state samples +on Node.js 24.18.0 and an Apple M3 Max (macOS/arm64); each figure is the median +of three runs. ASTs and stringified outputs were checked for equality before +timing. These measurements use PostCSS 8.5.30 and include the final +compatibility repairs. + +| CSS input | Size | V4.5.0 parse (ms) | V5 parse (ms) | V5 speedup | +|---|---:|---:|---:|---:| +| One rule | 20 bytes | 0.0057 | 0.0051 | 1.1x | +| `benchmark/small.css` | 7.8 KB | 0.477 | 0.336 | 1.4x | +| Pure.css 3.0.0 | 26.2 KB | 4.140 | 1.662 | 2.5x | +| Bootstrap 5.3.3 | 281 KB | 621.3 | 24.8 | 25.1x | + +For Bootstrap, parsing plus default stringification improved from **633.4 ms to +27.7 ms**, about **23x faster**. Stringification alone was broadly unchanged: +Bootstrap took about 0.76 ms in both V4 and V5. + +Warm throughput is not cold-start latency, and small inputs do not always favor +V5. Separate alternating-order, forced-GC batch runs measured a 17-byte rule at +0.0061 ms in V4 and 0.0127 ms in V5, and `benchmark/small.css` at 0.521 ms in V4 +and 0.591 ms in V5. Median module loading, excluding process startup, was +0.65 ms for V4's CJS entry and 8.87 ms for V5's ESM entry across eleven fresh +processes each; the first parse after loading took 0.60 ms and 3.05 ms. +Fresh-process Bootstrap peak RSS was about 72.1 MiB in V4 and 97.9 MiB in V5, +including module initialization, a live AST, and compressed stringification. +The standalone UMD bundle grew from 20,942 to 131,834 bytes, or from 4,701 to +39,296 bytes gzipped. + +These are sample measurements, not guaranteed speedups. Results depend on the +CSS, warm-up, garbage collection, runtime, and hardware. See the `benchmark/` +directory for the existing parser benchmark and its inputs, and +[known issues](#known-issues-in-v5) for upstream adversarial-input costs. + +## V4 Compatibility Tests + +The V5 parser uses PostCSS with compatibility shims, not the V4 parser. +`css-tools-v4` is a development-only alias pinned to the published +`@adobe/css-tools@4.5.0` release as the test oracle. + +```bash +npm ci +npm test -- --runInBand +npm run build +npm run test:bundles +npm run test:compatibility:public +``` + +The offline suite compares all existing CSS fixtures, lexical/error edge cases, +and 1,000 seeded generated inputs. It checks complete AST fields, source positions, +non-enumerable parent links, strict and silent errors, and byte-identical default, +compressed, and custom-indent output. It also checks that V5 can stringify V4 ASTs. +Bundle checks cover CJS, ESM, and standalone UMD browser, CommonJS, and AMD loading. +Each loader also parses depth-2048 nested media in an isolated process with a +128 MiB old-space limit and a five-second deadline, checking ASTs, positions, and +parent descriptors without recursively walking the result. This gate covers +parsing, not deep stringification. + +The public-CSS command samples eight complete stylesheets from ten pinned npm +distribution URLs on jsDelivr, using seed `0x405000`. It verifies SHA-256 checksums +before testing and stores downloads and their provenance in the gitignored +`.compatibility-css/` directory. The sample includes Bootstrap (normal and minified), +Bulma, Animate.css, Pure.css, Milligram, Water.css, and Modern Normalize. +Public files use default parse options and all three formatting modes; the offline +inputs exercise `source` and `silent` combinations. The published V4 parser is slow +on the full Bulma file, so this opt-in command can take several minutes. + +Passing these comparisons establishes exact parity for the tested inputs, not a +proof of identical behavior for every possible CSS string. Additional lexical +and malformed-input probes have confirmed differences outside that corpus; see +[known issues](#known-issues-in-v5). + +## Known Issues in V5 + +The following upstream resource limitations are accepted and **will not be fixed** +in css-tools. They affect both strict and silent parsing. + +**Core PostCSS at-rule token handling** takes superlinear time on headers with +many leading comments, such as `'@unknown ' + '/**/ '.repeat(n) + 'x;'`. +PostCSS repeatedly removes tokens from the front of an array before the +compatibility layer receives the AST. This is not regex backtracking. + +**Core PostCSS unclosed `url(` tokenization** searches the rest of the input +for a closing parenthesis at each unclosed `url(`, so input with many unclosed +`url(` takes quadratic time. To restore V4's recovery, V5's silent mode can +parse such input up to eight more times, which multiplies this cost: + +- On 384 KB inputs like `'a{b:' + 'url(x '.repeat(n) + '}'`, PostCSS ran two + or three times, and V5 reported about 320,000 errors, V4's error for each + character V4 skips. Parsing took 1.2–2.5 s. +- On 688 KB of `'a{b:url(x;}'.repeat(n)`, PostCSS ran nine times, and parsing + took about 5 s. + +`postcss-safe-parser` alone took about 0.23 s and 0.44 s on those inputs. V4's +silent mode took over 4 s on 12 KB of the first shape and 28 s on 43 KB of the +second. + +**Safe-parser recovery resource exhaustion** occurs when `postcss-safe-parser` +recursively recovers long sequences without declaration semicolons, such as +`'a {' + '\n color: red'.repeat(3100) + '\n}'`. Each recursion level copies the +remaining tokens, so this can overflow the stack or exhaust memory before the +compatibility layer receives an AST. With Node 24's default limits, 37 KB of +this shape threw a stack-overflow `RangeError` after about 0.15 s, 300 KB took +about 1.2 s and 3.4 GB of memory to throw, and 600 KB exhausted the heap, which +aborts the process. V4 parses each in under 5 ms. The thresholds depend on the +runtime and resource limits. This recovery issue is separate from core +PostCSS's token-handling cost. + +For untrusted CSS, `silent` is not an exception-safety or execution-time +guarantee. Limit input size and isolate parsing in a worker or process with an +enforceable timeout and memory limit, such as a `Worker` with `resourceLimits`; +an in-process timer cannot interrupt synchronous parsing, and heap exhaustion +cannot be caught. +Applications relying on V4's behavior for these inputs should not treat V5 as a +behaviorally identical upgrade. + +Separately, **some malformed CSS still parses differently from V4**, in strict +errors, silent recovery, or both. Known examples: + +- After eight re-parses, silent mode keeps PostCSS's reading of any further + malformed input. With nine or more copies of `a{b:(c;}d{e:f}`, V5 keeps fewer + rules than V4. With nine or more copies of `a{b:url(x;}`, it keeps `url(x` + values where V4 reports errors. +- V4 reads a nested block at-rule's prelude past the parent's `}` into a later + block, as in `@media y{@media x}b{}}`; V5 keeps PostCSS's structure. At the + root, V4 also reads some at-rules' preludes past a stray `}`, as in + `@foo x}b{c:d}`; V5 reads the later block as a separate rule. +- V4 accepts unclosed `[` in values and selectors, as in `a{b:[c;}d{e:f}` and + `a[b{}`. +- When no `)` follows an unclosed `url(` in a selector, as in `url(x {}`, V4 + skips the selector text through the `(`; V5 keeps it and reports PostCSS's + `Unclosed bracket` error. +- V4 rejects a block after an `@import` nested in a block at-rule, as in + `@media x{@import y{a:b}}`; V5 reads an `@import` rule. +- V4 ends a `@keyframes` block at a nested at-rule or selectorless block, as in + `@keyframes x{@media x{}}` and `@keyframes x{{}}`, reports a missing `}` and + reads the rest outside the block. V5 keeps the `@keyframes` block and drops + the nested content, reporting an error only for malformed content, such as a + missing selector. ## Documentation diff --git a/biome.json b/biome.json index de159cae..4d238501 100644 --- a/biome.json +++ b/biome.json @@ -1,5 +1,5 @@ { - "$schema": "https://biomejs.dev/schemas/2.1.2/schema.json", + "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json", "vcs": { "enabled": true, "clientKind": "git", @@ -7,7 +7,7 @@ }, "files": { "ignoreUnknown": false, - "includes": ["**", "!test/cases/**", "!benchmark/*.css"] + "includes": ["**", "!test/cases", "!benchmark/*.css"] }, "formatter": { "enabled": true, @@ -17,7 +17,7 @@ "linter": { "enabled": true, "rules": { - "recommended": true, + "preset": "recommended", "correctness": { "noEmptyCharacterClassInRegex": "off" } diff --git a/docs/API.md b/docs/API.md index 35f178c7..d3c8e810 100644 --- a/docs/API.md +++ b/docs/API.md @@ -20,8 +20,9 @@ Parses CSS code and returns an Abstract Syntax Tree (AST). - `code` (string) - The CSS code to parse - `options` (object, optional) - Parsing options - - `silent` (boolean) - Silently fail on parse errors instead of throwing. When `true`, errors are collected in `ast.stylesheet.parsingErrors` + - `silent` (boolean) - Collect recoverable parse errors in `ast.stylesheet.parsingErrors` instead of throwing. Some recovery failures can still throw; see [known V5 limitations](#known-v5-limitations). - `source` (string) - File path for better error reporting + - `stripCommentsInValues` (boolean, default: `true`) - Apply V4-style declaration-value normalization, removing `/* ... */` text even inside quoted strings. Set to `false` to preserve leading, embedded, and trailing value comments. Standalone comment AST nodes are unaffected. #### Returns @@ -43,6 +44,35 @@ const ast = parse(css); console.log(ast.stylesheet.rules); ``` +V4 historically treats comment-like text inside quoted values as a comment. +V5 preserves this behavior by default, with an explicit opt-out: + +```javascript +const css = 'a { content: "/* literal text */"; }'; + +parse(css).stylesheet.rules[0].declarations[0].value; +// => '""' + +parse(css, { stripCommentsInValues: false }) + .stylesheet.rules[0].declarations[0].value; +// => '"/* literal text */"' +``` + +The option is part of the exported `ParseOptions` TypeScript interface. + +Input source maps are not loaded. `sourceMappingURL` comments are parsed like +ordinary CSS comments; positions and parse errors refer to the provided CSS. + +#### Known V5 Limitations + +Two [upstream resource limitations](../README.md#known-issues-in-v5) are accepted +and **will not be fixed** in css-tools. Core PostCSS takes superlinear time on +at-rule headers with many leading comments. Separately, `postcss-safe-parser` +can exhaust the stack or memory on long sequences without declaration +semicolons. Both occur before the compatibility layer receives an AST and affect +strict and silent parsing. Exact V4 behavior is not guaranteed outside the tested +compatibility corpus. + ### `stringify(ast, options?)` Converts a CSS AST back to CSS string with configurable formatting. @@ -197,7 +227,8 @@ type CompilerOptions = { ### Silent Parsing -When parsing malformed CSS, you can use the `silent` option to collect errors instead of throwing: +For recoverable syntax errors, use the `silent` option to collect errors +instead of throwing: ```javascript import { parse } from '@adobe/css-tools'; @@ -220,6 +251,14 @@ if (result.stylesheet.parsingErrors) { console.log('Valid rules:', result.stylesheet.rules.length); ``` +Silent mode does not guarantee that parsing returns an AST or finishes within +a bounded time. Core PostCSS's leading-comment token handling and +`postcss-safe-parser`'s missing-semicolon recovery are +[known V5 limitations](../README.md#known-issues-in-v5) that will not be fixed +in css-tools. Bound untrusted input size and use a worker or process with an +externally enforceable timeout; an in-process timer cannot interrupt synchronous +parsing. + ### Source Tracking Enable source tracking for better error reporting: @@ -304,7 +343,7 @@ const output: string = stringify(ast); ## Performance Considerations -- The parser is optimized for large CSS files +- Parsing performance depends on the input; upstream safe-parser recovery can [exhaust the stack or memory](../README.md#known-issues-in-v5) on long sequences without semicolons - AST nodes are lightweight and memory-efficient - Stringification is fast and supports streaming for large outputs - Consider using `compress: true` for production builds to reduce file size diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 392767b6..aa2c9f91 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,6 +5,68 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [5.0.0] - 2026-10-13 + +### Added +- Add `parse` option `stripCommentsInValues`, enabled by default for V4 compatibility, with an opt-out that preserves leading, embedded, and trailing value comments. +- Export the `ParseOptions` TypeScript interface. +- Add differential tests against published V4, including seeded generated CSS, checksum-pinned public stylesheets, and package bundle checks. +- Add isolated depth-2048 parsing checks for every package loader, including source positions and parent descriptors. + +### Changed +- Replace the parser internals with `postcss` and `postcss-safe-parser`, keeping the css-tools API and AST format, with default-output compatibility verified for the tested corpus. +- Make V5 the final css-tools release; recommend migrating directly to PostCSS when possible. +- Use clean, lockfile-based installs and validate production dependencies and all package bundles before publishing. + +### Fixed +- Improve V4 compatibility for value normalization, property hacks, at-rule case handling, BOM positions, error details, and malformed-CSS recovery using PostCSS shims. The known issues below remain. +- Preserve V4 parsing and recovery for semicolons following ordinary rules, without spurious missing-brace errors or lost declarations. +- Preserve declarations and source positions after V4 whitespace characters such as non-breaking spaces and Unicode line separators. +- Eliminate per-error reparsing and repeated whole-tree and source-prefix scans in the compatibility layer. +- Preserve full declaration-value spans, including leading and trailing comments, V4 whitespace, and delimiter positions. +- Restore V4 property/value boundaries for escaped property-name colons. +- Preserve V4 nested-rule classification for custom-property blocks without per-block reparsing. +- Restore V4 handling of missing semicolons, extra colons, and empty-property recovery. +- Preserve comments in at-rule preludes. +- Include trailing whitespace in generic statement at-rule end positions, including bare EOF statements, matching V4. +- Preserve V4's generic at-rule classification and output for minified anonymous `@layer` blocks. +- Restore EOF at-rule comments, whitespace, source spans, and nested generic statements. +- Restore missing-block diagnostics for named/vendor keyframes, vendor documents, and page-margin boxes; bound nested recovery to the failed statement and enclosing body. +- Correct declaration-only custom-block and enclosing-node end positions. +- Replace recursive compatibility traversal, AST conversion, value normalization, and parent attachment with iterative traversal. +- Parse empty `@keyframes` blocks that contain whitespace or comments without spurious missing-brace errors. +- Restore V4 recovery from a stray `}` followed by `;` without spurious missing-brace errors. +- Restore V4 recovery where PostCSS reads the rest of the input as one node: unclosed parentheses, quotes and `url(` in selectors and values. +- Restore V4 block at-rule preludes that continue past a `;` or `}` to the end of the input or to a block in the same parent, such as `@media y{@media x}}` and `@media x}b{}`. +- Restore V4 handling of doubled semicolons after statements, `@page` statements, malformed import-like statements such as `@import;;` and `@import{}`, nameless keyframes, and unusual keyframe selectors. +- Restore V4 recovery for import-like statements after a selector containing one, as in `b}@import x}{}@import x}{}`, and for block at-rules after a `@layer` statement ending in `}`, as in `@layer x}@media y}`. +- Read at-rules whose preludes V4's dedicated parsers reject, such as `@property x{}`, as generic at-rules, matching V4. +- Read non-CSS whitespace such as a non-breaking space after an at-keyword as V4 does. +- Split selector lists in linear time instead of quadratic time, and parse deeply nested parentheses in selectors without overflowing the call stack. +- Bound compatibility-layer searches, recovery re-parsing, and recovered output so the compatibility layer does not take quadratic time or memory on malformed input, such as nested selectorless keyframe blocks, many unterminated or nameless (`@}`) at-rules, repeated or nested failed `@page` blocks, long at-rule preludes, deeply nested blocks containing stray semicolons, long runs of comments or unclosed comments, many properties or escaped semicolons in a nested `@font-face` or `@page`, declarations missing their semicolons, and many recovered declarations or errors. +- Avoid call-stack overflows in the compatibility layer on long runs of stray `}` or many recovery errors. +- Keep the UMD browser bundle self-contained without external PostCSS globals. + +### Security +- Require PostCSS 8.5.30 with patched `nanoid` and `source-map-js` dependencies. +- Disable input source-map processing, matching V4 and preventing embedded or external source maps from being loaded while parsing CSS. + +### Known Issues + +Core PostCSS takes superlinear time on at-rule headers with many leading comments +and on many unclosed `url(` tokens. Separately, upstream `postcss-safe-parser` +recovery of long sequences without declaration semicolons can exhaust the stack +or, from about 600 KB with Node's default limits, the heap, which aborts the +process. These affect strict and silent parsing, are accepted for the final V5 +release, and **will not be fixed** in css-tools. To restore V4's recovery, silent +mode can parse unclosed-`url(` input up to eight more times, which multiplies its +cost. Some malformed CSS still parses differently from V4. For example, after +eight re-parses silent mode keeps PostCSS's reading of any further malformed +input, and a nested block at-rule without a body keeps PostCSS's structure when +V4 reads its prelude past the parent's `}` into a later block, as in +`@media y{@media x}b{}}`. See +[known issues in V5](../README.md#known-issues-in-v5) for examples and mitigation. + ## [4.5.0] - 2026-05-20 ### Added diff --git a/package-lock.json b/package-lock.json index 039031d8..14c40f65 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,18 +1,23 @@ { "name": "@adobe/css-tools", - "version": "4.5.0", + "version": "5.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@adobe/css-tools", - "version": "4.5.0", + "version": "5.0.0", "license": "MIT", + "dependencies": { + "postcss": "^8.5.30", + "postcss-safe-parser": "^7.0.1" + }, "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", "@biomejs/biome": "^2.1.2", "@rollup/plugin-commonjs": "^29.0.0", "@rollup/plugin-node-resolve": "^16.0.1", + "@rollup/plugin-replace": "^6.0.3", "@rollup/plugin-terser": "^1.0.0", "@rollup/plugin-typescript": "^12.1.4", "@types/benchmark": "^2.1.1", @@ -21,6 +26,7 @@ "@types/node": "^25.0.3", "benchmark": "^2.1.4", "bytes": "^3.1.0", + "css-tools-v4": "npm:@adobe/css-tools@4.5.0", "jest": "^30.0.5", "rollup": "^4.45.1", "rollup-plugin-dts": "^6.2.1", @@ -29,24 +35,12 @@ "typescript": "^6.0.2" } }, - "node_modules/@ampproject/remapping": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", - "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", - "dev": true, - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/@andrewbranch/untar.js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@andrewbranch/untar.js/-/untar.js-1.0.3.tgz", - "integrity": "sha512-Jh15/qVmrLGhkKJBdXlK1+9tY4lZruYjsgkDFj08ZmDiWVBLJcqkok7Z0/R0In+i1rScBpJlSvrTS2Lm41Pbnw==", - "dev": true + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@andrewbranch/untar.js/-/untar.js-1.0.4.tgz", + "integrity": "sha512-pVXSwPsLuw8IGLo2Di0EaOfsk+ntVvpkk942J/sHYIkwvtKUakEcPh7HBgZ6tuimgzKSEHgCvO4XgQ05DEbwDw==", + "dev": true, + "license": "MIT" }, "node_modules/@arethetypeswrong/cli": { "version": "0.18.5", @@ -109,7 +103,6 @@ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", @@ -120,30 +113,30 @@ } }, "node_modules/@babel/compat-data": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.28.0.tgz", - "integrity": "sha512-60X7qkglvrap8mn1lh2ebxXdZYtUcpd7gsmy9kLaBJ4i/WdY8PqTSdxyA8qraikqKQK5C1KRBKXqznrVapyNaw==", + "version": "7.29.3", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.3.tgz", + "integrity": "sha512-LIVqM46zQWZhj17qA8wb4nW/ixr2y1Nw+r1etiAWgRM6U1IqP+LNhL1yg440jYZR72jCWcWbLWzIosH+uP1fqg==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/core": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.0.tgz", - "integrity": "sha512-UlLAnTPrFdNGoFtbSXwcGFQBtQZJCNjaN6hQNP3UPvuNXT1i82N26KL3dZeIpNalWywr9IuQuncaAfUaS1g6sQ==", - "dev": true, - "dependencies": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.27.1", - "@babel/generator": "^7.28.0", - "@babel/helper-compilation-targets": "^7.27.2", - "@babel/helper-module-transforms": "^7.27.3", - "@babel/helpers": "^7.27.6", - "@babel/parser": "^7.28.0", - "@babel/template": "^7.27.2", - "@babel/traverse": "^7.28.0", - "@babel/types": "^7.28.0", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", + "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helpers": "^7.28.6", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", @@ -168,13 +161,13 @@ } }, "node_modules/@babel/generator": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.0.tgz", - "integrity": "sha512-lJjzvrbEeWrhB4P3QBsH7tey117PjLZnDbLiQEKjQ/fNJTjuq4HSqgFA+UNSwZT8D7dxxbnuSBMsa1lrWzKlQg==", + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", "dev": true, "dependencies": { - "@babel/parser": "^7.28.0", - "@babel/types": "^7.28.0", + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" @@ -184,12 +177,12 @@ } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.27.2", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz", - "integrity": "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", + "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", "dev": true, "dependencies": { - "@babel/compat-data": "^7.27.2", + "@babel/compat-data": "^7.28.6", "@babel/helper-validator-option": "^7.27.1", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", @@ -227,27 +220,27 @@ } }, "node_modules/@babel/helper-module-imports": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.27.1.tgz", - "integrity": "sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", "dev": true, "dependencies": { - "@babel/traverse": "^7.27.1", - "@babel/types": "^7.27.1" + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.27.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.27.3.tgz", - "integrity": "sha512-dSOvYwvyLsWBeIRyOeHXp5vPj5l1I011r52FM1+r1jCERv+aFXYk4whgQccYEGYxK2H3ZAIA8nuPkQ0HaUo3qg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", "dev": true, "dependencies": { - "@babel/helper-module-imports": "^7.27.1", - "@babel/helper-validator-identifier": "^7.27.1", - "@babel/traverse": "^7.27.3" + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -280,7 +273,6 @@ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", "dev": true, - "license": "MIT", "engines": { "node": ">=6.9.0" } @@ -295,25 +287,25 @@ } }, "node_modules/@babel/helpers": { - "version": "7.27.6", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.27.6.tgz", - "integrity": "sha512-muE8Tt8M22638HU31A3CgfSUciwz1fhATfoVai05aPXGor//CdWDCbnlY1yvBPo07njuVOCNGCSp/GTt12lIug==", + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", + "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", "dev": true, "dependencies": { - "@babel/template": "^7.27.2", - "@babel/types": "^7.27.6" + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.0.tgz", - "integrity": "sha512-jVZGvOxOuNSsuQuLRTh13nU0AogFlw32w/MT+LV6D3sP5WdbW61E77RnkbaO2dUvmPAYrBDJXGn5gGS6tH4j8g==", + "version": "7.29.3", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.3.tgz", + "integrity": "sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==", "dev": true, "dependencies": { - "@babel/types": "^7.28.0" + "@babel/types": "^7.29.0" }, "bin": { "parser": "bin/babel-parser.js" @@ -327,7 +319,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -340,7 +331,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -353,7 +343,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.12.13" }, @@ -366,7 +355,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" }, @@ -378,13 +366,12 @@ } }, "node_modules/@babel/plugin-syntax-import-attributes": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.27.1.tgz", - "integrity": "sha512-oFT0FrKHgF53f4vOsZGi2Hh3I35PfSmVs4IBFLFj4dnafP+hIWDLg3VyKmUHfLoLHlyxY4C7DGtmHuJgn+IGww==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.28.6.tgz", + "integrity": "sha512-jiLC0ma9XkQT3TKJ9uYvlakm66Pamywo+qwL+oL8HJOvc6TWdZXVfhqJr8CCzbSGUAbDOzlGHJC1U+vRfLQDvw==", "dev": true, - "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -398,7 +385,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" }, @@ -411,7 +397,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -440,7 +425,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" }, @@ -453,7 +437,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -466,7 +449,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" }, @@ -479,7 +461,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -492,7 +473,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -505,7 +485,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -518,7 +497,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" }, @@ -534,7 +512,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" }, @@ -562,31 +539,31 @@ } }, "node_modules/@babel/template": { - "version": "7.27.2", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz", - "integrity": "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", "dev": true, "dependencies": { - "@babel/code-frame": "^7.27.1", - "@babel/parser": "^7.27.2", - "@babel/types": "^7.27.1" + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.28.0.tgz", - "integrity": "sha512-mGe7UK5wWyh0bKRfupsUchrQGqvDbZDbKJw+kcRGSmdHVYrv+ltd0pnpDTVpiTqnaBru9iEvA8pz8W46v0Amwg==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", "dev": true, "dependencies": { - "@babel/code-frame": "^7.27.1", - "@babel/generator": "^7.28.0", + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", "@babel/helper-globals": "^7.28.0", - "@babel/parser": "^7.28.0", - "@babel/template": "^7.27.2", - "@babel/types": "^7.28.0", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", "debug": "^4.3.1" }, "engines": { @@ -594,14 +571,13 @@ } }, "node_modules/@babel/types": { - "version": "7.28.2", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.2.tgz", - "integrity": "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", "dev": true, - "license": "MIT", "dependencies": { "@babel/helper-string-parser": "^7.27.1", - "@babel/helper-validator-identifier": "^7.27.1" + "@babel/helper-validator-identifier": "^7.28.5" }, "engines": { "node": ">=6.9.0" @@ -948,9 +924,9 @@ } }, "node_modules/@istanbuljs/schema": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz", + "integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==", "dev": true, "engines": { "node": ">=8" @@ -1143,9 +1119,9 @@ }, "node_modules/@jest/react-is-19": { "name": "react-is", - "version": "19.2.8", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.8.tgz", - "integrity": "sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ==", + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.0.tgz", + "integrity": "sha512-UpMYezM4v5/18F28aC66AEsjXIgE02kyEMH6yLdgLXu/UTfa1Ntwck/nNLrbqJsEXW7gPb0coNO9FQse9WTovA==", "dev": true, "license": "MIT" }, @@ -1315,9 +1291,9 @@ } }, "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.12", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.12.tgz", - "integrity": "sha512-OuLGC46TjB5BbN1dH8JULVVZY4WTdkF7tV9Ys6wLL1rubZnCMstOhNHueU5bLCrnRuDhKPDM4g6sw4Bel5Gzqg==", + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", "dev": true, "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", @@ -1329,7 +1305,6 @@ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", "dev": true, - "license": "MIT", "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" @@ -1345,9 +1320,9 @@ } }, "node_modules/@jridgewell/source-map": { - "version": "0.3.10", - "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.10.tgz", - "integrity": "sha512-0pPkgz9dY+bijgistcTTJ5mR+ocqRXLuhXHYdzoMmmoJ2C9S46RCm2GMUbatPEUK9Yjy26IrAy8D/M00lLkv+Q==", + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", "dev": true, "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", @@ -1358,15 +1333,13 @@ "version": "1.5.5", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" + "dev": true }, "node_modules/@jridgewell/trace-mapping": { "version": "0.3.31", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "dev": true, - "license": "MIT", "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" @@ -1403,9 +1376,9 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.4.tgz", - "integrity": "sha512-AJxoUD2/15ESHbvpcyjU274nsAPLuOtPHCk0vKJM5pj//Fg/B1FXNWjPnXTT9PymCYYiHo4zPj0ZomXBKhoy7g==", + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.5.tgz", + "integrity": "sha512-HshSvXzmBxNzqejd3k/KemgQ3hdREUYFRRrgxOZ+gPljDIsO2SDZrVZMd4Z/HsxudQbE62OVyVFE8z9BCurfjA==", "dev": true, "license": "MIT", "optional": true, @@ -1785,7 +1758,6 @@ "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.3.tgz", "integrity": "sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==", "dev": true, - "license": "MIT", "dependencies": { "@rollup/pluginutils": "^5.0.1", "@types/resolve": "1.20.2", @@ -1805,6 +1777,28 @@ } } }, + "node_modules/@rollup/plugin-replace": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-replace/-/plugin-replace-6.0.3.tgz", + "integrity": "sha512-J4RZarRvQAm5IF0/LwUUg+obsm+xZhYnbMXmXROyoSE1ATJe3oXSb9L5MMppdxP2ylNSjv6zFBwKYjcKMucVfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "magic-string": "^0.30.3" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, "node_modules/@rollup/plugin-terser": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-1.0.0.tgz", @@ -1832,7 +1826,6 @@ "resolved": "https://registry.npmjs.org/@rollup/plugin-typescript/-/plugin-typescript-12.3.0.tgz", "integrity": "sha512-7DP0/p7y3t67+NabT9f8oTBFE6gGkto4SA6Np2oudYmZE/m1dt8RB0SjL1msMxFpLo631qjRCcBlAbq1ml/Big==", "dev": true, - "license": "MIT", "dependencies": { "@rollup/pluginutils": "^5.1.0", "resolve": "^1.22.1" @@ -1855,9 +1848,9 @@ } }, "node_modules/@rollup/pluginutils": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.2.0.tgz", - "integrity": "sha512-qWJ2ZTbmumwiLFomfzTyt5Kng4hwPi9rwCYN4SHb6eaRU1KNO4ccxINHr/VhH4GgPlt1XfSTLX2LBTme8ne4Zw==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.3.0.tgz", + "integrity": "sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q==", "dev": true, "dependencies": { "@types/estree": "^1.0.0", @@ -2377,8 +2370,7 @@ "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", - "dev": true, - "license": "MIT" + "dev": true }, "node_modules/@types/istanbul-lib-coverage": { "version": "2.0.6", @@ -2409,7 +2401,6 @@ "resolved": "https://registry.npmjs.org/@types/jest/-/jest-30.0.0.tgz", "integrity": "sha512-XTYugzhuwqWjws0CVz8QpM36+T+Dz5mTEBKhNs/esGLnCIlGdRy+Dq78NRjd7ls7r8BC8ZRMOrKlkO1hU0JOwA==", "dev": true, - "license": "MIT", "dependencies": { "expect": "^30.0.0", "pretty-format": "^30.0.0" @@ -2435,13 +2426,12 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", - "dev": true, - "license": "MIT" + "dev": true }, "node_modules/@types/yargs": { - "version": "17.0.33", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.33.tgz", - "integrity": "sha512-WpxBCKWPLr4xSsHgz511rFJAM+wS28w2zEO1QDNY5zM/S8ok70NNfztH0xwhqKyaK0OHCbN98LDAZuy1ctxDkA==", + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", "dev": true, "dependencies": { "@types/yargs-parser": "*" @@ -2454,11 +2444,10 @@ "dev": true }, "node_modules/@ungap/structured-clone": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", - "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", - "dev": true, - "license": "ISC" + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.1.tgz", + "integrity": "sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==", + "dev": true }, "node_modules/@unrs/resolver-binding-android-arm-eabi": { "version": "1.12.2", @@ -2804,9 +2793,9 @@ ] }, "node_modules/acorn": { - "version": "8.15.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", - "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -2836,7 +2825,6 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", "dev": true, - "license": "MIT", "engines": { "node": ">=12" }, @@ -2960,7 +2948,6 @@ "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz", "integrity": "sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==", "dev": true, - "license": "MIT", "dependencies": { "@babel/plugin-syntax-async-generators": "^7.8.4", "@babel/plugin-syntax-bigint": "^7.8.3", @@ -3009,6 +2996,18 @@ "node": "18 || 20 || >=22" } }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.31", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.31.tgz", + "integrity": "sha512-MujYO3eP72uvmSE0i4wltsodRfIpZATP3jvzRNRGGxgzId7aVocVJJV3nf01qnzzKFGxQVC9bpWxl5cjxTr/7Q==", + "dev": true, + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/benchmark": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/benchmark/-/benchmark-2.1.4.tgz", @@ -3020,9 +3019,9 @@ } }, "node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, "license": "MIT", "dependencies": { @@ -3033,9 +3032,9 @@ } }, "node_modules/browserslist": { - "version": "4.25.1", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.25.1.tgz", - "integrity": "sha512-KGj0KoOMXLpSNkkEI6Z6mShmQy0bc1I+T7K9N81k4WWMrfz+6fQ6es80B/YLAeRoKvjYE1YSHHOW1qe9xIVzHw==", + "version": "4.28.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", + "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", "dev": true, "funding": [ { @@ -3052,10 +3051,11 @@ } ], "dependencies": { - "caniuse-lite": "^1.0.30001726", - "electron-to-chromium": "^1.5.173", - "node-releases": "^2.0.19", - "update-browserslist-db": "^1.1.3" + "baseline-browser-mapping": "^2.10.12", + "caniuse-lite": "^1.0.30001782", + "electron-to-chromium": "^1.5.328", + "node-releases": "^2.0.36", + "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" @@ -3121,9 +3121,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001727", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001727.tgz", - "integrity": "sha512-pB68nIHmbN6L/4C6MH1DokyR3bYqFwjaSs/sWDHGj4CTcFtQUQMuJftVwWkXq7mNWOybD3KhUv3oWHoGxgP14Q==", + "version": "1.0.30001793", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001793.tgz", + "integrity": "sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA==", "dev": true, "funding": [ { @@ -3166,9 +3166,9 @@ } }, "node_modules/ci-info": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.0.tgz", - "integrity": "sha512-l+2bNRMiQgcfILUi33labAZYIWlH1kWDp+ecNo5iisRKrbm0xcRyCww71/YU0Fkw0mAFpz9bJayXPjey6vkmaQ==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", "dev": true, "funding": [ { @@ -3176,7 +3176,6 @@ "url": "https://github.com/sponsors/sibiraj-s" } ], - "license": "MIT", "engines": { "node": ">=8" } @@ -3349,10 +3348,18 @@ "node": ">= 8" } }, + "node_modules/css-tools-v4": { + "name": "@adobe/css-tools", + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz", + "integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==", + "dev": true, + "license": "MIT" + }, "node_modules/debug": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", - "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "dependencies": { "ms": "^2.1.3" @@ -3418,9 +3425,9 @@ "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.190", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.190.tgz", - "integrity": "sha512-k4McmnB2091YIsdCgkS0fMVMPOJgxl93ltFzaryXqwip1AaxeDqKCGLxkXODDA5Ab/D+tV5EL5+aTx76RvLRxw==", + "version": "1.5.360", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.360.tgz", + "integrity": "sha512-GkcBt6YYAw9SxFWn+xVar4cLVGlXVuswwtRLBozi2zp0GjXs4ZnOrqV4zbXzg35n7w81hCkyJNYicgXlVHAmBA==", "dev": true }, "node_modules/emittery": { @@ -3470,6 +3477,15 @@ "is-arrayish": "^0.2.1" } }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -3491,7 +3507,6 @@ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", "dev": true, - "license": "MIT", "engines": { "node": ">=8" } @@ -3595,7 +3610,6 @@ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", "dev": true, - "license": "MIT", "engines": { "node": ">=12.0.0" }, @@ -3609,9 +3623,9 @@ } }, "node_modules/fflate": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", - "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", "dev": true, "license": "MIT" }, @@ -3764,9 +3778,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", + "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", "dev": true, "dependencies": { "function-bind": "^1.1.2" @@ -3826,7 +3840,6 @@ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", "dev": true, - "license": "MIT", "engines": { "node": ">=0.8.19" } @@ -3839,12 +3852,12 @@ "license": "MIT" }, "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", "dev": true, "dependencies": { - "hasown": "^2.0.2" + "hasown": "^2.0.3" }, "engines": { "node": ">= 0.4" @@ -3944,7 +3957,6 @@ "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", "dev": true, - "license": "BSD-3-Clause", "dependencies": { "@babel/core": "^7.23.9", "@babel/parser": "^7.23.9", @@ -4444,9 +4456,9 @@ } }, "node_modules/jest-runtime/node_modules/cjs-module-lexer": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.2.1.tgz", - "integrity": "sha512-Ca8swihM+/4yKecYHY52kgJd300hi2lADU/a1RxNTRe+RJ9jvqQlESpbz9DnG9mowez8qwXHB8qYdIUw9e+F5Q==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.3.0.tgz", + "integrity": "sha512-lmNyBzi6iYiqyrExTctfmjd8tInx+dHu9PBomTfH5RXS53c27JMFJgzNv5TyAnm3PgGf+MLy0+Ws41/HlVxdKQ==", "dev": true, "license": "MIT" }, @@ -4678,9 +4690,9 @@ "dev": true }, "node_modules/lru-cache": { - "version": "11.5.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", - "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", "dev": true, "license": "BlueOak-1.0.0", "engines": { @@ -4692,7 +4704,6 @@ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", "dev": true, - "license": "MIT", "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } @@ -4753,9 +4764,9 @@ } }, "node_modules/marked-terminal/node_modules/ansi-escapes": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.0.0.tgz", - "integrity": "sha512-GdYO7a61mR0fOlAsvC9/rIHf7L96sBc6dEWzeOu+KAea5bZyQRPIpojrVoI4AXGJS/ycu/fBTdLrUkA4ODrvjw==", + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", "dev": true, "dependencies": { "environment": "^1.0.0" @@ -4768,9 +4779,9 @@ } }, "node_modules/marked-terminal/node_modules/chalk": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz", - "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==", + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", "dev": true, "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" @@ -4847,6 +4858,24 @@ "thenify-all": "^1.0.0" } }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, "node_modules/napi-postinstall": { "version": "0.3.4", "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz", @@ -4905,10 +4934,13 @@ "dev": true }, "node_modules/node-releases": { - "version": "2.0.19", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz", - "integrity": "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==", - "dev": true + "version": "2.0.45", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.45.tgz", + "integrity": "sha512-iIbHXV9eBB2nB0wa7oTsrrXq+qQt+9SIlx9AX3T96YgobtEQfis5n6TJ6vV+3QP8DwdriEAcGhARaFCu37peBg==", + "dev": true, + "engines": { + "node": ">=18" + } }, "node_modules/normalize-path": { "version": "3.0.0", @@ -5101,8 +5133,7 @@ "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" }, "node_modules/picomatch": { "version": "4.0.4", @@ -5144,6 +5175,59 @@ "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", "dev": true }, + "node_modules/postcss": { + "version": "8.5.30", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz", + "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-safe-parser": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/postcss-safe-parser/-/postcss-safe-parser-7.0.1.tgz", + "integrity": "sha512-0AioNCJZ2DPYz5ABT6bddIqlhgwhpHZ/l65YAYo0BCIn0xiDpsnTHz0gnoTGk0OXZW0JRs+cDwL8u/teRdz+8A==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss-safe-parser" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, "node_modules/pretty-format": { "version": "30.5.1", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.1.tgz", @@ -5165,7 +5249,6 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "dev": true, - "license": "MIT", "engines": { "node": ">=10" }, @@ -5200,12 +5283,13 @@ } }, "node_modules/resolve": { - "version": "1.22.10", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", - "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", "dev": true, "dependencies": { - "is-core-module": "^2.16.0", + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, @@ -5320,14 +5404,14 @@ } }, "node_modules/rollup-plugin-dts/node_modules/@babel/code-frame": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.0.tgz", - "integrity": "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.6.tgz", + "integrity": "sha512-uMHhvmDmwFiLuiozaoRYTZHqMFuu3fem/X9JY78lohAuLoh8LSGGC8JqUzo2cVuBsBxkjMZNk56CE7ock8Xxkw==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@babel/helper-validator-identifier": "^8.0.0", + "@babel/helper-validator-identifier": "^8.0.6", "js-tokens": "^10.0.0" }, "engines": { @@ -5335,9 +5419,9 @@ } }, "node_modules/rollup-plugin-dts/node_modules/@babel/helper-validator-identifier": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.4.tgz", - "integrity": "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg==", + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz", + "integrity": "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ==", "dev": true, "license": "MIT", "optional": true, @@ -5403,7 +5487,6 @@ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", "dev": true, - "license": "ISC", "engines": { "node": ">=14" }, @@ -5433,10 +5516,13 @@ } }, "node_modules/smob": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/smob/-/smob-1.5.0.tgz", - "integrity": "sha512-g6T+p7QO8npa+/hNx9ohv1E5pVCmWrVCUzUXJyLdMmftX6ER0oiWY/w9knEonLpnOp6b6FenKnMfR8gqwWdwig==", - "dev": true + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/smob/-/smob-1.6.2.tgz", + "integrity": "sha512-RQsvleCbF8cVHEv+xuDGaA4pOizFqJ0GgjtMSRo6oP8pnN7WsigHgVGey6aILRBKv4W2YOMHLqbKdnB6hpB9fw==", + "dev": true, + "engines": { + "node": ">=20.0.0" + } }, "node_modules/source-map": { "version": "0.6.1", @@ -5447,6 +5533,15 @@ "node": ">=0.10.0" } }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -5459,7 +5554,6 @@ "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", "dev": true, - "license": "MIT", "dependencies": { "escape-string-regexp": "^2.0.0" }, @@ -5516,6 +5610,7 @@ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -5552,6 +5647,7 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -5646,13 +5742,13 @@ } }, "node_modules/terser": { - "version": "5.43.1", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.43.1.tgz", - "integrity": "sha512-+6erLbBm0+LROX2sPXlUYx/ux5PyE9K/a92Wrt6oA+WDAoFTdpHE5tCYCI5PNzq2y8df4rA+QgHLJuR4jNymsg==", + "version": "5.47.1", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.47.1.tgz", + "integrity": "sha512-tPbLXTI6ohPASb/1YViL428oEHu6/qv1OxqYnfaonVCFHqx4+wCd95pHrQWsL5X4pl90CTyW9piSAsS2L0VoMw==", "dev": true, "dependencies": { "@jridgewell/source-map": "^0.3.3", - "acorn": "^8.14.0", + "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, @@ -5702,9 +5798,9 @@ "license": "MIT" }, "node_modules/test-exclude/node_modules/brace-expansion": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", - "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -5893,7 +5989,6 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "dev": true, - "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -5919,8 +6014,7 @@ "version": "7.24.6", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", - "dev": true, - "license": "MIT" + "dev": true }, "node_modules/unicode-emoji-modifier-base": { "version": "1.0.0", @@ -5970,9 +6064,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz", - "integrity": "sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", "dev": true, "funding": [ { @@ -6051,6 +6145,7 @@ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -6087,7 +6182,6 @@ "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-5.0.1.tgz", "integrity": "sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==", "dev": true, - "license": "ISC", "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^4.0.1" diff --git a/package.json b/package.json index 4b8f1dc0..771e0534 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adobe/css-tools", - "version": "4.5.0", + "version": "5.0.0", "description": "A modern CSS parser and stringifier with TypeScript support", "source": "src/index.ts", "main": "./dist/cjs/adobe-css-tools.cjs", @@ -29,6 +29,7 @@ "@biomejs/biome": "^2.1.2", "@rollup/plugin-commonjs": "^29.0.0", "@rollup/plugin-node-resolve": "^16.0.1", + "@rollup/plugin-replace": "^6.0.3", "@rollup/plugin-terser": "^1.0.0", "@rollup/plugin-typescript": "^12.1.4", "@types/benchmark": "^2.1.1", @@ -37,6 +38,7 @@ "@types/node": "^25.0.3", "benchmark": "^2.1.4", "bytes": "^3.1.0", + "css-tools-v4": "npm:@adobe/css-tools@4.5.0", "jest": "^30.0.5", "rollup": "^4.45.1", "rollup-plugin-dts": "^6.2.1", @@ -47,6 +49,9 @@ "scripts": { "benchmark": "npm run build && node benchmark/index.mjs", "test": "jest", + "test:compatibility": "jest test/compatibility.test.ts --runInBand", + "test:compatibility:public": "node test/fetch-public-css.mjs && CSS_TOOLS_PUBLIC_CSS=1 npm run test:compatibility", + "test:bundles": "node test/bundle-compatibility.mjs && node test/parser-depth-compatibility.mjs", "clean": "rm -rf ./dist", "build": "rollup -c", "fix": "biome check --write", @@ -55,7 +60,12 @@ "prebuild": "npm run clean", "prepack": "rollup -c", "posttest": "npm run lint", - "postbuild": "tar -czf dist/archive.tgz LICENSE README.md dist/cjs dist/esm dist/umd docs package.json && npx attw --format ascii dist/archive.tgz && rm dist/archive.tgz" + "postbuild": "attw --pack ." + }, + "overrides": { + "@arethetypeswrong/core": { + "fflate": "0.8.2" + } }, "author": "TJ Holowaychuk ", "contributors": [ @@ -79,5 +89,9 @@ "minify", "format", "preprocessor" - ] + ], + "dependencies": { + "postcss": "^8.5.30", + "postcss-safe-parser": "^7.0.1" + } } diff --git a/rollup.config.mjs b/rollup.config.mjs index 7f35150b..2d05ca07 100644 --- a/rollup.config.mjs +++ b/rollup.config.mjs @@ -1,9 +1,14 @@ +import { readFileSync } from 'node:fs'; import commonjs from '@rollup/plugin-commonjs'; import resolve from '@rollup/plugin-node-resolve'; +import replace from '@rollup/plugin-replace'; import terser from '@rollup/plugin-terser'; import typescript from '@rollup/plugin-typescript'; import dts from 'rollup-plugin-dts'; +// Module builds use installed dependencies; UMD remains a standalone browser bundle. +const external = ['postcss', 'postcss-safe-parser']; + // Fix source map paths: tsconfig rootDir:"." causes extra "../" level // ../../../src/ → ../../src/ so paths resolve correctly within the package const fixSourceMapPath = (relativeSourcePath) => @@ -19,10 +24,17 @@ const config = [ sourcemap: true, exports: 'named', sourcemapPathTransform: fixSourceMapPath, + banner: + '/*! @adobe/css-tools | Third-party licenses: adobe-css-tools.LICENSES.txt */', }, plugins: [ - resolve(), + resolve({ browser: true, preferBuiltins: false }), commonjs(), + replace({ + preventAssignment: true, + 'process.env.NODE_ENV': JSON.stringify('production'), + 'process.env.LANG': 'undefined', + }), typescript({ outputToFilesystem: false, compilerOptions: { @@ -30,10 +42,29 @@ const config = [ }, }), terser(), + { + name: 'bundled-license-notices', + generateBundle() { + this.emitFile({ + type: 'asset', + fileName: 'adobe-css-tools.LICENSES.txt', + source: ['postcss', 'postcss-safe-parser', 'nanoid', 'picocolors'] + .map( + (name) => + `${name}\n\n${readFileSync( + new URL(`./node_modules/${name}/LICENSE`, import.meta.url), + 'utf8', + )}`, + ) + .join('\n\n'), + }); + }, + }, ], }, { input: 'src/index.ts', + external, output: [ { name: 'cssTools', @@ -49,12 +80,15 @@ const config = [ commonjs({ transformMixedEsModules: true, }), - typescript(), + typescript({ + outputToFilesystem: false, + }), terser(), ], }, { input: 'src/index.ts', + external, output: [ { name: 'cssTools', diff --git a/src/index.ts b/src/index.ts index ca821e3f..a847ee15 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,5 +4,6 @@ export const parse = parseFn; export const stringify = stringifyFn; export * from './CssParseError'; export * from './CssPosition'; +export type { ParseOptions } from './parse'; export * from './type'; export default { parse, stringify }; diff --git a/src/parse/index.ts b/src/parse/index.ts index 32a3a1ad..2a5af18e 100644 --- a/src/parse/index.ts +++ b/src/parse/index.ts @@ -1,10 +1,11 @@ +import postcss from 'postcss'; +import safeParser from 'postcss-safe-parser'; import CssParseError from '../CssParseError'; import Position from '../CssPosition'; import { type CssAtRuleAST, type CssCharsetAST, type CssCommentAST, - type CssCommonPositionAST, type CssContainerAST, type CssCounterStyleAST, type CssCustomMediaAST, @@ -33,1285 +34,5223 @@ import { type CssViewTransitionAST, } from '../type'; import { - indexOfArrayWithBracketAndQuoteSupport, + indexOfArrayNonEscaped, splitWithBracketAndQuoteSupport, } from '../utils/stringSearch'; -// http://www.w3.org/TR/CSS21/grammar.html -// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027 -// New rule => https://www.w3.org/TR/CSS22/syndata.html#comments -// [^] is equivalent to [.\n\r] const commentRegex = /\/\*[^]*?(?:\*\/|$)/g; +const nonCssWhitespaceRegex = /[^\S\t\n\f\r ]/; +const propertyPrefixRegex = /^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/; +// Sticky forms of V4's property and `:` matches, to read in place. +const propertyRegex = /\*?[-#/*\\\w]+(?:\[[0-9a-z_-]+\])?\s*/y; +const separatorRegex = /:\s*/y; +// Sticky forms of V4's keyframe value and `,` matches. +const keyframeValueRegex = /((?:\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/y; +const keyframeCommaRegex = /,\s*/y; +const atKeywordRegex = /@[-\w]+/y; +const keyframesRegex = /^([-\w]+)?keyframes$/; +const knownAtRuleRegex = + /^(?:import|charset|namespace|media|supports|container|host|font-face|page|property|counter-style|font-feature-values|scope|view-transition|position-try|starting-style)$/; +const DECLARATION_ONLY_AT_RULES = new Set([ + 'font-face', + 'page', + 'property', + 'counter-style', + 'view-transition', + 'position-try', +]); +// V4 reads these at-rules only with a name or prelude after the at-keyword, +// and reads one without as a generic at-rule. +const namedHeaderRegexes = new Map([ + ['property', /@property\s+--[-\w]/y], + ['position-try', /@position-try\s+--[-\w]/y], + ['counter-style', /@counter-style\s+[-\w]/y], + ['font-feature-values', /@font-feature-values\s[^{]/y], + ['import', /@import[^;]/y], + ['charset', /@charset[^;]/y], + ['namespace', /@namespace[^;]/y], +]); +// The prelude of an `@custom-media` V4 reads: a name and a media query. +const customMediaRegex = /^--\S+\s+[^{;\s][^{;]*$/; +const postcssOptions: postcss.ProcessOptions = { map: false }; + +export interface ParseOptions { + source?: string; + silent?: boolean; + stripCommentsInValues?: boolean; +} -export const parse = ( - css: string, - options?: { source?: string; silent?: boolean }, -): CssStylesheetAST => { - options = options || {}; - - /** - * Positional. - */ - let lineno = 1; - let column = 1; - - /** - * Update lineno and column based on `str`. - */ - function updatePosition(str: string) { - const lines = str.match(/\n/g); - if (lines) { - lineno += lines.length; - } - const i = str.lastIndexOf('\n'); - column = ~i ? str.length - i : column + str.length; - } - - /** - * Mark position and patch `node.position`. - */ - function position() { - const start = { line: lineno, column: column }; - return ( - node: Omit, - ): T1 => { - (node as T1).position = new Position( - start, - { line: lineno, column: column }, - options?.source || '', - ); - whitespace(); - return node as T1; - }; - } - - /** - * Error `msg`. - */ - const errorsList: Array = []; - - function error(msg: string): undefined { - const err = new CssParseError( - options?.source || '', - msg, - lineno, - column, - css, - ); +function trim(str: string): string { + return str ? str.trim() : ''; +} - if (options?.silent) { - errorsList.push(err); - } else { - throw err; +// Nodes in `skipped` are passed over together with their descendants. +// `inserted` gives, one at a time, the childless nodes to visit in a +// container before `next`, its node at the walk's index, as if there. +function walkNodes( + root: postcss.Container, + visit: (node: postcss.ChildNode, index: number) => void, + skipped?: ReadonlySet, + inserted?: ( + container: postcss.Container, + next: postcss.ChildNode | undefined, + ) => postcss.ChildNode | undefined, +): void { + const pending: Array<{ + container: postcss.Container; + index: number; + visited?: postcss.ChildNode; + }> = [{ container: root, index: 0 }]; + while (pending.length) { + const frame = pending[pending.length - 1]; + if (frame.visited) { + if (frame.container.nodes?.[frame.index] === frame.visited) frame.index++; + frame.visited = undefined; + continue; } - } - - /** - * Parse stylesheet. - */ - function stylesheet(): CssStylesheetAST { - const rulesList = rules(); - - const result: CssStylesheetAST = { - type: CssTypes.stylesheet, - stylesheet: { - source: options?.source, - rules: rulesList, - parsingErrors: errorsList, - }, - }; - - return result; - } - - /** - * Opening brace. - */ - function open(): boolean { - const openMatch = /^{\s*/.exec(css); - if (openMatch) { - processMatch(openMatch); - return true; + const node = frame.container.nodes?.[frame.index]; + const extra = inserted?.(frame.container, node); + if (extra) { + if (!skipped?.has(extra)) visit(extra, frame.index); + continue; + } + if (!node) { + pending.pop(); + continue; + } + // Descendants can remove this node; advance only after their traversal. + frame.visited = node; + if (skipped?.has(node)) continue; + visit(node, frame.index); + if ((node.type === 'rule' || node.type === 'atrule') && node.nodes) { + pending.push({ container: node, index: 0 }); } - return false; } +} - /** - * Closing brace. - */ - function close() { - const closeMatch = /^}/.exec(css); - if (closeMatch) { - processMatch(closeMatch); - return true; +function prepareCompatibilityInput(css: string): string { + if ( + !css.includes('--') && + !css.includes('@') && + !nonCssWhitespaceRegex.test(css) + ) + return css; + const contexts: Array<{ nesting: boolean; keyframes: boolean }> = []; + let nesting = true; + let keyframes = false; + let parentheses = 0; + let brackets = 0; + let quote = ''; + let start: number | undefined; + let colon = false; + let characters: string[] | undefined; + + // Equal-length masking preserves V4 token boundaries and source offsets. + function mask(from: number, until: number): void { + characters ??= css.split(''); + for (let offset = from; offset < until; offset++) { + if (css[offset] !== '\n' && css[offset] !== '\r') { + characters[offset] = ' '; + } } - return false; } - /** - * Parse ruleset. - */ - function rules() { - let node: CssRuleAST | CssAtRuleAST | undefined; - const rules: Array = []; - whitespace(); - comments(rules); - while (css.length) { - if (css.charAt(0) === '}') { - if (options?.silent) { - // Skip stray closing braces at top level - error("extra '}'"); - const fakeMatch = ['}'] as unknown as RegExpExecArray; - processMatch(fakeMatch); - whitespace(); - comments(rules); - continue; + for (let offset = 0; offset < css.length; offset++) { + const char = css[offset]; + if (char === '\\') { + if (start === undefined) start = offset; + offset++; + continue; + } + if (quote) { + if (char === quote) quote = ''; + continue; + } + if (char === '/' && css[offset + 1] === '*') { + const end = css.indexOf('*/', offset + 2); + if (end === -1) break; + offset = end + 1; + continue; + } + if (start === undefined) { + if (/\s/.test(char)) { + // The leading BOM is handled by the source-offset adjustment below. + if ( + nonCssWhitespaceRegex.test(char) && + (offset !== 0 || char !== '\uFEFF') + ) { + mask(offset, offset + 1); } - break; - } - node = atRule() || rule(); - if (node) { - rules.push(node); - comments(rules); } else { - if (options?.silent) { - // Skip unrecognized character to recover - const fakeMatch = [css.charAt(0)] as unknown as RegExpExecArray; - processMatch(fakeMatch); - whitespace(); - comments(rules); - continue; + start = offset; + colon = false; + // V4 reads whitespace after an at-keyword as whitespace, while + // PostCSS reads non-CSS whitespace there into the at-keyword. + atKeywordRegex.lastIndex = offset; + if (char === '@' && atKeywordRegex.test(css)) { + for ( + let end = atKeywordRegex.lastIndex; + end < css.length && /\s/.test(css[end]); + end++ + ) { + if (nonCssWhitespaceRegex.test(css[end])) mask(end, end + 1); + } } - break; } } - return rules; - } - - /** - * Update position and css string. Return the matches - */ - function processMatch(m: RegExpExecArray) { - const str = m[0]; - updatePosition(str); - css = css.slice(str.length); - return m; - } - - /** - * Parse whitespace. - */ - function whitespace() { - const m = /^\s*/.exec(css); - if (m) { - processMatch(m); + if (char === '"' || char === "'") { + quote = char; + continue; } - } - - /** - * Parse comments; - */ - function comments( - rules?: Array, - ) { - rules = rules || []; - let c: CssCommentAST | undefined = comment(); - while (c) { - rules.push(c); - c = comment(); + if (char === '(') parentheses++; + else if (char === ')') parentheses = Math.max(0, parentheses - 1); + else if (char === '[') brackets++; + else if (char === ']') brackets = Math.max(0, brackets - 1); + if ( + char === ':' && + !parentheses && + start !== undefined && + css[start] !== '@' + ) { + colon = true; } - return rules; - } - - /** - * Parse comment. - */ - function comment(): CssCommentAST | undefined { - const pos = position(); - if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) { - return; + if (!parentheses && char === '{' && colon && !nesting && !keyframes) { + mask(offset, offset + 1); + continue; } - - const m = /^\/\*[^]*?\*\//.exec(css); - if (!m) { - return error('End of comment missing'); + if (parentheses || brackets) continue; + + if (char === '{') { + const header = + start !== undefined && css[start] === '@' + ? css.slice(start, offset) + : undefined; + const name = header && /^@([-\w]+)/.exec(header)?.[1]; + if (nesting && start !== undefined && css.startsWith('--', start)) { + characters ??= css.split(''); + characters[start] = '_'; + characters[start + 1] = '_'; + } + // V4 reads the block of a root keyframes without a name as root text. + const blockKeyframes = + !!header && + !!name && + keyframesRegex.test(name) && + (contexts.length > 0 || + /^\s*[-\w]/.test(header.slice(name.length + 1))); + contexts.push({ nesting, keyframes }); + nesting = + !header || !name + ? nesting && !keyframes + : !blockKeyframes && + !( + DECLARATION_ONLY_AT_RULES.has(name) && + !headerFails(name, header, 0) + ) && + !PAGE_MARGIN_BOX_NAMES.has(name); + keyframes = blockKeyframes; + start = undefined; + } else if (char === '}') { + const context = contexts.pop(); + nesting = context?.nesting ?? true; + keyframes = context?.keyframes ?? false; + start = undefined; + } else if (char === ';') { + start = undefined; } - processMatch(m); - - return pos({ - type: CssTypes.comment, - comment: m[0].slice(2, -2), - }); } + return characters?.join('') ?? css; +} - /** - * Parse selector. - */ - function selector() { - const bracePos = indexOfArrayWithBracketAndQuoteSupport(css, ['{']); - if (bracePos === -1 || bracePos === 0) { - return; +// Splits CSS into top-level rule/at-rule/statement segments for error detection. +// Handles string literals and comments to avoid false boundaries. +function splitTopLevelSegments( + css: string, +): Array<{ text: string; offset: number }> { + const segments: Array<{ text: string; offset: number }> = []; + let depth = 0; + let parentheses = 0; + let brackets = 0; + let start = 0; + let i = 0; + + while (i < css.length) { + const ch = css[i]; + + if (ch === '\\') { + i += 2; + continue; } - const selectorStr = css.substring(0, bracePos); - const fakeMatch = [selectorStr] as unknown as RegExpExecArray; - processMatch(fakeMatch); - - // remove comment in selector; - const res = trim(selectorStr).replace(commentRegex, ''); - return splitWithBracketAndQuoteSupport(res, [',']).map((v) => trim(v)); - } - - /** - * Parse declaration. - */ - function declaration(): CssDeclarationAST | undefined { - const pos = position(); - - // prop - const propMatch = /^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/.exec(css); - if (!propMatch) { - return; + // Skip string literals + if (ch === '"' || ch === "'") { + const quote = ch; + i++; + while (i < css.length && css[i] !== quote) { + if (css[i] === '\\') i++; + i++; + } + i++; + continue; } - processMatch(propMatch); - const propValue = trim(propMatch[0]); - // : - const separatorMatch = /^:\s*/.exec(css); - if (!separatorMatch) { - return error("property missing ':'"); + // Skip block comments + if (ch === '/' && i + 1 < css.length && css[i + 1] === '*') { + i += 2; + while (i < css.length && !(css[i - 1] === '*' && css[i] === '/')) i++; + i++; + continue; } - processMatch(separatorMatch); - // val - let value = ''; - const endValuePosition = indexOfArrayWithBracketAndQuoteSupport(css, [ - ';', - '}', - ]); - if (endValuePosition !== -1) { - value = css.substring(0, endValuePosition); - const fakeMatch = [value] as unknown as RegExpExecArray; - processMatch(fakeMatch); + if (ch === '(') parentheses++; + else if (ch === ')') parentheses = Math.max(0, parentheses - 1); + else if (ch === '[') brackets++; + else if (ch === ']') brackets = Math.max(0, brackets - 1); - value = trim(value).replace(commentRegex, ''); + if (parentheses || brackets) { + i++; + continue; } - const ret = pos({ - type: CssTypes.declaration, - property: propValue.replace(commentRegex, ''), - value: value, - }); - - // ; - const endMatch = /^[;\s]*/.exec(css); - if (endMatch) { - processMatch(endMatch); - } - - return ret; - } - - /** - * Parse declarations (without nesting support). - * Used by @font-face, @page, keyframes. - */ - function declarations() { - const decls: Array = []; - - if (!open()) { - return error("missing '{'"); - } - comments(decls); - - // declarations - let decl: CssDeclarationAST | undefined = declaration(); - while (decl) { - decls.push(decl); - comments(decls); - decl = declaration(); - } - // In silent mode, try to recover from errors by skipping to next semicolon - while (options?.silent && css.length && css.charAt(0) !== '}') { - const semiPos = css.indexOf(';'); - const bracePos = css.indexOf('}'); - if (semiPos !== -1 && (bracePos === -1 || semiPos < bracePos)) { - const fakeMatch = [ - css.substring(0, semiPos + 1), - ] as unknown as RegExpExecArray; - processMatch(fakeMatch); - whitespace(); - comments(decls); - decl = declaration(); - while (decl) { - decls.push(decl); - comments(decls); - decl = declaration(); + if (ch === '{') { + depth++; + } else if (ch === '}') { + if (depth > 0) { + depth--; + if (depth === 0) { + segments.push({ text: css.slice(start, i + 1), offset: start }); + start = i + 1; } } else { - break; + // Orphan close brace + const before = css.slice(start, i); + if (before.trim()) segments.push({ text: before, offset: start }); + segments.push({ text: '}', offset: i }); + start = i + 1; } + } else if (ch === ';' && depth === 0) { + segments.push({ text: css.slice(start, i + 1), offset: start }); + start = i + 1; } - if (!close()) { - return error("missing '}'"); - } - return decls; + i++; } - /** - * Check if the current position looks like a nested rule - * ('{' appears before ';' and '}' at the top level). - */ - function looksLikeNestedRule(): boolean { - const bracePos = indexOfArrayWithBracketAndQuoteSupport(css, ['{']); - if (bracePos === -1) { - return false; - } - const semiPos = indexOfArrayWithBracketAndQuoteSupport(css, [';']); - const closePos = indexOfArrayWithBracketAndQuoteSupport(css, ['}']); + const tail = css.slice(start); + if (tail.trim()) segments.push({ text: tail, offset: start }); - if (semiPos !== -1 && semiPos < bracePos) { - return false; + return segments; +} + +class CompatibilitySource { + private readonly lineStarts = [0]; + private readonly charOffsets = new Map(); + private preludeStops: + | { from: number; until: number; stops: Int32Array } + | undefined; + private selectorStops: Int32Array | undefined; + private valueStops: Int32Array | undefined; + private commentValueStops: Int32Array | undefined; + private ruleStops: Int32Array | undefined; + private statementEnds: Int32Array | undefined; + private readonly contentEnds = new Map(); + // `chainReader` results, with the header each was read from. + readonly chainReaders = new WeakMap< + postcss.AtRule, + { + start: number; + open: number; + name: string; + reader: ChainReader | undefined; } - if (closePos !== -1 && closePos < bracePos) { - return false; + >(); + // Characters the whole-input searches may still scan directly before they + // build their tables. + private scanBudget: number; + // Block at-rule preludes in source order; each ends at the next `{`. + private readonly preludes: Array<{ start: number; end: number }> = []; + // Top-level `}` offsets outside block at-rule preludes. + readonly strayBraces: number[] = []; + // Ascending `{` offsets of root rules without a selector: V4 reports each + // and skips it, then reads the block content as root text. + readonly skippedBraces: number[] = []; + // Skipped braces that V4 instead reads as the opening of a rule after an + // abandoned root block. The input is then parsed again keeping them. + readonly braceConflicts: number[] = []; + // Root keyframes without a name, from their `@` to their `{`: V4 reports + // the name there and reads the rest like a rule without a selector. + readonly namelessKeyframes = new Map(); + // The first stray `}` outside every root node, where V4 stops strict parsing. + orphanBrace: number | undefined; + // PostCSS's unclosed bracket, reported only when nothing else is: V4 reads + // brackets differently, but the input is still invalid. + bracketError: CssParseError | undefined; + // Where V4 reads a rule or an at-rule again after skipping the root text + // after the last root node, which PostCSS reads all as one statement. + rootResume: number | undefined; + // Blocks V4 abandons at an unexpected token. Recovery still reports their + // earlier children, then rules lose their content and at-rules are dropped. + readonly abandoned = new Set(); + // Children of an abandoned root block that V4 reads as root nodes. They + // stay in the block until recovery has visited them. + readonly hoisted = new Set(); + // The missing `}` reported where V4 stops reading an at-rule's body. + readonly closingErrors = new Map(); + + constructor( + readonly css: string, + readonly sourceName: string, + // Braces of root rules without a selector that are not skipped. + readonly keptBraces: ReadonlySet = new Set(), + // The input before any range was blanked to parse it again. + readonly original: string = css, + ) { + this.scanBudget = css.length; + for ( + let offset = css.indexOf('\n'); + offset !== -1; + offset = css.indexOf('\n', offset + 1) + ) { + this.lineStarts.push(offset + 1); } - return true; } - /** - * Parse rule body with CSS nesting support. - * Handles declarations, comments, nested rules, and nested at-rules. - */ - function ruleBody(): - | Array - | undefined { - const items: Array = []; - - if (!open()) { - return error("missing '{'"); - } - comments(items); - - while (css.length && css.charAt(0) !== '}') { - // nested at-rule - if (css.charAt(0) === '@') { - const ar = atRule(); - if (ar) { - items.push(ar); - comments(items); - continue; - } - } - - // nested rule ('{' comes before ';' and '}') - if (looksLikeNestedRule()) { - const nestedR = rule(); - if (nestedR) { - items.push(nestedR); - comments(items); - continue; - } - } - - // declaration - const decl = declaration(); - if (decl) { - items.push(decl); - comments(items); - continue; - } + // Where V4 stops skipping `;` and whitespace from `offset`. A blanked + // range stops it, as V4 reads other text there. + semicolonsEnd(offset: number, until: number): number { + while (offset < until && /[;\s]/.test(this.original[offset])) offset++; + return offset; + } - // nothing matched — skip to next semicolon or closing brace to recover - if (options?.silent) { - const semiPos = css.indexOf(';'); - const bracePos = css.indexOf('}'); - if (semiPos !== -1 && (bracePos === -1 || semiPos < bracePos)) { - const fakeMatch = [ - css.substring(0, semiPos + 1), - ] as unknown as RegExpExecArray; - processMatch(fakeMatch); - whitespace(); - comments(items); - continue; - } - } - break; + // The offset after the last character before `end` that is not + // whitespace. Callers pass ends that are not whitespace themselves, so + // the cached runs are disjoint and the scans linear overall. + contentEnd(end: number): number { + let result = this.contentEnds.get(end); + if (result === undefined) { + result = end; + while (result > 0 && /\s/.test(this.css[result - 1])) result--; + this.contentEnds.set(end, result); } + return result; + } - if (!close()) { - return error("missing '}'"); - } - return items; - } - - /** - * Parse rules, declarations, and nested rules. - * Used by block at-rules (media, supports, etc.) to support - * both top-level rules and declarations when nested inside a rule. - */ - function rulesOrDeclarations() { - const items: Array = []; - whitespace(); - comments(items); - while (css.length && css.charAt(0) !== '}') { - // at-rule - if (css.charAt(0) === '@') { - const ar = atRule(); - if (ar) { - items.push(ar); - comments(items); - continue; - } - } - - // nested rule ('{' comes before ';' and '}') - if (looksLikeNestedRule()) { - const r = rule(); - if (r) { - items.push(r); - comments(items); - continue; - } - } - - // declaration - const decl = declaration(); - if (decl) { - items.push(decl); - comments(items); - continue; - } - - // nothing matched — skip to next semicolon or closing brace to recover - if (options?.silent) { - const semiPos = css.indexOf(';'); - const bracePos = css.indexOf('}'); - if (semiPos !== -1 && (bracePos === -1 || semiPos < bracePos)) { - const fakeMatch = [ - css.substring(0, semiPos + 1), - ] as unknown as RegExpExecArray; - processMatch(fakeMatch); - whitespace(); - comments(items); - continue; - } - } - break; + pointAt(offset: number) { + let low = 0; + let high = this.lineStarts.length; + while (low + 1 < high) { + const middle = (low + high) >>> 1; + if (this.lineStarts[middle] <= offset) low = middle; + else high = middle; } - return items; + return { line: low + 1, column: offset - this.lineStarts[low] + 1 }; } - /** - * Parse keyframe. - */ - function keyframe() { - const vals = []; - const pos = position(); + offsetAt(line: number, column: number): number { + return this.lineStarts[line - 1] + column - 1; + } - let m: RegExpExecArray | null = /^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/.exec( - css, - ); - while (m) { - const res = processMatch(m); - vals.push(res[1]); - const spacesMatch = /^,\s*/.exec(css); - if (spacesMatch) { - processMatch(spacesMatch); + // Offset of the first `char` at or after `offset`, or -1. `char` is a + // character or `*/`, which cannot overlap itself. Each one's offsets are + // listed once, so searches from nested blocks stay linear. + nextIndex(char: string, offset: number): number { + let offsets = this.charOffsets.get(char); + if (!offsets) { + offsets = []; + for ( + let index = this.css.indexOf(char); + index !== -1; + index = this.css.indexOf(char, index + 1) + ) { + offsets.push(index); } - m = /^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/.exec(css); + this.charOffsets.set(char, offsets); } - - if (!vals.length) { - return; + let low = 0; + let high = offsets.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (offsets[middle] < offset) low = middle + 1; + else high = middle; } - - return pos({ - type: CssTypes.keyframe, - values: vals, - declarations: declarations() || [], - }); + return offsets[low] ?? -1; } - /** - * Parse keyframes. - */ - function atKeyframes(): CssKeyframesAST | undefined { - const pos = position(); - const m1 = /^@([-\w]+)?keyframes\s*/.exec(css); - - if (!m1) { - return; - } - const vendor = processMatch(m1)[1]; + // Offset of the first `{` at or after `offset`, or the input length. + nextBrace(offset: number): number { + const brace = this.nextIndex('{', offset); + return brace === -1 ? this.css.length : brace; + } - // identifier - const m2 = /^([-\w]+)\s*/.exec(css); - if (!m2) { - return error('@keyframes missing name'); - } - const name = processMatch(m2)[1]; + // Whether V4 skipped the `{` at `offset` as a root rule without a selector. + skippedBrace(offset: number): boolean { + return this.nextSkippedBrace(offset) === offset; + } - if (!open()) { - return error("@keyframes missing '{'"); + // The first skipped `{` at or after `offset`, or -1. + nextSkippedBrace(offset: number): number { + const braces = this.skippedBraces; + let low = 0; + let high = braces.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (braces[middle] < offset) low = middle + 1; + else high = middle; } + return braces[low] ?? -1; + } - let frames: Array = comments(); - let frame: CssKeyframeAST | undefined = keyframe(); - while (frame) { - frames.push(frame); - frames = frames.concat(comments()); - frame = keyframe(); - } + addPrelude(start: number, end: number): void { + this.preludes.push({ start, end }); + } - if (!close()) { - return error("@keyframes missing '}'"); + // V4's generic at-rule prelude search from `offset`: the first `{` or `;` + // before `until` outside quotes and parentheses, or -1. Searches in one + // range share a table, so a range costs linear time however many search it. + preludeStop(offset: number, until: number): number { + if (offset >= until) return -1; + let table = this.preludeStops; + if (!table || table.until !== until || offset < table.from) { + table = { + from: offset, + until, + stops: preludeStops(this.css, offset, until), + }; + this.preludeStops = table; } + return table.stops[offset - table.from]; + } - return pos({ - type: CssTypes.keyframes, - name: name, - vendor: vendor, - keyframes: frames, - }); + // The whole-input search for `stopChars` from `offset` by a direct scan, + // or undefined once the scans have used up their budget. Valid input then + // builds no table, and the searches stay linear in the input length. + private scanStop(offset: number, stopChars: StopChars): number | undefined { + if (this.scanBudget <= 0) return undefined; + const until = Math.min(this.css.length, offset + this.scanBudget); + const stop = bracketedIndex(this.css, offset, until, stopChars); + this.scanBudget -= (stop === -1 ? until : stop + 1) - offset; + return stop !== -1 || until === this.css.length ? stop : undefined; } - /** - * Parse supports. - */ - function atSupports(): CssSupportsAST | undefined { - const pos = position(); - const m = /^@supports *([^{]+)/.exec(css); + // V4's selector search from `offset`: the first `{` outside quotes and + // parentheses, or -1. + selectorStop(offset: number): number { + if (offset >= this.css.length) return -1; + const stop = this.selectorStops ? undefined : this.scanStop(offset, '{'); + if (stop !== undefined) return stop; + this.selectorStops ??= preludeStops(this.css, 0, this.css.length, '{'); + return this.selectorStops[offset]; + } - if (!m) { - return; - } - const supports = trim(processMatch(m)[1]); + // V4's declaration value search from `offset`: the first `;` or `}` + // outside quotes and parentheses, or -1. + valueStop(offset: number): number { + if (offset >= this.css.length) return -1; + const stop = this.valueStops ? undefined : this.scanStop(offset, ';}'); + if (stop !== undefined) return stop; + this.valueStops ??= preludeStops(this.css, 0, this.css.length, ';}'); + return this.valueStops[offset]; + } - if (!open()) { - return error("@supports missing '{'"); + // The end of `declarationValueEnd(css.slice(offset, until), ...)` in the + // input, or -1: a direct scan while the scan budget lasts, then a table of + // whole-input scans, as a scan that reaches `until` finds no end before it. + valueEnd(offset: number, until: number, preserveComments: boolean): number { + if (offset >= until) return -1; + const stops = preserveComments ? this.commentValueStops : this.valueStops; + if (!stops && this.scanBudget > 0) { + const end = Math.min(until, offset + this.scanBudget); + const stop = declarationValueEnd( + this.css.slice(offset, end), + preserveComments, + ); + this.scanBudget -= stop === -1 ? end - offset : stop + 1; + if (stop !== -1) return offset + stop; + if (end === until) return -1; } - - const style = rulesOrDeclarations(); - - if (!close()) { - return error("@supports missing '}'"); + const { css } = this; + let table: Int32Array; + if (preserveComments) { + this.commentValueStops ??= preludeStops(css, 0, css.length, ';}', true); + table = this.commentValueStops; + } else { + this.valueStops ??= preludeStops(css, 0, css.length, ';}'); + table = this.valueStops; } - - return pos({ - type: CssTypes.supports, - supports: supports, - rules: style, - }); + const stop = table[offset]; + return stop < until ? stop : -1; } - /** - * Parse host. - */ - function atHost() { - const pos = position(); - const m = /^@host\s*/.exec(css); - - if (!m) { - return; - } - processMatch(m); + // V4's check for a nested rule from `offset`: the first `{`, `;` or `}` + // outside quotes and parentheses, or -1. + ruleStop(offset: number): number { + if (offset >= this.css.length) return -1; + const stop = this.ruleStops ? undefined : this.scanStop(offset, '{;}'); + if (stop !== undefined) return stop; + this.ruleStops ??= preludeStops(this.css, 0, this.css.length, '{;}'); + return this.ruleStops[offset]; + } - if (!open()) { - return error("@host missing '{'"); + // `statementEnd(this.css, offset)` by a direct scan while the scan budget + // lasts, then from a table, so many searches stay linear. + statementEnd(offset: number): number { + if (!this.statementEnds && this.scanBudget > 0) { + const until = Math.min(this.css.length, offset + this.scanBudget); + const end = statementEnd(this.css, offset, until); + this.scanBudget -= + (end === undefined || end === -1 ? until : end) - offset; + if (end !== undefined) return end; } + this.statementEnds ??= statementEnds(this.css); + return this.statementEnds[offset]; + } - const style = rulesOrDeclarations(); - - if (!close()) { - return error("@host missing '}'"); + // Whether V4 reads `offset` as block at-rule prelude text. Prelude ends + // never decrease, so only the last prelude starting before it can match. + inPrelude(offset: number): boolean { + let low = 0; + let high = this.preludes.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (this.preludes[middle].start <= offset) low = middle + 1; + else high = middle; } + return low > 0 && offset < this.preludes[low - 1].end; + } - return pos({ - type: CssTypes.host, - rules: style, - }); + error(reason: string, offset: number): CssParseError { + const point = this.pointAt(offset); + // Texts parsed again keep the input length, so errors quote the input + // itself and stay valid as they are in the outer parses. + return new CssParseError( + this.sourceName, + reason, + point.line, + point.column, + this.original.slice(offset), + ); } +} - /** - * Parse container. - */ - function atContainer(): CssContainerAST | undefined { - const pos = position(); - const m = /^@container *([^{]+)/.exec(css); +function declarationValueEnd(value: string, preserveComments: boolean): number { + // V4 scans comment text as value text; the opt-out respects comment boundaries. + let quote = ''; + let parentheses = 0; + for (let offset = 0; offset < value.length; offset++) { + const char = value[offset]; + if (char === '\\') offset++; + else if (quote) { + if (char === quote) quote = ''; + } else if (char === '"' || char === "'") quote = char; + else if (preserveComments && char === '/' && value[offset + 1] === '*') { + const end = value.indexOf('*/', offset + 2); + if (end === -1) return -1; + offset = end + 1; + } else if (char === '(') parentheses++; + else if (char === ')' && parentheses) parentheses--; + else if (!parentheses && (char === ';' || char === '}')) return offset; + } + return -1; +} - if (!m) { - return; - } - const container = trim(processMatch(m)[1]); +function blockPrelude(header: string): RegExpExecArray | null { + return ( + /^@(?:media|supports|container) *([^{]+)/.exec(header) ?? + /^@([-\w]+)?document *([^{]+)/.exec(header) ?? + /^@font-feature-values\s+([^{]+)/.exec(header) ?? + /^@scope\s*([^{]*)/.exec(header) + ); +} - if (!open()) { - return error("@container missing '{'"); - } +// End of `blockPrelude(css.slice(start))`, without scanning to the next `{`. +// Whether it matches depends only on the at-keyword, the whitespace after it +// and the next character; a match always runs up to the next `{` or the end. +function blockPreludeEnd( + source: CompatibilitySource, + start: number, +): number | undefined { + const { css } = source; + if (css[start] !== '@') return undefined; + let end = start + 1; + while (end < css.length && /[-\w]/.test(css[end])) end++; + while (end < css.length && /\s/.test(css[end])) end++; + return blockPrelude(css.slice(start, end + 1)) + ? source.nextBrace(start) + : undefined; +} - const style = rulesOrDeclarations(); +// Whether PostCSS ended a bodiless at-rule at a `}`, which closes its parent +// or is a stray at the root. V4 reads a block prelude on past that `}`. +function endsAtBrace( + node: postcss.AtRule, + css: string, + start: number, +): boolean { + let offset = node.source?.end?.offset ?? start + node.name.length + 1; + while (offset < css.length && /\s/.test(css[offset])) offset++; + return css[offset] === '}'; +} - if (!close()) { - return error("@container missing '}'"); - } +// Where PostCSS ends `node`. It sets no end on an unclosed block, which runs +// to the input end, nor on an at-rule without params or block, which ends at +// its name. +function parsedNodeEnd(node: postcss.ChildNode, css: string): number { + const end = node.source?.end?.offset; + if (end !== undefined) return end; + const start = node.source?.start?.offset; + return node.type === 'atrule' && !node.nodes && start !== undefined + ? start + 1 + node.name.length + : css.length; +} - return pos({ - type: CssTypes.container, - container: container, - rules: style, - }); - } +// End of the names V4 reads for a `@layer` statement from `from`: the first +// `{`, `;` or `@` before `until`, or `until`. Undefined where V4 reads none. +function layerNamesEnd( + css: string, + from: number, + until: number, +): number | undefined { + let end = from; + while ( + end < until && + css[end] !== '{' && + css[end] !== ';' && + css[end] !== '@' + ) + end++; + return end > from ? end : undefined; +} - /** - * Parse container. - */ - function atLayer(): CssLayerAST | undefined { - const pos = position(); - const m = /^@layer *([^{;@]+)/.exec(css); +// V4's `@page` reads its selector up to the next `{` outside quotes and +// parentheses, across `;` and `}`. Returns that `{` when it ends a selector. +function pageSelectorEnd( + source: CompatibilitySource, + start: number, +): number | undefined { + const { css } = source; + if (!css.startsWith('@page', start)) return undefined; + let from = start + 5; + while (css[from] === ' ') from++; + const brace = source.selectorStop(from); + return brace > from ? brace : undefined; +} - if (!m) { - return; - } - const layer = trim(processMatch(m)[1]); +// End of V4's `@import`, `@charset` or `@namespace` statement: past the first +// `;` outside quotes, the input end, or -1 when a quote is left open, as V4's +// regex then fails. Undefined when the scan reaches `until` first. +function statementEnd( + css: string, + start: number, + until = css.length, +): number | undefined { + let quote = ''; + for (let offset = start; offset < until; offset++) { + const char = css[offset]; + if (quote) { + if (char === '\\') offset++; + else if (char === quote) quote = ''; + } else if (char === ';') return offset + 1; + else if (char === '"' || char === "'") quote = char; + } + if (until < css.length) return undefined; + return quote ? -1 : css.length; +} - if (!open()) { - const m2 = /^[;\s]*/.exec(css); - if (m2) { - processMatch(m2); - } - return pos({ - type: CssTypes.layer, - layer: layer, - }); - } +// `statementEnd(css, offset)` for every offset up to the input length, right +// to left: a scan that skips a quoted string goes on as a fresh scan after it. +function statementEnds(css: string): Int32Array { + const ends = new Int32Array(css.length + 1); + ends[css.length] = css.length; + // Closing quote of each kind for a string read from offset + 1 and + // offset + 2, or -1. + let double1 = -1; + let double2 = -1; + let single1 = -1; + let single2 = -1; + for (let offset = css.length - 1; offset >= 0; offset--) { + const char = css[offset]; + const close = char === '"' ? double1 : char === "'" ? single1 : offset; + ends[offset] = + char === ';' ? offset + 1 : close === -1 ? -1 : ends[close + 1]; + [double1, double2] = [ + char === '\\' ? double2 : char === '"' ? offset : double1, + double1, + ]; + [single1, single2] = [ + char === '\\' ? single2 : char === "'" ? offset : single1, + single1, + ]; + } + return ends; +} - const style = rulesOrDeclarations(); +// The characters that end V4's selector, value and statement scans. +type StopChars = '{' | '{;' | ';}' | '{;}'; - if (!close()) { - return error("@layer missing '}'"); - } +// First of `stops` in [from, until) outside quotes and parentheses, as V4's +// selector scan finds it, or -1. +function bracketedIndex( + css: string, + from: number, + until: number, + stops: StopChars, +): number { + const brace = stops !== ';}'; + const semicolon = stops !== '{'; + const close = stops === ';}' || stops === '{;}'; + let quote = ''; + let depth = 0; + for (let offset = from; offset < until; offset++) { + const char = css[offset]; + if (char === '\\') offset++; + else if (quote) { + if (char === quote) quote = ''; + } else if (char === '"' || char === "'") quote = char; + else if (char === '(') depth++; + else if (char === ')') { + if (depth) depth--; + } else if ( + !depth && + (char === '{' ? brace : char === ';' ? semicolon : char === '}' && close) + ) + return offset; + } + return -1; +} - return pos({ - type: CssTypes.layer, - layer: layer, - rules: style, - }); +// `bracketedIndex(css, offset, until, stopChars)` for every offset in +// [from, until), right to left: a search that skips an escape, a quoted +// string or a parenthesized group goes on as a fresh search after it. With +// `comments`, a search also skips comments and fails at an unclosed one, as +// `declarationValueEnd` does when it preserves comments. +function preludeStops( + css: string, + from: number, + until: number, + stopChars: StopChars = '{;', + comments = false, +): Int32Array { + const stops = new Int32Array(until - from); + // First `)` that closes a group opened just before each offset. + const closes = new Int32Array(until - from); + const after = (table: Int32Array, end: number): number => + end === -1 || end + 1 >= until ? -1 : table[end + 1 - from]; + // Next unescaped quote of each kind from offset + 1 and offset + 2. + let double1 = -1; + let double2 = -1; + let single1 = -1; + let single2 = -1; + // Next `*/` from offset + 1 and offset + 2. + let comment1 = -1; + let comment2 = -1; + for (let offset = until - 1; offset >= from; offset--) { + const char = css[offset]; + const pair = offset + 1 < until ? css[offset + 1] : ''; + const end = + char === '\\' + ? offset + 1 + : char === '"' + ? double1 + : char === "'" + ? single1 + : comments && char === '/' && pair === '*' + ? comment2 === -1 + ? -1 + : comment2 + 1 + : char === '(' + ? after(closes, offset) + : offset; + closes[offset - from] = char === ')' ? offset : after(closes, end); + stops[offset - from] = stopChars.includes(char) + ? offset + : after(stops, end); + [double1, double2] = [ + char === '\\' ? double2 : char === '"' ? offset : double1, + double1, + ]; + [single1, single2] = [ + char === '\\' ? single2 : char === "'" ? offset : single1, + single1, + ]; + [comment1, comment2] = [ + char === '*' && pair === '/' ? offset : comment1, + comment1, + ]; } + return stops; +} - /** - * Parse media. - */ - function atMedia(): CssMediaAST | undefined { - const pos = position(); - const m = /^@media *([^{]+)/.exec(css); +function atRuleErrorName(name: string): string { + if (keyframesRegex.test(name)) return 'keyframes'; + if (/^([-\w]+)?document$/.test(name)) return 'document'; + return name; +} - if (!m) { - return; - } - const media = trim(processMatch(m)[1]); +// The `{` of a keyframes block that V4 finds right after the keyword, where +// it reports a missing name and then a missing selector. +function namelessKeyframesOpening( + node: postcss.AtRule, + css: string, +): number | undefined { + const start = node.source?.start?.offset; + if (start === undefined || !node.nodes || !keyframesRegex.test(node.name)) + return undefined; + let open = start + 1 + node.name.length; + while (/\s/.test(css[open] ?? '')) open++; + return css[open] === '{' && blockOpeningOffset(node) === open + ? open + : undefined; +} - if (!open()) { - return error("@media missing '{'"); +// V4 matches a block at-rule without a usable body up to `cursor`, then +// fails with `reason`. +function atRuleMiss( + node: postcss.AtRule, + source: CompatibilitySource, +): { cursor: number; reason: string } | undefined { + const start = node.source?.start?.offset ?? 0; + const header = source.css.slice(start); + let cursor: number | undefined; + let reason = `@${node.name} missing '{'`; + if (keyframesRegex.test(node.name)) { + const keyword = /^@([-\w]+)?keyframes\s*/.exec(header); + const identifier = + keyword && /^([-\w]+)\s*/.exec(header.slice(keyword[0].length)); + if (keyword && !identifier) { + cursor = start + keyword[0].length; + reason = '@keyframes missing name'; + } else if (keyword && identifier && !node.nodes) { + cursor = start + keyword[0].length + identifier[0].length; + reason = "@keyframes missing '{'"; } - - const style = rulesOrDeclarations(); - - if (!close()) { - return error("@media missing '}'"); + } else if (!node.nodes) { + const preludeEnd = blockPreludeEnd(source, start); + const named = + /^@(?:property|position-try)\s+(--[-\w]+)\s*/.exec(header) ?? + /^@counter-style\s+([-\w]+)\s*/.exec(header); + const keyword = + /^(?:host|font-face|view-transition|starting-style)$/.test(node.name) || + PAGE_MARGIN_BOX_NAMES.has(node.name) + ? /^@[-\w]+\s*/.exec(header) + : node.name === 'page' + ? /^@page */.exec(header) + : null; + const matched = named ?? keyword; + cursor = preludeEnd ?? (matched ? start + matched[0].length : undefined); + if (cursor !== undefined && /^([-\w]+)?document$/.test(node.name)) { + reason = "@document missing '{'"; } - - return pos({ - type: CssTypes.media, - media: media, - rules: style, - }); } + return cursor === undefined ? undefined : { cursor, reason }; +} - /** - * Parse custom-media. - */ - function atCustomMedia(): CssCustomMediaAST | undefined { - const pos = position(); - const m = /^@custom-media\s+(--\S+)\s+([^{;\s][^{;]*);/.exec(css); - if (!m) { - return; - } - const res = processMatch(m); - - return pos({ - type: CssTypes.customMedia, - name: trim(res[1]), - media: trim(res[2]), - }); - } +// Whether V4 fails to match the header of the at-rule named `name` at +// `start`, as `@property` without a `--` name, and so reads it as a generic +// at-rule. +function headerFails(name: string, css: string, start: number): boolean { + const header = namedHeaderRegexes.get(name); + if (!header) return false; + header.lastIndex = start; + return !header.test(css); +} - /** - * Parse @page margin box at-rules (@top-left, @bottom-right, @left-middle, etc.). - */ - const pageMarginBoxNames = [ - 'top-left-corner', - 'top-left', - 'top-center', - 'top-right', - 'top-right-corner', - 'bottom-left-corner', - 'bottom-left', - 'bottom-center', - 'bottom-right', - 'bottom-right-corner', - 'left-top', - 'left-middle', - 'left-bottom', - 'right-top', - 'right-middle', - 'right-bottom', - ]; - const pageMarginBoxRegex = new RegExp( - `^@(${pageMarginBoxNames.join('|')})(?![\\w-])\\s*`, +// Whether V4 reads the bodiless `node` as a statement that ends where +// PostCSS ends it, at its `;`. V4 reads other ones on to a `{`, or fails. +function statementLikeV4(node: postcss.AtRule, css: string): boolean { + const start = node.source?.start?.offset; + const end = node.source?.end?.offset; + if (start === undefined || end === undefined || css[end - 1] !== ';') + return false; + const { name } = node; + return ( + /^(?:import|charset|namespace)$/.test(name) || + !( + (knownAtRuleRegex.test(name) && !headerFails(name, css, start)) || + keyframesRegex.test(name) || + /^([-\w]+)?document$/.test(name) || + PAGE_MARGIN_BOX_NAMES.has(name) + ) ); +} - function atPageMarginBox(): CssPageMarginBoxAST | undefined { - const pos = position(); - const m = pageMarginBoxRegex.exec(css); - if (!m) { - return; - } - const name = processMatch(m)[1]; +// V4 matches a fixed header for some block at-rules, as `@font-face` or +// `@keyframes name`. Where text follows it before the `{`, V4 fails at that +// text with `reason`. +function headerMiss( + node: postcss.AtRule, + css: string, +): { cursor: number; reason: string } | undefined { + const start = node.source?.start?.offset; + const open = blockOpeningOffset(node); + if (start === undefined || open === undefined || css[open] !== '{') return; + const { name } = node; + const header = css.slice(start, open); + let reason = `@${name} missing '{'`; + let matched: string | undefined; + if (keyframesRegex.test(name)) { + const keyword = /^@([-\w]+)?keyframes\s*/.exec(header); + if (!keyword) return; + const identifier = /^([-\w]+)\s*/.exec(header.slice(keyword[0].length)); + if (!identifier) reason = '@keyframes missing name'; + else reason = "@keyframes missing '{'"; + matched = keyword[0] + (identifier?.[0] ?? ''); + } else if ( + /^(?:host|font-face|view-transition|starting-style)$/.test(name) || + PAGE_MARGIN_BOX_NAMES.has(name) + ) { + matched = /^@[-\w]+\s*/.exec(header)?.[0]; + } else if (name === 'property' || name === 'position-try') { + matched = /^@[-\w]+\s+--[-\w]+\s*/.exec(header)?.[0]; + } else if (name === 'counter-style') { + matched = /^@counter-style\s+[-\w]+\s*/.exec(header)?.[0]; + } + if (matched === undefined || matched.length >= header.length) return; + return { cursor: start + matched.length, reason }; +} - if (!open()) { - return error(`@${name} missing '{'`); - } - let decls = comments(); - let decl: CssDeclarationAST | undefined = declaration(); - while (decl) { - decls.push(decl); - decls = decls.concat(comments()); - decl = declaration(); - } - if (!close()) { - return error(`@${name} missing '}'`); +// The end of the keyframe selector V4 matches at `offset`, values such as +// `from` or `50%` with `,` and whitespace after each, or -1 where it +// matches none. +function keyframeSelectorEnd(css: string, offset: number): number { + const digitsEnd = (from: number): number => { + while (/\d/.test(css[from] ?? '')) from++; + return from; + }; + let matched = -1; + for (;;) { + let at = offset; + if (/[a-z]/.test(css[at] ?? '')) { + while (/[a-z]/.test(css[at] ?? '')) at++; + } else { + const whole = digitsEnd(at); + if (whole > at && css[whole] === '.' && digitsEnd(whole + 1) > whole + 1) + at = digitsEnd(whole + 1); + else if (whole > at) at = whole; + else if (css[at] === '.' && digitsEnd(at + 1) > at + 1) + at = digitsEnd(at + 1); + else return matched; + if (css[at] === '%') at++; } + while (/\s/.test(css[at] ?? '')) at++; + if (css[at] === ',') at++; + while (/\s/.test(css[at] ?? '')) at++; + matched = offset = at; + } +} - return pos({ - type: CssTypes.pageMarginBox, - name: name, - declarations: decls, - }); +// Whether V4's keyframes reader takes the block at-rule `node` and fails +// where PostCSS reads on: V4 reads only its own header, then keyframes +// with selectors it matches and declarations, between whitespace and +// comments, up to the closing `}`. +function keyframesMiss(node: postcss.AtRule, css: string): boolean { + if (!/^[-\w]*keyframes/.test(node.name)) return false; + const start = node.source?.start?.offset; + const open = blockOpeningOffset(node); + const end = node.source?.end?.offset; + if ( + start === undefined || + open === undefined || + end === undefined || + css[open] !== '{' || + css[end - 1] !== '}' + ) + return true; + const header = css.slice(start, open); + const keyword = /^@([-\w]+)?keyframes\s*/.exec(header); + const identifier = + keyword && /^([-\w]+)\s*/.exec(header.slice(keyword[0].length)); + if (!identifier || keyword[0].length + identifier[0].length < header.length) + return true; + let offset = open + 1; + for (const child of node.nodes ?? []) { + while (/\s/.test(css[offset] ?? '')) offset++; + const childEnd = child.source?.end?.offset; + if (child.source?.start?.offset !== offset || childEnd === undefined) + return true; + if (child.type === 'comment') { + if (childEnd - offset < 4 || !css.startsWith('*/', childEnd - 2)) + return true; + } else if ( + child.type !== 'rule' || + keyframeSelectorEnd(css, offset) !== blockOpeningOffset(child) || + css[childEnd - 1] !== '}' || + child.nodes.some( + (decl) => decl.type !== 'decl' && decl.type !== 'comment', + ) + ) + return true; + offset = childEnd; } + while (/\s/.test(css[offset] ?? '')) offset++; + return offset !== end - 1; +} - /** - * Parse paged media. - */ - function atPage(): CssPageAST | undefined { - const pos = position(); - const m = /^@page */.exec(css); - if (!m) { +// V4 has no at-rule for a name that does not start with `[-\w]`, as in +// `@@media x{}`. It reads such a block at-rule as a rule, and one without a +// block inside a block as text that is not a declaration. After the last +// block V4 finds no `{` for a rule, so it skips one character at a time and +// reads the at-rule that starts at the first `@` followed by `[-\w]`. +function readInvalidAtRules( + root: postcss.Root, + source: CompatibilitySource, +): void { + const { css } = source; + // Every at-rule still starts at an `@` of the input here. + if (!/@(?![-\w])/.test(css)) return; + const invalid = (node: postcss.ChildNode): node is postcss.AtRule => { + const start = node.source?.start?.offset; + return ( + node.type === 'atrule' && + start !== undefined && + !/[-\w]/.test(css[start + 1] ?? '') + ); + }; + const dropped = new Set(); + // Whether V4 reads the block at-rules in each parent as at-rules. Every + // child asks, and the answer reads the parent's whole name and header. + const kept = new Map(); + walkNodes(root, (node, index) => { + const parent = node.parent as postcss.Container | undefined; + if (!invalid(node) || !node.source || !parent?.nodes) return; + if (!node.nodes) { + if (parent.type !== 'root') dropped.add(node); return; } - processMatch(m); - - const sel = selector() || []; - - if (!open()) { - return error("@page missing '{'"); + let keeps = kept.get(parent); + if (keeps === undefined) { + const parentName = + parent.type === 'atrule' ? (parent as postcss.AtRule).name : ''; + keeps = + (DECLARATION_ONLY_AT_RULES.has(parentName) && + !headerFails(parentName, css, parent.source?.start?.offset ?? 0)) || + keyframesRegex.test(parentName) || + PAGE_MARGIN_BOX_NAMES.has(parentName); + kept.set(parent, keeps); } - const decls: Array = []; - comments(decls); - - // declarations and nested at-rules (margin boxes) - while (css.length && css.charAt(0) !== '}') { - if (css.charAt(0) === '@') { - const ar = atRule(); - if (ar) { - decls.push(ar); - comments(decls); - continue; + if (keeps) return; + const start = node.source.start?.offset ?? 0; + const open = blockOpeningOffset(node); + if (open === undefined || css[open] !== '{') return; + const rule = postcss.rule({ + selector: css.slice(start, open), + source: node.source, + }); + rule.raws.before = node.raws.before; + rule.raws.between = ''; + rule.raws.semicolon = node.raws.semicolon; + rule.raws.after = node.raws.after; + const children = node.nodes; + node.nodes = []; + rule.nodes = children; + for (const child of children) child.parent = rule; + parent.nodes[index] = rule; + rule.parent = node.parent; + node.parent = undefined; + }); + const parents = new Set(); + for (const node of dropped) parents.add(node.parent as postcss.Container); + for (const parent of parents) { + const retained = parent.nodes?.filter((node) => !dropped.has(node)) ?? []; + parent.removeAll(); + parent.append(retained); + } + // Where the root node after the one read below starts. + let next = css.length; + for (let index = root.nodes.length - 1; index >= 0; index--) { + const node = root.nodes[index]; + if ((node.type === 'rule' || node.type === 'atrule') && node.nodes) return; + const limit = next; + next = node.source?.start?.offset ?? next; + if (!invalid(node) || !node.source) continue; + const start = node.source.start?.offset ?? 0; + // V4 reads each at-rule once, in order: one from the next root node on is + // read from that node or from the root text between nodes. This also + // keeps the scans disjoint. + const end = Math.min(node.source.end?.offset ?? css.length, limit); + let at = start + 1; + for (let comment = false; at < end; at++) { + if (comment) { + if (css[at] === '*' && css[at + 1] === '/') { + comment = false; + at++; } + } else if (css[at] === '/' && css[at + 1] === '*') { + comment = true; + at++; + } else if (css[at] === '@' && /[-\w]/.test(css[at + 1] ?? '')) { + break; } - const decl = declaration(); - if (decl) { - decls.push(decl); - comments(decls); + } + if (at >= end) continue; + // The at-word PostCSS would read from there. + let wordEnd = at + 1; + while (wordEnd < end && !/[\t\n\f\r "#'()/;[\\\]{}]/.test(css[wordEnd])) + wordEnd++; + node.name = css.slice(at + 1, wordEnd); + node.source.start = { ...source.pointAt(at), offset: at }; + } +} + +// Restore V4 boundaries and raw fields from the unmodified input. +function restoreCompatibilitySpans( + root: postcss.Root, + source: CompatibilitySource, + preserveComments: boolean, +): void { + function restoreContainer(container: postcss.Container): void { + if (!container.nodes) return; + const children = container.nodes; + const retained: postcss.ChildNode[] = []; + let consumedEnd = -1; + let closedAt: number | undefined; + for (const node of children) { + const start = node.source?.start?.offset; + if ( + start !== undefined && + (start < consumedEnd || (closedAt !== undefined && start >= closedAt)) + ) continue; + retained.push(node); + if (node.type !== 'decl' || start === undefined || !node.source) continue; + const property = propertyPrefixRegex.exec(source.css.slice(start)); + if (!property) continue; + const colon = start + property[0].length; + if (source.css[colon] !== ':') continue; + let valueStart = colon + 1; + while (/\s/.test(source.css[valueStart] ?? '')) valueStart++; + const parsedEnd = node.source.end?.offset; + const hasSemicolon = + parsedEnd !== undefined && source.css[parsedEnd - 1] === ';'; + const limit = hasSemicolon + ? parsedEnd + : (container.source?.end?.offset ?? parsedEnd ?? source.css.length); + const valueEnd = source.valueEnd(valueStart, limit, preserveComments); + if (valueEnd === -1) continue; + consumedEnd = valueEnd; + if (node.prop !== property[1]) { + node.prop = property[1]; + node.raws.before = node.raws.before?.replace(/[*_]$/, ''); + node.raws.between = source.css.slice( + start + property[1].length, + valueStart, + ); + } + node.value = trim(source.css.slice(valueStart, consumedEnd)); + node.important = false; + delete node.raws.value; + delete node.raws.important; + node.source.end = { + ...source.pointAt(consumedEnd), + offset: consumedEnd + 1, + }; + if ( + (container.type === 'rule' || container.type === 'atrule') && + container.source && + source.css[consumedEnd] === '}' && + consumedEnd + 1 < (container.source.end?.offset ?? source.css.length) + ) { + closedAt = consumedEnd; + container.source.end = { ...node.source.end }; + container.raws.semicolon = false; } - break; } - - if (!close()) { - return error("@page missing '}'"); + if (retained.length !== children.length) { + container.removeAll(); + container.append(retained); + } + const last = container.last; + if ( + (last?.type === 'rule' || last?.type === 'atrule') && + last.source?.end?.offset !== undefined && + container.type !== 'root' && + container.source + ) { + let cursor = last.source.end.offset; + while (/\s/.test(source.css[cursor] ?? '')) cursor++; + if ( + source.css[cursor] === '}' && + cursor + 1 < (container.source.end?.offset ?? source.css.length) + ) { + container.source.end = { + ...source.pointAt(cursor), + offset: cursor + 1, + }; + } } - - return pos({ - type: CssTypes.page, - selectors: sel, - declarations: decls, - }); } - /** - * Parse document. - */ - function atDocument(): CssDocumentAST | undefined { - const pos = position(); - const m = /^@([-\w]+)?document *([^{]+)/.exec(css); - if (!m) { - return; + const containers: postcss.Container[] = [root]; + // Siblings merged into a preceding bodiless at-rule; removed after the walk. + const merged = new Set(); + const mergedParents = new Set(); + const removeMerged = (parent: postcss.Container): void => { + if (!mergedParents.delete(parent)) return; + const retained = parent.nodes?.filter((node) => !merged.has(node)) ?? []; + parent.removeAll(); + parent.append(retained); + }; + // Containers before this index, except the root, are restored. + let restored = 1; + // Restores the walked subtrees, deepest first, so that root nodes get the + // ends V4 reads before the walk visits the next root node. + const restoreWalked = (): void => { + for (let index = containers.length - 1; index >= restored; index--) { + removeMerged(containers[index]); + restoreContainer(containers[index]); } - const res = processMatch(m); - - const vendor = trim(res[1]); - const doc = trim(res[2]); - - if (!open()) { - return error("@document missing '{'"); + restored = containers.length; + }; + let previousRootNode: postcss.ChildNode | undefined; + // Root text before this offset was read by V4 as a skipped `{`. + let rootFloor = 0; + // Bounds the root nodes moved by unwrapping, keeping the restore linear. + let unwrapBudget = source.css.length; + // End of the last visited child of each container. + const lastEnds = new Map(); + // The last scan of each container's siblings from `from` for the block + // that a bodiless at-rule's prelude up to `cursor` reaches, which ended at + // `stop`. At-rules in a run share their prelude end, so each reuses it. + const preludeScans = new Map< + postcss.Container, + { + siblings: postcss.ChildNode[]; + cursor: number; + from: number; + stop: number; + bodyIndex: number; + consumed: number; } - - const style = rulesOrDeclarations(); - - if (!close()) { - return error("@document missing '}'"); + >(); + // Where V4 reads on after `node`, which ends at `end`. + const readOnFrom = (node: postcss.ChildNode, end: number): number => + node.parent && + skipsSemicolons(node, source.css) && + (node.parent.type === 'root' || readsAtRules(node.parent, source)) + ? source.semicolonsEnd(end, source.css.length) + : end; + // V4 reads text before this offset as `@import`-like statement params. + let statementsEnd = 0; + // Whether V4 reads the statement that set `statementsEnd` as selector text. + let statementsJunk = false; + // A root at-rule failed: V4 then reads a rule up to the next `{`. + let pendingMiss = false; + // Root text that is not a statement: V4 reads a rule up to the next `{`. + let rootJunk = false; + // A root statement ended at `}`: V4 reads its prelude on to a `;` or `{`. + let runOn = false; + // A nested statement ended its block at `}`: V4 blocks no longer align. + let desync = false; + const reached = (parent: postcss.Container, start: number): boolean => + !desync && start >= statementsEnd && !(parent.type === 'root' && runOn); + // The last root node with a block, per root node list. + let lastRootBlock: { nodes: postcss.ChildNode[]; index: number } | undefined; + const rootBlockFollows = (index: number): boolean => { + if (lastRootBlock?.nodes !== root.nodes) { + let at = root.nodes.length - 1; + while ( + at >= 0 && + !( + root.nodes[at].type === 'rule' || + (root.nodes[at].type === 'atrule' && + (root.nodes[at] as postcss.AtRule).nodes) + ) + ) + at--; + lastRootBlock = { nodes: root.nodes, index: at }; } - - return pos({ - type: CssTypes.document, - document: doc, - vendor: vendor, - rules: style, - }); - } - - /** - * Parse font-face. - */ - function atFontFace(): CssFontFaceAST | undefined { - const pos = position(); - const m = /^@font-face\s*/.exec(css); - if (!m) { - return; + return lastRootBlock.index > index; + }; + const formed = new Map(); + // Whether V4 opens this block at the same `{` and parses at-rules in it. + // Every V4 block at-rule reads its body as rules, generic ones included. + const formedLikeV4 = (container: postcss.Container): boolean => { + let result = formed.get(container); + if (result === undefined) { + const start = container.source?.start?.offset; + const open = + container.type === 'rule' || container.type === 'atrule' + ? blockOpeningOffset(container as postcss.Rule | postcss.AtRule) + : undefined; + result = + start !== undefined && + open !== undefined && + (container.type === 'rule' + ? start < open && + bracketedIndex( + source.css, + start, + open + 1, + container.parent?.type === 'root' ? '{' : '{;}', + ) === open + : blockPreludeEnd(source, start) === open || + chainReader(container as postcss.AtRule, source) === 'rules'); + formed.set(container, result); } - processMatch(m); - - if (!open()) { - return error("@font-face missing '{'"); + return result; + }; + // Whether V4 reads this bodiless block at-rule, whose prelude then runs up + // to `cursor`: a `{` at another level or inside a token, or the input end. + const reachesMiss = ( + parent: postcss.Container, + start: number, + cursor: number, + ): boolean => { + const { css } = source; + if (!reached(parent, start)) return false; + const atRoot = parent.type === 'root'; + const open = atRoot + ? -1 + : blockOpeningOffset(parent as postcss.Rule | postcss.AtRule); + if (open === undefined) return false; + const gap = Math.max(lastEnds.get(parent) ?? open + 1, statementsEnd); + if (atRoot) { + if (cursor === css.length) return true; + // Text before the at-rule starts a V4 rule that reads up to the `{`. + if (pendingMiss) return false; + for (let offset = gap; offset < start; offset++) { + if (!/\s/.test(css[offset]) && css[offset] !== '}') return false; + } + return true; } - let decls = comments(); - - // declarations - let decl: CssDeclarationAST | undefined = declaration(); - while (decl) { - decls.push(decl); - decls = decls.concat(comments()); - decl = declaration(); + if (cursor !== css.length) return false; + // Silent V4 skips a `;` after a nested block, except in a `@page` body. + const skipsSemicolon = + readsAtRules(parent, source) && + !(parent.type === 'atrule' && (parent as postcss.AtRule).name === 'page'); + for (let offset = gap; offset < start; offset++) { + if (!/\s/.test(css[offset]) && !(skipsSemicolon && css[offset] === ';')) + return false; } - - if (!close()) { - return error("@font-face missing '}'"); + for ( + let ancestor: postcss.Container | undefined = parent; + ancestor && ancestor.type !== 'root'; + ancestor = ancestor.parent as postcss.Container | undefined + ) { + if (!formedLikeV4(ancestor)) return false; } - - return pos({ - type: CssTypes.fontFace, - declarations: decls, - }); - } - - /** - * Parse @property. - */ - function atProperty(): CssPropertyAST | undefined { - const pos = position(); - const m = /^@property\s+(--[-\w]+)\s*/.exec(css); - if (!m) { + return true; + }; + // Without a `;`, V4 reads a root `@import`, `@charset` or `@namespace` on + // to the next `;` or the input end, so its params also take what PostCSS + // parsed as its block or as following siblings. A node cut after its last + // `;` leaves V4 only `}` to read: each is a stray. Returns false for other + // cuts, unless `lenient`: the node is then cut at `end` all the same, and + // keeps the CSS PostCSS parsed past `end` and a sibling that runs past it. + const consumeStatement = ( + node: postcss.AtRule, + index: number, + start: number, + parsedEnd: number, + end: number, + lenient = false, + ): boolean => { + const { css } = source; + const keywordEnd = start + 1 + node.name.length; + const stop = css[end - 1] === ';' ? end - 1 : end; + if (keywordEnd >= stop || !node.source) return false; + const strays: number[] = []; + const closesAt = (until: number): boolean => { + for (let offset = end; offset < until; offset++) { + if (css[offset] === '}') strays.push(offset); + else if (!/\s/.test(css[offset])) return false; + } + return css[until - 1] === '}'; + }; + // Whether a comment kept in raws runs past `end`: PostCSS has no nodes + // for the CSS that V4 reads after the statement. + const commentStraddles = (from: number): boolean => { + for (let offset = from; offset < end; offset++) { + const char = css[offset]; + if (char === '"' || char === "'") { + for (offset++; offset < end && css[offset] !== char; offset++) { + if (css[offset] === '\\') offset++; + } + } else if (char === '/' && css[offset + 1] === '*') { + offset += 2; + while ( + offset < end - 1 && + !(css[offset] === '*' && css[offset + 1] === '/') + ) + offset++; + if (offset >= end - 1) return true; + offset++; + } + } + return false; + }; + const siblings = root.nodes; + let consumed = index + 1; + if (parsedEnd > end) { + if (!closesAt(parsedEnd)) { + if (!lenient) return false; + strays.length = 0; + } + } else { + let cursor = parsedEnd; + for (; consumed < siblings.length; consumed++) { + const siblingStart = siblings[consumed].source?.start?.offset; + const siblingEnd = parsedNodeEnd(siblings[consumed], css); + if (siblingStart === undefined) { + if (!lenient) return false; + break; + } + if (siblingStart >= end) break; + cursor = siblingEnd; + if (siblingEnd > end) { + if (closesAt(siblingEnd)) consumed++; + else if (!lenient) return false; + else strays.length = 0; + break; + } + } + if (!lenient && commentStraddles(cursor)) return false; + } + if (node.nodes) { + node.removeAll(); + node.nodes = undefined; + } + let paramsStart = keywordEnd; + while (paramsStart < stop && /\s/.test(css[paramsStart])) paramsStart++; + let paramsEnd = stop; + while (paramsEnd > paramsStart && /\s/.test(css[paramsEnd - 1])) + paramsEnd--; + node.raws.afterName = css.slice(keywordEnd, paramsStart); + node.params = css.slice(paramsStart, paramsEnd); + node.raws.between = css.slice(paramsEnd, stop); + delete node.raws.params; + const point = source.pointAt(end); + node.source.end = { + line: point.line, + column: point.column - 1, + offset: end, + }; + for (const sibling of siblings.slice(index + 1, consumed)) { + merged.add(sibling); + } + if (consumed > index + 1) mergedParents.add(root); + // Spread arguments overflow the stack for long brace runs. + for (const stray of strays) source.strayBraces.push(stray); + return true; + }; + // Moves the children of a root rule without a selector to the root, so + // the walk visits them as root nodes. Its `}` is then a stray. + const unwrap = ( + node: postcss.Rule | postcss.AtRule, + index: number, + start: number, + ): boolean => { + const children = node.nodes ?? []; + if (!children.length) { + merged.add(node); + mergedParents.add(root); + } else if (children.length > 1) { + const cost = root.nodes.length + children.length; + if (cost > unwrapBudget) return false; + unwrapBudget -= cost; + root.nodes = root.nodes + .slice(0, index) + .concat(children, root.nodes.slice(index + 1)); + } else { + root.nodes[index] = children[0]; + } + for (const child of children) child.parent = root; + if (children.length) { + node.nodes = []; + node.parent = undefined; + } + const parsedEnd = node.source?.end?.offset; + const end = + parsedEnd === undefined + ? undefined + : parsedEnd - + ((node.type === 'rule' && node.raws.ownSemicolon?.length) || 0); + if (end !== undefined && source.css[end - 1] === '}') { + source.strayBraces.push(end - 1); + } + source.skippedBraces.push(start); + previousRootNode = undefined; + rootFloor = start + 1; + lastEnds.set(root, start + 1); + return true; + }; + const restoreNode = (node: postcss.ChildNode, index: number): void => { + const start = node.source?.start?.offset; + const parsedStatementEnd = node.source?.end?.offset; + let terminated = + parsedStatementEnd !== undefined && + source.css[parsedStatementEnd - 1] === ';'; + if (node.parent === root) { + restoreWalked(); + } + // Other text before a root node starts a V4 rule that reads up to a `{`. + const previousEnd = previousRootNode?.source?.end?.offset; + const gapJunk = + node.parent === root && + start !== undefined && + /[^\s}]/.test( + source.css.slice( + Math.max( + previousRootNode && previousEnd !== undefined + ? readOnFrom(previousRootNode, previousEnd) + : 0, + rootFloor, + statementsEnd, + ), + start, + ), + ); + if ( + node.type === 'rule' && + node.parent === root && + start !== undefined && + source.css[start] === '{' && + !node.selector.trim() && + !source.keptBraces.has(start) && + !gapJunk && + !rootJunk && + !pendingMiss && + reached(root, start) && + unwrap(node, index, start) + ) { return; } - const name = processMatch(m)[1]; - - if (!open()) { - return error("@property missing '{'"); + if ( + node.type === 'atrule' && + node.parent === root && + start !== undefined && + !gapJunk && + !rootJunk && + !pendingMiss && + reached(root, start) + ) { + const open = namelessKeyframesOpening(node, source.css); + if ( + open !== undefined && + !source.keptBraces.has(open) && + unwrap(node, index, open) + ) { + source.namelessKeyframes.set(start, open); + return; + } } - let decls = comments(); - let decl: CssDeclarationAST | undefined = declaration(); - while (decl) { - decls.push(decl); - decls = decls.concat(comments()); - decl = declaration(); + if (node.parent === root) previousRootNode = node; + if (node.type === 'rule' && start !== undefined) { + const selector = node.raws.selector?.raw ?? node.selector; + node.selector = source.css.slice(start, start + selector.length); + delete node.raws.selector; + const suffix = node.raws.ownSemicolon; + const end = node.source?.end?.offset; + if (suffix && end !== undefined && node.source) { + const offset = end - suffix.length; + node.source.end = { + ...source.pointAt(offset - 1), + offset, + }; + delete node.raws.ownSemicolon; + } + } else if (node.type === 'atrule' && start !== undefined && node.source) { + let parsedEnd = node.source.end?.offset; + let semicolon = + parsedEnd !== undefined && source.css[parsedEnd - 1] === ';'; + const parent = node.parent; + const page = + node.name === 'page' && + parent !== undefined && + (parent.type === 'root' || readsAtRules(parent, source)); + const cursor = + !node.nodes && (semicolon || endsAtBrace(node, source.css, start)) + ? (blockPreludeEnd(source, start) ?? + (page ? pageSelectorEnd(source, start) : undefined)) + : undefined; + // V4 reads the prelude up to the next `{`, consuming siblings before it. + let consumedEnd: number | undefined; + if (cursor !== undefined && parent?.nodes) { + const siblings = parent.nodes; + let bodyIndex = -1; + let consumed = index + 1; + const scan = preludeScans.get(parent); + if ( + scan?.siblings === siblings && + scan.cursor === cursor && + scan.from < index && + index < scan.stop + ) { + bodyIndex = scan.bodyIndex; + consumed = Math.max(consumed, scan.consumed); + } else { + let next = index + 1; + for (; next < siblings.length; next++) { + const sibling = siblings[next]; + const siblingStart = sibling.source?.start?.offset; + if (siblingStart === undefined) continue; + if (siblingStart > cursor) break; + if ( + (sibling.type === 'rule' || sibling.type === 'atrule') && + blockOpeningOffset(sibling) === cursor + ) { + bodyIndex = next; + break; + } + if (siblingStart < cursor) consumed = next + 1; + } + preludeScans.set(parent, { + siblings, + cursor, + from: index, + stop: next, + bodyIndex, + consumed, + }); + } + const body = siblings[bodyIndex]; + if (body?.type === 'rule' || body?.type === 'atrule') { + if (reached(parent, start)) source.addPrelude(start, cursor); + const children = [...(body.nodes ?? [])]; + body.removeAll(); + node.nodes = []; + node.append(children); + node.source.end = body.source?.end; + // A rule's end covers a `;` after its `}`, which the block leaves. + const suffix = body.type === 'rule' ? body.raws.ownSemicolon : ''; + const bodyEnd = node.source.end?.offset; + if (suffix && bodyEnd !== undefined) { + const offset = bodyEnd - suffix.length; + node.source.end = { ...source.pointAt(offset - 1), offset }; + } + node.raws.semicolon = body.raws.semicolon; + node.raws.afterName = ''; + node.params = source.css.slice(start + node.name.length + 1, cursor); + node.raws.between = ''; + delete node.raws.params; + for (const sibling of siblings.slice(index + 1, bodyIndex + 1)) { + merged.add(sibling); + } + mergedParents.add(parent); + parsedEnd = node.source.end?.offset; + semicolon = false; + } else if (!page && reachesMiss(parent, start, cursor)) { + source.addPrelude(start, cursor); + consumedEnd = Math.max(parsedEnd ?? cursor, cursor); + for (const sibling of siblings.slice(index + 1, consumed)) { + merged.add(sibling); + consumedEnd = Math.max( + consumedEnd, + sibling.source?.end?.offset ?? consumedEnd, + ); + } + if (consumed > index + 1) mergedParents.add(parent); + // A prelude up to the input end also takes the `}` of each + // ancestor: V4 closes none of them and reads nothing after it. + for ( + let ancestor: postcss.Container = parent; + cursor === source.css.length && ancestor.parent; + ancestor = ancestor.parent as postcss.Container + ) { + if (ancestor.source) delete ancestor.source.end; + const outer = ancestor.parent as postcss.Container; + const following = + outer.nodes?.slice( + outer.index(ancestor as postcss.ChildNode) + 1, + ) ?? []; + for (const sibling of following) merged.add(sibling); + if (following.length) mergedParents.add(outer); + } + } + } + const open = blockOpeningOffset(node); + // An unclosed parent runs to the input end, without a `}`. + const parentClose = node.parent?.source?.end?.offset; + const parentEnd = + node.parent?.type === 'root' || parentClose === undefined + ? source.css.length + : parentClose - 1; + // V4 reads the names of a `@layer` statement on past a `}` that ends + // it here, up to a `{`, `;` or `@`. + const layerNames = + open === undefined && !semicolon && node.name === 'layer' + ? layerNamesEnd(source.css, start + 6, parentEnd) + : undefined; + // Bounded where they would run over the next root node: at their end, + // or at that node where text PostCSS read in this one follows them. + const nextStart = + layerNames !== undefined && parent === root + ? root.nodes[index + 1]?.source?.start?.offset + : undefined; + let layerEnd: number | undefined; + if (layerNames !== undefined && nextStart !== undefined) { + const after = + source.css[layerNames] === ';' ? layerNames + 1 : layerNames; + layerEnd = + after >= nextStart || source.contentEnd(nextStart) <= after + ? layerNames + : nextStart; + } + const end = + open ?? + (semicolon && parsedEnd !== undefined + ? parsedEnd - 1 + : (layerEnd ?? parentEnd)); + let paramsStart = start + node.name.length + 1; + while (paramsStart < end && /\s/.test(source.css[paramsStart])) + paramsStart++; + // Siblings without a block can share `end`, so its trim is cached. + const paramsEnd = + paramsStart < end ? Math.max(paramsStart, source.contentEnd(end)) : end; + node.raws.afterName = source.css.slice( + start + node.name.length + 1, + paramsStart, + ); + node.params = source.css.slice(paramsStart, paramsEnd); + node.raws.between = source.css.slice(paramsEnd, end); + delete node.raws.params; + + if (!node.nodes && !semicolon) { + const name = node.name.endsWith(':') + ? node.name.slice(0, -1) + : node.name; + const known = + (knownAtRuleRegex.test(name) && + !headerFails(name, source.css, start)) || + keyframesRegex.test(node.name) || + /^([-\w]+)?document$/.test(node.name) || + PAGE_MARGIN_BOX_NAMES.has(node.name) || + layerNames !== undefined; + // V4 skips the `;` after the names of a `@layer` statement. + const cursor = !known + ? paramsStart + : end === layerEnd && end === layerNames && source.css[end] === ';' + ? end + 1 + : end; + // Names that end at a `;` or `@` end the statement there, and V4 + // reads the next root node as its own. + if ( + end === layerEnd && + end === layerNames && + (source.css[end] === ';' || source.css[end] === '@') + ) + terminated = true; + if (!known) { + node.params = ''; + node.raws.between = ''; + } + const point = source.pointAt(cursor); + node.source.end = { + line: point.line, + column: point.column - 1, + offset: cursor, + }; + // The root nodes PostCSS parsed inside the names are part of them. + for ( + let next = index + 1; + layerEnd !== undefined && next < root.nodes.length; + next++ + ) { + const sibling = root.nodes[next]; + const siblingStart = sibling.source?.start?.offset; + if ( + siblingStart === undefined || + siblingStart >= cursor || + parsedNodeEnd(sibling, source.css) > cursor + ) + break; + merged.add(sibling); + mergedParents.add(root); + } + } + if (consumedEnd !== undefined && consumedEnd !== parsedEnd) { + node.source.end = { + ...source.pointAt(consumedEnd - 1), + offset: consumedEnd, + }; + } + // The end of the statement V4 reads from `start`, when computed. + let statement: number | undefined; + // Whether V4 reads a statement at `start`, rather than selector text. + const atStatement = + reached(root, start) && !pendingMiss && !rootJunk && !gapJunk; + if ( + start >= statementsEnd && + /^(?:import|charset|namespace)/.test(node.name) + ) { + const end = source.statementEnd(start); + if (end !== -1) statement = end; + if ( + end !== -1 && + !terminated && + /^(?:import|charset|namespace):?$/.test(node.name) && + node.parent === root && + atStatement && + consumeStatement( + node, + index, + start, + parsedStatementEnd ?? source.css.length, + end, + ) + ) { + terminated = true; + } + statementsEnd = end === -1 ? source.css.length : end; + statementsJunk = !atStatement || end === -1; + } + // Bounds a root statement V4 reads differently that runs over the next + // root node, so that each of a run does not take the rest of the + // input: up to its V4 end, else up to the next root node. After text + // that V4 reads as a selector, a later block takes that selector and + // the node is dropped, so the node must not take the block. + const next = root.nodes[index + 1]?.source?.start?.offset; + const nodeEnd = node.source.end?.offset ?? source.css.length; + if ( + !terminated && + !node.nodes && + node.parent === root && + next !== undefined && + next < nodeEnd && + /^(?:import|charset|namespace):?$/.test(node.name) + ) { + if ( + statement !== undefined && + (atStatement || !rootBlockFollows(index)) + ) { + // PostCSS sets no end on an at-rule with only spaces and comments + // as params; the siblings up to the V4 end are then merged. + if (nodeEnd >= statement) + consumeStatement( + node, + index, + start, + parsedStatementEnd ?? start + 1 + node.name.length, + statement, + true, + ); + } else { + let paramsEnd = Math.max(paramsStart, source.contentEnd(next)); + if (paramsEnd > next) paramsEnd = next; + node.params = source.css.slice(paramsStart, paramsEnd); + node.raws.between = source.css.slice(paramsEnd, next); + const point = source.pointAt(next); + node.source.end = { + line: point.line, + column: point.column - 1, + offset: next, + }; + } + } } - if (!close()) { - return error("@property missing '}'"); + if (node.parent === root && start !== undefined) { + const miss = + node.type === 'atrule' && + !node.nodes && + /[-\w]/.test(source.css[start + 1] ?? '') && + blockPreludeEnd(source, start) === undefined + ? atRuleMiss(node, source) + : undefined; + // V4's rule() then fails at a `}` after the miss and skips it. + if ( + miss && + source.css[miss.cursor] === '}' && + reachesMiss(root, start, miss.cursor) + ) { + source.addPrelude(miss.cursor, miss.cursor + 1); + } + if (gapJunk || node.type === 'decl') rootJunk = true; + if ((node.type === 'rule' || node.type === 'atrule') && node.nodes) { + pendingMiss = false; + rootJunk = false; + runOn = false; + // V4 reads a statement it does not match as a selector up to this + // block, then reads the root nodes after the block. + const blockEnd = node.source?.end?.offset; + if ( + statementsJunk && + blockEnd !== undefined && + blockEnd < statementsEnd + ) + statementsEnd = blockEnd; + } else if (node.type === 'atrule' || node.type === 'decl') { + runOn = !terminated && (node.type === 'atrule' || runOn); + } + if (node.type === 'atrule' && !node.nodes) { + if (!/[-\w]/.test(source.css[start + 1] ?? '')) { + // No V4 at-rule matches, so V4 reads it as a rule. + pendingMiss = true; + } else if (miss && source.css[miss.cursor] !== '{') { + pendingMiss = true; + } + } + } else if ( + node.type === 'atrule' && + !node.nodes && + !terminated && + parsedStatementEnd !== undefined && + parsedStatementEnd < source.css.length + ) { + desync = true; } + const end = node.source?.end?.offset; + if (node.parent && end !== undefined) + lastEnds.set(node.parent, readOnFrom(node, end)); + if (node.type === 'rule' || node.type === 'atrule') containers.push(node); + }; + readInvalidAtRules(root, source); + walkNodes(root, restoreNode, merged); + restoreWalked(); + for (const parent of [...mergedParents]) removeMerged(parent); + restoreContainer(root); +} - return pos({ - type: CssTypes.property, - name: name, - declarations: decls, - }); +function commentAt( + root: postcss.Root, + source: CompatibilitySource, + start: number, + end: number, +): postcss.Comment { + const closed = source.css.slice(end - 2, end) === '*/'; + const comment = postcss.comment({ + text: source.css.slice(start + 2, closed ? end - 2 : end), + }); + if (root.source) { + comment.source = { + input: root.source.input, + start: { ...source.pointAt(start), offset: start }, + end: { ...source.pointAt(end - 1), offset: end }, + }; } + return comment; +} - /** - * Parse @counter-style. - */ - function atCounterStyle(): CssCounterStyleAST | undefined { - const pos = position(); - const m = /^@counter-style\s+([-\w]+)\s*/.exec(css); - if (!m) { - return; +// V4's generic at-rule at `start` before `until`, read as a statement up to +// where V4 reads on, or undefined where V4 reads another at-rule. `block` +// where V4 instead reads a block from the `{` ending its prelude. +function genericStatementSpan( + source: CompatibilitySource, + start: number, + until: number, +): + | { + name: string; + afterName: string; + params: string; + end: number; + block: boolean; } - const name = processMatch(m)[1]; + | undefined { + const text = source.css.slice(start, until); + const keyword = /^@([-\w]+)\s*/.exec(text); + const name = keyword?.[1]; + if ( + !keyword || + !name || + (knownAtRuleRegex.test(name) && !headerFails(name, text, 0)) || + name === 'layer' || + name === 'custom-media' || + keyframesRegex.test(name) || + /^([-\w]+)?document$/.test(name) || + PAGE_MARGIN_BOX_NAMES.has(name) + ) + return; + let end = start + keyword[0].length; + // V4 reads the prelude up to a `;`, then skips `;` and whitespace. + const stop = source.preludeStop(end, until); + let params = ''; + if (stop !== -1 && source.css[stop] === ';') { + params = source.css.slice(end, stop); + end = stop; + while (end < until && /[;\s]/.test(source.css[end])) end++; + } + return { + name, + afterName: keyword[0].slice(name.length + 1), + params, + end, + block: stop !== -1 && source.css[stop] === '{', + }; +} - if (!open()) { - return error("@counter-style missing '{'"); - } - let decls = comments(); - let decl: CssDeclarationAST | undefined = declaration(); - while (decl) { - decls.push(decl); - decls = decls.concat(comments()); - decl = declaration(); +function genericStatementAt( + root: postcss.Root, + source: CompatibilitySource, + start: number, + until: number, +): postcss.AtRule | undefined { + const span = genericStatementSpan(source, start, until); + if (!span) return; + const { name, params, end } = span; + const point = source.pointAt(end); + const statement = postcss.atRule({ name, params }); + statement.raws.afterName = span.afterName; + if (root.source) { + statement.source = { + input: root.source.input, + start: { ...source.pointAt(start), offset: start }, + end: { line: point.line, column: point.column - 1, offset: end }, + }; + } + return statement; +} + +function blockOpeningOffset( + node: postcss.Rule | postcss.AtRule, +): number | undefined { + const start = node.source?.start?.offset; + if (start === undefined || !node.nodes) return undefined; + const header = + node.type === 'rule' + ? (node.raws.selector?.raw ?? node.selector) + (node.raws.between ?? '') + : `@${node.name}${node.raws.afterName ?? ''}${ + node.raws.params?.raw ?? node.params + }${node.raws.between ?? ''}`; + return start + header.length; +} + +// The first `{` before `until` outside quotes and parentheses, as V4's +// selector search finds it, or -1. +function selectorOpeningOffset( + css: string, + from: number, + until: number, +): number { + let depth = 0; + for (let offset = from; offset < until; offset++) { + const char = css[offset]; + if (char === '\\') { + offset++; + } else if (char === '"' || char === "'") { + offset++; + while (offset < until && css[offset] !== char) { + offset += css[offset] === '\\' ? 2 : 1; + } + if (offset >= until) return -1; + } else if (char === '(') { + depth++; + } else if (char === ')' && depth) { + depth--; + } else if (char === '{' && !depth) { + return offset; } - if (!close()) { - return error("@counter-style missing '}'"); + } + return -1; +} + +// Where V4's root reading from `from` opens a rule before `until`: after +// whitespace, comments and stray `}`, the first `{` its selector search +// finds. -1 when the reading starts at an at-rule or a `{`, or finds none. +function rootRuleOpening(css: string, from: number, until: number): number { + let offset = from; + while (offset < until) { + if (/\s/.test(css[offset]) || css[offset] === '}') { + offset++; + } else if (css.startsWith('/*', offset)) { + const close = css.slice(offset + 2, until).indexOf('*/'); + if (close === -1) return -1; + offset += close + 4; + } else { + break; } + } + if ( + offset >= until || + css[offset] === '{' || + (css[offset] === '@' && /[-\w]/.test(css[offset + 1] ?? '')) + ) + return -1; + return selectorOpeningOffset(css, offset, until); +} - return pos({ - type: CssTypes.counterStyle, - name: name, - declarations: decls, - }); +function recoveryRule( + node: postcss.Rule | postcss.AtRule, + source: CompatibilitySource, + start: number, + open: number, +): postcss.Rule { + // Move the children rather than clone them, so per-node recovery state + // still applies to them. + const nodes = node.nodes ?? []; + node.removeAll(); + const rule = postcss.rule({ + selector: source.css.slice(start, open), + source: node.source, + }); + rule.append(nodes); + rule.raws.between = ''; + rule.raws.semicolon = node.raws.semicolon; + if (node.source) { + rule.source = { + ...node.source, + start: { ...source.pointAt(start), offset: start }, + }; } + if (source.abandoned.has(node)) source.abandoned.add(rule); + return rule; +} - /** - * Parse @font-feature-values. - */ - function atFontFeatureValues(): CssFontFeatureValuesAST | undefined { - const pos = position(); - const m = /^@font-feature-values\s+([^{]+)/.exec(css); - if (!m) { - return; +// Recovered comments are appended after root's source-ordered nodes. +const recoveredRootComments = new WeakSet(); + +function recoverRootText( + root: postcss.Root, + source: CompatibilitySource, + errors: CssParseError[], + from: number, + until: number, +): void { + const { css } = source; + for (let offset = from; offset < until; offset++) { + if (/\s/.test(css[offset])) continue; + if (css.startsWith('/*', offset)) { + const close = source.nextIndex('*/', offset + 2); + if (close !== -1) { + const comment = commentAt(root, source, offset, close + 2); + recoveredRootComments.add(comment); + root.append(comment); + offset = close + 1; + continue; + } + errors.push(source.error('End of comment missing', offset)); } - const fontFamily = trim(processMatch(m)[1]); + errors.push( + source.error( + css[offset] === '}' ? "extra '}'" : 'selector missing', + offset, + ), + ); + } +} - if (!open()) { - return error("@font-feature-values missing '{'"); +function recoverBodyText( + root: postcss.Root, + source: CompatibilitySource, + errors: CssParseError[], + from: number, + until: number, + preserveComments: boolean, + insert: (declaration: postcss.Declaration) => void, +): void { + const { css } = source; + let cursor = from; + // V4 attempts a declaration after a failed at-rule, even at a comment. + while (cursor < until) { + while (cursor < until && /[;\s]/.test(css[cursor])) cursor++; + if (cursor >= until) break; + const start = cursor; + const property = propertyPrefixRegex.exec(css.slice(cursor, until)); + if (property) { + cursor += property[0].length; + if (css[cursor] === ':') { + cursor++; + while (cursor < until && /\s/.test(css[cursor])) cursor++; + const valueStart = cursor; + const valueEnd = source.valueEnd( + valueStart, + until + Number(css[until] === '}'), + preserveComments, + ); + if (valueEnd !== -1) cursor = valueEnd; + const declaration = postcss.decl({ + prop: property[1], + value: trim(css.slice(valueStart, cursor)), + }); + declaration.raws.between = css.slice( + start + property[1].length, + valueStart, + ); + if (root.source) { + declaration.source = { + input: root.source.input, + start: { ...source.pointAt(start), offset: start }, + end: { ...source.pointAt(cursor), offset: cursor + 1 }, + }; + } + insert(declaration); + continue; + } + errors.push(source.error("property missing ':'", cursor)); } + const semicolon = source.nextIndex(';', cursor); + const close = source.nextIndex('}', cursor); + if ( + semicolon === -1 || + semicolon >= until || + (close !== -1 && close < semicolon) + ) + break; + cursor = semicolon + 1; + } +} - const style = rulesOrDeclarations(); +function startsBlockAtRule(root: postcss.Root, offset: number): boolean { + let found = false; + walkNodes(root, (node) => { + if ( + node.type === 'atrule' && + node.nodes && + node.source?.start?.offset === offset + ) + found = true; + }); + return found; +} - if (!close()) { - return error("@font-feature-values missing '}'"); +function collectCompatibilityErrors( + source: CompatibilitySource, + root: postcss.Root, + silent: boolean, + boundaryCSS: string, + syntaxError?: postcss.CssSyntaxError, + resumable = false, +): CssParseError[] { + const { css } = source; + const errors: CssParseError[] = []; + const segments = splitTopLevelSegments(boundaryCSS).map((segment) => ({ + ...segment, + text: css.slice(segment.offset, segment.offset + segment.text.length), + })); + for (const segment of segments) { + if (segment.text === '}' && !source.inPrelude(segment.offset)) + source.strayBraces.push(segment.offset); + } + if ( + syntaxError && + !syntaxError.reason.startsWith('Unknown word') && + ![ + 'Unexpected }', + 'Unclosed comment', + 'Unclosed string', + 'Unclosed block', + 'Missed semicolon', + 'Double colon', + ].includes(syntaxError.reason) + ) { + const offset = source.offsetAt( + syntaxError.line ?? 1, + syntaxError.column ?? 1, + ); + const segment = segments.find( + (entry) => + offset >= entry.offset && offset < entry.offset + entry.text.length, + ); + if ( + (!segment || !/^\s*@(?:import|charset|namespace)\b/.test(segment.text)) && + // V4 reads `@` without a name as text, unless PostCSS keeps a block + // at-rule for it where V4 rejects the text. + (syntaxError.reason !== 'At-rule without name' || + startsBlockAtRule(root, offset)) + ) { + const error = source.error(syntaxError.reason, offset); + if (syntaxError.reason === 'Unclosed bracket') + source.bracketError = error; + else errors.push(error); } + } - return pos({ - type: CssTypes.fontFeatureValues, - fontFamily: fontFamily, - rules: style, - }); + // PostCSS reads the input after an unclosed bracket as one token, so V4 + // reads its braces in blocks that PostCSS does not have. + const bracketOffset = + syntaxError?.reason === 'Unclosed bracket' + ? source.offsetAt(syntaxError.line ?? 1, syntaxError.column ?? 1) + : css.length; + + // `strays` where V4 skips every character, so reads each `}` as extra. + function recordRootGap(from: number, until: number, strays = false): void { + for (let offset = from; offset < until; offset++) { + const open = source.namelessKeyframes.get(offset); + if (open !== undefined) { + errors.push(source.error('@keyframes missing name', open)); + offset = open - 1; + continue; + } + if (css.startsWith('/*', offset)) { + const close = css.indexOf('*/', offset + 2); + const end = close === -1 ? until : close + 2; + retainedRoots.push(commentAt(root, source, offset, end)); + offset = end - 1; + continue; + } + if (css[offset] === '@') { + const statement = genericStatementAt(root, source, offset, until); + if (statement) { + retainedRoots.push(statement); + offset = statement.source?.end?.offset ?? offset + 1; + offset--; + continue; + } + } + if (css[offset] === '}') { + // V4 skips one character at a time here, even inside a string. + if (!source.inPrelude(offset) && (strays || offset < bracketOffset)) + source.strayBraces.push(offset); + continue; + } + if (!/\s/.test(css[offset])) { + errors.push(source.error('selector missing', offset)); + if (!silent) return; + } + } } - /** - * Parse @scope. - */ - function atScope(): CssScopeAST | undefined { - const pos = position(); - const m = /^@scope\s*([^{]*)/.exec(css); - if (!m) { + const retainedRoots: postcss.ChildNode[] = []; + let remainingBlocks = root.nodes.filter( + (node) => node.type === 'rule' || (node.type === 'atrule' && node.nodes), + ).length; + let cursor = 0; + let skippedIndex = 0; + for (let node of root.nodes) { + if (node.type === 'decl') continue; + const start = node.source?.start?.offset; + if (start === undefined) { + retainedRoots.push(node); + continue; + } + // No V4 at-rule matches this name, so V4 reads it as rule text. + if ( + node.type === 'atrule' && + !node.nodes && + !/[-\w]/.test(css[start + 1] ?? '') + ) + continue; + const open = + node.type === 'rule' || node.type === 'atrule' + ? blockOpeningOffset(node) + : undefined; + if (open !== undefined) remainingBlocks--; + while (cursor < start) { + while (source.skippedBraces[skippedIndex] < cursor) skippedIndex++; + const keyframesOpen = source.namelessKeyframes.get(cursor); + if (keyframesOpen !== undefined) { + errors.push(source.error('@keyframes missing name', keyframesOpen)); + cursor = keyframesOpen; + continue; + } + if (source.skippedBraces[skippedIndex] === cursor) { + errors.push(source.error('selector missing', cursor)); + } else if (!/\s/.test(css[cursor]) && css[cursor] !== '}') break; + cursor++; + } + if (cursor < start && remainingBlocks && open === undefined) continue; + if (cursor < start && open !== undefined && css[open] === '{') { + const selector = css.slice(cursor, open); + if (node.type === 'rule') { + node.selector = selector; + node.raws.between = ''; + delete node.raws.selector; + } else if (node.type === 'atrule') { + node = postcss.rule({ + selector, + source: node.source, + nodes: node.nodes, + }); + } + if (node.source) { + node.source.start = { ...source.pointAt(cursor), offset: cursor }; + } + } else { + recordRootGap(cursor, start); + } + retainedRoots.push(node); + cursor = node.source?.end?.offset ?? css.length; + if (skipsSemicolons(node, css)) + cursor = source.semicolonsEnd(cursor, css.length); + } + // V4 skips the text after the last root node one character at a time up + // to where it reads a rule or an at-rule. PostCSS reads that text as one + // statement after an unclosed bracket or string, so the input is then + // parsed again from there. Statements of unknown at-rules on the way stay + // as read here, as PostCSS reads their at-words on past V4's names. + let resume = css.length; + let skips = false; + for (let at = cursor; silent && at < css.length; at++) { + if (css.startsWith('/*', at)) { + const close = css.indexOf('*/', at + 2); + if (close === -1) break; + at = close + 1; + } else if (css[at] === '@' && /[-\w]/.test(css[at + 1] ?? '')) { + const statement = genericStatementSpan(source, at, css.length); + if (!statement || statement.block) { + resume = at; + break; + } + at = statement.end - 1; + } else if (!/\s/.test(css[at])) { + if (css[at] !== '}' && source.selectorStop(at) > at) { + resume = at; + break; + } + skips = true; + } + } + if (!skips) recordRootGap(cursor, css.length); + else { + recordRootGap(cursor, resume, true); + if (resume < css.length && resumable) source.rootResume = resume; + else recordRootGap(resume, css.length); + } + if ( + retainedRoots.length !== root.nodes.length || + retainedRoots.some((node, index) => node !== root.nodes[index]) + ) { + root.removeAll(); + root.append(retainedRoots); + } + + // Root comments V4 reads inside a selector; removed once the walk ends. + const droppedRoots = new Set(); + walkNodes(root, (container, index) => { + if ( + (container.type !== 'rule' && container.type !== 'atrule') || + !container.nodes + ) return; + const open = blockOpeningOffset(container); + if (open === undefined || css[open] !== '{') return; + const end = container.source?.end?.offset ?? css.length; + const limit = css[end - 1] === '}' ? end - 1 : end; + const children = container.nodes; + const retained: postcss.ChildNode[] = []; + + function stopAt(offset: number): void { + if (container.type === 'atrule') { + const error = source.error( + `@${atRuleErrorName(container.name)} missing '}'`, + offset, + ); + source.closingErrors.set(container, error); + errors.push(error); + } else { + errors.push(source.error("missing '}'", offset)); + } + if (container.type === 'rule' || container.type === 'atrule') + source.abandoned.add(container); + if (container.source) { + const point = source.pointAt(offset); + container.source.end = { + line: point.line, + column: point.column - 1, + offset, + }; + } + if (silent) { + const siblings = + (container.parent?.type === 'root' && container.parent.nodes) || []; + let from = offset; + if (siblings.length) { + from = hoistAbandonedChildren(offset); + if (from >= limit) { + // V4 reports the block's own `}` as extra. + if (css[limit] === '}') source.strayBraces.push(limit); + return; + } + } + // V4 reads the text up to the next `{` as a selector, comments + // included. + let nextIndex = index + 1; + while ( + siblings[nextIndex]?.type === 'comment' && + !recoveredRootComments.has(siblings[nextIndex]) + ) + nextIndex++; + const next = siblings[nextIndex]; + if (siblings.length) { + // V4 reads up to a `{` that was skipped as a root rule without a + // selector. That rule would be `next` when kept. + const brace = source.nextSkippedBrace(from); + if ( + brace !== -1 && + (next?.source?.start?.offset ?? css.length) > brace && + rootRuleOpening(css, from, brace + 1) === brace + ) + source.braceConflicts.push(brace); + } + const nextOpen = + next?.type === 'rule' ? blockOpeningOffset(next) : undefined; + // An unclosed quote or parenthesis hides every later `{` from V4. + // An earlier `{` that PostCSS reads inside a value or comment is + // approximated by the next rule's, but not a skipped block's. + const selectorOpen = + nextOpen === undefined + ? -1 + : selectorOpeningOffset(css, from, nextOpen + 1); + if ( + nextOpen !== undefined && + next?.type === 'rule' && + next.source && + selectorOpen !== -1 && + (selectorOpen === nextOpen || !source.skippedBrace(selectorOpen)) + ) { + for (const comment of siblings.slice(index + 1, nextIndex)) + droppedRoots.add(comment); + next.selector = css.slice(from, nextOpen); + next.raws.between = ''; + delete next.raws.selector; + next.source.start = { ...source.pointAt(from), offset: from }; + return; + } + recoverRootText(root, source, errors, from, end); + } } - const scope = trim(processMatch(m)[1]); - if (!open()) { - return error("@scope missing '{'"); + // Moves the block children that V4 reads as root rules after `offset` + // and returns where V4's root reading continues. + function hoistAbandonedChildren(offset: number): number { + let from = offset; + let childIndex = 0; + while (from < limit && css[from] !== '@') { + while ( + childIndex < children.length && + (children[childIndex].source?.start?.offset ?? -1) < from + ) + childIndex++; + let block: postcss.Rule | postcss.AtRule | undefined; + let blockIndex = childIndex; + for (; blockIndex < children.length; blockIndex++) { + const child = children[blockIndex]; + if ( + (child.type === 'rule' || child.type === 'atrule') && + child.nodes + ) { + block = child; + break; + } + } + const blockOpen = block && blockOpeningOffset(block); + if ( + !block || + blockOpen === undefined || + blockOpen === from || + css[blockOpen] !== '{' || + selectorOpeningOffset(css, from, blockOpen + 1) !== blockOpen + ) + break; + let rule: postcss.Rule; + if (block.type === 'rule') { + rule = block; + rule.selector = css.slice(from, blockOpen); + rule.raws.between = ''; + delete rule.raws.selector; + if (rule.source) + rule.source.start = { ...source.pointAt(from), offset: from }; + } else { + rule = recoveryRule(block, source, from, blockOpen); + } + retained.push(rule); + source.hoisted.add(rule); + from = Math.min(block.source?.end?.offset ?? limit, limit); + childIndex = blockIndex + 1; + // V4 keeps the comments that follow a rule. + for (;;) { + while (from < limit && /\s/.test(css[from])) from++; + const comment = children[childIndex]; + if ( + comment?.type !== 'comment' || + comment.source?.start?.offset !== from + ) + break; + retained.push(comment); + source.hoisted.add(comment); + from = comment.source?.end?.offset ?? limit; + childIndex++; + } + } + return from; } - const style = rulesOrDeclarations(); + function scanGap(cursor: number, until: number): number { + while (cursor < until) { + while (cursor < until && /\s/.test(css[cursor])) cursor++; + if (cursor >= until) break; + if (css.startsWith('/*', cursor)) { + const close = source.nextIndex('*/', cursor + 2); + if (close !== -1 && close + 2 <= until) { + retained.push(commentAt(root, source, cursor, close + 2)); + cursor = close + 2; + continue; + } + } + if (css[cursor] === '@') { + const statement = genericStatementAt(root, source, cursor, until); + if (statement) { + retained.push(statement); + cursor = statement.source?.end?.offset ?? cursor + 1; + continue; + } + } + const property = propertyPrefixRegex.exec(css.slice(cursor)); + if (property && css[cursor + property[0].length] === ':') break; + if (property) { + cursor += property[0].length; + errors.push(source.error("property missing ':'", cursor)); + if (cursor >= limit) break; + } else if (!silent) { + stopAt(cursor); + return limit; + } + const close = source.nextIndex('}', cursor); + const recoveryEnd = close === -1 ? limit : Math.min(close, limit); + const semicolon = source.nextIndex(';', cursor); + if (semicolon !== -1 && semicolon < recoveryEnd) { + cursor = semicolon + 1; + } else { + stopAt(cursor); + return limit; + } + } + return cursor; + } - if (!close()) { - return error("@scope missing '}'"); + let cursor = open + 1; + const atRules = readsAtRules(container, source); + for (const child of children) { + const childStart = child.source?.start?.offset; + if (childStart === undefined) { + retained.push(child); + continue; + } + cursor = scanGap(cursor, childStart); + if (child.type === 'decl' && cursor <= childStart) { + cursor = scanGap( + childStart, + Math.min(child.source?.end?.offset ?? limit, limit), + ); + } + if (childStart < cursor) continue; + retained.push(child); + cursor = Math.min(child.source?.end?.offset ?? limit, limit); + if (atRules && skipsSemicolons(child, css)) + cursor = source.semicolonsEnd(cursor, limit); + while ( + cursor < limit && + (/\s/.test(css[cursor]) || + (child.type === 'decl' && css[cursor] === ';')) + ) + cursor++; + } + if (container.type === 'atrule' && keyframesRegex.test(container.name)) { + // V4 accepts whitespace in empty keyframes, e.g. `@keyframes x { }`. + while (cursor < limit && /\s/.test(css[cursor])) cursor++; + if (cursor < limit) { + stopAt(cursor); + cursor = limit; + } + } + scanGap(cursor, limit); + if ( + retained.length !== children.length || + retained.some((child, childIndex) => child !== children[childIndex]) + ) { + container.removeAll(); + container.append(retained); } + }); + if (droppedRoots.size) { + const live = root.nodes.filter((node) => !droppedRoots.has(node)); + root.removeAll(); + root.append(live); + } + return errors; +} - return pos({ - type: CssTypes.scope, - scope: scope, - rules: style, - }); +// How V4 reads the body of a block: as rules and declarations, skipping to +// the next `;` in silent mode, or as declarations only. +type ChainReader = 'rules' | 'declarations'; + +// Where V4 fails to read a nested rule: one without a selector (`empty`) or +// text that is neither a rule nor a declaration (`text`). V4 closes every +// enclosing block there with an error, unless it skips to a `;`, and reads +// on at the root. Where a root rule opens a quote that never closes before +// its `{` (`quote`), V4 skips one character at a time up to the quote. +// Where V4 stops reading a block one declaration at a time before its `}` +// (`declarations`), it drops the block and reads on in the enclosing body. +// Where V4 fails to open an at-rule without a block at the end of a body +// read as rules (`miss`), it reads the rest as declarations, fails to close +// the body and reads on after it. +// Where V4 finds no end for a declaration value in a body read as rules +// (`value`), it reads the value as empty and fails to read the value text +// as a declaration: it skips to a `;`, closes the body at a `}`, or closes +// every enclosing block there and reads on at the root. +interface ChainBreak { + kind: + | 'empty' + | 'text' + | 'quote' + | 'declarations' + | 'miss' + | 'value' + | 'header'; + offset: number; + // The unclosed quote of a `quote` break. + quote: number; + // Whether a `declarations` break follows a property without `:`. + colon: boolean; + // Enclosing blocks, innermost first; for a `declarations` break, the + // dropped block first. + levels: Array<{ node: postcss.Rule | postcss.AtRule; reader: ChainReader }>; + // For a `miss` break, the at-rule's start and the errors V4 reports from + // there up to the break. + miss?: { start: number; errors: CssParseError[] }; + // For a `value` break, the declaration's and the value's start, and the + // end of the text V4 skips where it reads on in the same body, or -1. + value?: { start: number; valueStart: number; end: number }; + // For a `header` break, the at-rule's start and the error V4 reports + // where its header ends. + header?: { start: number; reason: string }; +} + +// `ChainBreak['levels']` from a block out, shared with the blocks inside it, +// and whether the scan cannot follow one of its blocks. +interface ChainLink { + node: postcss.Rule | postcss.AtRule; + reader: ChainReader; + outer: ChainLink | undefined; + unread: boolean; +} + +const blockReaderNames = + /^(?:media|supports|container|font-feature-values|scope|layer|host|starting-style)$/; +const declarationReaderNames = + /^(?:font-face|view-transition|page|property|position-try|counter-style)$/; +// Names V4 matches as a prefix, reading the rest as the prelude. +const prefixedAtRuleRegex = + /^(?:media|supports|import|charset|namespace|page|host|font-face|container|starting-style|layer|scope|view-transition)|keyframes|document/; + +// V4's reader for the body of `node`, or undefined where V4 matches its +// header otherwise. Every node in a block asks for the block's reader, so it +// is cached with the header it was read from. +function chainReader( + node: postcss.Rule | postcss.AtRule, + source: CompatibilitySource, +): ChainReader | undefined { + if (node.type === 'rule') return 'rules'; + const start = node.source?.start?.offset; + const open = blockOpeningOffset(node); + if (start === undefined || open === undefined) return undefined; + const { name } = node; + const cached = source.chainReaders.get(node); + if (cached?.start === start && cached.open === open && cached.name === name) + return cached.reader; + const reader = headerReader(name, source.css, start, open); + source.chainReaders.set(node, { start, open, name, reader }); + return reader; +} + +// V4's reader for the body of the at-rule named `name` at `start`, whose +// block PostCSS opens at `open`. +function headerReader( + name: string, + css: string, + start: number, + open: number, +): ChainReader | undefined { + if (css[open] !== '{') return undefined; + const preludeStart = start + 1 + name.length; + if (preludeStart > open) return undefined; + const prelude = css.slice(preludeStart, open); + if (prelude.includes('{')) return undefined; + const empty = !prelude.trim(); + if (genericAtRule(name, css, start)) + return bracketedIndex(css, preludeStart, open + 1, '{;') === open + ? 'rules' + : undefined; + if (PAGE_MARGIN_BOX_NAMES.has(name)) + return empty ? 'declarations' : undefined; + if (declarationReaderNames.test(name)) { + const matches = + (name === 'page' && + bracketedIndex(css, preludeStart, open + 1, '{') === open) || + ((name === 'font-face' || name === 'view-transition') && empty) || + ((name === 'property' || name === 'position-try') && + /^\s+--[-\w]+\s*$/.test(prelude)) || + (name === 'counter-style' && /^\s+[-\w]+\s*$/.test(prelude)); + return matches ? 'declarations' : undefined; } + if (blockReaderNames.test(name)) { + if ((name === 'host' || name === 'starting-style') && !empty) + return undefined; + if (name === 'layer' && /[;@]/.test(prelude)) return undefined; + return 'rules'; + } + if (/^([-\w]+)?document$/.test(name)) return prelude ? 'rules' : undefined; + return undefined; +} - /** - * Parse @view-transition. - */ - function atViewTransition(): CssViewTransitionAST | undefined { - const pos = position(); - const m = /^@view-transition\s*/.exec(css); - if (!m) { - return; - } - processMatch(m); +// Whether `node` is a keyframes at-rule. Every node in a block asks this of +// the block, so the answer is cached with the name it was read from. +const keyframesAtRules = new WeakMap< + postcss.Node, + { name: string; keyframes: boolean } +>(); +function keyframesAtRule(node: postcss.Node | undefined): boolean { + if (node?.type !== 'atrule') return false; + const { name } = node as postcss.AtRule; + let cached = keyframesAtRules.get(node); + if (cached?.name !== name) { + cached = { name, keyframes: keyframesRegex.test(name) }; + keyframesAtRules.set(node, cached); + } + return cached.keyframes; +} - if (!open()) { - return error("@view-transition missing '{'"); +// Whether V4 reads at-rules in the body of `container`. +function readsAtRules( + container: postcss.Container, + source: CompatibilitySource, +): boolean { + if (container.type === 'rule') return !keyframesAtRule(container.parent); + if (container.type !== 'atrule') return false; + const reader = chainReader(container as postcss.AtRule, source); + return ( + reader === 'rules' || + (reader === 'declarations' && (container as postcss.AtRule).name === 'page') + ); +} + +// Whether V4 reads an at-rule named `name` only as a generic one. +function genericAtRuleName(name: string): boolean { + return ( + /^[-\w]+$/.test(name) && + !prefixedAtRuleRegex.test(name) && + !blockReaderNames.test(name) && + !declarationReaderNames.test(name) && + !PAGE_MARGIN_BOX_NAMES.has(name) && + name !== 'custom-media' + ); +} + +// Whether V4 reads the at-rule named `name` at `start` as a generic one. +function genericAtRule(name: string, css: string, start: number): boolean { + return genericAtRuleName(name) || headerFails(name, css, start); +} + +const atNameRegex = /@([-\w]+)/y; + +// Whether V4 reads `node` as a generic or `@layer` statement, after which it +// skips every `;` and whitespace. +function skipsSemicolons(node: postcss.ChildNode, css: string): boolean { + if (node.type !== 'atrule' || node.nodes) return false; + const start = node.source?.start?.offset; + const end = node.source?.end?.offset; + if (start === undefined || end === undefined || css[end - 1] !== ';') + return false; + atNameRegex.lastIndex = start; + const name = atNameRegex.exec(css)?.[1]; + return ( + name !== undefined && + (genericAtRule(name, css, start) || + (name === 'custom-media' && + !customMediaRegex.test(atRuleHeader(node).params)) || + (/^layer/.test(name) && !/keyframes|document/.test(name))) + ); +} + +// Whether V4, trying the remaining at-rules at `offset` once `node` fails +// there, reads what it reads when it starts there: no at-rule it tries +// before `node`'s matches the name at `offset`. +function rereadsAtRule( + css: string, + offset: number, + node: postcss.AtRule, +): boolean { + atNameRegex.lastIndex = offset; + const name = atNameRegex.exec(css)?.[1]; + return ( + name === undefined || + genericAtRule(name, css, offset) || + (PAGE_MARGIN_BOX_NAMES.has(name) && !PAGE_MARGIN_BOX_NAMES.has(node.name)) + ); +} + +interface DeclarationBreak { + node: postcss.AtRule; + offset: number; + // Whether V4 finds no `:` after a property there. + colon: boolean; +} + +// Where V4 stops reading the body of `node`, a block read one declaration +// at a time (`@page` reads at-rules too), before PostCSS's `}`: V4 drops +// the block there and reads on in the enclosing body. Returns the innermost +// such block, undefined where V4 reads the body as PostCSS does, and null +// where V4 reads it in a way this does not follow. Blocks found to be read +// as PostCSS does are added to `read`. +function declarationBreak( + node: postcss.AtRule, + source: CompatibilitySource, + read: Set, +): DeclarationBreak | null | undefined { + if (read.has(node)) return undefined; + const { css } = source; + const open = blockOpeningOffset(node); + if (open === undefined || css[open] !== '{') return null; + const end = node.source?.end?.offset; + // Recovery abandons a block where V4 stops reading a rule body, which is + // where V4 stops reading a declaration block or after. + const abandoned = source.abandoned.has(node) ? end : undefined; + // PostCSS's `}`, or the end of the input where it is unknown or missing. + const close = + end === undefined || abandoned !== undefined ? css.length : end - 1; + if (close < css.length && css[close] !== '}') return null; + const found = (offset: number, colon: boolean) => + abandoned === undefined || offset <= abandoned + ? { node, offset, colon } + : null; + const closed = (offset: number) => { + if (offset !== close || abandoned !== undefined) return null; + read.add(node); + return undefined; + }; + const children = node.nodes ?? []; + let childIndex = 0; + let cursor = open + 1; + for (;;) { + // V4 skips whitespace and comments between declarations. + for (;;) { + while (cursor < css.length && /\s/.test(css[cursor])) cursor++; + if (!css.startsWith('/*', cursor)) break; + const comment = css.indexOf('*/', cursor + 2); + if (comment === -1) return null; + cursor = comment + 2; } - let decls = comments(); - let decl: CssDeclarationAST | undefined = declaration(); - while (decl) { - decls.push(decl); - decls = decls.concat(comments()); - decl = declaration(); + if (cursor >= close) return closed(cursor); + if (css[cursor] === '}') return null; + if (css[cursor] === '@') { + // Elsewhere, V4 tries the remaining at-rules there. + if (node.name !== 'page') + return rereadsAtRule(css, cursor, node) ? found(cursor, false) : null; + while ( + childIndex < children.length && + (children[childIndex].source?.start?.offset ?? -1) < cursor + ) + childIndex++; + const child = children[childIndex]; + const childEnd = child?.source?.end?.offset; + if ( + child?.type !== 'atrule' || + child.source?.start?.offset !== cursor || + childEnd === undefined + ) + return null; + if (child.nodes) { + if (chainReader(child, source) !== 'declarations') return null; + const inner = declarationBreak(child, source, read); + if (inner !== undefined) return inner; + cursor = childEnd; + continue; + } + if ( + !genericAtRule(child.name, css, cursor) || + bracketedIndex(css, cursor + 1 + child.name.length, childEnd, '{;') !== + childEnd - 1 + ) + return null; + // V4 skips every `;` and whitespace after a generic statement. + cursor = source.semicolonsEnd(childEnd, css.length); + continue; } - if (!close()) { - return error("@view-transition missing '}'"); + propertyRegex.lastIndex = cursor; + if (!propertyRegex.test(css)) return found(cursor, false); + cursor = propertyRegex.lastIndex; + if (css[cursor] !== ':') { + // V4 closes the block at a `}` after the missing `:`. + if (cursor >= close) return closed(cursor); + // V4 tries the remaining at-rules at a `@`, and reads a comment as + // part of a selector. + if ( + css[cursor] === '}' || + (css[cursor] === '@' && !rereadsAtRule(css, cursor, node)) || + css.startsWith('/*', cursor) + ) + return null; + return found(cursor, true); } + separatorRegex.lastIndex = cursor; + separatorRegex.test(css); + const valueStart = separatorRegex.lastIndex; + const valueEnd = source.valueStop(valueStart); + // Without an end, V4 reads the value as the next declaration. + cursor = valueEnd === -1 ? valueStart : valueEnd; + while (cursor < css.length && /[;\s]/.test(css[cursor])) cursor++; + } +} - return pos({ - type: CssTypes.viewTransition, - declarations: decls, - }); +// Where V4 fails to open `node`, an at-rule without a block that ends a body +// read as rules, it reads the rest of the body up to `until`, its `}` or the +// input end, as declarations, skipping to each `;` before a `}`. Returns the +// offset where V4 then fails to close the body, with the errors it reports +// from the at-rule on, or undefined where V4 closes the body or reads it in a +// way the scan does not follow. +function missBreak( + node: postcss.AtRule, + source: CompatibilitySource, + until: number, +): { offset: number; errors: CssParseError[] } | undefined { + const { css } = source; + const start = node.source?.start?.offset; + // A prelude V4 reads up to the next `{` is no miss at the at-rule. + if ( + start === undefined || + blockPreludeEnd(source, start) !== undefined || + pageSelectorEnd(source, start) !== undefined + ) + return undefined; + const miss = atRuleMiss(node, source); + if ( + !miss || + miss.cursor >= until || + css.slice(miss.cursor, until).includes('/*') + ) + return undefined; + const errors = [source.error(miss.reason, miss.cursor)]; + let cursor = miss.cursor; + for (;;) { + if (cursor >= until || css[cursor] === '}' || css[cursor] === '@') + return undefined; + // V4 reads a nested rule where a `{` comes before any `;` or `}`. + const stop = source.ruleStop(cursor); + if (stop !== -1 && css[stop] === '{') return undefined; + propertyRegex.lastIndex = cursor; + if (propertyRegex.test(css)) { + cursor = propertyRegex.lastIndex; + if (css[cursor] === ':') { + separatorRegex.lastIndex = cursor; + separatorRegex.test(css); + const valueStart = separatorRegex.lastIndex; + const valueEnd = source.valueStop(valueStart); + // Without an end, V4 reads the value as the next declaration. + cursor = valueEnd === -1 ? valueStart : valueEnd; + while (cursor < css.length && /[;\s]/.test(css[cursor])) cursor++; + continue; + } + errors.push(source.error("property missing ':'", cursor)); + } + let skip = cursor; + while (skip < until && css[skip] !== ';' && css[skip] !== '}') skip++; + if (skip >= until || css[skip] === '}') break; + cursor = skip + 1; + while (cursor < css.length && /\s/.test(css[cursor])) cursor++; } + return cursor >= until || /[}@\s]/.test(css[cursor]) + ? undefined + : { offset: cursor, errors }; +} + +// Offset of the quote closing the one at `offset`, or -1. +function quoteEnd(css: string, offset: number): number { + for (let at = offset + 1; at < css.length; at++) { + if (css[at] === '\\') at++; + else if (css[at] === css[offset]) return at; + } + return -1; +} + +// `css` with [from, until) as spaces. Line breaks stay, and with them every +// line and column. +function blankRange(css: string, from: number, until: number): string { + return ( + css.slice(0, from) + + css.slice(from, until).replace(/[^\n]/g, ' ') + + css.slice(until) + ); +} - /** - * Parse @position-try. - */ - function atPositionTry(): CssPositionTryAST | undefined { - const pos = position(); - const m = /^@position-try\s+(--[-\w]+)\s*/.exec(css); - if (!m) { +// An unclosed comment after a declaration value without a `;`, which V4 +// reads as value text up to the first `;` or `}` in the comment (`end`), +// reading on from there. The comment runs to the input end in PostCSS. +interface ValueComment { + declaration: number; + value: number; + start: number; + end: number; +} + +function valueComment( + root: postcss.Root, + css: string, +): ValueComment | undefined { + // Only the last `/*` of the input can open an unclosed comment. + const last = css.lastIndexOf('/*'); + if (last === -1 || css.includes('*/', last + 2)) return; + let comment = undefined as postcss.Comment | undefined; + walkNodes(root, (node) => { + const at = node.source?.start?.offset; + if ( + !comment && + node.type === 'comment' && + at !== undefined && + css.startsWith('/*', at) && + !css.includes('*/', at + 2) + ) + comment = node; + }); + const start = comment?.source?.start?.offset; + if (!comment || start === undefined || comment.parent?.type === 'root') + return; + // One backward walk: `prev()` searches the siblings at every step. + const siblings: postcss.ChildNode[] = comment.parent?.nodes ?? []; + let index = siblings.indexOf(comment) - 1; + while (siblings[index]?.type === 'comment') index--; + const previous = siblings[index] as postcss.ChildNode | undefined; + const declaration = previous?.source?.start?.offset; + const parsedEnd = previous?.source?.end?.offset; + if ( + previous?.type !== 'decl' || + declaration === undefined || + parsedEnd === undefined || + css[parsedEnd - 1] === ';' || + css[parsedEnd - 1] === '}' + ) + return; + const property = propertyPrefixRegex.exec(css.slice(declaration, start)); + const colon = declaration + (property?.[0].length ?? 0); + if (!property || css[colon] !== ':') return; + let value = colon + 1; + while (value < start && /\s/.test(css[value])) value++; + // V4's value scan reaches the comment outside quotes and parentheses. + if ( + declarationValueEnd(`${css.slice(value, start)};`, false) !== + start - value + ) + return; + const relativeEnd = declarationValueEnd(css.slice(start), false); + const end = start + relativeEnd; + // Without a `{`, V4 reads the declaration as one, not as a nested rule. + if (relativeEnd === -1 || css.slice(declaration, end).includes('{')) return; + return { declaration, value, start, end }; +} + +function recoverCompatibility( + root: postcss.Root, + source: CompatibilitySource, + errors: CssParseError[], + silent: boolean, + preserveComments: boolean, + detect: boolean, +): ChainBreak | undefined { + const { css } = source; + const recoveryEnds = new Map(); + // Error positions, indexed on first use so that each lookup is O(1). + // Closing errors are all collected before, and until the walk ends errors + // are only appended or replaced in place. + let errorIndexes: Map | undefined; + // V4 reads the block from `start` as a rule, so the `}` it misses there + // is a rule's. + const readAsRule = ( + node: postcss.Rule | postcss.AtRule, + start: number, + open: number, + ): postcss.Rule => { + const closing = + node.type === 'atrule' ? source.closingErrors.get(node) : undefined; + let index = -1; + if (closing) { + if (!errorIndexes) { + errorIndexes = new Map(); + for (let at = errors.length - 1; at >= 0; at--) + errorIndexes.set(errors[at], at); + } + index = errorIndexes.get(closing) ?? -1; + if (index !== -1 && errors[index] !== closing) + index = errors.indexOf(closing); + } + if (closing && index !== -1) { + errors[index] = source.error( + "missing '}'", + source.offsetAt(closing.line, closing.column), + ); + } + return recoveryRule(node, source, start, open); + }; + walkNodes(root, (node) => { + if (node.type !== 'comment') return; + const start = node.source?.start?.offset ?? 0; + if (css.startsWith('/*', start) && css.indexOf('*/', start + 2) === -1) { + errors.push(source.error('End of comment missing', start)); + const parent = node.parent; + node.remove(); + let cursor = start; + if (parent && parent.type !== 'root') { + const property = propertyPrefixRegex.exec(css.slice(start)); + cursor += property?.[0].length ?? 0; + recoveryEnds.set(parent, cursor); + errors.push(source.error("property missing ':'", cursor)); + } + if (silent) { + for (let offset = cursor; offset < css.length; offset++) { + if (!/\s/.test(css[offset])) { + errors.push(source.error('selector missing', offset)); + } + } + } + } + }); + // Removals are deferred so each one is O(1): detached nodes keep their + // index (the walk skips them) and are dropped once the walk completes. + const detached = new Set(); + const dirty = new Set(); + // Blocks whose visit is done, and their `chainFrom` results. Every node in + // a block asks for the block's, and after its visit only `detach` changes + // a block, so it is kept until then. + const settled = new Set(); + const chains = new Map(); + const detach = (node: postcss.ChildNode): void => { + detached.add(node); + if (node.parent) dirty.add(node.parent); + chains.delete(node as postcss.Container); + }; + // Declarations recovered in each block, in source order, and how many + // the walk has visited. Inserting each one in the block would shift the + // nodes after it, so the walk visits it where it goes, after the nodes + // starting at or before it, and it is merged in once the walk is done. + const recovered = new Map< + postcss.Container, + { nodes: postcss.ChildNode[]; visited: number } + >(); + const recover = ( + parent: postcss.Container, + declaration: postcss.Declaration, + ): void => { + let block = recovered.get(parent); + if (!block) { + block = { nodes: [], visited: 0 }; + recovered.set(parent, block); + } + declaration.parent = parent as postcss.Declaration['parent']; + const offset = declaration.source?.start?.offset ?? 0; + let at = block.nodes.length; + while ( + at > block.visited && + (block.nodes[at - 1].source?.start?.offset ?? 0) > offset + ) + at--; + block.nodes.splice(at, 0, declaration); + }; + const recoveredBefore = ( + container: postcss.Container, + next: postcss.ChildNode | undefined, + ): postcss.ChildNode | undefined => { + const block = recovered.get(container); + const node = block?.nodes[block.visited]; + if ( + !block || + !node || + (next && + (next.source?.start?.offset ?? 0) <= (node.source?.start?.offset ?? 0)) + ) return; + block.visited++; + return node; + }; + // A block's last node, which may be a declaration recovered in it. + const lastNode = ( + container: postcss.Container, + ): postcss.ChildNode | undefined => { + const last = container.last; + const nodes = recovered.get(container)?.nodes; + const declaration = nodes?.[nodes.length - 1]; + return declaration && + (declaration.source?.start?.offset ?? 0) >= + (last?.source?.start?.offset ?? 0) + ? declaration + : last; + }; + // Root nodes before `tail` are in source order; recovered comments follow. + let tail = root.nodes.length; + while (tail > 0 && recoveredRootComments.has(root.nodes[tail - 1])) tail--; + let rootIndex = 0; + // No live block remains at or after this root index. + let blocklessFrom = Number.POSITIVE_INFINITY; + // For each cursor, the last search for the first live root node from + // `from` that starts at or after it, which ended at `index`. Root + // at-rules in a run fail at the same cursor, so each search goes on from + // the previous one, also when at-rules failing elsewhere come between. + const nextSearches = new Map< + number, + { nodes: postcss.ChildNode[]; from: number; index: number } + >(); + // A root `@page` that V4 fails to read moves its nodes after the failed + // at-rule to the root, visited right after it. Inserting them there would + // shift every later root node, so the first move rebuilds the root with + // free slots after each page for what it can move, and later moves fill + // them. A slot is detached, so it is passed over as a removed node. + const pageSlot = postcss.comment({ text: '' }); + detached.add(pageSlot); + // The end of each run of free slots, by its start, which follows a node. + // Searches of the root skip a run at once. + const slotRuns = new Map(); + const slotsEnd = (index: number): number => slotRuns.get(index) ?? index + 1; + const isPage = (node: postcss.ChildNode): node is postcss.AtRule => + node.type === 'atrule' && + node.name === 'page' && + !!node.nodes && + !detached.has(node); + // How many nodes a page can move to the root, with those that the pages + // among them can move in turn: at most its nodes after its first at-rule. + // Nodes are only detached or removed meanwhile, so a count stays enough. + const pageMoves = new Map(); + const countMoves = (page: postcss.AtRule): number => { + const pending = [page]; + while (pending.length) { + const current = pending[pending.length - 1]; + if (pageMoves.has(current)) { + pending.pop(); + continue; + } + let count = 0; + let waiting = false; + let moving = false; + for (const child of current.nodes ?? []) { + if (!moving) { + moving = child.type === 'atrule'; + continue; + } + if (child.type === 'decl' || detached.has(child)) continue; + count++; + if (!isPage(child)) continue; + const moves = pageMoves.get(child); + if (moves === undefined) { + pending.push(child); + waiting = true; + } else count += moves; + } + if (!waiting) { + pageMoves.set(current, count); + pending.pop(); + } } - const name = processMatch(m)[1]; - - if (!open()) { - return error("@position-try missing '{'"); + return pageMoves.get(page) ?? 0; + }; + // Moves `moved`, the nodes of the failed root page `page`, right after it. + const movePage = (page: postcss.AtRule, moved: postcss.ChildNode[]): void => { + const nodes = root.nodes; + const at = nodes[rootIndex] === page ? rootIndex : nodes.indexOf(page); + let needed = 0; + for (const child of moved) + needed += 1 + (isPage(child) ? countMoves(child) : 0); + const end = nodes[at + 1] === pageSlot ? slotRuns.get(at + 1) : undefined; + if (end !== undefined && end - (at + 1) >= needed) { + slotRuns.delete(at + 1); + let slot = at + 1; + let run = -1; + for (const child of moved) { + child.parent = root; + nodes[slot++] = child; + const count = isPage(child) ? countMoves(child) : 0; + run = count ? slot : -1; + if (count) slotRuns.set(slot, slot + count); + slot += count; + } + // The slots left join the run before them. + if (slot < end) slotRuns.set(run === -1 ? slot : run, end); + } else { + slotRuns.clear(); + const rebuilt = nodes.slice(0, at + 1); + const place = (child: postcss.ChildNode): void => { + rebuilt.push(child); + const count = isPage(child) ? countMoves(child) : 0; + if (!count) return; + slotRuns.set(rebuilt.length, rebuilt.length + count); + for (let i = 0; i < count; i++) rebuilt.push(pageSlot); + }; + for (const child of moved) { + child.parent = root; + place(child); + } + let rebuiltTail = tail > at ? -1 : tail; + for (let i = at + 1; i < nodes.length; i++) { + if (i === tail) rebuiltTail = rebuilt.length; + if (nodes[i] !== pageSlot) place(nodes[i]); + } + tail = rebuiltTail === -1 ? rebuilt.length : rebuiltTail; + root.nodes = rebuilt; + dirty.add(root); + } + nextSearches.clear(); + blocklessFrom = Number.POSITIVE_INFINITY; + }; + // Rules that run to the end of the input; V4 keeps them without content. + const unclosed = new Set(); + // Errors closing the blocks that run to the end of the input, outermost + // first. Such blocks are nested in one another. + const closings: CssParseError[][] = []; + // Unclosed at-rules, detached as V4 drops them; their bodies are V4's. + const unclosedAtRules = new Set(); + let chainBreak: ChainBreak | undefined; + // Blocks read one declaration at a time that V4 reads as PostCSS does, + // and those it reads in a way the scan cannot follow. + const read = new Set(); + const unread = new Set(); + // The blocks from `container` out while V4 reads them as PostCSS did: + // undefined at the root, and null where V4 reads one otherwise. + const chainFrom = ( + container: postcss.Container | undefined, + ): ChainLink | null | undefined => { + const levels: ChainBreak['levels'] = []; + let chain: ChainLink | null | undefined; + for ( + let parent = container; + parent && parent !== root; + parent = parent.parent as postcss.Container | undefined + ) { + const kept = chains.get(parent); + if (kept !== undefined) { + chain = kept; + break; + } + if (parent.type !== 'rule' && parent.type !== 'atrule') { + chain = null; + break; + } + const block = parent as postcss.Rule | postcss.AtRule; + const reader = chainReader(block, source); + if ( + !reader || + source.abandoned.has(block) || + source.hoisted.has(block) || + (detached.has(block) && !unclosedAtRules.has(block)) + ) { + chain = null; + break; + } + levels.push({ node: block, reader }); + } + for (let index = levels.length - 1; index >= 0; index--) { + const { node, reader } = levels[index]; + if (chain !== null) { + chain = { + node, + reader, + outer: chain, + unread: unread.has(node) || chain?.unread === true, + }; + } + if (settled.has(node)) chains.set(node, chain); + } + return chain; + }; + // The blocks of `chain`, innermost first. + const chainLevels = (chain: ChainLink | undefined): ChainBreak['levels'] => { + const levels: ChainBreak['levels'] = []; + for (let link = chain; link; link = link.outer) + levels.push({ node: link.node, reader: link.reader }); + return levels; + }; + // A `miss` break at `node`, an at-rule without a block that ends a body + // read as rules. A rule V4 keeps is only moved back at the root. + const missChainBreak = (node: postcss.AtRule): ChainBreak | undefined => { + const parent = node.parent; + if (!parent || parent.type === 'root' || lastNode(parent) !== node) return; + const chain = chainFrom(parent); + if (chain?.reader !== 'rules' || chain.unread) return; + const block = chain.node; + if ( + (block.type === 'rule' && block.parent !== root) || + recoveryEnds.has(block) + ) + return; + const blockEnd = block.source?.end?.offset; + const open = + blockEnd === undefined || + unclosedAtRules.has(block) || + (block.type === 'rule' && unclosed.has(block)); + if (!open && css[blockEnd - 1] !== '}') return; + const found = missBreak(node, source, open ? css.length : blockEnd - 1); + if (!found) return; + return { + kind: 'miss', + offset: found.offset, + quote: -1, + colon: false, + levels: chainLevels(chain), + miss: { start: node.source?.start?.offset ?? 0, errors: found.errors }, + }; + }; + // Where V4 reads a value through text PostCSS reads as other nodes, as + // from a quote in a comment, V4 reads no declaration until this offset. + let swallowed = -1; + // The first offset with an error, over the first `scannedErrors` errors. + let firstError = Number.POSITIVE_INFINITY; + let scannedErrors = 0; + // From the first bodiless at-rule V4 may read past its end. + let runOnFrom = Number.POSITIVE_INFINITY; + // Whether V4 has an error before `offset`, after which it may no longer + // read the input as PostCSS does. + const errorBefore = (offset: number): boolean => { + for (; scannedErrors < errors.length; scannedErrors++) { + const { line, column } = errors[scannedErrors]; + firstError = Math.min(firstError, source.offsetAt(line, column)); + } + return firstError < offset; + }; + // A `header` break at `node`, a block at-rule V4 fails after its header, + // reading the text from there as a rule. + const headerChainBreak = (node: postcss.AtRule): ChainBreak | undefined => { + const miss = headerMiss(node, css); + const open = blockOpeningOffset(node); + const start = node.source?.start?.offset; + if (!miss || open === undefined || start === undefined) return; + const { cursor } = miss; + // V4 reads an at-rule from a `@`, and a comment there as a node only + // between rules. + if ( + css[cursor] === '@' || + css.startsWith('/*', cursor) || + // V4 reads the header as it is in the input, not blanked to parse + // the input again. + source.original.slice(start, open + 1) !== css.slice(start, open + 1) || + source.inPrelude(start) || + errorBefore(start) || + runOnFrom < start || + start < swallowed || + selectorOpeningOffset(css, cursor, open + 1) !== open + ) + return; + let levels: ChainBreak['levels'] = []; + if (node.parent !== root) { + const chain = chainFrom(node.parent); + // A body read as rules reads a rule where a `{` comes before any `;` + // or `}`. + if ( + chain?.reader !== 'rules' || + chain.unread || + bracketedIndex(css, cursor, open + 1, '{;}') !== open + ) + return; + levels = chainLevels(chain); + } + return { + kind: 'header', + offset: cursor, + quote: -1, + colon: false, + levels, + header: { start, reason: miss.reason }, + }; + }; + // A `value` break at `decl`, in `parent`, where V4 finds no end for the + // value: V4 reads the value as empty and the value text as a property + // without `:`, or as nothing. `null` where V4 then reads on in a way + // recovery cannot follow. + const valueBreak = ( + decl: postcss.Declaration, + parent: postcss.Container | undefined, + ): ChainBreak | null | undefined => { + const start = decl.source?.start?.offset; + if ( + start === undefined || + start < swallowed || + (parent?.type !== 'rule' && parent?.type !== 'atrule') + ) + return; + propertyRegex.lastIndex = start; + if (!propertyRegex.test(css) || css[propertyRegex.lastIndex] !== ':') + return; + separatorRegex.lastIndex = propertyRegex.lastIndex; + separatorRegex.test(css); + const valueStart = separatorRegex.lastIndex; + if (valueStart >= css.length) return; + // V4's search mostly ends where PostCSS ends the value, which is checked + // first so that valid input builds no search table. + let end = decl.source?.end?.offset ?? css.length; + while (end < css.length && /\s/.test(css[end])) end++; + if ( + bracketedIndex(css, valueStart, Math.min(end + 1, css.length), ';}') !== + -1 + ) + return; + const stop = source.valueStop(valueStart); + if (stop !== -1) { + // V4 reads a longer value, beyond comments when it takes other nodes. + let at = end; + for (;;) { + while (at < stop && /\s/.test(css[at])) at++; + if (at >= stop || !css.startsWith('/*', at)) break; + const comment = css.indexOf('*/', at + 2); + at = comment === -1 ? css.length : comment + 2; + } + if (at < stop) swallowed = stop; + return; + } + const chain = chainFrom(parent); + if ( + chain?.reader !== 'rules' || + chain.unread || + recoveryEnds.has(chain.node) || + source.inPrelude(start) + ) + return; + // V4 reads a nested rule from a `{`, and an at-rule or a comment there. + if ( + source.ruleStop(start) !== -1 || + css[valueStart] === '@' || + css.startsWith('/*', valueStart) + ) + return null; + propertyRegex.lastIndex = valueStart; + const colon = propertyRegex.test(css); + const cursor = colon ? propertyRegex.lastIndex : valueStart; + // Recovery reads a property up to the input end as V4 does. + if (cursor >= css.length) return; + // V4 reads another declaration there. + if (css[cursor] === ':') return null; + const levels = chainLevels(chain); + let skipped = -1; + if (silent) { + const semicolon = css.indexOf(';', cursor); + const brace = css.indexOf('}', cursor); + if (css[cursor] === '}') skipped = cursor; + else if (semicolon !== -1 && (brace === -1 || semicolon < brace)) + skipped = semicolon + 1; + // Each enclosing body then fails to read anything there, but V4 calls + // a block at-rule's reader for a rule right after it fails at the root. + else if ( + source.ruleStop(cursor) !== -1 || + levels.some((level) => level.reader !== 'rules') || + ((levels.length > 1 || + levels[levels.length - 1].node.type === 'atrule') && + (css[cursor] === '@' || css.startsWith('/*', cursor))) + ) + return null; + } + return { + kind: 'value', + offset: cursor, + quote: -1, + colon, + levels, + value: { start, valueStart, end: skipped }, + }; + }; + // A chain break at `node`, `null` where V4 reads it in a way recovery + // cannot follow, so that later nodes are no longer checked. + const findChainBreak = ( + node: postcss.ChildNode, + ): ChainBreak | null | undefined => { + if (node.type === 'decl') return valueBreak(node, node.parent); + if (node.type === 'atrule') { + if (!node.nodes) { + if (!statementLikeV4(node, css)) + runOnFrom = Math.min(runOnFrom, node.source?.start?.offset ?? 0); + return silent ? missChainBreak(node) : undefined; + } + const header = headerChainBreak(node); + if (header) return header; + // V4 may read on past a block at-rule it fails to read. + if (headerMiss(node, css) || keyframesMiss(node, css)) + runOnFrom = Math.min(runOnFrom, node.source?.start?.offset ?? 0); + if (chainReader(node, source) !== 'declarations') return; + // Where the scan cannot follow a block, it leaves the blocks inside + // to recovery as before. + const enclosing = chainFrom(node.parent); + if (enclosing === null || enclosing?.unread) return; + const found = declarationBreak(node, source, read); + if (found === null) unread.add(node); + if (!found) return; + const chain = chainFrom(found.node.parent); + if (chain === null) return; + return { + kind: 'declarations', + offset: found.offset, + quote: -1, + colon: found.colon, + levels: [ + { node: found.node, reader: 'declarations' }, + ...chainLevels(chain), + ], + }; + } + if (node.type !== 'rule' || node.source?.start?.offset === undefined) + return; + const start = node.source.start.offset; + const open = blockOpeningOffset(node); + if (open === undefined || css[open] !== '{') return; + if (node.parent === root) { + if (bracketedIndex(css, start, open + 1, '{') === open) return; + let quote = start; + while ( + quote < open && + !'"\'{}()\\@'.includes(css[quote]) && + !css.startsWith('/*', quote) + ) + quote++; + return (css[quote] === '"' || css[quote] === "'") && + quoteEnd(css, quote) === -1 + ? { kind: 'quote', offset: start, quote, colon: false, levels: [] } + : null; } - let decls = comments(); - let decl: CssDeclarationAST | undefined = declaration(); - while (decl) { - decls.push(decl); - decls = decls.concat(comments()); - decl = declaration(); + let kind: ChainBreak['kind']; + if (css[start] === '@') return null; + if (!node.selector.trim()) { + if (open !== start) return null; + kind = 'empty'; + } else { + // V4's check for a nested rule: a `{` before any `;` or `}`. + const stop = + bracketedIndex(css, start, open + 1, '{;}') === open + ? open + : bracketedIndex(css, start, css.length, '{;}'); + if (stop === open) return; + propertyRegex.lastIndex = start; + if (css[stop] === '{' || propertyRegex.test(css)) return null; + kind = 'text'; } - if (!close()) { - return error("@position-try missing '}'"); + const chain = chainFrom(node.parent); + if (chain === null) return null; + const levels = chainLevels(chain); + if (silent) { + const semicolon = css.indexOf(';', start); + const brace = css.indexOf('}', start); + // Only a body read as rules skips to the `;`; one read as + // declarations is closed, and the next enclosing body would skip. + if ( + semicolon !== -1 && + (brace === -1 || semicolon < brace) && + levels[0].reader === 'declarations' && + levels.some((level) => level.reader === 'rules') + ) + return null; } + return { kind, offset: start, quote: -1, colon: false, levels }; + }; + let detecting = detect; + // The last declaration of an unclosed block, removed by recovery. + let valueCandidate: + | { decl: postcss.Declaration; parent: postcss.Container } + | undefined; + // Where the text already reported by the rules without a selector around + // a block ends. V4 reports each character once, however deep they nest. + const reportedEnds = new Map(); + const recoverNode = (node: postcss.ChildNode, index: number): void => { + if (chainBreak) return; + if (detecting) { + const found = findChainBreak(node); + if (found !== undefined) detecting = false; + if (found) { + chainBreak = found; + return; + } + } + if (node.parent === root) rootIndex = index; + const start = node.source?.start?.offset ?? 0; + const reportedEnd = node.parent && reportedEnds.get(node.parent); + if ( + reportedEnd !== undefined && + (node.type === 'rule' || node.type === 'atrule') + ) + reportedEnds.set(node, reportedEnd); + if (node.type === 'rule' && !node.selector.trim()) { + detach(node); + const end = node.source?.end?.offset ?? css.length; + for ( + let offset = Math.max(start, reportedEnd ?? 0); + offset < end; + offset++ + ) { + if (!/\s/.test(css[offset])) { + errors.push( + source.error( + css[offset] === '}' ? "extra '}'" : 'selector missing', + offset, + ), + ); + } + } + reportedEnds.set(node, Math.max(end, reportedEnd ?? 0)); + } else if (node.type === 'decl') { + const value = node.raws.value?.raw ?? node.value; + if ( + (value.startsWith('"') || value.startsWith("'")) && + indexOfArrayNonEscaped(value, [value[0]], 1) === -1 && + node.source + ) { + const offset = + start + node.prop.length + (node.raws.between?.length ?? 1); + const end = source.pointAt(offset); + if (!silent) errors.push(source.error("missing '}'", offset)); + node.value = ''; + delete node.raws.value; + node.source.end = { ...end, offset }; + } + } else if ( + (node.type === 'rule' || node.type === 'atrule') && + node.nodes && + node.source && + !node.source.end + ) { + // V4 reads a nested import-like at-rule as a statement, which takes + // the rest of the input when no `;` ends it. + if ( + node.type === 'atrule' && + node.parent && + node.parent !== root && + /^(?:import|charset|namespace)/.test(node.name) && + !/^[-\w]*keyframes/.test(node.name) && + readsAtRules(node.parent, source) && + source.statementEnd(start) === css.length + ) { + detach(node); + for (const child of node.nodes) detach(child); + return; + } + const last = node.last; + const cursor = recoveryEnds.get(node) ?? css.length; + // V4 reads the whole body, reporting its errors, before the missing + // `}`, so these errors are added once the walk has visited the body. + const closing: CssParseError[] = []; + const lastStart = last?.source?.start?.offset ?? 0; + if ( + last?.type === 'decl' && + !recoveryEnds.has(node) && + !css.slice(lastStart).trimEnd().endsWith(';') + ) { + // The declaration runs to the input end, after every other node, so + // it is checked for a break once the walk is done. + valueCandidate = { decl: last, parent: node }; + last.remove(); + // V4 finds no end for the value, so it reads the value as empty and + // the value text as a property without `:`. + propertyRegex.lastIndex = lastStart; + const property = propertyRegex.exec(css); + separatorRegex.lastIndex = lastStart + (property?.[0].length ?? 0); + const separator = property && separatorRegex.exec(css); + if (!separator || separator.index + separator[0].length < css.length) + closing.push(source.error("property missing ':'", css.length)); + } + closing.push( + source.error( + node.type === 'atrule' + ? `@${atRuleErrorName(node.name)} missing '}'` + : "missing '}'", + cursor, + ), + ); + closings.push(closing); + if (node.type === 'atrule') { + detach(node); + unclosedAtRules.add(node); + // V4 then fails to read a rule at the root. + if (node.parent === root) + errors.push(source.error('selector missing', cursor)); + return; + } + // V4 keeps the rule without its content, cleared after the walk. + unclosed.add(node); + const end = source.pointAt(cursor); + node.source.end = { + line: end.line, + column: end.column - 1, + offset: cursor, + }; + } else if (node.type === 'atrule') { + const miss = atRuleMiss(node, source); + if (!miss) return; + const { cursor, reason } = miss; + errors.push(source.error(reason, cursor)); + // V4 reads a rule from where the keyframes name is missing. + const keyframesOpen = + reason === '@keyframes missing name' && + node.parent === root && + node.nodes && + css[cursor] !== '{' + ? blockOpeningOffset(node) + : undefined; + if ( + keyframesOpen !== undefined && + selectorOpeningOffset(css, cursor, keyframesOpen + 1) === keyframesOpen + ) { + const rule = readAsRule(node, cursor, keyframesOpen); + root.nodes[index] = rule; + rule.parent = root; + node.parent = undefined; + return; + } + const parent = node.parent; + const page = + parent?.type === 'atrule' && + parent.name === 'page' && + parent.parent?.type === 'root' && + !detached.has(parent) + ? parent + : undefined; + const pageEnd = page?.source?.end?.offset; + const parentEnd = parent?.source?.end?.offset ?? css.length; + const recoveryEnd = Math.min( + node.source?.end?.offset ?? parentEnd, + parentEnd - Number(css[parentEnd - 1] === '}'), + ); + const remaining = page?.nodes + ?.slice((page.nodes?.indexOf(node) ?? -1) + 1) + .filter((child) => child.type !== 'decl' && !detached.has(child)); + detach(node); + if (parent?.type === 'atrule' && parent.name === 'page') { + errors.push(source.error("@page missing '}'", cursor)); + if (page && remaining) { + page.removeAll(); + if (remaining.length) movePage(page, remaining); + } + detach(parent); + } + if (silent) { + if (parent?.type === 'root' || page) { + const from = rootIndex + 1; + let nextIndex = -1; + let lastBlock = -1; + const scanEnd = Math.min(blocklessFrom, root.nodes.length); + for (let i = from; i < scanEnd; i++) { + const child = root.nodes[i]; + if (child === pageSlot) { + i = slotsEnd(i) - 1; + continue; + } + if ( + detached.has(child) || + (child.type !== 'rule' && child.type !== 'atrule') || + !child.nodes + ) + continue; + if ((child.source?.start?.offset ?? -1) >= cursor) { + nextIndex = i; + break; + } + lastBlock = i; + } + if (nextIndex === -1) { + blocklessFrom = Math.min( + blocklessFrom, + Math.max(from, lastBlock + 1), + ); + } + const nextBlock = root.nodes[nextIndex]; + const open = + nextBlock?.type === 'rule' || nextBlock?.type === 'atrule' + ? blockOpeningOffset(nextBlock) + : undefined; + if ( + open !== undefined && + css[cursor] !== '{' && + (nextBlock?.type === 'rule' || nextBlock?.type === 'atrule') + ) { + const start = nextBlock.source?.start?.offset ?? cursor; + const skipped = (child: postcss.ChildNode): boolean => { + const offset = child.source?.start?.offset ?? -1; + return offset >= cursor && offset < start; + }; + // Source order bounds the skipped nodes before the next block; + // recovered comments can be anywhere in the tail. + for (let i = from; i < nextIndex; i++) { + const child = root.nodes[i]; + if (child === pageSlot) { + i = slotsEnd(i) - 1; + continue; + } + if (!detached.has(child) && skipped(child)) detach(child); + } + for ( + let i = Math.max(tail, nextIndex + 1); + i < root.nodes.length; + i++ + ) { + const child = root.nodes[i]; + if (!detached.has(child) && skipped(child)) detach(child); + } + const rule = readAsRule(nextBlock, cursor, open); + root.nodes[nextIndex] = rule; + rule.parent = root; + nextBlock.parent = undefined; + const last = remaining?.[remaining.length - 1]; + const after = last?.source?.end?.offset; + if ( + after !== undefined && + pageEnd !== undefined && + start < pageEnd && + after < pageEnd + ) { + recoverRootText(root, source, errors, after, pageEnd); + } + return; + } + let next: postcss.ChildNode | undefined; + let nextAt = from; + const search = nextSearches.get(cursor); + if (search?.nodes === root.nodes && search.from <= from) + nextAt = Math.max(from, search.index); + for (; nextAt < root.nodes.length; nextAt++) { + const child = root.nodes[nextAt]; + if (child === pageSlot) { + nextAt = slotsEnd(nextAt) - 1; + continue; + } + if ( + !detached.has(child) && + (child.source?.start?.offset ?? -1) >= cursor + ) { + next = child; + break; + } + } + nextSearches.set(cursor, { nodes: root.nodes, from, index: nextAt }); + // Collect reported the root text after the at-rule's own span. + const until = Math.min( + next?.source?.start?.offset ?? css.length, + page ? css.length : (node.source?.end?.offset ?? css.length), + ); + if (css[cursor] === '}') { + errors.push(source.error('selector missing', cursor)); + } + recoverRootText( + root, + source, + errors, + cursor + Number(css[cursor] === '}'), + until, + ); + const last = remaining?.[remaining.length - 1]; + const after = last?.source?.end?.offset; + if (after !== undefined && pageEnd !== undefined && after < pageEnd) { + recoverRootText(root, source, errors, after, pageEnd); + } + if (cursor === css.length) { + errors.push(source.error('selector missing', cursor)); + } + return; + } + if (parent) { + recoverBodyText( + root, + source, + errors, + cursor, + recoveryEnd, + preserveComments, + (declaration) => recover(parent, declaration), + ); + } + } + } + }; + walkNodes( + root, + (node, index) => { + recoverNode(node, index); + if (node.type === 'rule' || node.type === 'atrule') settled.add(node); + }, + detached, + recoveredBefore, + ); + for (const [parent, block] of recovered) { + const nodes = parent.nodes ?? []; + const merged: postcss.ChildNode[] = []; + let index = 0; + for (const node of block.nodes) { + const offset = node.source?.start?.offset ?? 0; + while ( + index < nodes.length && + (nodes[index].source?.start?.offset ?? 0) <= offset + ) + merged.push(nodes[index++]); + merged.push(node); + } + while (index < nodes.length) merged.push(nodes[index++]); + parent.nodes = merged; + } + if (detecting && !chainBreak && valueCandidate) { + const found = valueBreak(valueCandidate.decl, valueCandidate.parent); + if (found) chainBreak = found; + } + // V4 closes the innermost block first. + for (let index = closings.length - 1; index >= 0; index--) + errors.push(...closings[index]); + // V4 keeps an abandoned rule without its content and drops an abandoned + // at-rule. The children it reads as root nodes move to the root. + const hoisted: postcss.ChildNode[] = []; + for (const container of source.abandoned) { + if (container.type === 'atrule' && (!silent || !container.parent)) continue; + for (const child of container.nodes ?? []) { + if (source.hoisted.has(child) && !detached.has(child)) + hoisted.push(child); + } + if (container.type === 'atrule') detach(container); + container.removeAll(); + } + if (hoisted.length) root.append(hoisted); + for (const rule of unclosed) rule.removeAll(); + for (const container of dirty) { + const nodes = container.nodes ?? []; + const live = nodes.filter((child) => !detached.has(child)); + if (live.length !== nodes.length) { + container.removeAll(); + container.append(live); + } + } + root.nodes.sort( + (a, b) => (a.source?.start?.offset ?? 0) - (b.source?.start?.offset ?? 0), + ); + // V4 reads a stray `}` inside a statement as statement text, e.g. the + // selector `x} y` of `x} y{}`, so only braces outside root nodes are extra. + const extras: CssParseError[] = []; + let nodeIndex = 0; + let coveredUntil = 0; + source.strayBraces.sort((a, b) => a - b); + for (const [braceIndex, brace] of source.strayBraces.entries()) { + if (brace === source.strayBraces[braceIndex - 1]) continue; + while ( + nodeIndex < root.nodes.length && + (root.nodes[nodeIndex].source?.start?.offset ?? 0) <= brace + ) { + coveredUntil = Math.max( + coveredUntil, + root.nodes[nodeIndex].source?.end?.offset ?? 0, + ); + nodeIndex++; + } + if (brace < coveredUntil) continue; + source.orphanBrace ??= brace; + if (silent) extras.push(source.error("extra '}'", brace)); + } + if (extras.length) { + // Extra braces lead errors at the same position, as V4 reports them first. + const rest = errors.splice(0); + for (const error of extras) errors.push(error); + for (const error of rest) errors.push(error); + } + errors.sort( + (a, b) => + a.line - b.line || + a.column - b.column || + Number(a.reason === 'selector missing') - + Number(b.reason === 'selector missing'), + ); + return chainBreak; +} - return pos({ - type: CssTypes.positionTry, - name: name, - declarations: decls, - }); +// PostCSS end is inclusive (last char); v4 css-tools end is exclusive (past last char). +// Use for rules, at-rules, and comments where end = last char + 1. +function convertPos( + source: postcss.Source | undefined, + sourceName: string, +): Position | undefined { + if (!source?.start || !source.end) return undefined; + return new Position( + { line: source.start.line, column: source.start.column }, + { line: source.end.line, column: source.end.column + 1 }, + sourceName, + ); +} + +// Declarations use different end semantics: +// - With semicolon: end = position of ';' (PostCSS end, no +1) +// - Without semicolon: end = position of closing '}' (parent's end, no +1) +function convertDeclPos( + node: postcss.Declaration, + sourceName: string, +): Position | undefined { + if (!node.source?.start || !node.source.end) return undefined; + const parent = node.parent as postcss.Container & { + raws?: { semicolon?: boolean }; + }; + const isLastChild = parent?.nodes?.[parent.nodes.length - 1] === node; + const endsWithSemicolon = + node.source.end.offset !== undefined && + node.source.input.css[node.source.end.offset - 1] === ';'; + const noSemicolon = + !endsWithSemicolon && isLastChild && parent?.raws?.semicolon === false; + + const endLine = + noSemicolon && parent.source?.end + ? parent.source.end.line + : node.source.end.line; + const endCol = + noSemicolon && parent.source?.end + ? parent.source.end.column + : node.source.end.column; + + return new Position( + { line: node.source.start.line, column: node.source.start.column }, + { line: endLine, column: endCol }, + sourceName, + ); +} + +function convertSelectors(selectorStr: string): string[] { + const cleaned = trim(selectorStr).replace(commentRegex, ''); + return splitWithBracketAndQuoteSupport(cleaned, [',']).map((v) => trim(v)); +} + +function convertComment( + node: postcss.Comment, + sourceName: string, +): CssCommentAST { + const raws = node.raws as { left?: string; right?: string }; + return { + type: CssTypes.comment, + comment: (raws.left ?? '') + node.text + (raws.right ?? ''), + position: convertPos(node.source, sourceName), + }; +} + +function convertDeclaration( + node: postcss.Declaration, + sourceName: string, +): CssDeclarationAST { + // PostCSS stores !important separately; reconstruct full value string + const important = node.important + ? typeof (node.raws as Record)?.important === 'string' + ? ((node.raws as Record).important as string) + : ' !important' + : ''; + // PostCSS moves the IE6 star hack (*property) into raws.before — restore it. + const rawsBefore = + ((node.raws as Record).before as string) ?? ''; + const hackPrefix = /[*_]$/.exec(rawsBefore)?.[0] ?? ''; + return { + type: CssTypes.declaration, + property: + hackPrefix + + (node.prop + (node.raws.between ?? ':').split(':')[0]) + .replace(commentRegex, '') + .trim(), + value: trim((node.raws.value?.raw ?? node.value) + important), + position: convertDeclPos(node, sourceName), + }; +} + +type ConvertedNodes = WeakMap< + postcss.ChildNode, + CssAtRuleAST | CssDeclarationAST +>; + +function convertRule( + node: postcss.Rule, + sourceName: string, + convertedNodes: ConvertedNodes, +): CssRuleAST { + const selectors = convertSelectors(node.selector); + const declarations: Array = + []; + + for (const child of node.nodes ?? []) { + const converted = convertedNodes.get(child); + if (converted) + declarations.push( + converted as CssDeclarationAST | CssCommentAST | CssAtRuleAST, + ); } - /** - * Parse starting style. - */ - function atStartingStyle(): CssStartingStyleAST | undefined { - const pos = position(); - const m = /^@starting-style\s*/.exec(css); - if (!m) { - return; + return { + type: CssTypes.rule, + selectors, + declarations, + position: convertPos(node.source, sourceName), + }; +} + +// V4 reads keyframe values as a run of offsets and lowercase words, each +// optionally followed by a `,`, so `from to` and `0%50%` hold two values. A +// selector V4 does not read whole keeps the comma split. +function keyframeValues(selector: string): string[] { + const values: string[] = []; + let offset = 0; + for (;;) { + keyframeValueRegex.lastIndex = offset; + const match = keyframeValueRegex.exec(selector); + if (!match) break; + values.push(match[1]); + offset = keyframeValueRegex.lastIndex; + keyframeCommaRegex.lastIndex = offset; + if (keyframeCommaRegex.test(selector)) { + offset = keyframeCommaRegex.lastIndex; } - processMatch(m); + } + return values.length && offset === selector.length + ? values + : selector.split(',').map((v) => trim(v)); +} - if (!open()) { - return error("@starting-style missing '{'"); +function convertKeyframe( + node: postcss.Rule, + sourceName: string, + convertedNodes: ConvertedNodes, +): CssKeyframeAST { + const values = keyframeValues(node.selector); + const declarations: Array = []; + + for (const child of node.nodes ?? []) { + const converted = convertedNodes.get(child); + if ( + converted?.type === CssTypes.declaration || + converted?.type === CssTypes.comment + ) { + declarations.push(converted); } - const style = rulesOrDeclarations(); + } + + return { + type: CssTypes.keyframe, + values, + declarations, + position: convertPos(node.source, sourceName), + }; +} - if (!close()) { - return error("@starting-style missing '}'"); +const PAGE_MARGIN_BOX_NAMES = new Set([ + 'top-left-corner', + 'top-left', + 'top-center', + 'top-right', + 'top-right-corner', + 'bottom-left-corner', + 'bottom-left', + 'bottom-center', + 'bottom-right', + 'bottom-right-corner', + 'left-top', + 'left-middle', + 'left-bottom', + 'right-top', + 'right-middle', + 'right-bottom', +]); + +function convertKeyframes( + node: postcss.AtRule, + nameLower: string, + params: string, + sourceName: string, + convertedNodes: ConvertedNodes, +): CssKeyframesAST { + const vendorMatch = keyframesRegex.exec(nameLower); + const vendor = vendorMatch?.[1] || undefined; + + const keyframes: Array = []; + for (const child of node.nodes ?? []) { + if (child.type === 'comment') { + const converted = convertedNodes.get(child); + if (converted?.type === CssTypes.comment) keyframes.push(converted); + } else if (child.type === 'rule') { + keyframes.push(convertKeyframe(child, sourceName, convertedNodes)); } + } - return pos({ - type: CssTypes.startingStyle, - rules: style, - }); + return { + type: CssTypes.keyframes, + name: params, + vendor, + keyframes, + position: convertPos(node.source, sourceName), + }; +} + +function convertBlockNodes( + nodes: postcss.ChildNode[], + convertedNodes: ConvertedNodes, +): Array { + const result: Array = []; + for (const child of nodes) { + const converted = convertedNodes.get(child); + if (converted) result.push(converted as CssAtRuleAST | CssDeclarationAST); } + return result; +} - /** - * Parse import - */ - const atImport = _compileAtRule('import'); - - /** - * Parse charset - */ - const atCharset = _compileAtRule('charset'); - - /** - * Parse namespace - */ - const atNamespace = _compileAtRule('namespace'); - - /** - * Parse non-block at-rules - */ - function _compileAtRule( - name: string, - ): () => T1 | undefined { - const re = new RegExp( - '^@' + - name + - '\\s*((?::?[^;\'"]|"(?:\\\\"|[^"])*?"|\'(?:\\\\\'|[^\'])*?\')+)(?:;|$)', - ); +function convertDeclNodes( + nodes: postcss.ChildNode[], + convertedNodes: ConvertedNodes, +): Array { + const result: Array = []; + for (const child of nodes) { + const converted = convertedNodes.get(child); + if ( + converted?.type === CssTypes.declaration || + converted?.type === CssTypes.comment + ) { + result.push(converted); + } + } + return result; +} - // ^@import\s*([^;"']|("|')(?:\\\2|.)*?\2)+(;|$) +// The name and prelude V4 reads for `node`. The safe parser keeps a `:` after +// the at-keyword in the name, as in `@import:x`, which V4 reads as prelude +// text, keeping the whitespace after it. +function atRuleHeader(node: postcss.AtRule): { name: string; params: string } { + const params = `${node.raws.afterName ?? ''}${ + node.raws.params?.raw ?? node.params + }${node.raws.between ?? ''}`; + return node.name.endsWith(':') + ? { name: node.name.slice(0, -1), params: trim(`:${params}`) } + : { name: node.name, params: trim(params) }; +} - return (): T1 | undefined => { - const pos = position(); - const m = re.exec(css); - if (!m) { - return; - } - const res = processMatch(m); - const ret: Record = { type: name }; - ret[name] = res[1].trim(); - return pos(ret as unknown as T1) as T1; - }; +function convertAtRule( + node: postcss.AtRule, + sourceName: string, + convertedNodes: ConvertedNodes, +): CssAtRuleAST { + const { name: nameLower, params } = atRuleHeader(node); + + if (keyframesRegex.test(nameLower)) { + return convertKeyframes( + node, + nameLower, + params, + sourceName, + convertedNodes, + ); } + const hasPrelude = Boolean( + params || node.raws.afterName || node.raws.between, + ); + const start = node.source?.start?.offset; + // V4 reads an at-rule whose header it fails to match as a generic one. + const generic = + start !== undefined && + headerFails(nameLower, node.source?.input.css ?? '', start); + + switch (nameLower) { + case 'media': + if (!hasPrelude) break; + return { + type: CssTypes.media, + media: params, + rules: convertBlockNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssMediaAST; + + case 'supports': + if (!hasPrelude) break; + return { + type: CssTypes.supports, + supports: params, + rules: convertBlockNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssSupportsAST; + + case 'container': + if (!hasPrelude) break; + return { + type: CssTypes.container, + container: params, + rules: convertBlockNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssContainerAST; + + case 'import': + if (!hasPrelude) break; + return { + type: CssTypes.import, + import: params, + position: convertPos(node.source, sourceName), + } as CssImportAST; + + case 'charset': + if (!hasPrelude) break; + return { + type: CssTypes.charset, + charset: params, + position: convertPos(node.source, sourceName), + } as CssCharsetAST; + + case 'namespace': + if (!hasPrelude) break; + return { + type: CssTypes.namespace, + namespace: params, + position: convertPos(node.source, sourceName), + } as CssNamespaceAST; + + case 'custom-media': { + if ( + !customMediaRegex.test(params) || + node.source?.end?.offset === undefined || + node.source.input.css[node.source.end.offset - 1] !== ';' + ) + break; + const spaceIdx = params.search(/\s/); + return { + type: CssTypes.customMedia, + name: spaceIdx !== -1 ? params.slice(0, spaceIdx) : params, + media: spaceIdx !== -1 ? trim(params.slice(spaceIdx)) : '', + position: convertPos(node.source, sourceName), + } as CssCustomMediaAST; + } - /** - * Parse generic/unknown at-rule (fallback for any unrecognized at-rule). - * Handles both block at-rules (@scope { ... }) and statement at-rules (@foo ...;). - */ - function atGeneric(): CssGenericAtRuleAST | undefined { - const pos = position(); - const m = /^@([-\w]+)\s*/.exec(css); - if (!m) { - return; + case 'font-face': + return { + type: CssTypes.fontFace, + declarations: convertDeclNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssFontFaceAST; + + case 'font-feature-values': + if (generic) break; + return { + type: CssTypes.fontFeatureValues, + fontFamily: params, + rules: convertBlockNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssFontFeatureValuesAST; + + case 'host': + return { + type: CssTypes.host, + rules: convertBlockNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssHostAST; + + case 'layer': { + if (!hasPrelude) break; + if (!node.nodes) { + return { + type: CssTypes.layer, + layer: params, + position: statementPos(node, sourceName), + } as CssLayerAST; + } + return { + type: CssTypes.layer, + layer: params, + rules: convertBlockNodes(node.nodes, convertedNodes), + position: convertPos(node.source, sourceName), + } as CssLayerAST; } - const name = processMatch(m)[1]; - // Capture prelude (everything between the name and '{' or ';') - let prelude = ''; - const preludeEnd = indexOfArrayWithBracketAndQuoteSupport(css, ['{', ';']); - if (preludeEnd !== -1 && preludeEnd > 0) { - prelude = trim(css.substring(0, preludeEnd)); - const fakeMatch = [ - css.substring(0, preludeEnd), - ] as unknown as RegExpExecArray; - processMatch(fakeMatch); + case 'page': { + const selectors = params ? convertSelectors(params) : []; + const declarations: Array< + CssDeclarationAST | CssCommentAST | CssAtRuleAST + > = []; + for (const child of node.nodes ?? []) { + if ( + child.type === 'decl' || + child.type === 'comment' || + child.type === 'atrule' + ) { + const converted = convertedNodes.get(child); + if (converted) declarations.push(converted); + } + } + return { + type: CssTypes.page, + selectors, + declarations, + position: convertPos(node.source, sourceName), + } as CssPageAST; } - // Block at-rule - if (open()) { - const style = rulesOrDeclarations(); + case 'property': + if (generic) break; + return { + type: CssTypes.property, + name: params, + declarations: convertDeclNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssPropertyAST; + + case 'counter-style': + if (generic) break; + return { + type: CssTypes.counterStyle, + name: params, + declarations: convertDeclNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssCounterStyleAST; + + case 'scope': + return { + type: CssTypes.scope, + scope: params, + rules: convertBlockNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssScopeAST; + + case 'starting-style': + return { + type: CssTypes.startingStyle, + rules: convertBlockNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssStartingStyleAST; + + case 'view-transition': + return { + type: CssTypes.viewTransition, + declarations: convertDeclNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssViewTransitionAST; + + case 'position-try': + if (generic) break; + return { + type: CssTypes.positionTry, + name: params, + declarations: convertDeclNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssPositionTryAST; + } - if (!close()) { - return error(`@${name} missing '}'`); - } + // Document with optional vendor prefix (@-moz-document, @document) + if (hasPrelude && /^([-\w]+)?document$/.test(nameLower)) { + const vendorMatch = /^([-\w]+)?document$/.exec(nameLower); + // v4 used "" (empty string) when no vendor prefix, not undefined + const vendor = vendorMatch?.[1] ?? ''; + return { + type: CssTypes.document, + document: params, + vendor, + rules: convertBlockNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssDocumentAST; + } - return pos({ - type: CssTypes.atRule, - name: name, - prelude: prelude, - rules: style, + // Page margin boxes (@top-left, @bottom-right, etc.) + if (PAGE_MARGIN_BOX_NAMES.has(nameLower)) { + return { + type: CssTypes.pageMarginBox, + name: nameLower, + declarations: convertDeclNodes(node.nodes ?? [], convertedNodes), + position: convertPos(node.source, sourceName), + } as CssPageMarginBoxAST; + } + + // Generic/unknown at-rule fallback + if (!node.nodes) { + return { + type: CssTypes.atRule, + name: node.name, + prelude: params, + position: statementPos(node, sourceName), + } as CssGenericAtRuleAST; + } + return { + type: CssTypes.atRule, + name: node.name, + prelude: params, + rules: convertBlockNodes(node.nodes, convertedNodes), + position: convertPos(node.source, sourceName), + } as CssGenericAtRuleAST; +} + +function convertChildNode( + child: postcss.ChildNode, + sourceName: string, + convertedNodes: ConvertedNodes, +): CssAtRuleAST | CssDeclarationAST | undefined { + switch (child.type) { + case 'rule': + return convertRule(child, sourceName, convertedNodes); + case 'atrule': + return convertAtRule(child, sourceName, convertedNodes); + case 'decl': + return convertDeclaration(child as postcss.Declaration, sourceName); + case 'comment': + return convertComment(child as postcss.Comment, sourceName); + default: + return undefined; + } +} + +function addParent(obj: T, parent?: unknown): T { + const pending: Array<{ value: unknown; parent: unknown }> = [ + { value: obj, parent }, + ]; + while (pending.length) { + const entry = pending.pop(); + if (!entry?.value || typeof entry.value !== 'object') continue; + const isNode = + 'type' in entry.value && typeof entry.value.type === 'string'; + if (isNode) { + Object.defineProperty(entry.value, 'parent', { + configurable: true, + writable: true, + enumerable: false, + value: entry.parent ?? null, }); } + const childParent = isNode ? entry.value : entry.parent; + for (const value of Object.values(entry.value)) { + if (value && typeof value === 'object') { + pending.push({ value, parent: childParent }); + } + } + } + return obj; +} - // Statement at-rule (ends with ';') - const endMatch = /^[;\s]*/.exec(css); - if (endMatch) { - processMatch(endMatch); +// For layer and generic statements, V4 advanced past trailing `;` and +// whitespace to the start of the next token before recording end position. +function statementPos( + node: postcss.AtRule, + sourceName: string, +): Position | undefined { + if (!node.source?.start || !node.source.end) return undefined; + const css = (node.source.input as { css: string }).css; + // source.end.offset points one past the last char (exclusive end) + let offset = node.source.end.offset ?? 0; + let endLine = node.source.end.line; + let endCol = node.source.end.column + 1; + while (offset < css.length && /[;\s]/.test(css[offset])) { + if (css[offset] === '\n') { + endLine++; + endCol = 1; + } else { + endCol++; } + offset++; + } + return new Position( + { line: node.source.start.line, column: node.source.start.column }, + { line: endLine, column: endCol }, + sourceName, + ); +} - return pos({ - type: CssTypes.atRule, - name: name, - prelude: prelude, - }); +function buildStylesheet( + root: postcss.Root, + sourceName: string, + source: string | undefined, + parsingErrors: CssParseError[], + stripCommentsInValues: boolean, +): CssStylesheetAST { + const nodes: postcss.ChildNode[] = []; + walkNodes(root, (node) => { + nodes.push(node); + }); + const convertedNodes: ConvertedNodes = new WeakMap(); + for (let index = nodes.length - 1; index >= 0; index--) { + const node = nodes[index]; + if (node.type === 'rule' && keyframesAtRule(node.parent)) continue; + const converted = convertChildNode(node, sourceName, convertedNodes); + if (converted) convertedNodes.set(node, converted); + } + const rules: CssAtRuleAST[] = []; + for (const node of root.nodes ?? []) { + const converted = convertedNodes.get(node); + if (converted) rules.push(converted as CssAtRuleAST); } + if (stripCommentsInValues) stripValueComments(rules); + return addParent({ + type: CssTypes.stylesheet, + stylesheet: { source, rules, parsingErrors }, + } as CssStylesheetAST); +} - /** - * Parse at rule. - */ - function atRule(): CssAtRuleAST | undefined { - if (css[0] !== '@') { - return; +function stripValueComments(value: unknown): void { + const pending = [value]; + while (pending.length) { + const current = pending.pop(); + if (!current || typeof current !== 'object') continue; + if ('type' in current && current.type === CssTypes.declaration) { + const declaration = current as CssDeclarationAST; + declaration.value = declaration.value.replace(commentRegex, ''); + } else { + for (const child of Object.values(current)) pending.push(child); } + } +} - return ( - atKeyframes() || - atMedia() || - atCustomMedia() || - atSupports() || - atImport() || - atCharset() || - atNamespace() || - atDocument() || - atPage() || - atHost() || - atFontFace() || - atFontFeatureValues() || - atContainer() || - atStartingStyle() || - atLayer() || - atProperty() || - atCounterStyle() || - atScope() || - atViewTransition() || - atPositionTry() || - atPageMarginBox() || - atGeneric() +function parsePostcss( + css: string, + input: string, +): { root: postcss.Root; syntaxError?: postcss.CssSyntaxError } { + let root: postcss.Root; + let syntaxError: postcss.CssSyntaxError | undefined; + try { + root = postcss.parse(input, postcssOptions); + } catch (e) { + if (!(e instanceof postcss.CssSyntaxError)) throw e; + root = safeParser(input, postcssOptions); + syntaxError = e; + } + + if (css.startsWith('\uFEFF')) { + walkNodes(root, (node) => { + for (const point of [node.source?.start, node.source?.end]) { + if (point) { + if (point.line === 1) point.column++; + if (point.offset !== undefined) point.offset++; + } + } + }); + } + if (syntaxError) joinStrayBraces(root, input); + if (root.source && (input !== css || css.startsWith('\uFEFF'))) { + root.source.input.css = css; + } + return { root, syntaxError }; +} + +// PostCSS ends a rule after a `;` read after it (`ownSemicolon`), but the +// safe parser leaves the stray `}` before that `;` out of `ownSemicolon`. +// Only a root rule has one, as a `}` in a block closes the block. Adds the +// text after the rule's own `}`, found after its body, to `ownSemicolon`. +function joinStrayBraces(root: postcss.Root, input: string): void { + for (const node of root.nodes) { + if (node.type !== 'rule' || !node.raws.ownSemicolon) continue; + const end = node.source?.end?.offset; + const open = blockOpeningOffset(node); + const from = node.last + ? node.last.source?.end?.offset + : open === undefined + ? undefined + : open + 1; + const after = node.raws.after ?? ''; + if ( + end === undefined || + from === undefined || + !input.startsWith(after, from) + ) + continue; + const close = from + after.length; + if (input[close] === '}' && close + 1 < end - node.raws.ownSemicolon.length) + node.raws.ownSemicolon = input.slice(close + 1, end); + } +} + +interface CompatibilityParse { + root: postcss.Root; + source: CompatibilitySource; + errors: CssParseError[]; +} + +// `errors` with `inserted` before the first error at or after `offset`. +function insertErrors( + errors: CssParseError[], + inserted: CssParseError[], + source: CompatibilitySource, + offset: number, +): CssParseError[] { + let index = 0; + while ( + index < errors.length && + source.offsetAt(errors[index].line, errors[index].column) < offset + ) + index++; + return errors.slice(0, index).concat(inserted, errors.slice(index)); +} + +// Parses `css` as V4 does. From a chain break, V4 reads text PostCSS reads +// as nested, so the input is parsed again as V4 reads on, at most +// `budget.left` more times; past that, recovery approximates the rest. +function parseCompatibility( + css: string, + sourceName: string, + silent: boolean, + preserveComments: boolean, + budget: { left: number }, + original = css, +): CompatibilityParse { + const input = prepareCompatibilityInput(css); + let { root, syntaxError } = parsePostcss(css, input); + let source = new CompatibilitySource(css, sourceName, undefined, original); + restoreCompatibilitySpans(root, source, preserveComments); + let errors = collectCompatibilityErrors( + source, + root, + silent, + input, + syntaxError, + budget.left > 0, + ); + if (source.braceConflicts.length) { + // V4 opens rules at some skipped braces, so read them again as rules. + ({ root, syntaxError } = parsePostcss(css, input)); + source = new CompatibilitySource( + css, + sourceName, + new Set(source.braceConflicts), + original, + ); + restoreCompatibilitySpans(root, source, preserveComments); + errors = collectCompatibilityErrors( + source, + root, + silent, + input, + syntaxError, + budget.left > 0, + ); + } + const parseAgain = (text: string): CompatibilityParse => { + budget.left--; + const parsed = parseCompatibility( + text, + sourceName, + silent, + preserveComments, + budget, + original, ); + if (parsed.root.source) parsed.root.source.input.css = css; + source.orphanBrace = parsed.source.orphanBrace; + const bracket = parsed.source.bracketError; + source.bracketError = bracket + ? source.error( + bracket.reason, + source.offsetAt(bracket.line, bracket.column), + ) + : undefined; + return { + root: parsed.root, + source, + // Texts parsed again keep the input's line breaks, so their errors' + // lines and columns are already this parse's. + errors: parsed.errors, + }; + }; + const comment = + !preserveComments && budget.left > 0 ? valueComment(root, css) : undefined; + if (comment) { + // V4 reads the input as it reads it without the comment text it takes + // as value text, except for that value. + const parsed = parseAgain(blankRange(css, comment.start, comment.end)); + walkNodes(parsed.root, (node) => { + if ( + node.type === 'decl' && + node.source?.start?.offset === comment.declaration && + node.source.end?.offset === comment.end + 1 + ) { + node.value = trim(css.slice(comment.value, comment.end)); + node.important = false; + delete node.raws.value; + delete node.raws.important; + } + }); + return parsed; + } + const found = recoverCompatibility( + root, + source, + errors, + silent, + preserveComments, + !silent || budget.left > 0, + ); + if (!found) { + const resume = source.rootResume; + if (resume === undefined) return { root, source, errors }; + // V4 reads on from where it reads a rule or an at-rule. Everything + // before that stays as read here: V4 reads no selector across the text + // that stops it, so the text before it must not be parsed again. + const before = (offset: number | undefined) => + offset === undefined || offset < resume; + const read = root.nodes.filter((node) => + before(node.source?.start?.offset), + ); + const parsed = parseAgain(blankRange(css, 0, resume)); + parsed.errors = [ + ...errors.filter((error) => + before(source.offsetAt(error.line, error.column)), + ), + ...parsed.errors, + ]; + // Outer re-parses update the input text of the parsed root only. + const input = parsed.root.source?.input; + if (input) { + for (const node of read) { + if (node.source) node.source.input = input; + if (node.type === 'rule' || node.type === 'atrule') + node.walk((child) => { + if (child.source) child.source.input = input; + }); + } + } + // `prepend` moves nodes one at a time, so the roots are rebuilt instead. + const nodes = read.concat(parsed.root.nodes); + root.removeAll(); + parsed.root.removeAll(); + parsed.root.append(nodes); + return parsed; } - /** - * Parse rule. - */ - function rule() { - const pos = position(); - const sel = selector(); + const { kind, offset, levels } = found; + const before = errors.filter( + (error) => + source.offsetAt(error.line, error.column) < + (found.value?.start ?? offset), + ); + const missing = (error: string) => source.error(error, offset); + const closing = (node: postcss.Rule | postcss.AtRule) => + missing( + node.type === 'atrule' + ? `@${atRuleErrorName(node.name)} missing '}'` + : "missing '}'", + ); + if (kind === 'header' && found.header) { + // V4 reads on from where the header ends, as a rule. + const error = missing(found.header.reason); + if (!silent) return { root, source, errors: before.concat(error) }; + const parsed = parseAgain(blankRange(css, found.header.start, offset)); + parsed.errors = insertErrors(parsed.errors, [error], source, offset); + return parsed; + } + if (!silent) { + // Strict parsing stops at the first error. + before.push( + kind === 'quote' || (kind === 'empty' && levels[0].reader === 'rules') + ? missing('selector missing') + : found.colon + ? missing("property missing ':'") + : closing(levels[0].node), + ); + return { root, source, errors: before }; + } - if (!sel) { - return error('selector missing'); + if (kind === 'quote') { + // V4 fails to read a selector at each character up to the quote. + const skipped: CssParseError[] = []; + for (let at = offset; at <= found.quote; at++) { + if (!/\s/.test(css[at])) + skipped.push(source.error('selector missing', at)); } - comments(); + const parsed = parseAgain(blankRange(css, offset, found.quote + 1)); + parsed.errors = insertErrors(parsed.errors, skipped, source, offset); + return parsed; + } - return pos({ - type: CssTypes.rule, - selectors: sel, - declarations: ruleBody() || [], + if (kind === 'declarations') { + // V4 reads on in the enclosing body from where it drops the block. + const block = levels[0].node; + const start = block.source?.start?.offset ?? 0; + const dropped = errors.filter((error) => { + const at = source.offsetAt(error.line, error.column); + return at >= start && at < offset; }); + if (found.colon) dropped.push(missing("property missing ':'")); + dropped.push(closing(block)); + const parsed = parseAgain(blankRange(css, start, offset)); + parsed.errors = insertErrors(parsed.errors, dropped, source, start); + return parsed; } - return addParent(stylesheet()); -}; - -/** - * Trim `str`. - */ -function trim(str: string) { - return str ? str.trim() : ''; -} + if (kind === 'miss' && found.miss) { + // V4 drops an at-rule body it fails to close, keeps a rule without its + // content, and reads on in the enclosing body. + const block = levels[0].node; + const start = block.source?.start?.offset ?? 0; + const { miss } = found; + const dropped = errors.filter((error) => { + const at = source.offsetAt(error.line, error.column); + return at >= start && at < miss.start; + }); + // Spread arguments overflow the stack for many errors. + for (const error of miss.errors) dropped.push(error); + dropped.push(closing(block)); + const parsed = parseAgain(blankRange(css, start, offset)); + parsed.errors = insertErrors(parsed.errors, dropped, source, start); + if (block.type === 'rule' && block.source) { + block.removeAll(); + const end = source.pointAt(offset); + block.source.end = { line: end.line, column: end.column - 1, offset }; + const next = parsed.root.nodes.find( + (node) => (node.source?.start?.offset ?? 0) >= offset, + ); + if (next) parsed.root.insertBefore(next, block); + else parsed.root.append(block); + } + return parsed; + } -/** - * Adds non-enumerable parent node reference to each node. - */ -function addParent( - obj: T1, - parent?: unknown, -): T1 { - const isNode = obj && typeof obj.type === 'string'; - const childParent = isNode ? obj : parent; - - for (const k in obj) { - const value = obj[k]; - if (Array.isArray(value)) { - value.forEach((v) => { - addParent(v, childParent); - }); - } else if (value && typeof value === 'object') { - addParent(value, childParent); + if (kind === 'value' && found.value) { + const { valueStart, end } = found.value; + const property = found.colon ? [missing("property missing ':'")] : []; + if (end !== -1) { + // V4 reads the value as empty, then reads on in the same body from + // where it skips to, as it reads an empty value ended by `;`. + const blank = blankRange(css, valueStart, end); + const parsed = parseAgain( + `${blank.slice(0, valueStart)};${blank.slice(valueStart + 1)}`, + ); + parsed.errors = insertErrors(parsed.errors, property, source, offset); + return parsed; } + before.push(...property); } - if (isNode) { - Object.defineProperty(obj, 'parent', { - configurable: true, - writable: true, - enumerable: false, - value: parent || null, - }); + const semicolon = css.indexOf(';', offset); + const brace = css.indexOf('}', offset); + if ( + semicolon !== -1 && + (brace === -1 || semicolon < brace) && + levels[0].reader === 'rules' + ) { + // V4 skips to the `;` and reads on in the same block. + const parsed = parseAgain(blankRange(css, offset, semicolon + 1)); + if (kind === 'empty') { + parsed.errors = insertErrors( + parsed.errors, + [missing('selector missing')], + source, + offset, + ); + } + return parsed; } - return obj; + // V4 closes every enclosing block there, each failing to read a rule + // without a selector first, and reads the rest from the root. + for (const { node, reader } of levels) { + if (kind === 'empty' && reader === 'rules') + before.push(missing('selector missing')); + before.push(closing(node)); + } + const outer = levels[levels.length - 1].node; + const outerStart = outer.source?.start?.offset ?? 0; + const kept = root.nodes.filter( + (node) => (node.source?.start?.offset ?? 0) < outerStart, + ); + if (outer.type === 'rule' && outer.source) { + // V4 keeps the rule without its content. + outer.removeAll(); + const end = source.pointAt(offset); + outer.source.end = { line: end.line, column: end.column - 1, offset }; + kept.push(outer); + } + const rest = parseAgain(blankRange(css, 0, offset)); + const nodes = rest.root.nodes.slice(); + rest.root.removeAll(); + root.removeAll(); + root.append(kept.concat(nodes)); + return { root, source, errors: before.concat(rest.errors) }; } +export const parse = ( + css: string, + options?: ParseOptions, +): CssStylesheetAST => { + const sourceName = options?.source ?? ''; + const silent = options?.silent ?? false; + const preserveComments = options?.stripCommentsInValues === false; + const { root, source, errors } = parseCompatibility( + css, + sourceName, + silent, + preserveComments, + { left: 8 }, + ); + let parsingErrors = errors; + const orphan = silent ? undefined : source.orphanBrace; + const before = (error: CssParseError) => + orphan === undefined || source.offsetAt(error.line, error.column) < orphan; + if (orphan !== undefined) { + const retained = root.nodes.filter( + (node) => (node.source?.start?.offset ?? 0) < orphan, + ); + if (retained.length !== root.nodes.length) { + root.removeAll(); + root.append(retained); + } + parsingErrors = parsingErrors.filter(before); + } + if ( + !parsingErrors.length && + source.bracketError && + before(source.bracketError) + ) + parsingErrors = [source.bracketError]; + if (!silent && parsingErrors.length) throw parsingErrors[0]; + + return buildStylesheet( + root, + sourceName, + options?.source, + parsingErrors, + options?.stripCommentsInValues !== false, + ); +}; + export default parse; diff --git a/src/postcss-safe-parser.d.ts b/src/postcss-safe-parser.d.ts new file mode 100644 index 00000000..62812bc3 --- /dev/null +++ b/src/postcss-safe-parser.d.ts @@ -0,0 +1,9 @@ +declare module 'postcss-safe-parser' { + import type { ProcessOptions, Root } from 'postcss'; + + function safeParse( + css: string | { toString(): string }, + opts?: ProcessOptions, + ): Root; + export = safeParse; +} diff --git a/src/utils/stringSearch.test.ts b/src/utils/stringSearch.test.ts index 70777284..7c68588d 100644 --- a/src/utils/stringSearch.test.ts +++ b/src/utils/stringSearch.test.ts @@ -97,6 +97,17 @@ describe('indexOfArrayWithBracketAndQuoteSupport', () => { indexOfArrayWithBracketAndQuoteSupport(tooManyBrackets, [')']), ).toThrow('Too many escaping'); }); + + it('should handle deeply nested brackets without overflowing the stack', () => { + const depth = 100_000; + const nested = `${'('.repeat(depth)}"a,b"${')'.repeat(depth)}`; + expect(indexOfArrayWithBracketAndQuoteSupport(`${nested},c`, [','])).toBe( + nested.length, + ); + expect( + indexOfArrayWithBracketAndQuoteSupport(`${'('.repeat(depth)},c`, [',']), + ).toBe(-1); + }); }); describe('splitWithBracketAndQuoteSupport', () => { @@ -136,4 +147,11 @@ describe('splitWithBracketAndQuoteSupport', () => { test('handles empty strings', () => { expect(splitWithBracketAndQuoteSupport('', [','])).toEqual([]); }); + + test('splits long lists', () => { + const parts = Array.from({ length: 50_000 }, (_, index) => `.c${index}`); + expect(splitWithBracketAndQuoteSupport(parts.join(','), [','])).toEqual( + parts, + ); + }); }); diff --git a/src/utils/stringSearch.ts b/src/utils/stringSearch.ts index 3d99c3ba..331e4e5d 100644 --- a/src/utils/stringSearch.ts +++ b/src/utils/stringSearch.ts @@ -1,5 +1,27 @@ export const MAX_LOOP = 10000; +const BACKSLASH = 92; +const DOUBLE_QUOTE = 34; +const SINGLE_QUOTE = 39; +const OPEN_PARENTHESIS = 40; +const CLOSE_PARENTHESIS = 41; + +// The searches below read the string only up to their result, unlike one +// `indexOf` per token, so splitting a string with repeated searches is linear. +const startsWithAny = ( + string: string, + search: Array, + position: number, +): boolean => { + const char = string.charCodeAt(position); + for (let index = 0; index < search.length; index++) { + const value = search[index]; + if (value.charCodeAt(0) === char && string.startsWith(value, position)) + return true; + } + return false; +}; + /** * Find the first occurrence of any search string in the input string, ignoring escaped characters * @param string - The input string to search in @@ -21,26 +43,18 @@ export const indexOfArrayNonEscaped = ( search: Array, position?: number, ): number => { - let currentPosition = position; let maxLoop = MAX_LOOP; - do { - const all = search.map((v) => string.indexOf(v, currentPosition)); - all.push(string.indexOf('\\', currentPosition)); - const foundAll = all.filter((v) => v !== -1); - if (foundAll.length === 0) { - return -1; - } - - const found = Math.min(...foundAll); - if (string[found] === '\\') { - currentPosition = found + 2; - maxLoop--; + for (let offset = Math.max(0, position ?? 0); offset < string.length; ) { + if (string.charCodeAt(offset) === BACKSLASH) { + if (--maxLoop === 0) throw new Error('Too many escaping'); + offset += 2; + } else if (startsWithAny(string, search, offset)) { + return offset; } else { - return found; + offset++; } - } while (maxLoop > 0); - - throw new Error('Too many escaping'); + } + return -1; }; /** @@ -71,74 +85,44 @@ export const indexOfArrayWithBracketAndQuoteSupport = ( search: Array, position?: number, ): number => { - let currentSearchPosition = position; - let maxLoop = MAX_LOOP; - - do { - const all = search.map((v) => string.indexOf(v, currentSearchPosition)); - - all.push(string.indexOf('(', currentSearchPosition)); - all.push(string.indexOf('"', currentSearchPosition)); - all.push(string.indexOf("'", currentSearchPosition)); - all.push(string.indexOf('\\', currentSearchPosition)); - - const foundAll = all.filter((v) => v !== -1); - if (foundAll.length === 0) { - return -1; + // Each `(` starts a nested search for its `)` with its own loop budget. The + // enclosing budgets are kept on a stack instead of recursing, so deep + // nesting cannot overflow the call stack. + const enclosing: Array = []; + let budget = MAX_LOOP; + for (let offset = Math.max(0, position ?? 0); offset < string.length; ) { + const char = string.charCodeAt(offset); + let end: number; + if (char === BACKSLASH) { + end = offset + 1; + } else if (char === OPEN_PARENTHESIS) { + enclosing.push(budget); + budget = MAX_LOOP; + offset++; + continue; + } else if (char === DOUBLE_QUOTE || char === SINGLE_QUOTE) { + end = indexOfArrayNonEscaped(string, [string[offset]], offset + 1); + if (end === -1) { + return -1; + } + } else if (char === CLOSE_PARENTHESIS && enclosing.length > 0) { + budget = enclosing.pop() as number; + end = offset; + } else if ( + enclosing.length === 0 && + startsWithAny(string, search, offset) + ) { + return offset; + } else { + offset++; + continue; } - - const firstMatchPos = Math.min(...foundAll); - const char = string[firstMatchPos]; - switch (char) { - case '\\': - currentSearchPosition = firstMatchPos + 2; - break; - case '(': - { - const endPosition = indexOfArrayWithBracketAndQuoteSupport( - string, - [')'], - firstMatchPos + 1, - ); - if (endPosition === -1) { - return -1; - } - currentSearchPosition = endPosition + 1; - } - break; - case '"': - { - const endQuotePosition = indexOfArrayNonEscaped( - string, - ['"'], - firstMatchPos + 1, - ); - if (endQuotePosition === -1) { - return -1; - } - currentSearchPosition = endQuotePosition + 1; - } - break; - case "'": - { - const endQuotePosition = indexOfArrayNonEscaped( - string, - ["'"], - firstMatchPos + 1, - ); - if (endQuotePosition === -1) { - return -1; - } - currentSearchPosition = endQuotePosition + 1; - } - break; - default: - return firstMatchPos; + if (--budget === 0) { + throw new Error('Too many escaping'); } - maxLoop--; - } while (maxLoop > 0); - - throw new Error('Too many escaping'); + offset = end + 1; + } + return -1; }; /** diff --git a/test/bundle-compatibility.mjs b/test/bundle-compatibility.mjs new file mode 100644 index 00000000..70bc3014 --- /dev/null +++ b/test/bundle-compatibility.mjs @@ -0,0 +1,226 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { runInNewContext } from 'node:vm'; +import * as v4 from 'css-tools-v4'; + +const require = createRequire(import.meta.url); +const umd = readFileSync( + new URL('../dist/umd/adobe-css-tools.js', import.meta.url), + 'utf8', +); +const notices = readFileSync( + new URL('../dist/umd/adobe-css-tools.LICENSES.txt', import.meta.url), + 'utf8', +); +for (const name of ['postcss', 'postcss-safe-parser', 'nanoid', 'picocolors']) { + const license = readFileSync( + new URL(`../node_modules/${name}/LICENSE`, import.meta.url), + 'utf8', + ); + assert.ok(notices.includes(`${name}\n\n${license}`)); +} +assert.ok(umd.includes('adobe-css-tools.LICENSES.txt')); +const browser = {}; +runInNewContext(umd, browser); +const commonjsExports = {}; +runInNewContext(umd, { + exports: commonjsExports, + module: { exports: commonjsExports }, +}); +let amdExports; +const define = (dependencies, factory) => { + assert.deepEqual(Array.from(dependencies), ['exports']); + amdExports = {}; + factory(amdExports); +}; +define.amd = true; +runInNewContext(umd, { define }); + +const bundles = [ + ['CJS', require('../dist/cjs/adobe-css-tools.cjs')], + ['ESM', await import('../dist/esm/adobe-css-tools.mjs')], + ['UMD/browser', browser.cssTools], + ['UMD/CommonJS', commonjsExports], + ['UMD/AMD', amdExports], +]; +const inputs = [ + '', + 'a { color: red; }', + 'a{color:red;};\nb{color:blue;}', + '@supports (x:y){a{b:c;};d{e:f}}', + 'a{color:red;\u00A0background:blue}', + '@media x{a{\u2028background:blue}}', + '\u00A0a{color:red}', + '\u00A0@media x{a{color:red}}', + 'a{--x:{color:red};\uFEFFmargin:0;}', + '@media screen { a { content: "/* text */"; color: red/**/blue; } }', + 'a { _color: blue; *zoom: 1; }', + '@keyframes example { from { opacity: 0 } to { opacity: 1 } }', + 'a { color red; }', + 'a {} /*', + '{ color: red; }', + 'a {} } b {}', + 'a { color: red; }\n/*# sourceMappingURL=data:application/json;base64,bm90LWpzb24= */', + 'a { color: /* keep */ red; }', + 'a {\n color: red\n background: blue;\n}', + 'a { color:: red }', + 'a { color: red: blue }', + 'a { : red }', + 'a { color: red; : blue; margin: 0; }', + '@media /* keep */ screen { a {} }', + '@import url(x.css) /* keep */ screen;', + '@unknown /* keep */ value;', + '@custom-media --x /* keep spacing */ (width > 1px);', + 'a { color: red /* brand */ }', + 'a { color: red /* a */ /* b */ }', + '@tailwind base;\n', + '@unknown value;\r\n \t a {}', + '@media screen { @unknown value;\n a {} }', + '\uFEFFa {\r\n color red;\r\n margin: 0;\r\n}', + 'a { color red }\na { color red }', + 'garbage', + 'a{} garbage', + 'garbage; a{}', + 'a{--foo\\:bar:red;}', + 'a{*foo\\:bar:red; _foo\\:bar:blue;}', + 'a{--x:{color:red; padding:0}}', + 'a{--x:{--y:{color:red}}}', + '@media x{--x:{color:red; padding:0}}', + 'a{--x:{color:red}; margin:0;}', + '@foo', + '@foo\r\n \t', + 'a{}\r\n@foo\n', + '\uFEFF@foo\n', + '@layer{a{color:red}}', + '@unknown x', + '@foo /*c*/ @bar', + '@layer a,b /*c*/', + '@charset "UTF-8" \n', + '@import "x" \n', + '@namespace url(x) \n', + 'a{\\63 olor:red}', + '@keyframes x;', + '@-webkit-keyframes x;', + '@-moz-document url(x);', + '@page{@top-left;}', + '@page{@top-left;/*c*/}', + '@font-face{--x:{a:b}}', + '@font-face{color: /* } */red}b{}', + '@keyframes x{0%{--x:{a:b}}}', + '@media a{@foo /*c*/}', + '@media a{@foo /*c*/ @bar}', + '@page{@foo /*c*/}', + '@media a{@keyframes x;}b{c:d}', + 'a{@-webkit-keyframes x; /*c*/ c:d;}b{c:d}', + '@supports (display:grid){@keyframes x junk; c:d;}b{c:d}', + '@layer a{@keyframes x c:/*keep*/d;}b{c:d}', + 'a{@keyframes x /**/ c:d;}', +]; + +function visible(value) { + if (Array.isArray(value)) return Array.from(value, visible); + if (value && typeof value === 'object') { + return Object.fromEntries([ + ...(typeof value.message === 'string' + ? [ + ['name', value.name], + ['message', value.message], + ] + : []), + ...Object.entries(value).map(([key, child]) => [key, visible(child)]), + ]); + } + return value; +} + +function outcome(parser, css, options) { + try { + return { ast: parser(css, options) }; + } catch (error) { + return { error: visible(error) }; + } +} + +for (const [name, api] of bundles) { + assert.deepEqual(Object.keys(api).sort(), Object.keys(v4).sort(), name); + assert.equal(api.default.parse, api.parse, name); + assert.equal(api.default.stringify, api.stringify, name); + assert.deepEqual(visible(api.CssTypes), visible(v4.CssTypes), name); + for (const css of inputs) { + for (const options of [ + {}, + { source: 'bundle.css' }, + { silent: true, source: 'bundle.css' }, + ]) { + const expected = outcome(v4.parse, css, options); + const actual = outcome(api.parse, css, options); + assert.deepEqual(visible(actual), visible(expected), name); + if (actual.ast && expected.ast) { + for (const formatting of [{}, { compress: true }, { indent: '\t' }]) { + assert.equal( + api.stringify(actual.ast, formatting), + v4.stringify(expected.ast, formatting), + name, + ); + assert.equal( + api.stringify(expected.ast, formatting), + v4.stringify(expected.ast, formatting), + name, + ); + } + } + } + } + for (const [css, expected] of [ + ['a { content: "/* text */"; }', 'a{content:"/* text */";}'], + ['a{color:/*keep*/red;}', 'a{color:/*keep*/red;}'], + ['a{\u00A0color:/*keep*/red;}', 'a{color:/*keep*/red;}'], + [ + '@media x{\u00A0a{\u2028color:/*keep*/red;}}', + '@media x{a{color:/*keep*/red;}}', + ], + ['a{color:/*keep*/red !important;}', 'a{color:/*keep*/red !important;}'], + ['a { color: red /* brand */ }', 'a{color:red /* brand */;}'], + ['a{color:/* ; } ( " */red;}', 'a{color:/* ; } ( " */red;}'], + ['a{color:red/* ; } ( " */}', 'a{color:red/* ; } ( " */;}'], + [ + 'a{color:var(--x, /* ) ; } */ red);}', + 'a{color:var(--x, /* ) ; } */ red);}', + ], + ['a{--foo\\:bar:/*keep*/red;}', 'a{--foo\\:bar:/*keep*/red;}'], + [ + 'a{--x:{color:/*keep*/red; padding:0}}', + 'a{--x:{color:/*keep*/red;padding:0;}}', + ], + ]) { + for (const silent of [false, true]) { + assert.equal( + api.stringify( + api.parse(css, { silent, stripCommentsInValues: false }), + { compress: true }, + ), + expected, + name, + ); + } + } + for (const value of ['/*keep*/red', 'red /*keep*/', '/* ; } */red']) { + const ast = api.parse(`@media a{@keyframes x color:${value};}`, { + silent: true, + stripCommentsInValues: false, + }); + assert.equal(ast.stylesheet.parsingErrors.length, 1, name); + assert.equal( + ast.stylesheet.parsingErrors[0].reason, + "@keyframes missing '{'", + name, + ); + assert.equal( + api.stringify(ast, { compress: true }), + `@media a{color:${value};}`, + name, + ); + } + console.log(`${name}: exports, ASTs, errors, formatting and option passed`); +} diff --git a/test/compatibility.test.ts b/test/compatibility.test.ts new file mode 100644 index 00000000..037b0b4b --- /dev/null +++ b/test/compatibility.test.ts @@ -0,0 +1,1035 @@ +import { createHash } from 'node:crypto'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { parse as parseV4, stringify as stringifyV4 } from 'css-tools-v4'; +import postcss from 'postcss'; +import { type ParseOptions, parse, stringify } from '../src/index'; +import type { CssAtRuleAST, CssDeclarationAST } from '../src/type'; + +const cases = fs.readdirSync(path.join(__dirname, 'cases')).map((name) => ({ + name: `fixture/${name}`, + css: fs.readFileSync( + path.join(__dirname, 'cases', name, 'input.css'), + 'utf8', + ), +})); + +const edgeCases = [ + '', + ' \r\n\t', + 'a { color: red }', + 'a { color: red ; }', + 'a {\n color: red\n}', + 'a { color: red /* comment */; }', + 'a { *color: red; _color: blue; }', + 'a { color: red!important; }', + 'a { color: red ! important; }', + 'a { content: "/* not a comment */"; }', + 'a { content: "}"; }', + '@MEDIA screen { a { color: red; } }', + '@layer reset;\n\n a {}', + '@unknown x { color: red; }', + 'a { color red; }', + 'a { color: red', + 'a {} /*', + '{ color: red; }', + 'a {} } b {}', + 'foo { color= red; } bar { color: blue; } baz {}} boo { display: none}', + 'a { content: "/*"; }', + 'a { color: /* before */red/* after */; }', + 'a { color: red !/**/important; }', + 'a { co/**/lor: red; }', + '.a\\{b { color: red; } .x {}', + '.a\\}b { color: red; } .x {}', + 'a { background: url(data:image/svg+xml,{x}); } .x {}', + 'a { COLOR: RED; }', + '\uFEFFa { color: red; }', + 'a { color: red; /* trailing */ }', + '@media screen { a { color: red } }', + '@keyframes test { 0%, 100% { opacity: 0; } }', + '@media screen { a { color red; } }', + 'a { color red; background blue; }', + 'a {\n color red;\n background blue;\n}', + 'a { color: red;', + 'a {', + '@media screen { a {}', + '@font-face { font-family: test;', + '@media screen;', + '@supports (display: grid);', + '@keyframes {}', + '@import "x";\n a { color red; }', + 'a { color: red }\n/* unterminated', + 'a { color: red; /* unterminated', + 'a { content: "unterminated; }', + 'a { color:red;;background:blue; }', + 'a { & b { color: blue; } }', + '@unknown a { color:red; a { margin:0; } }', + '@charset "UTF-8";\r\n/* comment */\r\na{color: red}', + 'a{color: red}\n\nb {margin: 0}', + 'a { color: red; }\n/*# sourceMappingURL=data:application/json;base64,bm90LWpzb24= */', + 'a { color red; }\n/*# sourceMappingURL=data:application/json;base64,bm90LWpzb24= */', +]; + +cases.push(...edgeCases.map((css, index) => ({ name: `edge/${index}`, css }))); + +const regressions = [ + ['leading-value-comment', 'a { color: /* keep */ red; }'], + ['missing-semicolon', 'a {\n color: red\n background: blue;\n}'], + ['double-colon', 'a { color:: red }'], + ['extra-value-colon', 'a { color: red: blue }'], + ['empty-property', 'a { : red }'], + ['empty-property-after-declaration', 'a { color: red; : blue; margin: 0; }'], + ['media-prelude-comment', '@media /* c */ screen { a {} }'], + ['import-prelude-comment', '@import url(x.css) /* c */ screen;'], + ['generic-prelude-comment', '@unknown /* c */ value;'], + ['trailing-value-comment', 'a { color: red /* brand */ }'], + ['multiple-trailing-value-comments', 'a { color: red /* a */ /* b */ }'], + ['trailing-value-comment-newline', 'a {\n color: red /* brand */\n}'], + ['generic-statement-newline', '@tailwind base;\n'], + ['generic-statement-whitespace', '@unknown value;\r\n \t a {}'], + ['nested-generic-statement', '@media screen { @unknown value;\n a {} }'], + ['commented-property', 'a { co/**/lor: /* keep */ red; }'], + [ + 'commented-hack-values', + 'a { *zoom: /* keep */ 1; _color: blue /* end */ }', + ], + [ + 'standalone-comments-after-semicolons', + 'a { color: red; /* keep */ margin: 0; /* end */ }', + ], + ['nested-trailing-value-comment', 'a { & b { color: red /* end */ } }'], + [ + 'important-trailing-comment', + 'a { color: /* keep */ red !/**/important /* end */ }', + ], + [ + 'quoted-value-delimiters', + 'a { content: "a;}"; background: url("data:x,{};"); }', + ], + ['bom-trailing-value-comment', '\uFEFFa { color: red /* end */ }'], + [ + 'bom-malformed-declarations', + '\uFEFFa {\r\n color red;\r\n margin: 0;\r\n}', + ], + [ + 'bom-malformed-empty-property', + '\uFEFFa { color: red; : blue; margin: 0; }', + ], + ['crlf-missing-semicolon', 'a {\r\n color: red\r\n margin: 0;\r\n}'], + ['layer-block-position', '@layer /* keep */ base { a {} }\r\n b {}'], + [ + 'document-block-position', + '@-moz-document /* keep */ url(x) { a {} }\n b {}', + ], + [ + 'supports-prelude-comments', + '@supports /* keep */ (display: grid) /* end */ { a {} }', + ], + ['import-leading-prelude-comment', '@import /* keep */ url(x.css) screen;'], + ['namespace-prelude-comment', '@namespace /* keep */ url("x");'], + [ + 'custom-media-prelude-comments', + '@custom-media --x /* keep spacing */ (width > 1px);', + ], + [ + 'custom-media-multiline-prelude', + '@custom-media --x\n /* keep */ (width:\n 1px);\n', + ], + ['generic-block-prelude-comment', '@unknown /* keep */ x /* end */ { a {} }'], + [ + 'malformed-declarations-with-valid-siblings', + 'a { color red; margin: 0; background blue; padding: 1px; }', + ], + [ + 'nested-malformed-declarations', + '@media screen { a { color red; margin: 0; } b {} }', + ], + [ + 'valid-rule-after-malformed-declarations', + 'a { color red; margin: 0; } b { color: blue; }', + ], + ['malformed-unclosed-declaration', 'a { color red; margin: 0;'], + ['unknown-top-level-word', 'garbage'], + ['unknown-top-level-tail', 'a{} garbage'], + ['unknown-before-statement', 'garbage; @import "x";'], + ['unknown-prefix-in-selector', 'garbage; a{}'], + ['unknown-tail-after-malformed-rule', 'a { color red; } garbage'], + ['bom-unknown-top-level-tail', '\uFEFFa{} \r\ngarbage'], + ['top-level-declaration', 'color:red;'], + ['declaration-prefix-in-selector', 'color:red; a{}'], + ['escaped-custom-property-colon', 'a{--foo\\:bar:red;}'], + ['escaped-property-colon', 'a{foo\\:bar:red;}'], + ['escaped-hack-property-colon', 'a{*foo\\:bar:red; _foo\\:bar:blue;}'], + ['escaped-commented-property-colon', 'a{co/**/lor\\:name:/* keep */red;}'], + ['multiple-escaped-property-colons', 'a{--foo\\:bar\\:baz:red;}'], + ['escaped-property-empty-value', 'a{--foo\\:bar:;}'], + ['escaped-property-important', 'a{--foo\\:bar:red !important;}'], + ['escaped-property-separator-whitespace', 'a { --foo\\:bar : "red"; }'], + ['custom-property-block', 'a{--x : {a:b}}'], + ['custom-property-block-semicolons', 'a{--x:{color:red; padding:0}}'], + ['custom-property-block-prefix', 'a{--x:prefix {a:b}}'], + ['custom-property-block-comments', 'a{--x:/* name */{color:/* keep */red}}'], + ['nested-custom-property-blocks', 'a{--x:{--y:{color:red}}}'], + ['custom-property-block-quoted-header', 'a{--x:"{};--z:" {color:red}}'], + [ + 'custom-property-literal-delimiters', + 'a{--x:"{color:red;}"; --y:var(--z,{padding:0});}', + ], + [ + 'custom-property-block-siblings', + 'a{color:blue; --x:{color:red; padding:0} margin:0;} b{padding:1px;}', + ], + ['custom-property-block-trailing-semicolon', 'a{--x:{color:red}; margin:0;}'], + ['custom-property-block-media', '@media x{--x:{color:red; padding:0}}'], + ['custom-property-block-layer', '@layer x{a{--x:{color:red}}}'], + ['custom-property-block-generic', '@unknown x{--x:{color:red}}'], + ['custom-property-block-root', '--x:{color:red}'], + [ + 'custom-property-block-bom-crlf', + '\uFEFFa{\r\n --x : {\r\n color:red;\r\n padding:0\r\n }\r\n}', + ], + ['generic-eof', '@foo'], + ['generic-eof-space', '@foo '], + ['generic-eof-newline', '@foo\n'], + ['generic-eof-crlf', '@foo\r\n \t'], + ['generic-eof-after-rule', 'a{}\r\n@foo\n'], + ['generic-eof-bom', '\uFEFF@foo\n'], + ['anonymous-layer-minified', '@layer{a{color:red}}'], + ['anonymous-layer-spaced', '@layer {a{color:red}}'], + ['anonymous-layer-empty', '@layer{}b{margin:0}'], + ['parameterized-generic-eof', '@unknown x'], + ['parameterized-generic-eof-comment', '@unknown x /*c*/'], + ['generic-eof-comment', '@foo /*c*/'], + ['generic-eof-comment-crlf', '@foo \r\n/* c */\r\n'], + ['generic-eof-following-generic', '@foo /*c*/ @bar'], + ['parameterized-generic-eof-following-generic', '@unknown x /*c*/ @bar'], + ['parameterized-generic-eof-trivia', '@unknown x \n'], + ['bare-known-media-eof', '@media'], + ['bare-known-supports-eof', '@supports'], + ['bare-known-import-eof', '@import'], + ['layer-statement-eof-comment', '@layer a,b /*c*/'], + ['layer-statement-eof-comment-control', '@layer a,b /*c*/;'], + ['statement-eof-trivia-charset', '@charset "UTF-8" \n'], + ['statement-eof-trivia-import', '@import "x" \n'], + ['statement-eof-trivia-namespace', '@namespace url(x) \n'], + ['escaped-hex-property', 'a{\\63 olor:red}'], + ['empty-keyframes-space', '@keyframes x { }'], + ['empty-keyframes-newline', '@keyframes x{\n}'], + ['empty-keyframes-crlf-tab', '@keyframes x {\r\n\t}\nb{}'], + ['empty-keyframes-v4-whitespace', '@keyframes x{\u00A0\u2028}'], + ['empty-vendor-keyframes', '@-webkit-keyframes x {\n}\n@keyframes x {\n}'], + ['empty-nested-keyframes', '@media screen { @keyframes x { } }'], + ['empty-keyframes-comment', '@keyframes x { /* c */ }'], + ['missing-block-keyframes', '@keyframes x;'], + ['missing-block-keyframes-trivia', '@keyframes x \r\n;'], + ['missing-block-keyframes-following-rule', '@keyframes x; a{}'], + ['missing-block-vendor-keyframes', '@-webkit-keyframes x;'], + ['missing-block-vendor-document', '@-moz-document url(x);'], + [ + 'missing-block-vendor-document-prelude-semicolon', + '@-moz-document url(x); a{}', + ], + ['missing-block-page-margin', '@page{@top-left;}'], + ['missing-block-page-margin-root', '@top-left;'], + ['missing-block-page-margin-comment', '@page{@top-left;/*c*/}'], + ['missing-block-page-margin-following-rule', '@page{@top-left;} a{}'], + [ + 'missing-block-page-margin-remaining-child', + '@page{@top-left; @bottom-left{x:y}}', + ], + ['declaration-only-font-face', '@font-face{--x:{a:b}}'], + [ + 'declaration-only-font-face-following-rule', + '@font-face{--x:{a:b}}/*end*/b{color:red}', + ], + ['declaration-only-nested-custom-block', '@font-face{x:{{a:b}}}'], + [ + 'declaration-only-font-face-comment-closer', + '@font-face{color: /* } */red}b{}', + ], + ['declaration-only-font-face-bracketed-value', '@font-face{x:[{a:b}]}b{}'], + ['declaration-only-page', '@page{--x:{a:b}}'], + ['declaration-only-property', '@property --test{--x:{a:b}}'], + ['declaration-only-counter-style', '@counter-style test{--x:{a:b}}'], + ['declaration-only-view-transition', '@view-transition{--x:{a:b}}'], + ['declaration-only-position-try', '@position-try --test{--x:{a:b}}'], + ['declaration-only-keyframes', '@keyframes x{0%{--x:{a:b}}}'], + [ + 'declaration-only-keyframes-following-rule', + '@keyframes x{0%{--x:{a:b}}}b{color:red}', + ], + [ + 'declaration-only-keyframe-comment-closer', + '@keyframes x{0%{color: /* } */red}}b{}', + ], + ['declaration-only-vendor-keyframes', '@-webkit-keyframes x{0%{--x:{a:b}}}'], + ['declaration-only-page-margin', '@page{@top-left{--x:{a:b}}}'], + [ + 'declaration-only-page-margin-following-rule', + '@page{@top-left{--x:{a:b}}}b{color:red}', + ], + ['stray-semicolon-after-rule', 'a{color:red;};\nb{color:blue;}'], + ['stray-semicolon-after-empty-rule', 'a{};b{}'], + ['stray-semicolon-after-spaced-rule', 'a{b:c;}\t;b{c:d}'], + ['stray-semicolon-before-comment', 'a{b:c;}; /*x*/ c{d:e;}'], + ['stray-semicolon-repeated', 'a{};;b{}'], + ['stray-semicolon-at-eof', '.a { color: red; };'], + [ + 'stray-semicolon-without-declaration-semicolon', + 'a{color:red};b{color:blue}', + ], + [ + 'stray-semicolon-after-trailing-comment', + 'a{color:red;/*tail*/};b{color:blue;}', + ], + ['stray-semicolon-in-supports', '@supports (x:y){a{b:c;};d{e:f}}'], + ['stray-semicolon-in-nested-rule', '.a{&:hover{color:blue;};color:red;}'], + ['stray-semicolon-in-media', '@media x{a{};b{c:d}}'], + ['stray-semicolon-in-layer', '@layer x{a{b:c;};d{e:f}}'], + ['stray-semicolon-in-generic-rule', '@unknown x{a{b:c;};d{e:f}}'], + [ + 'v4-whitespace-value-preservation', + 'a{content:"left\u00A0right";--x:var(--y,\u2028red)}', + ], + [ + 'v4-whitespace-selector-preservation', + '[data-value="left\u00A0right"]{color:red}', + ], + [ + 'v4-whitespace-bom-crlf', + '\uFEFF\u00A0a{\r\n\u2000color:red;\u2028background:blue}', + ], + [ + 'v4-whitespace-mixed-comments', + '/*x*/\r\n\u00A0 \u2028a{\uFEFF\tcolor:red}', + ], + ['v4-whitespace-property-hacks', 'a{\u00A0*zoom:1;\u2028_color:red;}'], + [ + 'v4-whitespace-long-runs', + `a{${'\u00A0'.repeat(1024)}color:red;${'\u2028'.repeat(1024)}background:blue}`, + ], + ['stray-brace-semicolon-after-empty-rule', 'y{}};'], + ['stray-brace-semicolon-after-rule', 'y{a:b;}};'], + ['stray-brace-semicolon-after-rules', 'a{}b{}};'], + ['stray-brace-semicolon-after-selectorless-rule', '{}};'], + ['stray-brace-semicolon-after-malformed-rule', 'y{a}};'], + ['stray-brace-semicolon-before-rule', 'a{}};b{c:d}'], + ['header-fail-property', '@property x{}'], + ['header-fail-nameless-property', '@property{}'], + ['header-fail-quoted-counter-style', '@counter-style "x"{}'], + ['header-fail-font-feature-values', '@font-feature-values {}'], + ['header-fail-position-try', '@position-try x{}'], + ['header-fail-property-statement', '@property x;'], + ['header-fail-property-in-page', '@page{@property x;}'], + ['header-fail-property-nested-rule', '@property x{a{b:c}}'], + ['double-semicolon-after-generic-statement', '@foo x;;a{b:c}'], + ['double-semicolon-after-layer-statement', '@layer x;;a{b:c}'], + ['double-semicolon-after-nested-statement', 'a{@foo x;;b:c}'], + ['page-double-semicolon-after-statement', '@page{@foo x;;a:b}'], + ['named-page-double-semicolon-after-statement', '@page x{@foo y;;a:b}'], + ['page-statement-before-rule', '@page;a{b:c}'], + ['page-double-semicolon-before-rule', '@page ;;a{b:c}'], + ['empty-import-double-semicolon', '@import;;a{b:c}'], + ['empty-charset-double-semicolon', '@charset;;a{b:c}'], + ['nested-empty-import-double-semicolon', 'a{@import;;b:c}'], + ['custom-media-double-semicolon', '@custom-media --x;;a{b:c}'], + ['import-with-block', '@import{}a{b:c}'], + ['charset-with-block', '@charset{a{b:c}}'], + ['property-junk-header', '@property --x junk{a:b}'], + ['font-face-with-prelude', '@font-face x{a:b}'], + ['unclosed-string-value-eof', 'a{b:"x'], + ['nameless-media-statement-paren-eof', '@media{@container c;a)'], + ['generic-parent-statement-paren-eof', '@foo{@container c;a)'], + ['nameless-supports-statement-paren-eof', '@supports{@media c;b)'], + ['nested-prelude-reaches-media-close', '@media x{@container c;a b}'], + ['nested-prelude-reaches-rule-close', 'a{x:y;@container c;b:c}'], + ['nested-prelude-reaches-nested-rule-close', '@media x{a{@container c;b}}'], + ['nested-prelude-reaches-close-before-tail', 'x{}@media x{@container c;}a b'], + ['keyframe-selector-without-comma', '@keyframes x{from to{a:b}}'], + ['keyframe-selector-adjacent-percentages', '@keyframes x{0%50%{a:b}}'], + ['keyframe-selector-trailing-comma', '@keyframes x{from,{a:b}}'], + ['keyframe-selector-exponent', '@keyframes x{1.5e2%{a:b}}'], + ['nameless-keyframes-spaced', '@keyframes {0%{a:b}}'], + ['nameless-keyframes', '@keyframes{from{a:b}}'], + ['nbsp-after-media', '@media\u00A0screen{a{b:c}}'], + ['nbsp-after-import', '@import\u00A0"x";'], + ['nbsp-after-font-face', '@font-face\u00A0{a:b}'], + ['nbsp-after-generic', '@foo\u00A0bar{a:b}'], + ['nested-chain-break-eof', '@media b{@top-left (@media a'], + ['unclosed-paren-value', 'a{b:(c;}d{e:f}'], + ['unclosed-url-value', 'a{b:url(x;}d{e:f}'], + ['unclosed-function-value', 'a{b:c(d}e{f:g}'], + ['unclosed-single-quote-value', "a{b:'c}d{e:f}"], + ['unclosed-paren-selector', 'a(b{c:d}e{f:g}'], + ['unclosed-quote-selector', 'a"b{c:d}e{f:g}'], + ['escaped-semicolon-nested-prelude', '@foo{@media x \\;c:d'], + ['brace-ended-nested-prelude-eof', '@media y{@media x}'], + ['brace-ended-nested-prelude-stray-close', '@media y{@media x}}'], + ['brace-ended-nested-prelude-comment', '@supports y{@media x}/*c*/'], + ['brace-ended-deep-nested-prelude', '@media y{@media z{@media x}}/*c*/'], + ['brace-ended-nested-prelude-import', '@media y{@media x}@import z;'], + ['brace-ended-root-prelude', '@media x}b{}'], + ['nested-prelude-unclosed-parent', '@media x{ @media x;'], + ['import-block-then-string', '@import a{b:c}"d";e'], + ['document-block', '@document{a{b:c}}'], + ['nested-import-block-eof', '@media x{@import y{a:b'], + ['bodiless-at-rules-whitespace', `${'@a}'.repeat(3)}${' '.repeat(9)}`], + ['nameless-at-rules-comments', `${'@}/**/'.repeat(3)}@b`], + ['nameless-at-rules-long-at-word', `${'@}'.repeat(3)}@a${'a'.repeat(8)}`], + ['nameless-at-rule-comment-statement', '@} /*c*/ a:@b;'], + ['nameless-at-rule-statements', '@} a:@b;'.repeat(3)], + ['long-at-rule-name-nameless-blocks', `@aaaaaaaa{${'@{}'.repeat(3)}}`], + ['long-at-rule-name-rules', `@aaaaaaaa{${'b{}'.repeat(3)}}`], + ['spaced-page-statements', `@page${' '.repeat(8)}{${'@b;'.repeat(3)}}`], + [ + 'spaced-property-statements', + `@property${' '.repeat(8)}--x{${'@b;'.repeat(3)}}`, + ], + [ + 'deep-media-pages', + `${'@media x{'.repeat(3)}${'@page{}'.repeat(3)}${'}'.repeat(3)}`, + ], + ['deep-rule-statements', `${'a{'.repeat(3)}${'@x;}'.repeat(3)}`], + ['deep-media-statements', `${'@media x{'.repeat(3)}${'@x;}'.repeat(3)}`], + ['brace-ended-layer-runs', '@layer x}'.repeat(3)], + ['brace-ended-import-runs', '@import x}'.repeat(3)], + ['brace-ended-import-runs-then-rule', `x ${'@import x}'.repeat(3)}a{}`], + ['import-bracket-stray-braces', `@import [x;${'}'.repeat(8)}`], + ['nested-font-face-paren-errors', `a{@font-face (${'x;'.repeat(4)})}`], + ['unclosed-nested-pages', '@page{'.repeat(4)], + ['page-flatten-siblings', '@page{@font-face;a{}}'.repeat(3)], + ['page-flatten-sibling-at-rules', '@page{@font-face;@foo{}}'.repeat(3)], + ['page-flatten-sibling-margins', '@page{@top-left;a{}}'.repeat(3)], + ['page-flatten-sibling-media', '@page{@media x;@foo{}}'.repeat(3)], + [ + 'page-flatten-nested', + `${'@page{@font-face;a{}'.repeat(3)}${'}'.repeat(3)}`, + ], + [ + 'page-flatten-page-in-page', + '@page{@font-face;@page{@font-face;a{}}b{}}'.repeat(2), + ], + [ + 'page-flatten-deep-page-in-page', + `${'@page{@font-face;@page{@font-face;@page{x;}a{}}'.repeat(2)}}}`, + ], + [ + 'page-flatten-margin-then-statement', + '@page{@top-left{}a{}@font-face;b{}}'.repeat(2), + ], + [ + 'recovered-font-face-declarations', + `a{${'@font-face x:y;'.repeat(3)}${'d:e;'.repeat(3)}}`, + ], + [ + 'recovered-font-face-declaration-pairs', + `a{${'@font-face x:y;d:e;'.repeat(3)}}`, + ], + [ + 'recovered-font-face-paren-declarations', + `a{@font-face (${'b:c;'.repeat(3)});${'d:e;'.repeat(3)}}`, + ], + [ + 'recovered-page-string-declarations', + `a{@page "${'b:c;'.repeat(3)}";${'d:e;'.repeat(3)}}`, + ], + [ + 'recovered-media-font-face-declarations', + `@media x{${'@font-face x:y;'.repeat(3)}${'b{}'.repeat(3)}}`, + ], + ['junk-import-blocks', `a:b;${'@import x}{}'.repeat(3)}}`], + ['junk-namespace-blocks', `a:b;${'@namespace x}{}'.repeat(3)}}`], + ['junk-import-block-runs', `b}@import x}${'{}@import x}'.repeat(3)}`], + ['junk-import-unclosed-blocks', `${'b}@import x}{'.repeat(3)}}`], + ['junk-import-layer-blocks', 'b}@import x}{}@layer y}'.repeat(3)], + ['junk-charset-namespace-blocks', 'b}@charset x}{}@namespace y}{}'.repeat(3)], + ['brace-ended-layer-then-media', '@layer x}@media y}'], + ['brace-ended-layer-then-supports', '@layer x}@supports y}'], + ['brace-ended-layer-then-font-face', '@layer x}@font-face}'], + ['brace-ended-layer-then-keyframes', '@layer x}@keyframes y}'], + ['brace-ended-layer-runs-then-media', '@layer x}@media y}'.repeat(2)], +]; +for (const whitespace of [ + ' ', + '\t', + '\n', + '\r', + '\r\n', + '\f', + '\v', + '\u00A0', + '\u1680', + ...Array.from({ length: 11 }, (_, index) => + String.fromCharCode(0x2000 + index), + ), + '\u2028', + '\u2029', + '\u202F', + '\u205F', + '\u3000', + '\uFEFF', +]) { + const name = Array.from(whitespace, (character) => + character.charCodeAt(0).toString(16), + ).join('-'); + for (const [context, css] of [ + ['leading-rule', `${whitespace}a{color:red}`], + ['leading-at-rule', `${whitespace}@media x{a{color:red}}`], + ['following-rule-comment', `a{color:red}/*x*/${whitespace}b{color:blue}`], + ['leading-declaration', `a{${whitespace}color:red}`], + ['following-declaration', `a{color:red;${whitespace}background:blue}`], + ['following-comment', `a{color:red;/*x*/${whitespace}background:blue}`], + ['nested-rule', `@media x{a{${whitespace}background:blue}}`], + ['nested-at-rule', `@supports (x:y){${whitespace}@media x{a{color:red}}}`], + ['custom-property-block', `a{${whitespace}--x:{color:red}; margin:0;}`], + ['font-face', `@font-face{${whitespace}font-family:test}`], + ['page', `@page{${whitespace}color:red}`], + ['property-separator', `a{color${whitespace}:red}`], + ]) { + regressions.push([`v4-whitespace-${name}-${context}`, css]); + } +} +for (const [name, opening] of [ + ['media', '@media a{'], + ['supports', '@supports (display:grid){'], + ['rule', 'a{'], + ['layer', '@layer a{'], + ['generic', '@unknown a{'], + ['page', '@page{'], +]) { + for (const [variant, body] of [ + ['comment', '@foo /*c*/'], + ['comment-crlf', '@foo /* c */\r\n'], + ['multiple-comments', '@foo /*c*/ /*d*/'], + ['statement', '@foo @bar'], + ['comment-and-statement', '@foo /*c*/ @bar'], + ]) { + regressions.push([`nested-eof-${name}-${variant}`, `${opening}${body}}`]); + } + if (name === 'page') continue; + for (const [variant, body] of [ + ['keyframes', '@keyframes x;'], + ['vendor-keyframes', '@-webkit-keyframes x;'], + ['valid-sibling', '@keyframes x; c:d;'], + ['commented-sibling', '@keyframes x; /*c*/ c:d;'], + ['commented-header', '@keyframes x /**/ c:d;'], + ['comment-only-header', '@keyframes x /*c*/;'], + ['malformed-header', '@keyframes x junk; c:d;'], + ['header-declaration', '@keyframes x c:d;'], + ['header-value-comment', '@keyframes x c:/*keep*/d;'], + ]) { + regressions.push([ + `nested-recovery-${name}-${variant}`, + `${opening}${body}}b{c:d}`, + ]); + } +} +cases.push( + ...regressions.map(([name, css]) => ({ name: `regression/${name}`, css })), +); + +// A fixed seed makes generated failures reproducible. +let seed = 0x405000; +function pick(values: readonly T[]): T { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + return values[Math.floor((seed / 0x100000000) * values.length)]; +} + +for (let index = 0; index < 1000; index++) { + const selector = pick(['a', '.x:hover', '#id', '[data-x="a,b"]', 'a, b']); + const whitespace = pick([' ', '\n', '\r\n', '\t', ' ']); + const property = pick(['color', '--x', 'margin', 'content', '*zoom']); + const value = pick([ + 'red', + '0', + 'calc(100% - 1px)', + '"a,b"', + 'url("x.svg")', + 'red !important', + 'red/**/blue', + '', + ]); + const body = `${selector}${whitespace}{${whitespace}${property}:${whitespace}${value}${pick([';', '', ' ;'])}${whitespace}}`; + const css = pick([ + body, + `/* generated */${whitespace}${body}`, + `@media screen {${whitespace}${body}${whitespace}}`, + `@supports (display: grid) {${body}}`, + `@layer test {${body}}`, + ]); + cases.push({ name: `generated/${index}`, css }); +} + +const publicDirectory = path.join(__dirname, '..', '.compatibility-css'); +if (process.env.CSS_TOOLS_PUBLIC_CSS === '1') { + if (!fs.existsSync(publicDirectory)) { + throw new Error( + 'Run node test/fetch-public-css.mjs before public CSS tests.', + ); + } + const manifest: unknown = JSON.parse( + fs.readFileSync(path.join(publicDirectory, 'manifest.json'), 'utf8'), + ); + if (!Array.isArray(manifest) || manifest.length !== 8) { + throw new Error('Expected eight pinned public CSS samples.'); + } + for (const entry of manifest) { + const sample: unknown = entry; + if ( + !sample || + typeof sample !== 'object' || + !('name' in sample) || + typeof sample.name !== 'string' || + path.basename(sample.name) !== sample.name || + !sample.name.endsWith('.css') || + !('sha256' in sample) || + typeof sample.sha256 !== 'string' + ) { + throw new Error('Invalid public CSS manifest entry.'); + } + const css = fs.readFileSync( + path.join(publicDirectory, sample.name), + 'utf8', + ); + if (createHash('sha256').update(css).digest('hex') !== sample.sha256) { + throw new Error(`Public CSS checksum mismatch: ${sample.name}`); + } + cases.push({ name: `public/${sample.name}`, css }); + } +} + +function outcome( + parser: typeof parse, + css: string, + options: { source?: string; silent?: boolean }, +) { + try { + return { ast: parser(css, options) }; + } catch (error) { + if (!(error instanceof Error)) throw error; + return { + error: { + ...error, + name: error.name, + message: error.message, + }, + }; + } +} + +function observable(value: unknown): unknown { + if (Array.isArray(value)) return value.map(observable); + if (value && typeof value === 'object') { + return { + ...(value instanceof Error + ? { name: value.name, message: value.message } + : {}), + ...Object.fromEntries( + Object.entries(value).map(([key, child]) => [key, observable(child)]), + ), + }; + } + return value; +} + +function firstDifference( + actual: unknown, + expected: unknown, + location = '$', +): unknown { + if (Object.is(actual, expected)) return undefined; + if ( + actual === null || + expected === null || + typeof actual !== 'object' || + typeof expected !== 'object' + ) { + return { location, actual, expected }; + } + const actualKeys = Object.keys(actual); + const expectedKeys = Object.keys(expected); + if ( + actualKeys.length !== expectedKeys.length || + expectedKeys.some((key) => !Object.hasOwn(actual, key)) + ) { + return { location, actualKeys, expectedKeys }; + } + for (const key of expectedKeys) { + const difference = firstDifference( + Reflect.get(actual, key), + Reflect.get(expected, key), + `${location}.${key}`, + ); + if (difference) return difference; + } + return undefined; +} + +function parentDifference( + value: unknown, + parent: object | null = null, + location = '$', +): string | undefined { + if (!value || typeof value !== 'object') return undefined; + if ('type' in value && typeof value.type === 'string') { + const descriptor = Object.getOwnPropertyDescriptor(value, 'parent'); + if ( + !descriptor || + descriptor.value !== parent || + descriptor.enumerable || + !descriptor.writable || + !descriptor.configurable + ) { + return `${location}: invalid parent link or descriptor`; + } + parent = value; + } + for (const [key, child] of Object.entries(value)) { + const difference = parentDifference(child, parent, `${location}.${key}`); + if (difference) return difference; + } + return undefined; +} + +describe.each(cases)('V4 compatibility: $name', ({ name, css }) => { + const options = name.startsWith('public/') + ? [{}] + : [ + {}, + { source: 'compatibility.css' }, + { silent: true }, + { silent: true, source: 'compatibility.css' }, + ]; + it.each(options)('matches AST and errors for %j', (options) => { + const expected = outcome(parseV4, css, options); + const actual = outcome(parse, css, options); + // Separate package copies have different class identities, but the same + // observable fields (including undefined properties) must be preserved. + expect( + firstDifference(observable(actual), observable(expected)), + ).toBeUndefined(); + if (!expected.ast || !actual.ast) return; + expect(parentDifference(actual.ast)).toBeUndefined(); + expect(parentDifference(expected.ast)).toBeUndefined(); + + for (const formatting of [{}, { compress: true }, { indent: '\t' }]) { + expect(stringify(actual.ast, formatting)).toBe( + stringifyV4(expected.ast, formatting), + ); + expect(stringify(expected.ast, formatting)).toBe( + stringifyV4(expected.ast, formatting), + ); + } + }); +}); + +describe.each([ + { name: 'separate rules', css: 'a { color red; }\n'.repeat(128) }, + { name: 'one rule', css: `a {${' color red;'.repeat(128)} }` }, + { name: 'rules without semicolons', css: 'a { color red }\n'.repeat(128) }, + { + name: 'empty recovered properties', + css: `a {${' : red;'.repeat(128)} margin: 0; }`, + }, +])('V5 error recovery complexity: $name', ({ css }) => { + it.each([false, true])( + 'does not reparse or traverse all declarations per error, silent=%j', + (silent) => { + const expected = outcome(parseV4, css, { silent }); + const parsing = jest.spyOn(postcss, 'parse'); + const walking = jest.spyOn(postcss.Container.prototype, 'walkDecls'); + try { + const actual = outcome(parse, css, { silent }); + expect( + firstDifference(observable(actual), observable(expected)), + ).toBeUndefined(); + expect(parsing.mock.calls.length).toBeLessThanOrEqual(2); + expect(walking.mock.calls.length).toBeLessThanOrEqual(1); + } finally { + parsing.mockRestore(); + walking.mockRestore(); + } + }, + ); +}); + +describe.each([ + { + name: 'separate custom-property blocks', + css: 'a{--x:{color:red; padding:0}}\n'.repeat(128), + }, + { + name: 'nested custom-property blocks', + css: `a{${'--x:{'.repeat(128)}color:red${'}'.repeat(128)}}`, + }, +])('V4 block classification complexity: $name', ({ css }) => { + it('does not reparse each custom-property block', () => { + const expected = parseV4(css); + const parsing = jest.spyOn(postcss, 'parse'); + try { + const actual = parse(css); + expect( + firstDifference(observable(actual), observable(expected)), + ).toBeUndefined(); + expect(parentDifference(actual)).toBeUndefined(); + expect(parsing).toHaveBeenCalledTimes(1); + } finally { + parsing.mockRestore(); + } + }); +}); + +describe('deep V4-compatible media blocks', () => { + it.each([false, true])( + 'preserves values, positions and parents without wrapper recursion, silent=%j', + (silent) => { + const depth = 512; + const css = `${'@media all{'.repeat(depth)}a{x:y;}${'} '.repeat(depth)}`; + const expected = parseV4(css, { silent }); + const actual = parse(css, { silent }); + let expectedNode: CssAtRuleAST | CssDeclarationAST = + expected.stylesheet.rules[0]; + let actualNode: CssAtRuleAST | CssDeclarationAST = + actual.stylesheet.rules[0]; + let parent: object = actual; + for (let index = 0; index < depth; index++) { + if (expectedNode.type !== 'media' || actualNode.type !== 'media') { + throw new Error(`Expected a media node at depth ${index}`); + } + expect(actualNode.media).toBe(expectedNode.media); + expect(actualNode.position).toEqual(expectedNode.position); + const descriptor = Object.getOwnPropertyDescriptor( + actualNode, + 'parent', + ); + expect(descriptor).toEqual({ + value: parent, + enumerable: false, + writable: true, + configurable: true, + }); + parent = actualNode; + actualNode = actualNode.rules[0]; + expectedNode = expectedNode.rules[0]; + } + expect(observable(actualNode)).toEqual(observable(expectedNode)); + expect(actual.stylesheet.parsingErrors).toEqual( + expected.stylesheet.parsingErrors, + ); + }, + ); +}); + +describe('V5 malformed-input scaling', () => { + it('reports one error per selectorless keyframe block', () => { + const depth = 512; + const css = `@keyframes x{${'{'.repeat(depth)}}`; + expect( + parse(css, { silent: true }).stylesheet.parsingErrors?.length, + ).toBeLessThanOrEqual(2 * depth); + }); + + it('reports the errors of each nameless at-rule once', () => { + const count = 512; + const css = `${'@}/**/'.repeat(count)}@b`; + expect( + parse(css, { silent: true }).stylesheet.parsingErrors?.length, + ).toBeLessThanOrEqual(2 * count); + }); + + it.each([ + { + name: 'imports in keyframes', + css: `@keyframes x{${'@import x}'.repeat(1 << 12)}`, + }, + { name: 'layer statements', css: '@layer x}'.repeat(1 << 12) }, + { + name: 'nameless at-rules', + css: `${'@}'.repeat(1 << 11)}@a${'a'.repeat(1 << 12)}`, + }, + ])('keeps output linear for brace-ended $name', ({ css }) => { + const output = stringify(parse(css, { silent: true }), { compress: true }); + expect(output.length).toBeLessThanOrEqual(2 * css.length); + }); + + it.each([ + { + name: 'stray braces after an import', + css: `@import [x;${'}'.repeat(1 << 17)}`, + errors: 1 << 17, + }, + { + name: 'declarations in a nested font-face prelude', + css: `a{@font-face (${'x;'.repeat(1 << 17)})}`, + errors: (1 << 17) + 3, + }, + ])('reports every error for $name', ({ css, errors }) => { + expect(parse(css, { silent: true }).stylesheet.parsingErrors?.length).toBe( + errors, + ); + }); + + // Native searches hide a rescan per nesting level or per repeated token at + // test sizes, so count the characters and nodes they visit instead of + // timing the parse. Spies would record every call of a reverted rescan. + function searchedLength(css: string, options: ParseOptions): number { + const strings = String.prototype; + const arrays = Array.prototype; + const { indexOf, includes, lastIndexOf } = strings; + const arrayIndexOf = arrays.indexOf; + let searched = 0; + const count = (length: number, index: number, from?: number) => { + searched += (index === -1 ? length : index) - Math.max(from ?? 0, 0); + }; + strings.indexOf = function (this: string, search: string, from?: number) { + const index = indexOf.call(this, search, from); + count(this.length, index, from); + return index; + }; + strings.includes = function (this: string, search: string, from?: number) { + const index = indexOf.call(this, search, from); + count(this.length, index, from); + return index !== -1; + }; + strings.lastIndexOf = function ( + this: string, + search: string, + from?: number, + ) { + const index = lastIndexOf.call(this, search, from); + searched += + Math.min(from ?? this.length, this.length) - Math.max(index, 0); + return index; + }; + arrays.indexOf = function ( + this: unknown[], + search: unknown, + from?: number, + ) { + const index = arrayIndexOf.call(this, search, from); + count(this.length, index, from); + return index; + }; + try { + parse(css, options); + } finally { + Object.assign(strings, { indexOf, includes, lastIndexOf }); + arrays.indexOf = arrayIndexOf; + } + return searched; + } + + it.each<{ name: string; css: string; options?: ParseOptions }>([ + { + name: 'each nested block', + css: `${'@page{;'.repeat(1 << 9)}${' '.repeat(1 << 14)}`, + }, + { + name: 'each split declaration with preserved comments', + css: `a{${`c:d /*${'x'.repeat(16)}*/ `.repeat(1 << 10)}`, + options: { stripCommentsInValues: false }, + }, + { + name: 'semicolons in parentheses in a nested font-face', + css: `a{@font-face ${'(;'.repeat(1 << 12)}`, + }, + { + name: 'escaped semicolons in a nested font-face', + css: `a{@font-face ${'\\;'.repeat(1 << 12)}`, + }, + { + name: 'properties with preserved comments in a nested font-face', + css: `a{@font-face ${`x:/*${'x'.repeat(16)}*/`.repeat(1 << 10)}`, + options: { stripCommentsInValues: false }, + }, + { + name: 'unclosed comments after a font-face', + css: `@font-face ${'/* '.repeat(1 << 12)}`, + }, + { + name: 'unclosed comments in keyframes', + css: `@keyframes k{from{${'\\;/*'.repeat(1 << 12)})}`, + }, + { + name: 'unclosed comments in nested rules', + css: `a{b{${'\\;/*@supports '.repeat(1 << 12)})}`, + }, + { + name: 'comments in a block', + css: `a{${'/**/'.repeat(1 << 12)}/*`, + }, + { + name: 'comments in a declaration value', + css: `a{b:c${'/*}*//*'.repeat(1 << 12)}@x;`, + }, + ])('does not rescan the source for $name', ({ css, options }) => { + expect(searchedLength(css, { ...options, silent: true })).toBeLessThan( + 100 * css.length, + ); + }); + + describe('parse time', () => { + // Bounds are relative to well-formed CSS parsed in the same process, so + // they hold on slow machines. These inputs cost under 3 times the + // reference per character; the quadratic paths they guard against cost + // over 15 times as much at these sizes. + const limit = 10; + let reference = Number.POSITIVE_INFINITY; + + function parseTime(css: string): number { + const start = performance.now(); + parse(css, { silent: true }); + return (performance.now() - start) / css.length; + } + + beforeAll(() => { + const css = 'a{b:c}'.repeat(1 << 14); + parseTime(css); + for (let run = 0; run < 3; run++) { + reference = Math.min(reference, parseTime(css)); + } + }); + + it.each([ + { + name: 'bodiless at-rules before whitespace', + css: `${'@a}'.repeat(1 << 14)}${' '.repeat(3 << 14)}`, + }, + { + name: 'nameless blocks in a long-named at-rule', + css: `@${'a'.repeat(1 << 15)}{${'@{}'.repeat(10000)}}`, + }, + { + name: 'rules in a long-named at-rule', + css: `@${'a'.repeat(1 << 15)}{${'b{}'.repeat(10000)}}`, + }, + { + name: 'pages in deep media blocks', + css: `${'@media x{'.repeat(7500)}${'@page{}'.repeat(7500)}${'}'.repeat(7500)}`, + }, + { + name: 'statements in deep rules', + css: `${'a{'.repeat(20000)}${'@x;}'.repeat(20000)}`, + }, + { + name: 'brace-ended media in keyframes', + css: `@keyframes x{${'@media x}'.repeat(30000)}`, + }, + { name: 'unclosed nested pages', css: '@page{'.repeat(10000) }, + { + name: 'imports read as selectors', + css: 'b}@import x}{}'.repeat(30000), + }, + { + name: 'properties in a nested font-face', + css: `a{@font-face ${'x:'.repeat(1 << 14)}`, + }, + ])('parses $name in linear time', ({ css }) => { + let ratio = Number.POSITIVE_INFINITY; + for (let attempt = 0; attempt < 3 && ratio >= limit; attempt++) { + ratio = Math.min(ratio, parseTime(css) / reference); + } + expect(ratio).toBeLessThan(limit); + }); + }); +}); diff --git a/test/fetch-public-css.mjs b/test/fetch-public-css.mjs new file mode 100644 index 00000000..3523f093 --- /dev/null +++ b/test/fetch-public-css.mjs @@ -0,0 +1,97 @@ +import { createHash } from 'node:crypto'; +import { mkdir, writeFile } from 'node:fs/promises'; + +const directory = new URL('../.compatibility-css/', import.meta.url); +const files = [ + 'normalize.css@8.0.1/normalize.css', + 'bootstrap@5.3.3/dist/css/bootstrap.css', + 'bootstrap@5.3.3/dist/css/bootstrap.min.css', + 'bulma@1.0.2/css/bulma.css', + 'animate.css@4.1.1/animate.css', + 'purecss@3.0.0/build/pure.css', + 'tachyons@4.12.0/css/tachyons.css', + 'milligram@1.4.1/dist/milligram.css', + 'water.css@2.1.1/out/water.css', + 'modern-normalize@2.0.0/modern-normalize.css', +]; +const hashes = new Map([ + [ + 'normalize.css@8.0.1/normalize.css', + '580818700724d42d7fcc4979b0197971fca1c6d2e0286769237a0ac897df5512', + ], + [ + 'bootstrap@5.3.3/dist/css/bootstrap.css', + '18a105d7cb38e01e5ed0ca255c092992a2e211b39594a7fa57262bfc6fc4ea9c', + ], + [ + 'bootstrap@5.3.3/dist/css/bootstrap.min.css', + '3c8f27e6009ccfd710a905e6dcf12d0ee3c6f2ac7da05b0572d3e0d12e736fc8', + ], + [ + 'bulma@1.0.2/css/bulma.css', + '113149035b8b7543113ca93d6f8c75a7ff4a73a1c0877d5e50c710aa1fe5f404', + ], + [ + 'animate.css@4.1.1/animate.css', + 'c1b6f9ed1effff87233740ce612ed3cd3fbd3cb34c0863373d820fde1b2c8d8f', + ], + [ + 'purecss@3.0.0/build/pure.css', + '61642839d5e0d04641fceb5a4dcfc479a6ea17510c57c489314c3a662dcc7c9b', + ], + [ + 'tachyons@4.12.0/css/tachyons.css', + 'e24dd3551dab4c568876e42c086a4b0a960d22a4446bd4c0a5fd47cda142e021', + ], + [ + 'milligram@1.4.1/dist/milligram.css', + '0e79dc73372d7747b20efa42310eed3f4b9826ead1d998175ec374a51d363bab', + ], + [ + 'water.css@2.1.1/out/water.css', + '47073611dda0977c57c95d5bbda291084a589e5c7af197fa4d09822657249a0e', + ], + [ + 'modern-normalize@2.0.0/modern-normalize.css', + 'e7ac1d317608989e22143074fbe95fb77027f230e8540c566f5d596616721308', + ], +]); + +// Sample without replacement, using a fixed seed for reproducible coverage. +let seed = 0x405000; +for (let index = files.length - 1; index > 0; index--) { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + const other = Math.floor((seed / 0x100000000) * (index + 1)); + [files[index], files[other]] = [files[other], files[index]]; +} + +await mkdir(directory, { recursive: true }); +const manifest = await Promise.all( + files.slice(0, 8).map(async (file) => { + const url = `https://cdn.jsdelivr.net/npm/${file}`; + const response = await fetch(url, { signal: AbortSignal.timeout(60000) }); + if (!response.ok) { + throw new Error(`Unable to fetch ${url}: HTTP ${response.status}`); + } + const css = await response.text(); + const sha256 = createHash('sha256').update(css).digest('hex'); + if (sha256 !== hashes.get(file)) { + throw new Error(`Checksum mismatch for ${url}: ${sha256}`); + } + const name = file.replaceAll('/', '__'); + await writeFile(new URL(name, directory), css); + return { + name, + url, + bytes: Buffer.byteLength(css), + sha256, + }; + }), +); +await writeFile( + new URL('manifest.json', directory), + `${JSON.stringify(manifest, null, 2)}\n`, +); +for (const file of manifest) { + console.log(`${file.name}: ${file.bytes} bytes, SHA-256 ${file.sha256}`); +} diff --git a/test/parse-options.test.ts b/test/parse-options.test.ts new file mode 100644 index 00000000..108da544 --- /dev/null +++ b/test/parse-options.test.ts @@ -0,0 +1,187 @@ +import { parse as parseV4, stringify as stringifyV4 } from 'css-tools-v4'; +import { type ParseOptions, parse, stringify } from '../src/index'; + +const css = + '@media screen { a { content: "/* text */"; color: red/**/blue; } }'; + +describe('stripCommentsInValues', () => { + it.each([undefined, {}, { stripCommentsInValues: true }])( + 'preserves V4 normalization by default with %j', + (options: ParseOptions | undefined) => { + expect(stringify(parse(css, options), { compress: true })).toBe( + '@media screen{a{content:"";color:redblue;}}', + ); + }, + ); + + it.each([false, true])( + 'preserves quoted and embedded comment text when disabled, silent=%j', + (silent) => { + expect( + stringify(parse(css, { silent, stripCommentsInValues: false }), { + compress: true, + }), + ).toBe('@media screen{a{content:"/* text */";color:red/**/blue;}}'); + }, + ); + + it('preserves raw value comments that PostCSS separates from the value', () => { + expect( + stringify( + parse('a { color: red /* trailing */; }', { + stripCommentsInValues: false, + }), + { compress: true }, + ), + ).toBe('a{color:red /* trailing */;}'); + }); + + describe.each([false, true])('comment preservation, silent=%j', (silent) => { + it.each([ + ['a{color:/*keep*/red;}', 'a{color:/*keep*/red;}'], + ['a{\u00A0color:/*keep*/red;}', 'a{color:/*keep*/red;}'], + [ + 'a{color:blue;\u2028content:"/*keep*/";}', + 'a{color:blue;content:"/*keep*/";}', + ], + [ + '@media x{\u00A0a{\u2028color:/*keep*/red;}}', + '@media x{a{color:/*keep*/red;}}', + ], + ['a{--x:/*keep*/red;}', 'a{--x:/*keep*/red;}'], + ['a{color:/*keep*/red !important;}', 'a{color:/*keep*/red !important;}'], + ['a{color:/*a*/red/*b*/;}', 'a{color:/*a*/red/*b*/;}'], + ['a { color: red /* brand */ }', 'a{color:red /* brand */;}'], + ['a{--x:/*keep*/;}', 'a{--x:/*keep*/;}'], + ['a{color:/*keep*/!important;}', 'a{color:/*keep*/!important;}'], + ['a{color:/* ; } ( " */red;}', 'a{color:/* ; } ( " */red;}'], + ['a{color:red/* ; } ( " */;}', 'a{color:red/* ; } ( " */;}'], + ['a{color:red/* ; } ( " */}', 'a{color:red/* ; } ( " */;}'], + ['a{content:"/* ; } () */";}', 'a{content:"/* ; } () */";}'], + ['a{content:"x;}" /*keep*/}', 'a{content:"x;}" /*keep*/;}'], + [ + 'a{color:var(--x, /* ) ; } */ red);}', + 'a{color:var(--x, /* ) ; } */ red);}', + ], + ['a{--foo\\:bar:/*keep*/red;}', 'a{--foo\\:bar:/*keep*/red;}'], + [ + 'a{--x:{color:/*keep*/red; padding:0}}', + 'a{--x:{color:/*keep*/red;padding:0;}}', + ], + ['a{--x:{--y:{color:/*keep*/red}}}', 'a{--x:{--y:{color:/*keep*/red;}}}'], + ])('preserves the full value of %s', (input, expected) => { + expect( + stringify(parse(input, { silent, stripCommentsInValues: false }), { + compress: true, + }), + ).toBe(expected); + }); + }); + + it('does not remove standalone comment nodes when enabled', () => { + expect(stringify(parse('/* standalone */a { color: red; }'))).toContain( + '/* standalone */', + ); + }); + + it.each(['/*keep*/red', 'red /*keep*/', '/* ; } */red'])( + 'preserves recovered declaration comments in %s', + (value) => { + const ast = parse(`@media a{@keyframes x color:${value};}`, { + silent: true, + stripCommentsInValues: false, + }); + expect(ast.stylesheet.parsingErrors).toHaveLength(1); + expect(ast.stylesheet.parsingErrors?.[0].reason).toBe( + "@keyframes missing '{'", + ); + expect(stringify(ast, { compress: true })).toBe( + `@media a{color:${value};}`, + ); + }, + ); + + it.each([false, true])( + 'keeps failed-header comments as property text, stripCommentsInValues=%j', + (stripCommentsInValues) => { + const input = 'a{@keyframes x /**/ c:d;}'; + expect(parse(input, { silent: true, stripCommentsInValues })).toEqual( + parseV4(input, { silent: true }), + ); + }, + ); + + it('does not share options between successive parses', () => { + const plain = 'a { content: "/* text */"; }'; + expect(stringify(parse(plain, { stripCommentsInValues: false }))).toContain( + '"/* text */"', + ); + expect(stringify(parse(plain))).toContain('""'); + }); + + it.each([false, true])( + 'keeps V4 escaped-property fields, stripCommentsInValues=%j', + (stripCommentsInValues) => { + expect( + parse('a{--foo\\:bar:/*keep*/red;}', { stripCommentsInValues }), + ).toMatchObject({ + stylesheet: { + rules: [ + { + declarations: [ + { + property: '--foo\\', + value: stripCommentsInValues ? 'bar:red' : 'bar:/*keep*/red', + }, + ], + }, + ], + }, + }); + }, + ); + + it.each([ + '@font-face{--x:{a:b}}', + '@page{--x:{a:b}}', + '@property --test{--x:{a:b}}', + '@counter-style test{--x:{a:b}}', + '@view-transition{--x:{a:b}}', + '@position-try --test{--x:{a:b}}', + '@keyframes x{0%{--x:{a:b}}}', + '@-webkit-keyframes x{0%{--x:{a:b}}}', + '@page{@top-left{--x:{a:b}}}', + ])('keeps declaration-only block handling for %s', (input) => { + const expected = parseV4(input); + const actual = parse(input); + expect(actual).toEqual(expected); + expect(stringify(actual, { compress: true })).toBe( + stringifyV4(expected, { compress: true }), + ); + }); + + describe.each([false, true])( + 'large declaration values, stripCommentsInValues=%j', + (stripCommentsInValues) => { + it.each([ + { + name: 'deep parentheses', + value: `${'('.repeat(4096)}0${')'.repeat(4096)}`, + }, + { name: 'many strings', value: '"x" '.repeat(4096).trim() }, + { name: 'many functions', value: 'f(0) '.repeat(4096).trim() }, + { name: 'many escapes', value: '\\x '.repeat(12000).trim() }, + ])( + 'handles $name without recursive or repeated suffix scans', + ({ value }) => { + const input = `a{x:${value};}`; + expect( + stringify(parse(input, { stripCommentsInValues }), { + compress: true, + }), + ).toBe(input); + }, + ); + }, + ); +}); diff --git a/test/parser-depth-compatibility.mjs b/test/parser-depth-compatibility.mjs new file mode 100644 index 00000000..ddc39921 --- /dev/null +++ b/test/parser-depth-compatibility.mjs @@ -0,0 +1,151 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; +import { runInNewContext } from 'node:vm'; +import * as v4 from 'css-tools-v4'; + +const require = createRequire(import.meta.url); +const bundles = ['CJS', 'ESM', 'UMD/browser', 'UMD/CommonJS', 'UMD/AMD']; +const depth = 2048; +const opening = '@media all{'; +const leaf = 'a{x:y;}'; +const nestedCSS = (depth) => opening.repeat(depth) + leaf + '} '.repeat(depth); +const css = nestedCSS(depth); + +function expectedAST(depth, source) { + const leafStart = opening.length * depth; + const position = (start, end) => ({ + start: { line: 1, column: start + 1 }, + end: { line: 1, column: end + 1 }, + source, + }); + let node = { + type: 'rule', + selectors: ['a'], + declarations: [ + { + type: 'declaration', + property: 'x', + value: 'y', + position: position(leafStart + 2, leafStart + 5), + }, + ], + position: position(leafStart, leafStart + leaf.length), + }; + for (let level = depth - 1; level >= 0; level--) { + node = { + type: 'media', + media: 'all', + rules: [node], + position: position( + opening.length * level, + leafStart + leaf.length + (depth - level) * 2 - 1, + ), + }; + } + return { + type: 'stylesheet', + stylesheet: { source, rules: [node], parsingErrors: [] }, + }; +} + +function assertSameAST(actual, expected) { + const pending = [{ actual, expected, parent: null }]; + while (pending.length) { + const entry = pending.pop(); + const { actual, expected } = entry; + if (!expected || typeof expected !== 'object') { + assert.equal(actual, expected); + continue; + } + assert.ok(actual && typeof actual === 'object'); + assert.equal(Array.isArray(actual), Array.isArray(expected)); + assert.deepEqual(Object.keys(actual).sort(), Object.keys(expected).sort()); + const parent = typeof actual.type === 'string' ? actual : entry.parent; + if (typeof actual.type === 'string') { + assert.deepEqual(Object.getOwnPropertyDescriptor(actual, 'parent'), { + value: entry.parent, + enumerable: false, + writable: true, + configurable: true, + }); + } + for (const key of Object.keys(expected)) { + pending.push({ actual: actual[key], expected: expected[key], parent }); + } + } +} + +async function loadBundle(name) { + if (name === 'CJS') return require('../dist/cjs/adobe-css-tools.cjs'); + if (name === 'ESM') return import('../dist/esm/adobe-css-tools.mjs'); + const umd = readFileSync( + new URL('../dist/umd/adobe-css-tools.js', import.meta.url), + 'utf8', + ); + if (name === 'UMD/browser') { + const browser = {}; + runInNewContext(umd, browser); + return browser.cssTools; + } + if (name === 'UMD/CommonJS') { + const exports = {}; + runInNewContext(umd, { exports, module: { exports } }); + return exports; + } + if (name === 'UMD/AMD') { + let exports; + const define = (dependencies, factory) => { + assert.deepEqual(Array.from(dependencies), ['exports']); + exports = {}; + factory(exports); + }; + define.amd = true; + runInNewContext(umd, { define }); + return exports; + } + assert.fail(`Unknown bundle: ${name}`); +} + +if (process.argv[2] === '--worker') { + const name = process.argv[3]; + const api = await loadBundle(name); + for (const silent of [false, true]) { + const options = { silent, source: 'resource.css' }; + // V4 itself overflows at depth 2048 on some supported Node versions. + assertSameAST( + v4.parse(nestedCSS(16), options), + expectedAST(16, options.source), + ); + const expected = expectedAST(depth, options.source); + for (const stripCommentsInValues of [false, true]) { + const actual = api.parse(css, { + ...options, + stripCommentsInValues, + }); + assertSameAST(actual, expected); + } + } + console.log(`${name}: depth-2048 ASTs, positions and parents passed`); +} else { + for (const name of bundles) { + const child = spawnSync( + process.execPath, + [ + '--max-old-space-size=128', + fileURLToPath(import.meta.url), + '--worker', + name, + ], + { encoding: 'utf8', timeout: 5000, maxBuffer: 1024 * 1024 }, + ); + assert.equal( + child.status, + 0, + `${name}: ${child.error?.message ?? child.signal ?? ''}\n${child.stderr}`, + ); + process.stdout.write(child.stdout); + } +}