{"id":13018,"library":"css-selector-parser","title":"CSS Selector Parser","description":"css-selector-parser is a high-performance JavaScript/TypeScript library designed for parsing CSS selectors into a comprehensive Abstract Syntax Tree (AST). It provides an AST-based object model that enables programmatic manipulation, analysis, and transformation of selectors through its visitor pattern implementation. The library offers full compliance with a wide array of CSS selector specifications, including CSS1, CSS2, CSS3, and Selectors Level 4, with an additional \"progressive\" mode for handling unknown or future pseudo-classes and attributes. Currently at version 3.3.0, the package suggests an active development cycle, evidenced by its multiple migration guides for major versions. Key differentiators include its speed, memory efficiency, extensive TypeScript support for a well-documented API, and an interactive playground for real-time testing and visualization of AST outputs.","status":"active","version":"3.3.0","language":"javascript","source_language":"en","source_url":"https://github.com/mdevils/css-selector-parser","tags":["javascript","css","css selector","css selector parser","pseudo-classes","pseudo-elements","css attributes","css tags","css classes","typescript"],"install":[{"cmd":"npm install css-selector-parser","lang":"bash","label":"npm"},{"cmd":"yarn add css-selector-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add css-selector-parser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library is primarily designed for ESM consumption in modern environments. While `require` might work in some transpiled setups, `import` is the idiomatic way to use it since v3.","wrong":"const createParser = require('css-selector-parser').createParser;","symbol":"createParser","correct":"import { createParser } from 'css-selector-parser';"},{"note":"Used alongside `createParser` to implement the visitor pattern for AST analysis or transformation.","wrong":"const { traverse } = require('css-selector-parser');","symbol":"traverse","correct":"import { createParser, traverse } from 'css-selector-parser';"},{"note":"Key interfaces like `Selector`, `Rule`, `Attribute`, `TagName`, etc., are exported directly for strong typing in TypeScript projects.","wrong":"import { Selector } from 'css-selector-parser/dist/ast';","symbol":"AST Node Types","correct":"import type { Selector, Rule, TagName, Attribute } from 'css-selector-parser';"}],"quickstart":{"code":"import { createParser, traverse } from 'css-selector-parser';\n\nconst parse = createParser();\nconst selectorString = 'a[href^=\"/\"]::before, .container:has(nav) > a[href]:nth-child(2)';\nconst selectorAst = parse(selectorString);\n\nconsole.log('Parsed Selector AST:', JSON.stringify(selectorAst, null, 2));\n\n// Example of AST traversal\ntraverse(selectorAst, (node, context) => {\n  if (node.type === 'TagName') {\n    console.log(`Found TagName: ${node.name} at depth ${context.parents.length}`);\n  } else if (node.type === 'Attribute') {\n    console.log(`Found Attribute: ${node.name} with operator ${node.operator || 'none'}`);\n  }\n});","lang":"typescript","description":"This quickstart demonstrates parsing a complex CSS selector into an AST and then traversing the AST to log specific node types like TagName and Attribute, showcasing basic library usage."},"warnings":[{"fix":"Review the 'Migrating from 1.x to 3.x' and 'Migrating from 2.x to 3.x' sections in the `CHANGELOG.md` file to adapt your codebase to the new API and AST structure.","message":"Upgrading from versions 1.x or 2.x to 3.x introduced significant breaking changes in the API and the structure of the generated AST. Users must consult the `CHANGELOG.md` and dedicated migration guides for detailed information.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Configure your project to use ES Modules by adding `\"type\": \"module\"` to your `package.json` or by using `.mjs` file extensions for ESM files. Use `import` statements as shown in the documentation.","message":"Version 3+ of css-selector-parser is designed primarily for ES Modules (ESM). While older Node.js versions or CommonJS projects might attempt to use `require()`, this can lead to compatibility issues without proper transpilation or explicit ESM configuration.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"For strict CSS compliance, explicitly specify a W3C standard (e.g., `css: 'selectors-4'`) when creating the parser: `createParser({ css: 'selectors-4' })`. Only use `progressive` if you intend to support experimental or custom syntax.","message":"Using the `progressive` standard option can be a footgun. While it allows for parsing unknown pseudo-classes, pseudo-elements, and attribute case sensitivity modifiers, it means the parser will accept potentially invalid or non-standard CSS selectors without error, which might be undesirable for strict validation.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure your project is configured for ES Modules by adding `\"type\": \"module\"` to your `package.json`, or rename the file to `.mjs`. If you must use CommonJS, consider dynamic `import()` or transpile your code.","cause":"Attempting to use ES module `import` syntax in a CommonJS (CJS) module context, typically in a `.js` file without `\"type\": \"module\"` in `package.json` or in a `.cjs` file.","error":"SyntaxError: Cannot use import statement outside a module"},{"fix":"Ensure your project is configured for ES Modules and use `import { createParser } from 'css-selector-parser';`. If you need to use CommonJS, consider using dynamic `import()`: `const { createParser } = await import('css-selector-parser');` (requires Node.js 14+).","cause":"This error often occurs when trying to `require()` an ES Module-first package, or incorrectly destructuring its exports in a CommonJS context.","error":"TypeError: (0 , css_selector_parser_1.createParser) is not a function"},{"fix":"Review the problematic selector for syntax errors against W3C specifications. If the selector uses modern or experimental features, try configuring the parser with a higher compliance level or the `progressive` option: `createParser({ css: 'selectors-4' })` or `createParser({ css: 'progressive' })`.","cause":"The input CSS selector string is malformed, contains a syntax error, or uses a CSS feature not supported by the currently configured parsing standard (e.g., `css1`, `css2`, `selectors-3`, `selectors-4`).","error":"Error: Selector parse error: Unexpected token at ..."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}