@tbela99/css-parser 1.4.10 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/README.md +11 -4
  3. package/dist/index-umd-web.js +2118 -1701
  4. package/dist/index.cjs +2130 -1696
  5. package/dist/index.d.ts +781 -269
  6. package/dist/lib/ast/clone.js +13 -8
  7. package/dist/lib/ast/expand.js +45 -9
  8. package/dist/lib/ast/features/calc.js +2 -1
  9. package/dist/lib/ast/features/if.js +24 -4
  10. package/dist/lib/ast/features/prefix.js +13 -31
  11. package/dist/lib/ast/features/shorthand.js +1 -1
  12. package/dist/lib/ast/features/transform.js +5 -2
  13. package/dist/lib/ast/find.js +7 -5
  14. package/dist/lib/ast/minify.js +80 -35
  15. package/dist/lib/ast/node.js +50 -0
  16. package/dist/lib/ast/types.js +1 -1
  17. package/dist/lib/ast/walk.js +27 -7
  18. package/dist/lib/fs/resolve.js +64 -32
  19. package/dist/lib/parser/declaration/map.js +14 -5
  20. package/dist/lib/parser/linesmap.js +5 -13
  21. package/dist/lib/parser/parse.js +489 -719
  22. package/dist/lib/parser/source.js +16 -2
  23. package/dist/lib/parser/tokenize.js +382 -278
  24. package/dist/lib/parser/utils/at-rule-container.js +2 -1
  25. package/dist/lib/parser/utils/selector.js +88 -10
  26. package/dist/lib/renderer/render.js +174 -99
  27. package/dist/lib/renderer/sourcemap/lib/codec.js +78 -0
  28. package/dist/lib/renderer/sourcemap/sourcemap.js +190 -34
  29. package/dist/lib/syntax/syntax.js +14 -151
  30. package/dist/lib/validation/match.js +81 -1
  31. package/dist/node.js +41 -26
  32. package/dist/utils/sync.d.ts +16 -0
  33. package/dist/utils/sync.js +52 -0
  34. package/dist/web.js +26 -28
  35. package/llms.txt +12 -5
  36. package/package.json +1 -1
  37. package/dist/lib/renderer/sourcemap/lib/encode.js +0 -37
package/dist/node.js CHANGED
@@ -14,6 +14,7 @@ import { ResponseType } from './types.js';
14
14
  import { resolve as resolve$1 } from 'node:path';
15
15
  import { SourceFile } from './lib/parser/source.js';
16
16
  import { cwd } from 'node:process';
17
+ import { parseResult, validateSyncArguments } from './utils/sync.js';
17
18
  export { minify } from './lib/ast/minify.js';
18
19
  export { expand } from './lib/ast/expand.js';
19
20
  export { WalkerEvent, WalkerOptionEnum, walk, walkValues } from './lib/ast/walk.js';
@@ -24,6 +25,7 @@ export { cloneNode } from './lib/ast/clone.js';
24
25
  export { replaceNodeOrValue } from './lib/parser/utils/token.js';
25
26
  export { SourceMap } from './lib/renderer/sourcemap/sourcemap.js';
26
27
  export { FeatureWalkMode } from './lib/ast/features/type.js';
28
+ export { getNodeProperty, setNodeProperty } from './lib/ast/node.js';
27
29
 
28
30
  /**
29
31
  * Load file or url
@@ -108,7 +110,7 @@ function render(data, options = {}, mapping) {
108
110
  return doRender(data, Object.assign(options, { resolve, dirname, cwd: options.cwd ?? resolve$1() }), mapping);
109
111
  }
110
112
  /**
111
- * Parse css file
113
+ * Parse CSS file
112
114
  * @param file url or path
113
115
  * @param options
114
116
  * @param asStream load file as stream
@@ -134,17 +136,17 @@ function render(data, options = {}, mapping) {
134
136
  */
135
137
  const parseFile = deprecate(async (file, options = {}, asStream = false) => parse({ file, asStream, ...options }), "parseFile is deprecated, use parse instead as parse({file, asStream, ...options})");
