@tbela99/css-parser 1.4.11 → 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 +6 -0
  2. package/README.md +11 -4
  3. package/dist/index-umd-web.js +2116 -1699
  4. package/dist/index.cjs +2128 -1694
  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 +60 -28
  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
@@ -4,9 +4,9 @@ import { renderValue } from '../renderer/render.js';
4
4
  import { EnumToken, EnumAstNodeStatus, ModuleCaseTransformEnum, ModuleScopeEnumOptions } from '../ast/types.js';
5
5
  import { minify } from '../ast/minify.js';
6
6
  import { expand } from '../ast/expand.js';
7
- import { WalkerEvent, walk, walkValues } from '../ast/walk.js';
7
+ import { walk, walkValues, WalkerEvent } from '../ast/walk.js';
8
8
  import { tokenizeStream, tokenize } from './tokenize.js';
9
- import { ROOT, LOC, tokensfuncDefMap, STATE, PARENT, TOKENS, ERRORS, pageMarginBoxType } from '../syntax/constants.js';
9
+ import { LOC, tokensfuncDefMap, STATE, PARENT, TOKENS, ROOT, ERRORS, pageMarginBoxType } from '../syntax/constants.js';
10
10
  import { hashAlgorithms, hash, syncHash } from './utils/hash.js';
11
11
  import { parseSelector } from './utils/selector.js';
12
12
  import { parseDeclaration } from './utils/declaration.js';
@@ -24,6 +24,7 @@ import { parseAtRuleFontFeatureValues } from './utils/at-rule-font-feature-value
24
24
  import { matchGenericSyntax } from './utils/at-rule-generic.js';
25
25
  import { memoize } from './utils/cache.js';
26
26
  import { SourceFile } from './source.js';
27
+ import { dirname } from '../fs/resolve.js';
27
28
 
28
29
  function renderTokens(tokens, options) {
29
30
  if (tokens == null || tokens.length === 0)
@@ -47,7 +48,6 @@ const BadTokensTypes = [
47
48
  EnumToken.BadStringTokenType,
48
49
  ];
49
50
  let keyNameCounter = 0;
50
- const forbiddenStartCharacters = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"].map((c) => c.charCodeAt(0));
51
51
  /**
52
52
  * Short-scoped name generator.
53
53
  *
@@ -58,12 +58,15 @@ const forbiddenStartCharacters = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "
58
58
  *
59
59
  * @returns string
60
60
  */
61
- const getShortNameGenerator = memoize((localName, filePath, pattern, hashLength = 5) => {
61
+ const getShortNameGenerator = memoize(() => {
62
62
  let value = keyNameCounter.toString(36);
63
+ let val = value.charAt(0).charCodeAt(0);
63
64
  keyNameCounter++;
64
- while (forbiddenStartCharacters.includes(value.charCodeAt(0))) {
65
+ // starts with'0' - '9'
66
+ while (48 <= val && val <= 57) {
65
67
  value = keyNameCounter.toString(36);
66
68
  keyNameCounter++;
69
+ val = value.charAt(0).charCodeAt(0);
67
70
  }
68
71
  return value;
69
72
  });
@@ -290,6 +293,144 @@ const generateSyncScopedName = memoize((localName, filePath, pattern, hashLength
290
293
  // if leading char is digit, prefix underscore (very rare)
291
294
  return (/^[0-9]/.test(result) ? "_" : "") + result;
292
295
  });
296
+ /**
297
+ *
298
+ * @param visitorsDef
299
+ * @param errors
300
+ * @private
301
+ */
302
+ function parseVisitors(visitorsDef, errors) {
303
+ const visitors = Object.entries(typeof visitorsDef === "function" ? [visitorsDef] : visitorsDef);
304
+ let key;
305
+ let value;
306
+ let i;
307
+ const valuesHandlers = new Map();
308
+ const preValuesHandlers = new Map();
309
+ const postValuesHandlers = new Map();
310
+ const visitorsHandlersMap = new Map();
311
+ const preVisitorsHandlersMap = new Map();
312
+ const postVisitorsHandlersMap = new Map();
313
+ for (i = 0; i < visitors.length; i++) {
314
+ key = visitors[i][0];
315
+ value = visitors[i][1];
316
+ if (Number.isInteger(+key)) {
317
+ // if (Array.isArray(value)) {
318
+ // visitors.splice(i + 1, 0, ...Object.entries(value));
319
+ // continue;
320
+ // }
321
+ if (typeof value == "function") {
322
+ key = value.name;
323
+ }
324
+ }
325
+ // if (Array.isArray(value)) {
326
+ // // @ts-ignore
327
+ // visitors.splice(i + 1, 0, ...value.map((item) => [key, item]));
328
+ // continue;
329
+ // }
330
+ if (key in EnumToken) {
331
+ if (typeof value == "function") {
332
+ if (!valuesHandlers.has(EnumToken[key])) {
333
+ valuesHandlers.set(EnumToken[key], []);
334
+ }
335
+ valuesHandlers.get(EnumToken[key]).push(value);
336
+ }
337
+ else if (typeof value == "object") {
338
+ if ("type" in value && "handler" in value && value.type in WalkerEvent) {
339
+ if (value.type == WalkerEvent.Enter) {
340
+ if (!preValuesHandlers.has(EnumToken[key])) {
341
+ preValuesHandlers.set(EnumToken[key], []);
342
+ }
343
+ preValuesHandlers
344
+ .get(EnumToken[key])
345
+ .push(value.handler);
346
+ }
347
+ else if (value.type == WalkerEvent.Leave) {
348
+ if (!postValuesHandlers.has(EnumToken[key])) {
349
+ postValuesHandlers.set(EnumToken[key], []);
350
+ }
351
+ postValuesHandlers
352
+ .get(EnumToken[key])
353
+ .push(value.handler);
354
+ }
355
+ }
356
+ else {
357
+ visitors.push(...Object.entries(value));
358
+ }
359
+ }
360
+ else {
361
+ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
362
+ }
363
+ }
364
+ else if (["Declaration", "Rule", "AtRule", "KeyframesRule", "KeyframesAtRule"].includes(key)) {
365
+ if (typeof value == "function") {
366
+ if (!visitorsHandlersMap.has(key)) {
367
+ visitorsHandlersMap.set(key, []);
368
+ }
369
+ visitorsHandlersMap
370
+ .get(key)
371
+ .push(value);
372
+ }
373
+ else if (typeof value == "object") {
374
+ // visitors.push(...Object.entries(value));
375
+ if ("type" in value && "handler" in value && value.type in WalkerEvent) {
376
+ if (value.type == WalkerEvent.Enter) {
377
+ if (!preVisitorsHandlersMap.has(key)) {
378
+ preVisitorsHandlersMap.set(key, []);
379
+ }
380
+ preVisitorsHandlersMap
381
+ .get(key)
382
+ .push(value.handler);
383
+ }
384
+ else if (value.type == WalkerEvent.Leave) {
385
+ if (!postVisitorsHandlersMap.has(key)) {
386
+ postVisitorsHandlersMap.set(key, []);
387
+ }
388
+ postVisitorsHandlersMap
389
+ .get(key)
390
+ .push(value.handler);
391
+ }
392
+ }
393
+ else {
394
+ if (!visitorsHandlersMap.has(key)) {
395
+ visitorsHandlersMap.set(key, []);
396
+ }
397
+ visitorsHandlersMap
398
+ .get(key)
399
+ .push(value);
400
+ }
401
+ }
402
+ else {
403
+ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
404
+ }
405
+ }
406
+ else {
407
+ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
408
+ }
409
+ }
410
+ const allHandlers = [];
411
+ if (preVisitorsHandlersMap.size > 0) {
412
+ allHandlers.push(preVisitorsHandlersMap);
413
+ }
414
+ if (preValuesHandlers.size > 0) {
415
+ allHandlers.push(preValuesHandlers);
416
+ }
417
+ if (visitorsHandlersMap.size > 0) {
418
+ allHandlers.push(visitorsHandlersMap);
419
+ }
420
+ if (valuesHandlers.size > 0) {
421
+ allHandlers.push(valuesHandlers);
422
+ }
423
+ if (postVisitorsHandlersMap.size > 0) {
424
+ allHandlers.push(postVisitorsHandlersMap);
425
+ }
426
+ if (postValuesHandlers.size > 0) {
427
+ allHandlers.push(postValuesHandlers);
428
+ }
429
+ return {
430
+ allHandlers,
431
+ includeTokens: preValuesHandlers.size > 0 || valuesHandlers.size > 0 || postValuesHandlers.size > 0,
432
+ };
433
+ }
293
434
  /**
294
435
  * Parse css string
295
436
  * @param iter
@@ -355,131 +496,20 @@ function doParseSync(iter, options = {}) {
355
496
  };
356
497
  let tokens = [];
357
498
  let context = ast;
358
- ast[ROOT] = ast;
359
- ast[LOC] = {
360
- sta: 0,
361
- end: 0,
362
- srcId: options.source.id,
363
- };
364
- let valuesHandlers;
365
- let preValuesHandlers;
366
- let postValuesHandlers;
367
- let preVisitorsHandlersMap;
368
- let visitorsHandlersMap;
369
- let postVisitorsHandlersMap;
370
499
  let item;
371
500
  let node;
372
501
  // @ts-ignore ignore error
373
502
  let parensMatch = 0;
374
503
  let curlyBracketMatch = 0;
375
- if (options.visitor != null) {
376
- valuesHandlers = new Map();
377
- preValuesHandlers = new Map();
378
- postValuesHandlers = new Map();
379
- preVisitorsHandlersMap = new Map();
380
- visitorsHandlersMap = new Map();
381
- postVisitorsHandlersMap = new Map();
382
- const visitors = Object.entries(options.visitor);
383
- let key;
384
- let value;
385
- let i;
386
- for (i = 0; i < visitors.length; i++) {
387
- key = visitors[i][0];
388
- value = visitors[i][1];
389
- if (Number.isInteger(+key)) {
390
- visitors.splice(i + 1, 0, ...Object.entries(value));
391
- continue;
392
- }
393
- if (Array.isArray(value)) {
394
- // @ts-ignore
395
- visitors.splice(i + 1, 0, ...value.map((item) => [key, item]));
396
- continue;
397
- }
398
- if (key in EnumToken) {
399
- if (typeof value == "function") {
400
- if (!valuesHandlers.has(EnumToken[key])) {
401
- valuesHandlers.set(EnumToken[key], []);
402
- }
403
- valuesHandlers.get(EnumToken[key]).push(value);
404
- }
405
- else if (typeof value == "object" &&
406
- "type" in value &&
407
- "handler" in value &&
408
- value.type in WalkerEvent) {
409
- if (value.type == WalkerEvent.Enter) {
410
- if (!preValuesHandlers.has(EnumToken[key])) {
411
- preValuesHandlers.set(EnumToken[key], []);
412
- }
413
- preValuesHandlers
414
- .get(EnumToken[key])
415
- .push(value.handler);
416
- }
417
- else if (value.type == WalkerEvent.Leave) {
418
- if (!postValuesHandlers.has(EnumToken[key])) {
419
- postValuesHandlers.set(EnumToken[key], []);
420
- }
421
- postValuesHandlers
422
- .get(EnumToken[key])
423
- .push(value.handler);
424
- }
425
- }
426
- else {
427
- errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
428
- }
429
- }
430
- else if (["Declaration", "Rule", "AtRule", "KeyframesRule", "KeyframesAtRule"].includes(key)) {
431
- if (typeof value == "function") {
432
- if (!visitorsHandlersMap.has(key)) {
433
- visitorsHandlersMap.set(key, []);
434
- }
435
- visitorsHandlersMap
436
- .get(key)
437
- .push(value);
438
- }
439
- else if (typeof value == "object") {
440
- if ("type" in value && "handler" in value && value.type in WalkerEvent) {
441
- if (value.type == WalkerEvent.Enter) {
442
- if (!preVisitorsHandlersMap.has(key)) {
443
- preVisitorsHandlersMap.set(key, []);
444
- }
445
- preVisitorsHandlersMap
446
- .get(key)
447
- .push(value.handler);
448
- }
449
- else if (value.type == WalkerEvent.Leave) {
450
- if (!postVisitorsHandlersMap.has(key)) {
451
- postVisitorsHandlersMap.set(key, []);
452
- }
453
- postVisitorsHandlersMap
454
- .get(key)
455
- .push(value.handler);
456
- }
457
- }
458
- else {
459
- if (!visitorsHandlersMap.has(key)) {
460
- visitorsHandlersMap.set(key, []);
461
- }
462
- visitorsHandlersMap
463
- .get(key)
464
- .push(value);
465
- }
466
- }
467
- else {
468
- errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
469
- }
470
- }
471
- else {
472
- errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
473
- }
474
- }
475
- }
476
- if (Array.isArray(iter)) {
477
- // @ts-expect-error
478
- iter = iter[Symbol.iterator]();
479
- }
480
- while (
481
- // @ts-expect-error
482
- (item = iter.next().value)) {
504
+ let currentItemIndex;
505
+ // ast[ROOT] = ast;
506
+ ast[LOC] = {
507
+ sta: 0,
508
+ end: 0,
509
+ srcId: options.source.id,
510
+ };
511
+ for (currentItemIndex = 0; currentItemIndex < iter.length; currentItemIndex++) {
512
+ item = iter[currentItemIndex];
483
513
  stats.bytesIn = item.bytesIn;
484
514
  stats.tokensCount++;
485
515
  if (BadTokensTypes.includes(item.token.typ)) {
@@ -507,8 +537,6 @@ function doParseSync(iter, options = {}) {
507
537
  curlyBracketMatch--;
508
538
  }
509
539
  tokens.push(item.token);
510
- // console.debug([item.token, {parensMatch, curlyBracketMatch}]);
511
- // if (parensMatch === 0) {
512
540
  if (parensMatch === 0 &&
513
541
  (item.token.typ === EnumToken.SemiColonTokenType ||
514
542
  item.token.typ === EnumToken.BlockStartTokenType ||
@@ -524,8 +552,7 @@ function doParseSync(iter, options = {}) {
524
552
  let inBlock = 1;
525
553
  tokens = [item.token];
526
554
  do {
527
- // @ts-expect-error
528
- item = iter.next().value;
555
+ item = iter[++currentItemIndex];
529
556
  if (item == null) {
530
557
  break;
531
558
  }
@@ -580,198 +607,162 @@ function doParseSync(iter, options = {}) {
580
607
  ast = expand(ast);
581
608
  }
582
609
  let replacement;
583
- let callable;
584
610
  if (options.visitor != null) {
611
+ const handlers = [];
612
+ const visitors = parseVisitors(options.visitor, errors);
613
+ const subNodes = [];
585
614
  let parens;
586
- for (const result of walk(ast)) {
615
+ let genericKey;
616
+ let nodes = new Array(stats.tokensCount);
617
+ let i;
618
+ let k;
619
+ let j;
620
+ let freeBlock = 1;
621
+ nodes[0] = ast;
622
+ for (i = 0; i < nodes.length; i++) {
623
+ if (nodes[i] == null) {
624
+ break;
625
+ }
626
+ subNodes.length = 0;
627
+ if (visitors.includeTokens) {
628
+ switch (nodes[i].typ) {
629
+ case EnumToken.RuleNodeType:
630
+ case EnumToken.AtRuleNodeType:
631
+ case EnumToken.KeyframesRuleNodeType:
632
+ case EnumToken.KeyframesAtRuleNodeType:
633
+ subNodes.push(...nodes[i][TOKENS]);
634
+ break;
635
+ case EnumToken.DeclarationNodeType:
636
+ subNodes.push(...nodes[i].val);
637
+ break;
638
+ }
639
+ }
640
+ // @ts-ignore
641
+ if (nodes[i].chi != null) {
642
+ // @ts-ignore
643
+ subNodes.push(...nodes[i].chi);
644
+ }
645
+ if (subNodes.length > 0) {
646
+ if (freeBlock <= i) {
647
+ freeBlock = i + 1;
648
+ }
649
+ for (k = 0; k < subNodes.length; k++) {
650
+ j = k + freeBlock;
651
+ nodes[j] = subNodes[k];
652
+ nodes[j][PARENT] = nodes[i];
653
+ }
654
+ freeBlock += subNodes.length;
655
+ }
587
656
  parens = null;
588
- if (valuesHandlers.size > 0 ||
589
- preVisitorsHandlersMap.size > 0 ||
590
- visitorsHandlersMap.size > 0 ||
591
- postVisitorsHandlersMap.size > 0) {
592
- if ((result.node.typ == EnumToken.DeclarationNodeType &&
593
- (preVisitorsHandlersMap.has("Declaration") ||
594
- visitorsHandlersMap.has("Declaration") ||
595
- postVisitorsHandlersMap.has("Declaration"))) ||
596
- (result.node.typ == EnumToken.AtRuleNodeType &&
597
- (preVisitorsHandlersMap.has("AtRule") ||
598
- visitorsHandlersMap.has("AtRule") ||
599
- postVisitorsHandlersMap.has("AtRule"))) ||
600
- (result.node.typ == EnumToken.KeyframesAtRuleNodeType &&
601
- (preVisitorsHandlersMap.has("KeyframesAtRule") ||
602
- visitorsHandlersMap.has("KeyframesAtRule") ||
603
- postVisitorsHandlersMap.has("KeyframesAtRule")))) {
604
- const handlers = [];
605
- const key = result.node.typ == EnumToken.DeclarationNodeType
606
- ? "Declaration"
607
- : result.node.typ == EnumToken.AtRuleNodeType
608
- ? "AtRule"
609
- : "KeyframesAtRule";
610
- if (preVisitorsHandlersMap.has(key)) {
611
- handlers.push(
612
- // @ts-expect-error
613
- ...preVisitorsHandlersMap.get(key));
614
- }
615
- if (visitorsHandlersMap.has(key)) {
616
- // @ts-ignore
617
- handlers.push(...visitorsHandlersMap.get(key));
618
- }
619
- if (postVisitorsHandlersMap.has(key)) {
620
- // @ts-ignore
621
- handlers.push(...postVisitorsHandlersMap.get(key));
622
- }
623
- let node = result.node;
624
- for (const handler of handlers) {
625
- callable =
626
- typeof handler == "function"
627
- ? handler
628
- : handler[camelize(node.typ === EnumToken.DeclarationNodeType ||
629
- node.typ === EnumToken.AtRuleNodeType
630
- ? node.nam
631
- : node.val)];
632
- if (callable == null) {
633
- continue;
634
- }
635
- // @ts-expect-error
636
- replacement = callable(node, result[PARENT], ast, function* () {
637
- if (parens == null) {
638
- // @ts-expect-error
639
- parens = [...result.parents()];
640
- }
641
- yield* parens[Symbol.iterator]();
642
- });
643
- if (replacement == null) {
644
- continue;
645
- }
646
- if (replacement == null || replacement == node) {
647
- continue;
648
- }
657
+ handlers.length = 0;
658
+ genericKey =
659
+ nodes[i].typ == EnumToken.DeclarationNodeType
660
+ ? "Declaration"
661
+ : nodes[i].typ == EnumToken.AtRuleNodeType
662
+ ? "AtRule"
663
+ : nodes[i].typ == EnumToken.KeyframesAtRuleNodeType
664
+ ? "KeyframesAtRule"
665
+ : nodes[i].typ === EnumToken.KeyframesRuleNodeType
666
+ ? "KeyframesRule"
667
+ : nodes[i].typ == EnumToken.RuleNodeType
668
+ ? "Rule"
669
+ : nodes[i].typ == EnumToken.KeyframesRuleNodeType
670
+ ? "KeyframesRule"
671
+ : null;
672
+ let keyName = nodes[i].typ == EnumToken.DeclarationNodeType || nodes[i].typ == EnumToken.AtRuleNodeType
673
+ ? camelize(nodes[i].nam)
674
+ : nodes[i].typ == EnumToken.KeyframesAtRuleNodeType
675
+ ? camelize(nodes[i].val)
676
+ : null;
677
+ for (const map of visitors.allHandlers) {
678
+ // @ts-ignore
679
+ if (genericKey != null && map.has(genericKey)) {
680
+ // @ts-ignore
681
+ for (const handler of map.get(genericKey)) {
682
+ if (typeof handler == "function") {
683
+ handlers.push(handler);
684
+ }
685
+ // else if (Array.isArray(handler)) {
686
+ // for (const h of handler) {
687
+ // if (typeof h == "function") {
688
+ // handlers.push(h);
689
+ // }
690
+ // // @ts-ignore
691
+ // else if (h[keyName] != null) {
692
+ // // @ts-ignore
693
+ // handlers.push(h[keyName]);
694
+ // }
695
+ // }
696
+ // } else if (typeof handler.handler! == "function") {
697
+ // handlers.push(handler.handler);
698
+ // }
649
699
  // @ts-ignore
650
- node = replacement;
651
- if (Array.isArray(node)) {
652
- break;
700
+ else if (typeof handler[keyName] == "function") {
701
+ // @ts-ignore
702
+ handlers.push(handler[keyName]);
653
703
  }
654
704
  }
655
- if (node != result.node) {
656
- replaceNodeOrValue(result.parent, result.node, node);
657
- }
658
705
  }
659
- else if ((result.node.typ == EnumToken.RuleNodeType &&
660
- (preVisitorsHandlersMap.has("Rule") ||
661
- visitorsHandlersMap.has("Rule") ||
662
- postVisitorsHandlersMap.has("Rule"))) ||
663
- (result.node.typ == EnumToken.KeyFramesRuleNodeType &&
664
- (preVisitorsHandlersMap.has("KeyframesRule") ||
665
- visitorsHandlersMap.has("KeyframesRule") ||
666
- postVisitorsHandlersMap.has("KeyframesRule")))) {
667
- const handlers = [];
668
- const key = result.node.typ == EnumToken.RuleNodeType ? "Rule" : "KeyframesRule";
669
- if (preVisitorsHandlersMap.has(key)) {
670
- handlers.push(...preVisitorsHandlersMap.get(key));
671
- }
672
- if (visitorsHandlersMap.has(key)) {
673
- handlers.push(...visitorsHandlersMap.get(key));
674
- }
675
- if (postVisitorsHandlersMap.has(key)) {
676
- handlers.push(...postVisitorsHandlersMap.get(key));
677
- }
678
- let node = result.node;
679
- for (const callable of handlers) {
680
- replacement = callable(node, result.parent, result.root,
681
- // @ts-expect-error
682
- function* () {
683
- if (parens == null) {
684
- // @ts-expect-error
685
- parens = [...result.parents()];
706
+ // @ts-ignore
707
+ if (map.has(nodes[i].typ)) {
708
+ // @ts-ignore
709
+ for (const handler of map.get(nodes[i].typ)) {
710
+ if (typeof handler == "function") {
711
+ handlers.push(handler);
712
+ }
713
+ else if (Array.isArray(handler)) {
714
+ for (const h of handler) {
715
+ if (typeof h == "function") {
716
+ handlers.push(h);
717
+ }
686
718
  }
687
- yield* parens[Symbol.iterator]();
688
- });
689
- if (replacement == null) {
690
- continue;
691
719
  }
692
- if (replacement == null || replacement == node) {
693
- continue;
720
+ else if (typeof handler.handler == "function") {
721
+ handlers.push(handler.handler);
694
722
  }
695
723
  // @ts-ignore
696
- node = replacement;
697
- //
698
- if (Array.isArray(node)) {
699
- break;
724
+ else if (typeof handler[keyName] == "function") {
725
+ // @ts-ignore
726
+ handlers.push(handler[keyName]);
700
727
  }
701
728
  }
702
- // @ts-ignore
703
- if (node != result.node) {
704
- // @ts-ignore
705
- replaceNodeOrValue(result.parent, result.node, node);
706
- }
707
729
  }
708
- else if (valuesHandlers.size > 0) {
709
- let node = null;
710
- node = result.node;
711
- if (valuesHandlers.has(node.typ)) {
712
- for (const valueHandler of valuesHandlers.get(node.typ)) {
713
- callable = valueHandler;
714
- replacement = callable(node, result.parent, ast,
715
- // @ts-expect-error
716
- function* () {
717
- if (parens == null) {
718
- // @ts-expect-error
719
- parens = [...result.parents()];
720
- }
721
- yield* parens[Symbol.iterator]();
722
- });
723
- if (replacement == null) {
724
- continue;
725
- }
726
- if (replacement != null && replacement != node) {
727
- node = replacement;
728
- }
729
- }
730
- }
731
- if (node != result.node) {
732
- // @ts-ignore
733
- replaceNodeOrValue(result[PARENT], value, node);
734
- }
735
- const tokens = Array.isArray(result.node[TOKENS]) ? result.node[TOKENS] : [];
736
- if (Array.isArray(result.node.val)) {
737
- tokens.push(...result.node.val);
738
- }
739
- if (tokens.length == 0) {
740
- continue;
741
- }
742
- for (const { value, parent, root, parents } of walkValues(tokens, result.node)) {
743
- node = value;
744
- if (valuesHandlers.has(node.typ)) {
745
- let parens = null;
746
- for (const valueHandler of valuesHandlers.get(node.typ)) {
747
- callable = valueHandler;
748
- // @ts-expect-error
749
- let result = callable(node, parent, root, function* () {
750
- if (parens == null) {
751
- // @ts-expect-error
752
- parens = [...parents()];
753
- }
754
- yield* parens[Symbol.iterator]();
755
- });
756
- if (result == null) {
757
- continue;
758
- }
759
- if (result != null && result != node) {
760
- node = result;
761
- }
762
- if (Array.isArray(node)) {
763
- break;
764
- }
765
- }
766
- }
767
- if (node != value) {
768
- // @ts-ignore
769
- replaceNodeOrValue(parent, value, node);
730
+ }
731
+ if (handlers.length == 0) {
732
+ continue;
733
+ }
734
+ let node = nodes[i];
735
+ for (const callable of handlers) {
736
+ replacement = callable(node, nodes[i][PARENT], ast,
737
+ // @ts-expect-error
738
+ function* () {
739
+ if (parens == null) {
740
+ let node = nodes[i][PARENT];
741
+ while (node != null) {
742
+ yield node;
743
+ node = node[PARENT];
770
744
  }
771
745
  }
746
+ });
747
+ if (replacement == null) {
748
+ continue;
749
+ }
750
+ if (replacement == node) {
751
+ continue;
752
+ }
753
+ // @ts-ignore
754
+ node = replacement;
755
+ //
756
+ if (Array.isArray(node)) {
757
+ break;
772
758
  }
773
759
  }
760
+ if (node != nodes[i]) {
761
+ // @ts-ignore
762
+ replaceNodeOrValue(nodes[i][PARENT], nodes[i], node);
763
+ }
774
764
  }
765
+ nodes = null;
775
766
  }
776
767
  if (invalidNodes.length > 0) {
777
768
  let count = invalidNodes.length;
@@ -794,19 +785,6 @@ function doParseSync(iter, options = {}) {
794
785
  }
795
786
  }
796
787
  }
797
- while (stack.length > 0 && context != ast) {
798
- const previousNode = stack.pop();
799
- context = (stack[stack.length - 1] ?? ast);
800
- // remove empty nodes
801
- if (options.removeEmpty &&
802
- previousNode != null &&
803
- previousNode.chi.length == 0 &&
804
- context.chi[context.chi.length - 1] == previousNode) {
805
- context.chi.pop();
806
- continue;
807
- }
808
- break;
809
- }
810
788
  if (options.minify) {
811
789
  if (ast.chi.length > 0) {
812
790
  let passes = options.pass ?? 1;
@@ -835,7 +813,7 @@ function doParseSync(iter, options = {}) {
835
813
  scoped: ModuleScopeEnumOptions.Local,
836
814
  naming: ModuleCaseTransformEnum.IgnoreCase,
837
815
  pattern: "",
838
- generateScopedName,
816
+ generateScopedName: generateSyncScopedName,
839
817
  ...(typeof options.module != "object" ? {} : options.module),
840
818
  };
841
819
  const parseModuleTime = performance.now();
@@ -900,6 +878,7 @@ function doParseSync(iter, options = {}) {
900
878
  throw new Error("css variable import not supported by parseSync() or transformSync(). use parse() or transform() instead.\nat " +
901
879
  options.source.getSourceLocation(node[LOC].sta).join(":"));
902
880
  }
881
+ // @ts-ignore
903
882
  if (node.typ == EnumToken.CssVariableDeclarationMapTokenType) {
904
883
  const from = node.from.find((t) => t.typ == EnumToken.IdenTokenType || isIdentColor(t));
905
884
  if (!(from.val in cssVariablesMap)) {
@@ -941,10 +920,9 @@ function doParseSync(iter, options = {}) {
941
920
  if (node.typ == EnumToken.DeclarationNodeType) {
942
921
  if (node.nam.startsWith("--")) {
943
922
  if (!(node.nam in namesMapping)) {
944
- let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
923
+ let value = moduleSettings.scoped & ModuleScopeEnumOptions.Global
945
924
  ? node.nam
946
925
  : moduleSettings.generateScopedName(node.nam, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
947
- let value = result;
948
926
  mapping[node.nam] =
949
927
  "--" +
950
928
  (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
@@ -986,10 +964,9 @@ function doParseSync(iter, options = {}) {
986
964
  continue;
987
965
  }
988
966
  if (!(rule.val in mapping)) {
989
- let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
967
+ let value = moduleSettings.scoped & ModuleScopeEnumOptions.Global
990
968
  ? rule.val
991
969
  : moduleSettings.generateScopedName(rule.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
992
- let value = result;
993
970
  mapping[rule.val] =
994
971
  (rule.typ == EnumToken.DashedIdenTokenType ? "--" : "") +
995
972
  (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
@@ -1160,10 +1137,10 @@ function doParseSync(iter, options = {}) {
1160
1137
  "unset",
1161
1138
  ].includes(value.val)) {
1162
1139
  if (!(value.val in mapping)) {
1163
- const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1164
- ? value.val
1165
- : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1166
- mapping[value.val] = result;
1140
+ mapping[value.val] =
1141
+ moduleSettings.scoped & ModuleScopeEnumOptions.Global
1142
+ ? value.val
1143
+ : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1167
1144
  revMapping[mapping[value.val]] = value.val;
1168
1145
  }
1169
1146
  value.val = mapping[value.val];
@@ -1176,6 +1153,7 @@ function doParseSync(iter, options = {}) {
1176
1153
  }
1177
1154
  else if ((value.typ == EnumToken.IdenTokenType || isIdentColor(value)) &&
1178
1155
  value.val in importedCssVariables) {
1156
+ // @ts-ignore
1179
1157
  replaceNodeOrValue(parent, value, importedCssVariables[value.val].val);
1180
1158
  }
1181
1159
  }
@@ -1235,10 +1213,9 @@ function doParseSync(iter, options = {}) {
1235
1213
  if (value.typ == EnumToken.ClassSelectorTokenType) {
1236
1214
  const val = value.val.slice(1);
1237
1215
  if (!(val in mapping)) {
1238
- const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1216
+ let value = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1239
1217
  ? val
1240
1218
  : moduleSettings.generateScopedName(val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1241
- let value = result;
1242
1219
  mapping[val] =
1243
1220
  moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
1244
1221
  moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
@@ -1252,7 +1229,7 @@ function doParseSync(iter, options = {}) {
1252
1229
  }
1253
1230
  if (moduleSettings.scoped & ModuleScopeEnumOptions.Pure) {
1254
1231
  if (!hasIdOrClass) {
1255
- throw new Error(`pure module: No id or class found in selector '${node.sel}' at '${node[LOC]?.src ?? ""}':${node[LOC]?.sta?.lin ?? ""}:${node[LOC]?.sta?.col ?? ""}`);
1232
+ throw new Error(`pure module: No id or class found in selector '${node.sel}' at '${options.source.getOffsets(node[LOC]?.sta).join(":")}'`);
1256
1233
  }
1257
1234
  }
1258
1235
  node.sel = "";
@@ -1271,10 +1248,9 @@ function doParseSync(iter, options = {}) {
1271
1248
  if ((prefix == "--" && value.typ == EnumToken.DashedIdenTokenType) ||
1272
1249
  (prefix == "" && value.typ == EnumToken.IdenTokenType)) {
1273
1250
  if (!(value.val in mapping)) {
1274
- const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1251
+ let val = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1275
1252
  ? value.val
1276
1253
  : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1277
- let val = result;
1278
1254
  mapping[value.val] =
1279
1255
  prefix +
1280
1256
  (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
@@ -1292,12 +1268,13 @@ function doParseSync(iter, options = {}) {
1292
1268
  }
1293
1269
  if (moduleSettings.naming != ModuleCaseTransformEnum.IgnoreCase) {
1294
1270
  revMapping = {};
1295
- mapping = Object.entries(mapping).reduce((acc, [key, value]) => {
1296
- const keyName = getKeyName(key, moduleSettings.naming);
1297
- acc[keyName] = value;
1271
+ mapping = {};
1272
+ let keyName;
1273
+ for (const [key, value] of Object.entries(mapping)) {
1274
+ keyName = getKeyName(key, moduleSettings.naming);
1275
+ mapping[keyName] = value;
1298
1276
  revMapping[value] = keyName;
1299
- return acc;
1300
- }, {});
1277
+ }
1301
1278
  }
1302
1279
  result.mapping = mapping;
1303
1280
  result.revMapping = revMapping;
@@ -1382,18 +1359,6 @@ async function doParse(iter, options = {}) {
1382
1359
  };
1383
1360
  let tokens = [];
1384
1361
  let context = ast;
1385
- ast[ROOT] = ast;
1386
- ast[LOC] = {
1387
- sta: 0,
1388
- end: 0,
1389
- srcId: options.source.id,
1390
- };
1391
- let valuesHandlers;
1392
- let preValuesHandlers;
1393
- let postValuesHandlers;
1394
- let preVisitorsHandlersMap;
1395
- let visitorsHandlersMap;
1396
- let postVisitorsHandlersMap;
1397
1362
  const imports = [];
1398
1363
  let item;
1399
1364
  let node;
@@ -1401,107 +1366,12 @@ async function doParse(iter, options = {}) {
1401
1366
  let isAsync = typeof iter[Symbol.asyncIterator] === "function";
1402
1367
  let parensMatch = 0;
1403
1368
  let curlyBracketMatch = 0;
1404
- if (options.visitor != null) {
1405
- valuesHandlers = new Map();
1406
- preValuesHandlers = new Map();
1407
- postValuesHandlers = new Map();
1408
- preVisitorsHandlersMap = new Map();
1409
- visitorsHandlersMap = new Map();
1410
- postVisitorsHandlersMap = new Map();
1411
- const visitors = Object.entries(options.visitor);
1412
- let key;
1413
- let value;
1414
- let i;
1415
- for (i = 0; i < visitors.length; i++) {
1416
- key = visitors[i][0];
1417
- value = visitors[i][1];
1418
- if (Number.isInteger(+key)) {
1419
- visitors.splice(i + 1, 0, ...Object.entries(value));
1420
- continue;
1421
- }
1422
- if (Array.isArray(value)) {
1423
- // @ts-ignore
1424
- visitors.splice(i + 1, 0, ...value.map((item) => [key, item]));
1425
- continue;
1426
- }
1427
- if (key in EnumToken) {
1428
- if (typeof value == "function") {
1429
- if (!valuesHandlers.has(EnumToken[key])) {
1430
- valuesHandlers.set(EnumToken[key], []);
1431
- }
1432
- valuesHandlers.get(EnumToken[key]).push(value);
1433
- }
1434
- else if (typeof value == "object" &&
1435
- "type" in value &&
1436
- "handler" in value &&
1437
- value.type in WalkerEvent) {
1438
- if (value.type == WalkerEvent.Enter) {
1439
- if (!preValuesHandlers.has(EnumToken[key])) {
1440
- preValuesHandlers.set(EnumToken[key], []);
1441
- }
1442
- preValuesHandlers
1443
- .get(EnumToken[key])
1444
- .push(value.handler);
1445
- }
1446
- else if (value.type == WalkerEvent.Leave) {
1447
- if (!postValuesHandlers.has(EnumToken[key])) {
1448
- postValuesHandlers.set(EnumToken[key], []);
1449
- }
1450
- postValuesHandlers
1451
- .get(EnumToken[key])
1452
- .push(value.handler);
1453
- }
1454
- }
1455
- else {
1456
- errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
1457
- }
1458
- }
1459
- else if (["Declaration", "Rule", "AtRule", "KeyframesRule", "KeyframesAtRule"].includes(key)) {
1460
- if (typeof value == "function") {
1461
- if (!visitorsHandlersMap.has(key)) {
1462
- visitorsHandlersMap.set(key, []);
1463
- }
1464
- visitorsHandlersMap
1465
- .get(key)
1466
- .push(value);
1467
- }
1468
- else if (typeof value == "object") {
1469
- if ("type" in value && "handler" in value && value.type in WalkerEvent) {
1470
- if (value.type == WalkerEvent.Enter) {
1471
- if (!preVisitorsHandlersMap.has(key)) {
1472
- preVisitorsHandlersMap.set(key, []);
1473
- }
1474
- preVisitorsHandlersMap
1475
- .get(key)
1476
- .push(value.handler);
1477
- }
1478
- else if (value.type == WalkerEvent.Leave) {
1479
- if (!postVisitorsHandlersMap.has(key)) {
1480
- postVisitorsHandlersMap.set(key, []);
1481
- }
1482
- postVisitorsHandlersMap
1483
- .get(key)
1484
- .push(value.handler);
1485
- }
1486
- }
1487
- else {
1488
- if (!visitorsHandlersMap.has(key)) {
1489
- visitorsHandlersMap.set(key, []);
1490
- }
1491
- visitorsHandlersMap
1492
- .get(key)
1493
- .push(value);
1494
- }
1495
- }
1496
- else {
1497
- errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
1498
- }
1499
- }
1500
- else {
1501
- errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
1502
- }
1503
- }
1504
- }
1369
+ // ast[ROOT] = ast;
1370
+ ast[LOC] = {
1371
+ sta: 0,
1372
+ end: 0,
1373
+ srcId: options.source.id,
1374
+ };
1505
1375
  if (Array.isArray(iter)) {
1506
1376
  // @ts-expect-error
1507
1377
  iter = iter[Symbol.iterator]();
@@ -1538,8 +1408,6 @@ async function doParse(iter, options = {}) {
1538
1408
  curlyBracketMatch--;
1539
1409
  }
1540
1410
  tokens.push(item.token);
1541
- // console.debug([item.token, {parensMatch, curlyBracketMatch}]);
1542
- // if (parensMatch === 0) {
1543
1411
  if (parensMatch === 0 &&
1544
1412
  (item.token.typ === EnumToken.SemiColonTokenType ||
1545
1413
  item.token.typ === EnumToken.BlockStartTokenType ||
@@ -1623,7 +1491,7 @@ async function doParse(iter, options = {}) {
1623
1491
  const token = node[TOKENS][0];
1624
1492
  const url = token.typ == EnumToken.StringTokenType ? token.val.slice(1, -1) : token.val;
1625
1493
  try {
1626
- const src = options.resolve(url, options.src || options.cwd);
1494
+ const src = options.resolve(url, options.src ? dirname(options.src) : options.cwd);
1627
1495
  const result = options.load(src);
1628
1496
  const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == "AsyncFunction"
1629
1497
  ? await result
@@ -1632,11 +1500,10 @@ async function doParse(iter, options = {}) {
1632
1500
  options.sourcesMap.set(source.id, source);
1633
1501
  const parseInfo = {
1634
1502
  stream,
1635
- buffer: "",
1636
1503
  offset: 0,
1637
1504
  source,
1638
1505
  position: 0,
1639
- currentPosition: -1,
1506
+ currentPosition: 0,
1640
1507
  };
1641
1508
  const root = await doParse(stream instanceof ReadableStream ? tokenizeStream(stream, parseInfo) : tokenize(parseInfo), Object.assign({}, options, {
1642
1509
  minify: false,
@@ -1647,6 +1514,7 @@ async function doParse(iter, options = {}) {
1647
1514
  stats.nodesCount += root.stats.nodesCount;
1648
1515
  stats.tokensCount += root.stats.tokensCount;
1649
1516
  stats.imports.push(root.stats);
1517
+ // @ts-ignore
1650
1518
  node[PARENT].chi.splice(node[PARENT].chi.indexOf(node), 1, ...root.ast.chi);
1651
1519
  if (root.errors.length > 0) {
1652
1520
  errors.push(...root.errors);
@@ -1663,210 +1531,165 @@ async function doParse(iter, options = {}) {
1663
1531
  ast = expand(ast);
1664
1532
  }
1665
1533
  let replacement;
1666
- let callable;
1667
1534
  if (options.visitor != null) {
1668
1535
  let parens;
1669
- for (const result of walk(ast)) {
1536
+ let genericKey;
1537
+ const handlers = [];
1538
+ const visitors = parseVisitors(options.visitor, errors);
1539
+ let nodes = new Array(stats.tokensCount);
1540
+ const subNodes = [];
1541
+ let i;
1542
+ let k;
1543
+ let j;
1544
+ let freeblock = 1;
1545
+ nodes[0] = ast;
1546
+ for (i = 0; i < nodes.length; i++) {
1547
+ if (nodes[i] == null) {
1548
+ break;
1549
+ }
1550
+ subNodes.length = 0;
1551
+ if (visitors.includeTokens) {
1552
+ switch (nodes[i].typ) {
1553
+ case EnumToken.RuleNodeType:
1554
+ case EnumToken.AtRuleNodeType:
1555
+ case EnumToken.KeyframesRuleNodeType:
1556
+ case EnumToken.KeyframesAtRuleNodeType:
1557
+ subNodes.push(...nodes[i][TOKENS]);
1558
+ break;
1559
+ case EnumToken.DeclarationNodeType:
1560
+ subNodes.push(...nodes[i].val);
1561
+ break;
1562
+ }
1563
+ }
1564
+ // @ts-ignore
1565
+ if (nodes[i].chi != null) {
1566
+ // @ts-ignore
1567
+ subNodes.push(...nodes[i].chi);
1568
+ }
1569
+ if (subNodes.length > 0) {
1570
+ if (freeblock <= i) {
1571
+ freeblock = i + 1;
1572
+ }
1573
+ for (k = 0; k < subNodes.length; k++) {
1574
+ j = k + freeblock;
1575
+ nodes[j] = subNodes[k];
1576
+ nodes[j][PARENT] = nodes[i];
1577
+ }
1578
+ freeblock += subNodes.length;
1579
+ }
1670
1580
  parens = null;
1671
- if (valuesHandlers.size > 0 ||
1672
- preVisitorsHandlersMap.size > 0 ||
1673
- visitorsHandlersMap.size > 0 ||
1674
- postVisitorsHandlersMap.size > 0) {
1675
- if ((result.node.typ == EnumToken.DeclarationNodeType &&
1676
- (preVisitorsHandlersMap.has("Declaration") ||
1677
- visitorsHandlersMap.has("Declaration") ||
1678
- postVisitorsHandlersMap.has("Declaration"))) ||
1679
- (result.node.typ == EnumToken.AtRuleNodeType &&
1680
- (preVisitorsHandlersMap.has("AtRule") ||
1681
- visitorsHandlersMap.has("AtRule") ||
1682
- postVisitorsHandlersMap.has("AtRule"))) ||
1683
- (result.node.typ == EnumToken.KeyframesAtRuleNodeType &&
1684
- (preVisitorsHandlersMap.has("KeyframesAtRule") ||
1685
- visitorsHandlersMap.has("KeyframesAtRule") ||
1686
- postVisitorsHandlersMap.has("KeyframesAtRule")))) {
1687
- const handlers = [];
1688
- const key = result.node.typ == EnumToken.DeclarationNodeType
1689
- ? "Declaration"
1690
- : result.node.typ == EnumToken.AtRuleNodeType
1691
- ? "AtRule"
1692
- : "KeyframesAtRule";
1693
- if (preVisitorsHandlersMap.has(key)) {
1694
- handlers.push(
1695
- // @ts-expect-error
1696
- ...preVisitorsHandlersMap.get(key));
1697
- }
1698
- if (visitorsHandlersMap.has(key)) {
1699
- // @ts-ignore
1700
- handlers.push(...visitorsHandlersMap.get(key));
1701
- }
1702
- if (postVisitorsHandlersMap.has(key)) {
1703
- // @ts-ignore
1704
- handlers.push(...postVisitorsHandlersMap.get(key));
1705
- }
1706
- let node = result.node;
1707
- for (const handler of handlers) {
1708
- callable =
1709
- typeof handler == "function"
1710
- ? handler
1711
- : handler[camelize(node.typ === EnumToken.DeclarationNodeType ||
1712
- node.typ === EnumToken.AtRuleNodeType
1713
- ? node.nam
1714
- : node.val)];
1715
- if (callable == null) {
1716
- continue;
1717
- }
1718
- // @ts-expect-error
1719
- replacement = callable(node, result[PARENT], ast, function* () {
1720
- if (parens == null) {
1721
- // @ts-expect-error
1722
- parens = [...result.parents()];
1723
- }
1724
- yield* parens[Symbol.iterator]();
1725
- });
1726
- if (replacement == null) {
1727
- continue;
1728
- }
1729
- if (replacement instanceof Promise) {
1730
- replacement = await replacement;
1731
- }
1732
- if (replacement == null || replacement == node) {
1733
- continue;
1734
- }
1581
+ handlers.length = 0;
1582
+ genericKey =
1583
+ nodes[i].typ == EnumToken.DeclarationNodeType
1584
+ ? "Declaration"
1585
+ : nodes[i].typ == EnumToken.AtRuleNodeType
1586
+ ? "AtRule"
1587
+ : nodes[i].typ == EnumToken.KeyframesAtRuleNodeType
1588
+ ? "KeyframesAtRule"
1589
+ : nodes[i].typ === EnumToken.KeyframesRuleNodeType
1590
+ ? "KeyframesRule"
1591
+ : nodes[i].typ == EnumToken.RuleNodeType
1592
+ ? "Rule"
1593
+ : nodes[i].typ == EnumToken.KeyframesRuleNodeType
1594
+ ? "KeyframesRule"
1595
+ : null;
1596
+ let keyName = nodes[i].typ == EnumToken.DeclarationNodeType || nodes[i].typ == EnumToken.AtRuleNodeType
1597
+ ? camelize(nodes[i].nam)
1598
+ : nodes[i].typ == EnumToken.KeyframesAtRuleNodeType
1599
+ ? camelize(nodes[i].val)
1600
+ : null;
1601
+ for (const map of visitors.allHandlers) {
1602
+ // @ts-ignore
1603
+ if (genericKey != null && map.has(genericKey)) {
1604
+ // @ts-ignore
1605
+ for (const handler of map.get(genericKey)) {
1606
+ if (typeof handler == "function") {
1607
+ handlers.push(handler);
1608
+ }
1609
+ // else if (Array.isArray(handler)) {
1610
+ // for (const h of handler) {
1611
+ // if (typeof h == "function") {
1612
+ // handlers.push(h);
1613
+ // }
1614
+ // // @ts-ignore
1615
+ // else if (h[keyName] != null) {
1616
+ // // @ts-ignore
1617
+ // handlers.push(h[keyName]);
1618
+ // }
1619
+ // }
1620
+ // } else if (typeof handler.handler! == "function") {
1621
+ // handlers.push(handler.handler);
1622
+ // }
1735
1623
  // @ts-ignore
1736
- node = replacement;
1737
- if (Array.isArray(node)) {
1738
- break;
1624
+ else if (typeof handler[keyName] == "function") {
1625
+ // @ts-ignore
1626
+ handlers.push(handler[keyName]);
1739
1627
  }
1740
1628
  }
1741
- if (node != result.node) {
1742
- replaceNodeOrValue(result.parent, result.node, node);
1743
- }
1744
1629
  }
1745
- else if ((result.node.typ == EnumToken.RuleNodeType &&
1746
- (preVisitorsHandlersMap.has("Rule") ||
1747
- visitorsHandlersMap.has("Rule") ||
1748
- postVisitorsHandlersMap.has("Rule"))) ||
1749
- (result.node.typ == EnumToken.KeyFramesRuleNodeType &&
1750
- (preVisitorsHandlersMap.has("KeyframesRule") ||
1751
- visitorsHandlersMap.has("KeyframesRule") ||
1752
- postVisitorsHandlersMap.has("KeyframesRule")))) {
1753
- const handlers = [];
1754
- const key = result.node.typ == EnumToken.RuleNodeType ? "Rule" : "KeyframesRule";
1755
- if (preVisitorsHandlersMap.has(key)) {
1756
- handlers.push(...preVisitorsHandlersMap.get(key));
1757
- }
1758
- if (visitorsHandlersMap.has(key)) {
1759
- handlers.push(...visitorsHandlersMap.get(key));
1760
- }
1761
- if (postVisitorsHandlersMap.has(key)) {
1762
- handlers.push(...postVisitorsHandlersMap.get(key));
1763
- }
1764
- let node = result.node;
1765
- for (const callable of handlers) {
1766
- replacement = callable(node, result.parent, result.root,
1767
- // @ts-expect-error
1768
- function* () {
1769
- if (parens == null) {
1770
- // @ts-expect-error
1771
- parens = [...result.parents()];
1630
+ // @ts-ignore
1631
+ if (map.has(nodes[i].typ)) {
1632
+ // @ts-ignore
1633
+ for (const handler of map.get(nodes[i].typ)) {
1634
+ if (typeof handler == "function") {
1635
+ handlers.push(handler);
1636
+ }
1637
+ else if (Array.isArray(handler)) {
1638
+ for (const h of handler) {
1639
+ if (typeof h == "function") {
1640
+ handlers.push(h);
1641
+ }
1772
1642
  }
1773
- yield* parens[Symbol.iterator]();
1774
- });
1775
- if (replacement == null) {
1776
- continue;
1777
- }
1778
- if (replacement instanceof Promise) {
1779
- replacement = await replacement;
1780
1643
  }
1781
- if (replacement == null || replacement == node) {
1782
- continue;
1644
+ else if (typeof handler.handler == "function") {
1645
+ handlers.push(handler.handler);
1783
1646
  }
1784
1647
  // @ts-ignore
1785
- node = replacement;
1786
- //
1787
- if (Array.isArray(node)) {
1788
- break;
1648
+ else if (typeof handler[keyName] == "function") {
1649
+ // @ts-ignore
1650
+ handlers.push(handler[keyName]);
1789
1651
  }
1790
1652
  }
1791
- // @ts-ignore
1792
- if (node != result.node) {
1793
- // @ts-ignore
1794
- replaceNodeOrValue(result.parent, result.node, node);
1795
- }
1796
1653
  }
1797
- else if (valuesHandlers.size > 0) {
1798
- let node = null;
1799
- node = result.node;
1800
- if (valuesHandlers.has(node.typ)) {
1801
- for (const valueHandler of valuesHandlers.get(node.typ)) {
1802
- callable = valueHandler;
1803
- replacement = callable(node, result.parent, ast,
1804
- // @ts-expect-error
1805
- function* () {
1806
- if (parens == null) {
1807
- // @ts-expect-error
1808
- parens = [...result.parents()];
1809
- }
1810
- yield* parens[Symbol.iterator]();
1811
- });
1812
- if (replacement == null) {
1813
- continue;
1814
- }
1815
- if (replacement instanceof Promise) {
1816
- replacement = await replacement;
1817
- }
1818
- if (replacement != null && replacement != node) {
1819
- node = replacement;
1820
- }
1821
- }
1822
- }
1823
- if (node != result.node) {
1824
- // @ts-ignore
1825
- replaceNodeOrValue(result[PARENT], value, node);
1826
- }
1827
- const tokens = Array.isArray(result.node[TOKENS]) ? result.node[TOKENS] : [];
1828
- if (Array.isArray(result.node.val)) {
1829
- tokens.push(...result.node.val);
1830
- }
1831
- if (tokens.length == 0) {
1832
- continue;
1833
- }
1834
- for (const { value, parent, root, parents } of walkValues(tokens, result.node)) {
1835
- node = value;
1836
- if (valuesHandlers.has(node.typ)) {
1837
- let parens = null;
1838
- for (const valueHandler of valuesHandlers.get(node.typ)) {
1839
- callable = valueHandler;
1840
- // @ts-expect-error
1841
- let result = callable(node, parent, root, function* () {
1842
- if (parens == null) {
1843
- // @ts-expect-error
1844
- parens = [...parents()];
1845
- }
1846
- yield* parens[Symbol.iterator]();
1847
- });
1848
- if (result == null) {
1849
- continue;
1850
- }
1851
- if (result instanceof Promise) {
1852
- result = await result;
1853
- }
1854
- if (result != null && result != node) {
1855
- node = result;
1856
- }
1857
- if (Array.isArray(node)) {
1858
- break;
1859
- }
1860
- }
1861
- }
1862
- if (node != value) {
1863
- // @ts-ignore
1864
- replaceNodeOrValue(parent, value, node);
1654
+ }
1655
+ if (handlers.length == 0) {
1656
+ continue;
1657
+ }
1658
+ let node = nodes[i];
1659
+ for (const callable of handlers) {
1660
+ replacement = callable(node, nodes[i][PARENT], ast,
1661
+ // @ts-expect-error
1662
+ function* () {
1663
+ if (parens == null) {
1664
+ let node = nodes[i][PARENT];
1665
+ while (node != null) {
1666
+ yield node;
1667
+ node = node[PARENT];
1865
1668
  }
1866
1669
  }
1670
+ });
1671
+ if (replacement == null) {
1672
+ continue;
1673
+ }
1674
+ if (replacement instanceof Promise) {
1675
+ replacement = await replacement;
1676
+ }
1677
+ if (replacement == null || replacement == node) {
1678
+ continue;
1679
+ }
1680
+ // @ts-ignore
1681
+ node = replacement;
1682
+ //
1683
+ if (Array.isArray(node)) {
1684
+ break;
1867
1685
  }
1868
1686
  }
1687
+ if (node != nodes[i]) {
1688
+ // @ts-ignore
1689
+ replaceNodeOrValue(nodes[i][PARENT], nodes[i], node);
1690
+ }
1869
1691
  }
1692
+ nodes = null;
1870
1693
  }
1871
1694
  if (invalidNodes.length > 0) {
1872
1695
  let count = invalidNodes.length;
@@ -1889,19 +1712,6 @@ async function doParse(iter, options = {}) {
1889
1712
  }
1890
1713
  }
1891
1714
  }
1892
- while (stack.length > 0 && context != ast) {
1893
- const previousNode = stack.pop();
1894
- context = (stack[stack.length - 1] ?? ast);
1895
- // remove empty nodes
1896
- if (options.removeEmpty &&
1897
- previousNode != null &&
1898
- previousNode.chi.length == 0 &&
1899
- context.chi[context.chi.length - 1] == previousNode) {
1900
- context.chi.pop();
1901
- continue;
1902
- }
1903
- break;
1904
- }
1905
1715
  if (options.minify) {
1906
1716
  if (ast.chi.length > 0) {
1907
1717
  let passes = options.pass ?? 1;
@@ -2007,7 +1817,7 @@ async function doParse(iter, options = {}) {
2007
1817
  time: 0,
2008
1818
  source,
2009
1819
  position: 0,
2010
- currentPosition: -1,
1820
+ currentPosition: 0,
2011
1821
  };
2012
1822
  const root = await doParse(stream instanceof ReadableStream ? tokenizeStream(stream, parseInfo) : tokenize(parseInfo), Object.assign({}, options, {
2013
1823
  source,
@@ -2020,6 +1830,7 @@ async function doParse(iter, options = {}) {
2020
1830
  parent.chi.splice(parent.chi.indexOf(node), 1);
2021
1831
  continue;
2022
1832
  }
1833
+ // @ts-ignore
2023
1834
  if (node.typ == EnumToken.CssVariableDeclarationMapTokenType) {
2024
1835
  const from = node.from.find((t) => t.typ == EnumToken.IdenTokenType || isIdentColor(t));
2025
1836
  if (!(from.val in cssVariablesMap)) {
@@ -2064,6 +1875,7 @@ async function doParse(iter, options = {}) {
2064
1875
  let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
2065
1876
  ? node.nam
2066
1877
  : moduleSettings.generateScopedName(node.nam, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1878
+ // @ts-ignore
2067
1879
  let value = result instanceof Promise ? await result : result;
2068
1880
  mapping[node.nam] =
2069
1881
  "--" +
@@ -2097,6 +1909,7 @@ async function doParse(iter, options = {}) {
2097
1909
  parentRule.chi.splice(parentRule.chi.indexOf(node), 1);
2098
1910
  continue;
2099
1911
  }
1912
+ const resolvedSrc = options.resolve(options.src, options.cwd);
2100
1913
  for (const token of composeSelectors) {
2101
1914
  // composes: a b c;
2102
1915
  if (token.r == null) {
@@ -2148,26 +1961,26 @@ async function doParse(iter, options = {}) {
2148
1961
  : result;
2149
1962
  const root = await doParse(stream instanceof ReadableStream
2150
1963
  ? tokenizeStream(stream, {
2151
- buffer: "",
2152
1964
  offset: 0,
2153
1965
  source: new SourceFile("", [], src.relative),
2154
1966
  position: 0,
2155
- currentPosition: -1,
1967
+ currentPosition: 0,
2156
1968
  })
2157
1969
  : tokenize({
2158
1970
  stream,
2159
- buffer: "",
2160
1971
  offset: 0,
2161
1972
  position: 0,
2162
1973
  source: new SourceFile(stream, [], src.relative),
2163
- currentPosition: -1,
1974
+ currentPosition: 0,
2164
1975
  }), Object.assign({}, options, {
2165
1976
  minify: false,
2166
1977
  setParent: false,
2167
1978
  src: src.relative,
2168
1979
  }));
2169
- const srcIndex = (src.relative.startsWith("/") || src.relative.startsWith("../") ? "" : "./") +
2170
- src.relative;
1980
+ let srcIndex = options.resolve(src.absolute, resolvedSrc.absolute).relative;
1981
+ if (!srcIndex.startsWith("/") && !srcIndex.startsWith("../")) {
1982
+ srcIndex = `./${srcIndex}`;
1983
+ }
2171
1984
  if (Object.keys(root.mapping).length > 0) {
2172
1985
  importMapping[srcIndex] = {};
2173
1986
  }
@@ -2368,30 +2181,13 @@ async function doParse(iter, options = {}) {
2368
2181
  }
2369
2182
  for (const { value, parent } of walkValues(node.val, node)) {
2370
2183
  if (value.typ == EnumToken.DashedIdenTokenType) {
2371
- // if (!((value as DashedIdentToken).val in mapping)) {
2372
- // const result =
2373
- // moduleSettings.scoped! & ModuleScopeEnumOptions.Global
2374
- // ? (value as DashedIdentToken).val
2375
- // : moduleSettings.generateScopedName!(
2376
- // (value as DashedIdentToken).val,
2377
- // moduleSettings.filePath as string,
2378
- // moduleSettings.pattern as string,
2379
- // moduleSettings.hashLength,
2380
- // );
2381
- // let val: string = result instanceof Promise ? await result : result;
2382
- // mapping[(value as DashedIdentToken).val] =
2383
- // "--" +
2384
- // (moduleSettings.naming! & ModuleCaseTransformEnum.DashCaseOnly ||
2385
- // moduleSettings.naming! & ModuleCaseTransformEnum.CamelCaseOnly
2386
- // ? getKeyName(val, moduleSettings.naming as ModuleCaseTransformEnum)
2387
- // : val);
2388
- // revMapping[mapping[(value as DashedIdentToken).val]] = (value as DashedIdentToken).val;
2389
- // }
2390
2184
  value.val = mapping[value.val];
2391
2185
  }
2392
2186
  else if ((value.typ == EnumToken.IdenTokenType || isIdentColor(value)) &&
2393
2187
  value.val in importedCssVariables) {
2394
- replaceNodeOrValue(parent, value, importedCssVariables[value.val].val);
2188
+ replaceNodeOrValue(
2189
+ // @ts-ignore
2190
+ parent, value, importedCssVariables[value.val].val);
2395
2191
  }
2396
2192
  }
2397
2193
  }
@@ -2419,26 +2215,6 @@ async function doParse(iter, options = {}) {
2419
2215
  EnumToken.DescendantCombinatorTokenType) {
2420
2216
  parent[TOKENS].splice(index, 1);
2421
2217
  }
2422
- // if (val == ":global") {
2423
- // for (; index < (parent as AstRule)[TOKENS]!.length; index++) {
2424
- // if (
2425
- // (parent as AstRule)[TOKENS]![index].typ ==
2426
- // EnumToken.CommaTokenType ||
2427
- // ([
2428
- // EnumToken.PseudoClassFuncTokenType,
2429
- // EnumToken.PseudoClassTokenType,
2430
- // ].includes((parent as AstRule)[TOKENS]![index].typ) &&
2431
- // [":global", ":local"].includes(
2432
- // (
2433
- // (parent as AstRule)[TOKENS]![index] as PseudoClassToken
2434
- // ).val.toLowerCase(),
2435
- // ))
2436
- // ) {
2437
- // break;
2438
- // }
2439
- // global.add((parent as AstRule)[TOKENS]![index]);
2440
- // }
2441
- // }
2442
2218
  }
2443
2219
  break;
2444
2220
  }
@@ -2452,12 +2228,6 @@ async function doParse(iter, options = {}) {
2452
2228
  case ":local":
2453
2229
  parent[TOKENS].splice(parent[TOKENS].indexOf(value), 1, ...value.chi);
2454
2230
  break;
2455
- // (parent as AstRule)[TOKENS]!.splice(
2456
- // (parent as AstRule)[TOKENS]!.indexOf(value),
2457
- // 1,
2458
- // ...(value as FunctionToken).chi,
2459
- // );
2460
- // break;
2461
2231
  }
2462
2232
  }
2463
2233
  })) {
@@ -2495,7 +2265,7 @@ async function doParse(iter, options = {}) {
2495
2265
  }
2496
2266
  if (moduleSettings.scoped & ModuleScopeEnumOptions.Pure) {
2497
2267
  if (!hasIdOrClass) {
2498
- throw new Error(`pure module: No id or class found in selector '${node.sel}' at '${node[LOC]?.src ?? ""}':${node[LOC]?.sta?.lin ?? ""}:${node[LOC]?.sta?.col ?? ""}`);
2268
+ throw new Error(`pure module: No id or class found in selector '${node.sel}' at '${(options.source?.getOffsets?.(node[LOC]?.sta) ?? []).join(":")}'`);
2499
2269
  }
2500
2270
  }
2501
2271
  node.sel = "";
@@ -2743,6 +2513,8 @@ function parseNode(tokens, context, options, errors, stats, invalidNodes) {
2743
2513
  return null;
2744
2514
  }
2745
2515
  /**
2516
+ * @param stream
2517
+ * @param context
2746
2518
  * @param options
2747
2519
  * @param errors
2748
2520
  * @param parseAsBlock
@@ -2819,7 +2591,6 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2819
2591
  parseAsBlock = blockAllowed;
2820
2592
  }
2821
2593
  if (syntax != null && atRule.nam !== "layer" && parseAsBlock !== blockAllowed) {
2822
- success = false;
2823
2594
  errors.push({
2824
2595
  action: "drop",
2825
2596
  node: atRule,
@@ -3114,10 +2885,13 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
3114
2885
  let definedAfterLastElse = false;
3115
2886
  if (sibling == null || sibling.typ !== EnumToken.AtRuleNodeType) {
3116
2887
  missingWhen = true;
2888
+ // @ts-expect-error
3117
2889
  }
3118
2890
  else if (sibling.nam !== "when") {
2891
+ // @ts-expect-error
3119
2892
  if (sibling.nam !== "else") {
3120
2893
  missingWhen = true;
2894
+ // @ts-expect-error
3121
2895
  }
3122
2896
  else if (sibling.val === "") {
3123
2897
  definedAfterLastElse = true;
@@ -3307,7 +3081,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
3307
3081
  action: "drop",
3308
3082
  node: atRule,
3309
3083
  location: options.source.getSourceLocation(atRule[LOC].sta),
3310
- message: "node is allowd only in @page rule",
3084
+ message: "node is allowed only in @page rule",
3311
3085
  });
3312
3086
  }
3313
3087
  else {
@@ -3446,9 +3220,6 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
3446
3220
  if (result.errors.length > 0) {
3447
3221
  errors.push(...result.errors);
3448
3222
  }
3449
- // else if (atRuleName === "document") {
3450
- // parseUrlToken(stream);
3451
- // }
3452
3223
  if (result.success) {
3453
3224
  let i = 0;
3454
3225
  const stack = [];
@@ -3503,11 +3274,10 @@ async function parseDeclarations(declaration) {
3503
3274
  const stream = `.x{${declaration}}`;
3504
3275
  return doParse(tokenize({
3505
3276
  stream,
3506
- buffer: "",
3507
3277
  offset: 0,
3508
3278
  position: 0,
3509
3279
  source: new SourceFile(stream, [], ""),
3510
- currentPosition: -1,
3280
+ currentPosition: 0,
3511
3281
  }), { setParent: false, minify: false, validation: false }).then((result) => {
3512
3282
  return result.ast.chi[0].chi.filter((t) => t.typ == EnumToken.DeclarationNodeType || t.typ == EnumToken.CommentNodeType);
3513
3283
  });
@@ -3537,19 +3307,20 @@ async function parseDeclarations(declaration) {
3537
3307
  function parseString(src, options = { parseColor: true }, errors) {
3538
3308
  const parseInfo = {
3539
3309
  stream: src,
3540
- buffer: "",
3541
3310
  offset: 0,
3542
3311
  time: 0,
3543
3312
  source: new SourceFile(src, [], ""),
3544
3313
  position: 0,
3545
- currentPosition: -1,
3314
+ currentPosition: 0,
3546
3315
  };
3547
- const result = parseTokens([...tokenize(parseInfo)].map((t) => t.token), options, errors);
3548
- // remove EOF token
3549
- result.pop();
3550
- if (result.at(-1)?.typ === EnumToken.WhitespaceTokenType) {
3551
- result.pop();
3316
+ const tokenResults = tokenize(parseInfo);
3317
+ const mapped = [];
3318
+ for (const token of tokenResults) {
3319
+ mapped.push(token.token);
3552
3320
  }
3321
+ const result = parseTokens(mapped, options, errors);
3322
+ // remove EOF token
3323
+ result.splice(result.length - (result[result.length - 2]?.typ === EnumToken.WhitespaceTokenType ? 2 : 1), 2);
3553
3324
  return result;
3554
3325
  }
3555
3326
  /**
@@ -3640,7 +3411,6 @@ function parseTokens(tokens, options, errors) {
3640
3411
  node,
3641
3412
  location: options.source.getSourceLocation(node[LOC].sta),
3642
3413
  });
3643
- // return [];
3644
3414
  continue;
3645
3415
  }
3646
3416
  index = tokens.indexOf(stack.at(-1));