136
138
  /**
137
- * Parse css
139
+ * Parse CSS
138
140
  * @param args
139
141
  *
140
142
  * Parsing a string
141
143
  *
142
144
  * ```ts
143
145
  *
144
- * import {parse} from '@tbela99/css-parser';
146
+ * import {parseSync} from '@tbela99/css-parser';
145
147
  *
146
148
  * // css string
147
- * let result = await parse(css, {nestingRules: true});
149
+ * let result = parseSync(css, {nestingRules: true});
148
150
  * console.log(result.ast);
149
151
  * ```
150
152
  *
@@ -161,9 +163,12 @@ function parseSync(...args) {
161
163
  options = opt;
162
164
  stream = input;
163
165
  }
166
+ if (options != null) {
167
+ validateSyncArguments(options);
168
+ }
164
169
  options ??= {};
165
170
  options.src ??= "";
166
- options.sourcesMap ??= new Map;
171
+ options.sourcesMap ??= new Map();
167
172
  Object.assign(options, {
168
173
  resolve,
169
174
  dirname,
@@ -183,26 +188,24 @@ function parseSync(...args) {
183
188
  time: 0,
184
189
  source: options.source,
185
190
  position: 0,
186
- currentPosition: -1,
191
+ currentPosition: 0,
187
192
  };
188
193
  const result = doParseSync(tokenize(options.parseInfo), options);
189
- const { revMapping, ...res } = result;
190
- return res;
194
+ return !options.module && !options.inputSourceMap && !options.sourcemap ? result : parseResult(result, options);
191
195
  }
192
196
  /**
193
- * Transform css
194
- * @param css
195
- * @param options
197
+ * Transform CSS
196
198
  *
197
199
  * ```ts
198
200
  *
199
- * import {transform} from '@tbela99/css-parser';
201
+ * import {transformSync} from '@tbela99/css-parser';
200
202
  *
201
203
  * // css string
202
- * const result = await transform(css);
204
+ * const result = transformSync(css);
203
205
  * console.log(result.code);
204
206
  * ```
205
207
  *
208
+ * @param args
206
209
  */
207
210
  function transformSync(...args) {
208
211
  let options;
@@ -218,7 +221,15 @@ function transformSync(...args) {
218
221
  stream = input;
219
222
  }
220
223
  options ??= {};
221
- options = { minify: true, removeEmpty: true, removeCharset: true, ...options };
224
+ if (options.minify == null) {
225
+ options.minify = true;
226
+ }
227
+ if (options.removeEmpty == null) {
228
+ options.removeEmpty = true;
229
+ }
230
+ if (options.removeCharset == null) {
231
+ options.removeCharset = true;
232
+ }
222
233
  const startTime = performance.now();
223
234
  const parseResult = parseSync(stream, options);
224
235
  let mapping = null;
@@ -251,7 +262,7 @@ function transformSync(...args) {
251
262
  };
252
263
  }
253
264
  /**
254
- * Parse css
265
+ * Parse CSS
255
266
  * @param args
256
267
  *
257
268
  * @throws Error file not found
@@ -314,7 +325,7 @@ async function parse(...args) {
314
325
  }
315
326
  options ??= {};
316
327
  options.src ??= "";
317
- options.sourcesMap ??= new Map;
328
+ options.sourcesMap ??= new Map();
318
329
  Object.assign(options, {
319
330
  load,
320
331
  resolve,
@@ -335,15 +346,12 @@ async function parse(...args) {
335
346
  time: 0,
336
347
  source: options.source,
337
348
  position: 0,
338
- currentPosition: -1,
349
+ currentPosition: 0,
339
350
  };
340
- return doParse(stream instanceof ReadableStream ? tokenizeStream(stream, options.parseInfo) : tokenize(options.parseInfo), options).then((result) => {
341
- const { revMapping, ...res } = result;
342
- return res;
343
- });
351
+ return doParse(stream instanceof ReadableStream ? tokenizeStream(stream, options.parseInfo) : tokenize(options.parseInfo), options).then((result) => (!options.module && !options.inputSourceMap ? result : parseResult(result, options)));
344
352
  }
345
353
  /**
346
- * Transform css file
354
+ * Transform CSS file
347
355
  * @param file url or path
348
356
  * @param options
349
357
  * @param asStream load file as stream
@@ -372,9 +380,7 @@ const transformFile = deprecate(async (file, options = {}, asStream = false) =>
372
380
  ...options,
373
381
  }), "transformFile is deprecated, use transform instead as transform({file, asStream, ...options})");
374
382
  /**
375
- * Transform css
376
- * @param css
377
- * @param options
383
+ * Transform CSS
378
384
  *
379
385
  * Parsing a string
380
386
  *
@@ -413,6 +419,7 @@ const transformFile = deprecate(async (file, options = {}, asStream = false) =>
413
419
  *
414
420
  * console.log(result.code);
415
421
  * ```
422
+ * @param args
416
423
  */
417
424
  async function transform(...args) {
418
425
  let options;
@@ -433,7 +440,15 @@ async function transform(...args) {
433
440
  }
434
441
  }
435
442
  options ??= {};
436
- options = { minify: true, removeEmpty: true, removeCharset: true, ...options };
443
+ if (options.minify == null) {
444
+ options.minify = true;
445
+ }
446
+ if (options.removeEmpty == null) {
447
+ options.removeEmpty = true;
448
+ }
449
+ if (options.removeCharset == null) {
450
+ options.removeCharset = true;
451
+ }
437
452
  const startTime = performance.now();
438
453
  return parse(stream, options).then((parseResult) => {
439
454
  let mapping = null;
@@ -0,0 +1,16 @@
1
+ import type { ParseResult, ParserOptions, ParserSyncOptions } from "../@types/index.d.ts";
2
+ /**
3
+ * parse result. process input sourcemap
4
+ * @param result
5
+ * @param options
6
+ * @returns
7
+ * @private
8
+ */
9
+ export declare function parseResult(result: ParseResult, options: ParserOptions): ParseResult;
10
+ /**
11
+ *
12
+ * @param options
13
+ * @param prefix
14
+ * @private
15
+ */
16
+ export declare function validateSyncArguments(options: ParserSyncOptions, prefix?: string): void;
@@ -0,0 +1,52 @@
1
+ import { EnumToken } from '../lib/ast/types.js';
2
+
3
+ /**
4
+ * parse result. process input sourcemap
5
+ * @param result
6
+ * @param options
7
+ * @returns
8
+ * @private
9
+ */
10
+ function parseResult(result, options) {
11
+ if (options.sourcemap != null && options.source.getInputSourceMap() == null) {
12
+ if (options.inputSourceMap != null) {
13
+ options.source.setInputSourceMap(options.inputSourceMap);
14
+ }
15
+ else {
16
+ // extract inline source map from the input CSS
17
+ const token = result.ast.chi.at(-1);
18
+ if (token?.typ == EnumToken.CommentTokenType &&
19
+ token.val.startsWith("/*# sourceMappingURL=")) {
20
+ options.source.setInputSourceMap(token.val.slice(21, -2).trim());
21
+ }
22
+ }
23
+ }
24
+ if (options.module) {
25
+ const { revMapping, ...res } = result;
26
+ return res;
27
+ }
28
+ return result;
29
+ }
30
+ /**
31
+ *
32
+ * @param options
33
+ * @param prefix
34
+ * @private
35
+ */
36
+ function validateSyncArguments(options, prefix = "options.") {
37
+ const args = Object.entries(options);
38
+ let i;
39
+ for (i = 0; i < args.length; i++) {
40
+ const [key, value] = args[i];
41
+ if (typeof value == "function") {
42
+ if (value instanceof Promise || Object.getPrototypeOf(value).constructor.name == "AsyncFunction") {
43
+ throw new Error(`[${prefix + key}]: Async functions are not supported in sync mode. Use parse() or transform() instead.`);
44
+ }
45
+ }
46
+ else if (value != null && typeof value == "object") {
47
+ validateSyncArguments(value, prefix + key + ".");
48
+ }
49
+ }
50
+ }
51
+
52
+ export { parseResult, validateSyncArguments };
package/dist/web.js CHANGED
@@ -8,6 +8,7 @@ import { tokenizeStream, tokenize } from './lib/parser/tokenize.js';
8
8
  import { matchUrl, resolve, dirname } from './lib/fs/resolve.js';
9
9
  import { ResponseType } from './types.js';
10
10
  import { SourceFile } from './lib/parser/source.js';
11
+ import { parseResult, validateSyncArguments } from './utils/sync.js';
11
12
  export { minify } from './lib/ast/minify.js';
12
13
  export { expand } from './lib/ast/expand.js';
13
14
  export { WalkerEvent, WalkerOptionEnum, walk, walkValues } from './lib/ast/walk.js';
@@ -18,6 +19,7 @@ export { cloneNode } from './lib/ast/clone.js';
18
19
  export { replaceNodeOrValue } from './lib/parser/utils/token.js';
19
20
  export { SourceMap } from './lib/renderer/sourcemap/sourcemap.js';
20
21
  export { FeatureWalkMode } from './lib/ast/features/type.js';
22
+ export { getNodeProperty, setNodeProperty } from './lib/ast/node.js';
21
23
 
22
24
  /**
23
25
  * Load file or url
@@ -27,7 +29,7 @@ export { FeatureWalkMode } from './lib/ast/features/type.js';
27
29
  * @throws Error file not found
28
30
  *
29
31
  * ```ts
30
- * import {load, ResponseType} from '@tbela99/css-parser';
32
+ * import {load, ResponseType} from '@tbela99/css-parser/web';
31
33
  * const result = await load(file, '.', ResponseType.ArrayBuffer) as ArrayBuffer;
32
34
  * ```
33
35
  */
@@ -69,7 +71,7 @@ async function load(url, currentDirectory = ".", responseType = false) {
69
71
  *
70
72
  * ```ts
71
73
  *
72
- * import {render, ColorType} from '@tbela99/css-parser';
74
+ * import {render, ColorType} from '@tbela99/css-parser/web';
73
75
  *
74
76
  * const css = 'body { color: color(from hsl(0 100% 50%) xyz x y z); }';
75
77
  * const parseResult = await parse(css);
@@ -98,7 +100,7 @@ function render(data, options = {}, mapping) {
98
100
  }), mapping);
99
101
  }
100
102
  /**
101
- * Parse css file
103
+ * Parse CSS file
102
104
  * @param file url or path
103
105
  * @param options
104
106
  * @param asStream load file as stream
@@ -126,17 +128,17 @@ async function parseFile(file, options = {}, asStream = false) {
126
128
  return parse({ file, asStream, ...options });
127
129
  }
128
130
  /**
129
- * Parse css
131
+ * Parse CSS
130
132
  * @param args
131
133
  *
132
134
  * Parsing a string
133
135
  *
134
136
  * ```ts
135
137
  *
136
- * import {parse} from '@tbela99/css-parser';
138
+ * import {parseSync} from '@tbela99/css-parser/web';
137
139
  *
138
140
  * // css string
139
- * let result = await parse(css, {nestingRules: true});
141
+ * let result = await parseSync(css, {nestingRules: true});
140
142
  * console.log(result.ast);
141
143
  * ```
142
144
  *
@@ -153,9 +155,12 @@ function parseSync(...args) {
153
155
  options = opt;
154
156
  stream = input;
155
157
  }
158
+ if (options != null) {
159
+ validateSyncArguments(options);
160
+ }
156
161
  options ??= {};
157
162
  options.src ??= "";
158
- options.sourcesMap ??= new Map;
163
+ options.sourcesMap ??= new Map();
159
164
  Object.assign(options, {
160
165
  resolve,
161
166
  dirname,
@@ -177,26 +182,24 @@ function parseSync(...args) {
177
182
  time: 0,
178
183
  source: options.source,
179
184
  position: 0,
180
- currentPosition: -1,
185
+ currentPosition: 0,
181
186
  };
182
187
  const result = doParseSync(tokenize(options.parseInfo), options);
183
- const { revMapping, ...res } = result;
184
- return res;
188
+ return !options.module && !options.inputSourceMap && !options.sourcemap ? result : parseResult(result, options);
185
189
  }
186
190
  /**
187
- * Transform css
188
- * @param css
189
- * @param options
191
+ * Transform CSS
190
192
  *
191
193
  * ```ts
192
194
  *
193
- * import {transform} from '@tbela99/css-parser';
195
+ * import {transformSync} from '@tbela99/css-parser/web';
194
196
  *
195
197
  * // css string
196
- * const result = await transform(css);
198
+ * const result = transformSync(css);
197
199
  * console.log(result.code);
198
200
  * ```
199
201
  *
202
+ * @param args
200
203
  */
201
204
  function transformSync(...args) {
202
205
  let options;
@@ -245,9 +248,7 @@ function transformSync(...args) {
245
248
  };
246
249
  }
247
250
  /**
248
- * Parse css
249
- * @param stream
250
- * @param options
251
+ * Parse CSS
251
252
  *
252
253
  * Example:
253
254
  *
@@ -271,6 +272,7 @@ function transformSync(...args) {
271
272
  *
272
273
  * console.log(result.ast);
273
274
  * ```
275
+ * @param args
274
276
  */
275
277
  async function parse(...args) {
276
278
  let options;
@@ -292,7 +294,7 @@ async function parse(...args) {
292
294
  }
293
295
  options ??= {};
294
296
  options.src ??= "";
295
- options.sourcesMap ??= new Map;
297
+ options.sourcesMap ??= new Map();
296
298
  Object.assign(options, {
297
299
  load,
298
300
  resolve,
@@ -314,15 +316,12 @@ async function parse(...args) {
314
316
  time: 0,
315
317
  source: options.source,
316
318
  position: 0,
317
- currentPosition: -1,
319
+ currentPosition: 0,
318
320
  };
319
- return doParse(stream instanceof ReadableStream ? tokenizeStream(stream, options.parseInfo) : tokenize(options.parseInfo), options).then((result) => {
320
- const { revMapping, ...res } = result;
321
- return res;
322
- });
321
+ return doParse(stream instanceof ReadableStream ? tokenizeStream(stream, options.parseInfo) : tokenize(options.parseInfo), options).then((result) => (!options.module && !options.inputSourceMap ? result : parseResult(result, options)));
323
322
  }
324
323
  /**
325
- * Transform css file
324
+ * Transform CSS file
326
325
  * @param file url or path
327
326
  * @param options
328
327
  * @param asStream load file as stream
@@ -352,9 +351,7 @@ async function transformFile(file, options = {}, asStream = false) {
352
351
  });
353
352
  }
354
353
  /**
355
- * Transform css
356
- * @param css
357
- * @param options
354
+ * Transform CSS
358
355
  *
359
356
  * Example:
360
357
  *
@@ -372,6 +369,7 @@ async function transformFile(file, options = {}, asStream = false) {
372
369
  *
373
370
  * console.log(result.code);
374
371
  * ```
372
+ * @param args
375
373
  */
376
374
  async function transform(...args) {
377
375
  let options;
package/llms.txt CHANGED
@@ -1,9 +1,10 @@
1
1
  # css-parser
2
2
 
3
3
  ## Project overview
4
- - This repository contains css-parser, a dependency-free CSS parser, transformer, minifier, and validator for Node.js and browsers.
4
+ - This repository contains css-parser, a dependency-free all-in-one CSS parsing solution for Node.js and browsers.
5
5
  - The library follows the CSS Syntax Module Level 3 specification and uses MDN syntax data for validation.
6
- - It is designed for fault-tolerant parsing, AST manipulation, CSS Modules, minification, color processing, and syntax lowering.
6
+ - It is designed for fault-tolerant parsing, full AST and typed-token analysis, AST manipulation, CSS Modules, minification, color processing, and syntax lowering.
7
+ - CSS is always fully parsed into a structured AST, and token values are typed so plugins and transforms can work against semantic data instead of raw strings.
7
8
 
8
9
  ## Installation
9
10
  - npm: npm install @tbela99/css-parser
@@ -26,9 +27,15 @@
26
27
  - Support CSS Modules with scoped class generation.
27
28
  - Minify CSS safely with options such as inlineCssVariables, computeCalcExpression, removeDuplicateDeclarations, and beautify.
28
29
  - Transform ASTs through visitors and custom traversal logic.
30
+ - Support plugin-style extensions through the visitor API, where custom handlers can observe and mutate AST nodes during enter/visit/leave phases.
29
31
  - Lower modern CSS syntax such as nested CSS and if() to broadly compatible output.
30
32
  - Generate source maps and handle advanced color functions and conversions.
31
33
 
34
+ ## Visitor-based plugin model
35
+ - The parser exposes a visitor option that accepts node-specific handlers keyed by AST node type and event type.
36
+ - Plugins can be implemented as reusable visitor maps that inspect or transform nodes such as Rule, AtRule, Declaration, KeyframesRule, and Value nodes.
37
+ - This allows extension code to run alongside the core parser without modifying the parser itself.
38
+
32
39
  ## Typical usage
33
40
  ```ts
34
41
  import {transform, ColorType} from '@tbela99/css-parser';
@@ -43,15 +50,15 @@ console.log(result.code);
43
50
  ```
44
51
 
45
52
  ## Important behavior notes
46
- - parse() and transform() are lenient by default and preserve unknown constructs unless configured otherwise.
53
+ - parse(), parseSync(), transform() and transformSync() are lenient by default and preserve unknown constructs unless configured otherwise.
47
54
  - Comments are removed by default; preserve them with removeComments: false or preserveLicense: true.
48
55
  - Validation errors are available through the parse/transform result and through node.state and node.errors.
49
56
  - The library prioritizes compact output while preserving semantics.
50
57
 
51
58
  ## Useful concepts
52
- - parse() returns AST, errors, and stats.
59
+ - parse(), parseSync() return AST, errors, and stats.
53
60
  - render() turns an AST into CSS text.
54
- - transform() performs parsing and rendering together.
61
+ - transform(), transformSync() perform parsing and rendering together.
55
62
  - AST node types include StyleSheet, Rule, AtRule, Declaration, Comment, and Keyframes variants.
56
63
 
57
64
  ## Documentation files
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tbela99/css-parser",
3
3
  "description": "CSS parser, minifier and validator for node and the browser",
4
- "version": "1.4.10",
4
+ "version": "1.5.0",
5
5
  "exports": {
6
6
  ".": "./dist/node.js",
7
7
  "./node": "./dist/node.js",
@@ -1,37 +0,0 @@
1
- // from https://github.com/Rich-Harris/vlq/tree/master
2
- // credit: Rich Harris
3
- const integer_to_char = {};
4
- let i = 0;
5
- for (const char of 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=') {
6
- integer_to_char[i++] = char;
7
- }
8
- function encode(value) {
9
- if (typeof value === 'number') {
10
- return encode_integer(value);
11
- }
12
- let result = '';
13
- for (let i = 0; i < value.length; i += 1) {
14
- result += encode_integer(value[i]);
15
- }
16
- return result;
17
- }
18
- function encode_integer(num) {
19
- let result = '';
20
- if (num < 0) {
21
- num = (-num << 1) | 1;
22
- }
23
- else {
24
- num <<= 1;
25
- }
26
- do {
27
- let clamped = num & 31;
28
- num >>>= 5;
29
- if (num > 0) {
30
- clamped |= 32;
31
- }
32
- result += integer_to_char[clamped];
33
- } while (num > 0);
34
- return result;
35
- }
36
-
37
- export { encode };