@tbela99/css-parser 2.1.0 → 2.2.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 (125) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/README.md +14 -7
  3. package/architecture.png +0 -0
  4. package/dist/{src/data → data}/properties.json.js +86 -2
  5. package/dist/{src/data → data}/validation.json.js +5 -2
  6. package/dist/index-umd-web.js +10738 -4359
  7. package/dist/index.d.ts +734 -100
  8. package/dist/{src/lib → lib}/ast/arena-node.js +10 -10
  9. package/dist/{src/lib → lib}/ast/arena.js +304 -139
  10. package/dist/{src/lib → lib}/ast/cache.js +2 -2
  11. package/dist/{src/lib → lib}/ast/features/calc.js +11 -9
  12. package/dist/{src/lib → lib}/ast/features/if.js +6 -6
  13. package/dist/{src/lib → lib}/ast/features/index.js +3 -2
  14. package/dist/{src/lib → lib}/ast/features/inlinecssvariables.js +12 -10
  15. package/dist/lib/ast/features/mixin.js +953 -0
  16. package/dist/{src/lib → lib}/ast/features/prefix.js +39 -39
  17. package/dist/lib/ast/features/shorthand.js +129 -0
  18. package/dist/lib/ast/features/transform.js +188 -0
  19. package/dist/{src/lib → lib}/ast/features/type.js +2 -2
  20. package/dist/{src/lib → lib}/ast/math/expression.js +24 -24
  21. package/dist/{src/lib → lib}/ast/math/math.js +2 -2
  22. package/dist/{src/lib → lib}/ast/minify.js +745 -201
  23. package/dist/lib/ast/mixins/custom-function.js +393 -0
  24. package/dist/lib/ast/mixins/utils.js +53 -0
  25. package/dist/lib/ast/mixins/variables.js +678 -0
  26. package/dist/lib/ast/strings.js +906 -0
  27. package/dist/lib/ast/transform/compute.js +560 -0
  28. package/dist/lib/ast/transform/matrix.js +67 -0
  29. package/dist/lib/ast/transform/minify.js +325 -0
  30. package/dist/lib/ast/transform/perspective.js +24 -0
  31. package/dist/{src/lib → lib}/ast/transform/rotate.js +16 -7
  32. package/dist/lib/ast/transform/scale.js +43 -0
  33. package/dist/lib/ast/transform/skew.js +38 -0
  34. package/dist/lib/ast/transform/translate.js +56 -0
  35. package/dist/lib/ast/transform/utils.js +390 -0
  36. package/dist/{src/lib → lib}/ast/types.js +2 -2
  37. package/dist/{src/lib → lib}/ast/walk.js +2 -2
  38. package/dist/{src/lib → lib}/fs/resolve.js +2 -2
  39. package/dist/{src/lib → lib}/parser/declaration/list.js +25 -8
  40. package/dist/{src/lib → lib}/parser/declaration/map.js +15 -15
  41. package/dist/{src/lib → lib}/parser/declaration/set.js +5 -5
  42. package/dist/{src/lib → lib}/parser/input.js +18 -3
  43. package/dist/{src/lib → lib}/parser/linesmap.js +2 -2
  44. package/dist/{src/lib → lib}/parser/parse.js +425 -258
  45. package/dist/{src/lib → lib}/parser/source.js +2 -2
  46. package/dist/{src/lib → lib}/parser/tokenize.js +480 -312
  47. package/dist/{src/lib → lib}/parser/utils/angle.js +3 -3
  48. package/dist/{src/lib → lib}/parser/utils/at-rule-container.js +12 -12
  49. package/dist/{src/lib → lib}/parser/utils/at-rule-font-feature-values.js +3 -3
  50. package/dist/{src/lib → lib}/parser/utils/at-rule-generic.js +7 -7
  51. package/dist/{src/lib → lib}/parser/utils/at-rule-import.js +10 -10
  52. package/dist/{src/lib → lib}/parser/utils/at-rule-media.js +14 -14
  53. package/dist/{src/lib → lib}/parser/utils/at-rule-support.js +9 -14
  54. package/dist/{src/lib → lib}/parser/utils/at-rule-when-else.js +6 -6
  55. package/dist/{src/lib → lib}/parser/utils/at-rule.js +3 -3
  56. package/dist/{src/lib → lib}/parser/utils/base64.js +2 -2
  57. package/dist/lib/parser/utils/cache.js +53 -0
  58. package/dist/lib/parser/utils/canonical.js +78 -0
  59. package/dist/lib/parser/utils/codes.js +93 -0
  60. package/dist/{src/lib → lib}/parser/utils/config.js +2 -2
  61. package/dist/{src/lib → lib}/parser/utils/declaration.js +31 -26
  62. package/dist/{src/lib → lib}/parser/utils/eq.js +2 -2
  63. package/dist/{src/lib → lib}/parser/utils/hash.js +2 -2
  64. package/dist/{src/lib → lib}/parser/utils/selector.js +305 -63
  65. package/dist/{src/lib → lib}/parser/utils/text.js +2 -2
  66. package/dist/{src/lib → lib}/parser/utils/token.js +2 -2
  67. package/dist/{src/lib → lib}/parser/utils/type.js +9 -7
  68. package/dist/{src/lib → lib}/printer/render.js +420 -152
  69. package/dist/lib/printer/result.js +148 -0
  70. package/dist/{src/lib → lib}/printer/sourcemap/lib/codec.js +2 -2
  71. package/dist/{src/lib → lib}/printer/sourcemap/sourcemap.js +2 -2
  72. package/dist/lib/printer/writer.js +252 -0
  73. package/dist/{src/lib → lib}/syntax/color/a98rgb.js +2 -2
  74. package/dist/{src/lib → lib}/syntax/color/alpha.js +10 -10
  75. package/dist/{src/lib → lib}/syntax/color/cmyk.js +2 -2
  76. package/dist/{src/lib → lib}/syntax/color/color-mix.js +18 -18
  77. package/dist/{src/lib → lib}/syntax/color/color.js +18 -18
  78. package/dist/{src/lib → lib}/syntax/color/hex.js +3 -3
  79. package/dist/{src/lib → lib}/syntax/color/hsl.js +2 -2
  80. package/dist/{src/lib → lib}/syntax/color/hwb.js +2 -2
  81. package/dist/{src/lib → lib}/syntax/color/lab.js +2 -2
  82. package/dist/{src/lib → lib}/syntax/color/lch.js +2 -2
  83. package/dist/{src/lib → lib}/syntax/color/oklab.js +2 -2
  84. package/dist/{src/lib → lib}/syntax/color/oklch.js +3 -3
  85. package/dist/{src/lib → lib}/syntax/color/p3.js +2 -2
  86. package/dist/{src/lib → lib}/syntax/color/prophotorgb.js +2 -2
  87. package/dist/{src/lib → lib}/syntax/color/rec2020.js +2 -2
  88. package/dist/{src/lib → lib}/syntax/color/relative-color.js +14 -14
  89. package/dist/{src/lib → lib}/syntax/color/rgb.js +4 -4
  90. package/dist/{src/lib → lib}/syntax/color/srgb.js +5 -5
  91. package/dist/{src/lib → lib}/syntax/color/utils/color-type.js +4 -4
  92. package/dist/{src/lib → lib}/syntax/color/utils/colorspace.js +10 -10
  93. package/dist/{src/lib → lib}/syntax/color/utils/components.js +5 -5
  94. package/dist/{src/lib → lib}/syntax/color/utils/distance.js +2 -2
  95. package/dist/{src/lib → lib}/syntax/color/utils/make-color.js +3 -3
  96. package/dist/{src/lib → lib}/syntax/color/utils/matrix.js +2 -2
  97. package/dist/{src/lib → lib}/syntax/color/xyz.js +2 -2
  98. package/dist/{src/lib → lib}/syntax/color/xyzd50.js +2 -2
  99. package/dist/{src/lib → lib}/syntax/constants.js +26 -3
  100. package/dist/{src/lib → lib}/syntax/syntax.js +37 -29
  101. package/dist/{src/lib → lib}/validation/config.js +23 -10
  102. package/dist/lib/validation/first.js +571 -0
  103. package/dist/{src/lib → lib}/validation/match.js +292 -150
  104. package/dist/{src/lib → lib}/validation/parser/parse.js +2 -2
  105. package/dist/{src/lib → lib}/validation/parser/typedef.js +2 -2
  106. package/dist/{src/lib → lib}/validation/utils/list.js +3 -19
  107. package/dist/{src/node.js → node.js} +52 -34
  108. package/dist/{src/types.js → types.js} +2 -2
  109. package/dist/{src/utils → utils}/sync.js +10 -5
  110. package/dist/version.d.ts +4 -0
  111. package/dist/version.js +13 -0
  112. package/dist/{src/web.js → web.js} +47 -34
  113. package/package.json +12 -12
  114. package/dist/package.json.js +0 -10
  115. package/dist/src/lib/ast/features/shorthand.js +0 -95
  116. package/dist/src/lib/ast/features/transform.js +0 -90
  117. package/dist/src/lib/ast/transform/compute.js +0 -362
  118. package/dist/src/lib/ast/transform/matrix.js +0 -88
  119. package/dist/src/lib/ast/transform/minify.js +0 -267
  120. package/dist/src/lib/ast/transform/perspective.js +0 -16
  121. package/dist/src/lib/ast/transform/scale.js +0 -39
  122. package/dist/src/lib/ast/transform/skew.js +0 -30
  123. package/dist/src/lib/ast/transform/translate.js +0 -39
  124. package/dist/src/lib/ast/transform/utils.js +0 -287
  125. package/dist/src/lib/parser/utils/cache.js +0 -54
@@ -0,0 +1,953 @@
1
+ /*
2
+ CSS parser, minifier and validator for node, deno, bun and the browser
3
+
4
+ Author(s): Thierry Bela
5
+ Version: 2.2.0
6
+ License: MIT
7
+ */
8
+ import { EnumToken, EnumAstNodeStatus } from '../types.js';
9
+ import { FeatureWalkMode } from './type.js';
10
+ import { splitRule } from '../minify.js';
11
+ import { parseRuleContent, parseDeclarations } from '../../parser/parse.js';
12
+ import { collectDefinitions, isCustomProperty, isAtRule, finalizeDefinitions, resolveDefinitions, ruleProperties, firstToken, parseParameters, parseArguments, UNDEFINED, RuleScope, substitute, resolve, matchesType, render, declarationValue, splitArguments, trim } from '../mixins/variables.js';
13
+ import { FunctionRegistry, evaluateFunctions, parseFunction, findCalls } from '../mixins/custom-function.js';
14
+
15
+ /**
16
+ * the subject of the rule is the element the mixin is applied to: `&`, `&.active`, `&::before`
17
+ */
18
+ const SELF = 0;
19
+ /**
20
+ * the subject of the rule is a descendant of the element the mixin is applied to: `& *`, `& > *`, `.child`
21
+ */
22
+ const DESCENDANT = 1;
23
+ /**
24
+ * the subject of the rule is not in the subtree of the element the mixin is applied to: `& + *`, `& ~ *`
25
+ */
26
+ const OUTSIDE = 2;
27
+ /**
28
+ * maximum number of nested `@apply` rules: guard against the mixins that apply each other
29
+ */
30
+ const MAX_DEPTH = 32;
31
+ /**
32
+ * application of a mixin: the variables shared by the scopes of the mixin body
33
+ */
34
+ class MixinApplication {
35
+ name;
36
+ properties;
37
+ contents;
38
+ names;
39
+ registry;
40
+ /**
41
+ * mixin arguments and default values
42
+ */
43
+ args = new Map();
44
+ /**
45
+ * the typed arguments that depend on the element the mixin is applied to
46
+ */
47
+ typed = new Map();
48
+ /**
49
+ * registered custom properties of the typed arguments
50
+ */
51
+ registered = [];
52
+ /**
53
+ * the mixin cannot be evaluated: a typed argument cannot be registered
54
+ */
55
+ failed = false;
56
+ /**
57
+ * the variables visible from the bodies of the custom functions called by the mixin body: the custom properties
58
+ * of the rule. the private variables are not visible
59
+ */
60
+ dynamic;
61
+ /**
62
+ * @param name mixin name
63
+ * @param properties custom properties declared in the rule the mixin is applied to
64
+ * @param contents serialized contents block of the `@apply` rule. null when the `@apply` rule has no contents block
65
+ * @param names names of the custom properties of the stylesheet
66
+ * @param registry the custom function calls of the mixin body are evaluated. null when they are not evaluated
67
+ */
68
+ constructor(name, properties, contents, names, registry = null) {
69
+ this.name = name;
70
+ this.properties = properties;
71
+ this.contents = contents;
72
+ this.names = names;
73
+ this.registry = registry;
74
+ this.dynamic = new RuleScope(properties, registry);
75
+ }
76
+ /**
77
+ * variable that references the registered custom property of a typed argument. null when the argument cannot be
78
+ * registered
79
+ * @param name
80
+ */
81
+ typedEntry(name) {
82
+ const argument = this.typed.get(name);
83
+ if (argument.entry == null) {
84
+ const initialValue = initialValueOf(argument.syntax);
85
+ if (initialValue == null || this.names == null) {
86
+ this.failed = true;
87
+ return null;
88
+ }
89
+ const prefix = `--${this.name.slice(2)}-${name.slice(2)}-`;
90
+ let index = 1;
91
+ while (this.names.has(prefix + index)) {
92
+ index++;
93
+ }
94
+ argument.property = prefix + index;
95
+ argument.entry = { tokens: null, text: `var(${argument.property})`, scope: null };
96
+ argument.entry.descendantText = argument.entry.text;
97
+ this.names.add(argument.property);
98
+ this.registered.push({
99
+ name: argument.property,
100
+ syntax: argument.syntax,
101
+ initialValue,
102
+ value: argument.value,
103
+ });
104
+ }
105
+ return argument.entry;
106
+ }
107
+ }
108
+ /**
109
+ * variables visible from a node of a mixin body
110
+ */
111
+ class MixinScope {
112
+ levels;
113
+ application;
114
+ masked;
115
+ /**
116
+ * the custom function calls of the mixin body are evaluated with the mixin
117
+ */
118
+ get functions() {
119
+ return this.application.registry;
120
+ }
121
+ /**
122
+ * the custom functions see the custom properties of the rule, not the private variables
123
+ */
124
+ get dynamic() {
125
+ return this.application.dynamic;
126
+ }
127
+ /**
128
+ * @param levels variables declared by the mixin body and the rules that contain the current node, outer first
129
+ * @param application the mixin application
130
+ * @param masked custom properties declared in the mixin body: they override the rule custom properties
131
+ */
132
+ constructor(levels, application, masked) {
133
+ this.levels = levels;
134
+ this.application = application;
135
+ this.masked = masked;
136
+ }
137
+ /**
138
+ * the subject of the current rule is a descendant of the element the mixin is applied to
139
+ */
140
+ get descendant() {
141
+ return this.levels[0].relation === DESCENDANT;
142
+ }
143
+ /**
144
+ * scope of a nested rule
145
+ * @param relation relation of the subject of the nested rule to the subject of the current rule
146
+ * @param masked custom properties declared in the nested rule
147
+ */
148
+ child(relation, masked) {
149
+ const levels = this.levels.map((level) => ({
150
+ privates: level.privates,
151
+ relation: compose(level.relation, relation),
152
+ }));
153
+ levels.push({ privates: new Map(), relation: SELF });
154
+ return new MixinScope(levels, this.application, masked.size === 0 ? this.masked : new Set([...this.masked, ...masked]));
155
+ }
156
+ /**
157
+ * find a variable
158
+ * - the variable entry
159
+ * - {@link UNDEFINED} if the variable is a private variable that is not visible
160
+ * - null if the variable is not a private variable: the var() function is evaluated by the browser
161
+ * @param name
162
+ * @param descendant the variable is referenced by a descendant of the element the mixin is applied to
163
+ */
164
+ lookup(name, descendant) {
165
+ // the inner declarations override the outer declarations. the private variables of a nested rule are private
166
+ // variables of its nested rules: each nested rule has its own context
167
+ for (let i = this.levels.length - 1; i > 0; i--) {
168
+ const entry = this.levels[i].privates.get(name);
169
+ if (entry !== undefined) {
170
+ return entry;
171
+ }
172
+ }
173
+ // the private variables of the mixin body are not visible from the siblings of the element the mixin is
174
+ // applied to
175
+ const visible = this.levels[0].relation !== OUTSIDE;
176
+ const isPrivate = this.levels[0].privates.has(name);
177
+ if (isPrivate && visible) {
178
+ return this.levels[0].privates.get(name);
179
+ }
180
+ const application = this.application;
181
+ if (application.args.has(name)) {
182
+ if (!visible) {
183
+ return UNDEFINED;
184
+ }
185
+ // the descendants inherit the value computed on the element
186
+ if (descendant && application.typed.has(name)) {
187
+ return application.typedEntry(name) ?? application.args.get(name);
188
+ }
189
+ return application.args.get(name);
190
+ }
191
+ if (isPrivate) {
192
+ return UNDEFINED;
193
+ }
194
+ // the custom properties of the rule the mixin is applied to. the descendants inherit them
195
+ if (visible && !this.masked.has(name) && application.properties.has(name)) {
196
+ return application.properties.get(name);
197
+ }
198
+ return null;
199
+ }
200
+ }
201
+ /**
202
+ * initial value of a registered custom property: a computationally independent value that matches the syntax.
203
+ * null when the syntax is not supported
204
+ * @param syntax
205
+ */
206
+ function initialValueOf(syntax) {
207
+ const defaults = {
208
+ length: "0px",
209
+ "length-percentage": "0px",
210
+ percentage: "0%",
211
+ number: "0",
212
+ integer: "0",
213
+ angle: "0deg",
214
+ time: "0s",
215
+ resolution: "1dppx",
216
+ color: "transparent",
217
+ "custom-ident": "none",
218
+ string: '""',
219
+ "transform-function": "scale(1)",
220
+ "transform-list": "scale(1)",
221
+ };
222
+ for (const component of syntax.split("|")) {
223
+ const match = component.trim().match(/^(?:<([a-z-]+)>|([a-z][a-z0-9-]*))[+#]?$/i);
224
+ if (match == null) {
225
+ // the syntax is not supported by a registered custom property
226
+ return null;
227
+ }
228
+ if (match[2] != null) {
229
+ return match[2];
230
+ }
231
+ if (match[1].toLowerCase() in defaults) {
232
+ return defaults[match[1].toLowerCase()];
233
+ }
234
+ }
235
+ return null;
236
+ }
237
+ /**
238
+ * relation of the subject of a nested rule to the subject of an outer rule
239
+ * @param outer relation of the current rule to the outer rule
240
+ * @param relation relation of the nested rule to the current rule
241
+ */
242
+ function compose(outer, relation) {
243
+ if (outer === SELF) {
244
+ return relation;
245
+ }
246
+ // the siblings and the descendants of a descendant are descendants.
247
+ // the siblings and the descendants of an element outside the subtree are outside the subtree
248
+ return outer;
249
+ }
250
+ /**
251
+ * names of the custom properties declared by a mixin body or a rule. the declarations of the nested at-rules
252
+ * (`@media`, `@supports`, ...) are included, the declarations of the nested rules and `@private` are not
253
+ * @param arena
254
+ * @param node
255
+ * @param result
256
+ */
257
+ function collectMasked(arena, node, result = new Set()) {
258
+ for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) {
259
+ if (isCustomProperty(arena, child)) {
260
+ result.add(arena.resolveString(arena.name[child]));
261
+ }
262
+ else if (arena.dataTypes[child] === EnumToken.AtRuleNodeType &&
263
+ arena.flags[child] & EnumAstNodeStatus.HasChildren &&
264
+ !isAtRule(arena, child, "private")) {
265
+ collectMasked(arena, child, result);
266
+ }
267
+ }
268
+ return result;
269
+ }
270
+ /**
271
+ * declare the private variables (`@private`) of a mixin body or a rule in the innermost level of the scope
272
+ * @param arena
273
+ * @param node
274
+ * @param scope
275
+ */
276
+ function declarePrivates(arena, node, scope) {
277
+ const privates = scope.levels[scope.levels.length - 1].privates;
278
+ for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) {
279
+ if (!isAtRule(arena, child, "private")) {
280
+ continue;
281
+ }
282
+ for (let node = arena.firstChild[child]; node !== 0; node = arena.nextSibling[node]) {
283
+ if (isCustomProperty(arena, node)) {
284
+ // the last declaration wins
285
+ privates.set(arena.resolveString(arena.name[node]), { tokens: declarationValue(arena, node), scope });
286
+ }
287
+ }
288
+ }
289
+ }
290
+ /**
291
+ * true if a node contains nested rules
292
+ * @param arena
293
+ * @param node
294
+ */
295
+ function hasNestedRules(arena, node) {
296
+ for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) {
297
+ if (arena.dataTypes[child] === EnumToken.RuleNodeType ||
298
+ (arena.dataTypes[child] === EnumToken.AtRuleNodeType &&
299
+ arena.flags[child] & EnumAstNodeStatus.HasChildren &&
300
+ hasNestedRules(arena, child))) {
301
+ return true;
302
+ }
303
+ }
304
+ return false;
305
+ }
306
+ /**
307
+ * true if the compound selector part references the nesting selector: `&`, `:is(&)`, `:where(&)`
308
+ * @param part
309
+ */
310
+ function isNestingPart(part) {
311
+ return part === "&" || /^:(is|where)\(\s*&\s*\)$/i.test(part);
312
+ }
313
+ /**
314
+ * relation of the subject of a nested selector to the subject of the rule that contains it
315
+ * @param parts complex selector parts, see {@link splitRule}
316
+ */
317
+ function selectorRelation(parts) {
318
+ const compounds = [[]];
319
+ const combinators = [];
320
+ let whitespace = false;
321
+ for (const part of parts) {
322
+ if (part.trim() === "") {
323
+ whitespace = true;
324
+ continue;
325
+ }
326
+ if (part === ">" || part === "+" || part === "~" || part === "||") {
327
+ combinators.push(part);
328
+ compounds.push([]);
329
+ whitespace = false;
330
+ continue;
331
+ }
332
+ if (whitespace && compounds[compounds.length - 1].length > 0) {
333
+ // descendant combinator
334
+ combinators.push(" ");
335
+ compounds.push([]);
336
+ }
337
+ whitespace = false;
338
+ compounds[compounds.length - 1].push(part);
339
+ }
340
+ // relative selector: `> .child`, `+ .sibling`
341
+ if (compounds[0].length === 0) {
342
+ compounds[0].push("&");
343
+ }
344
+ let index = -1;
345
+ for (let i = compounds.length - 1; i >= 0; i--) {
346
+ if (compounds[i].some(isNestingPart)) {
347
+ index = i;
348
+ break;
349
+ }
350
+ }
351
+ if (index === -1) {
352
+ // '&' used in a way that is not handled: `:not(&)`, `:has(+ &)`. the relation is unknown
353
+ if (parts.some((part) => part.includes("&"))) {
354
+ return OUTSIDE;
355
+ }
356
+ // the selector is implicitly prefixed with `& `
357
+ return DESCENDANT;
358
+ }
359
+ if (index === compounds.length - 1) {
360
+ return SELF;
361
+ }
362
+ return combinators[index] === " " || combinators[index] === ">" ? DESCENDANT : OUTSIDE;
363
+ }
364
+ /**
365
+ * serialize a declaration of a mixin body. the declaration is left as is when it references an invalid variable
366
+ * without fallback
367
+ * @param arena
368
+ * @param declaration
369
+ * @param scope
370
+ */
371
+ function serializeDeclaration(arena, declaration, scope) {
372
+ const name = arena.resolveString(arena.name[declaration]);
373
+ if (scope.application.registry != null) {
374
+ scope.application.registry.customProperty = arena.startsWith(declaration, "nam", "--");
375
+ }
376
+ // a custom property is inherited by the descendants: a typed argument is the value computed on the element
377
+ const value = substitute(arena, arena.tokens(declaration), scope, scope.descendant || arena.startsWith(declaration, "nam", "--"));
378
+ // an invalid value is left as is
379
+ return name + ":" + (value ?? render(arena, arena.tokens(declaration)));
380
+ }
381
+ /**
382
+ * serialize an `@apply` rule of a mixin body. its arguments may reference the private variables
383
+ * @param arena
384
+ * @param node
385
+ * @param scope
386
+ */
387
+ function serializeApply(arena, node, scope) {
388
+ const tokens = arena.tokens(node);
389
+ const reference = firstToken(arena, tokens);
390
+ let prelude;
391
+ if (reference != null && arena.dataTypes[reference] === EnumToken.CustomFunctionTokenType) {
392
+ // the arguments are substituted one by one: an invalid argument is kept
393
+ prelude =
394
+ arena.resolveString(arena.stringValue[reference]) +
395
+ "(" +
396
+ splitArguments(arena, arena.tokens(reference))
397
+ .map((arg) => substitute(arena, arg, scope, scope.descendant) ?? render(arena, arg))
398
+ .join(",") +
399
+ ")";
400
+ }
401
+ else {
402
+ prelude = render(arena, trim(arena, tokens));
403
+ }
404
+ return ("@apply " +
405
+ prelude +
406
+ (arena.flags[node] & EnumAstNodeStatus.HasChildren
407
+ ? "{" + serializeDeclarations(arena, node, scope) + "}"
408
+ : ";"));
409
+ }
410
+ /**
411
+ * serialize the declarations of a contents block: `@apply --mixin { color: red }`, `@contents { color: red }`
412
+ * @param arena
413
+ * @param node
414
+ * @param scope
415
+ */
416
+ function serializeDeclarations(arena, node, scope) {
417
+ let result = "";
418
+ for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) {
419
+ if (arena.dataTypes[child] === EnumToken.DeclarationNodeType) {
420
+ result += serializeDeclaration(arena, child, scope) + ";";
421
+ }
422
+ else if (isAtRule(arena, child, "contents")) {
423
+ // the contents block is forwarded: `@apply --mixin { @contents; }`
424
+ result += serializeContents(arena, child, scope);
425
+ }
426
+ }
427
+ return result;
428
+ }
429
+ /**
430
+ * serialize a `@contents` rule: the contents block of the `@apply` rule, otherwise the default contents block of the
431
+ * `@contents` rule, otherwise nothing. the contents block is a copy: it is parsed again
432
+ * @param arena
433
+ * @param node `@contents` rule
434
+ * @param scope
435
+ */
436
+ function serializeContents(arena, node, scope) {
437
+ if (scope.application.contents != null) {
438
+ return scope.application.contents;
439
+ }
440
+ return arena.flags[node] & EnumAstNodeStatus.HasChildren ? serializeDeclarations(arena, node, scope) : "";
441
+ }
442
+ /**
443
+ * serialize a nested rule of a mixin body. the rule is split when its selectors do not have the same relation to the
444
+ * rule the mixin is applied to: the private variables are visible to some of them only
445
+ * @param arena
446
+ * @param rule
447
+ * @param scope
448
+ */
449
+ function serializeRule(arena, rule, scope) {
450
+ const groups = new Map();
451
+ // the element and its descendants see the same variables, unless the rule has nested rules (the relation of the
452
+ // nested rules depends on it) or a typed argument is computed on the element (the descendants inherit it)
453
+ const merge = !hasNestedRules(arena, rule) && scope.application.typed.size === 0;
454
+ for (const parts of splitRule(arena.resolveString(arena.name[rule]))) {
455
+ let relation = selectorRelation(parts);
456
+ if (merge && relation === DESCENDANT) {
457
+ relation = SELF;
458
+ }
459
+ if (!groups.has(relation)) {
460
+ groups.set(relation, []);
461
+ }
462
+ groups.get(relation).push(parts.join(""));
463
+ }
464
+ let result = "";
465
+ const masked = collectMasked(arena, rule);
466
+ for (const [relation, selectors] of groups) {
467
+ const child = scope.child(relation, masked);
468
+ declarePrivates(arena, rule, child);
469
+ result += selectors.join(",") + "{" + serializeBlock(arena, rule, child) + "}";
470
+ }
471
+ return result;
472
+ }
473
+ /**
474
+ * serialize the children of a mixin body, a nested rule or a nested at-rule. the private variables are substituted
475
+ * @param arena
476
+ * @param node
477
+ * @param scope
478
+ */
479
+ function serializeBlock(arena, node, scope) {
480
+ let result = "";
481
+ for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) {
482
+ switch (arena.dataTypes[child]) {
483
+ case EnumToken.DeclarationNodeType:
484
+ result += serializeDeclaration(arena, child, scope) + ";";
485
+ break;
486
+ case EnumToken.RuleNodeType:
487
+ result += serializeRule(arena, child, scope);
488
+ break;
489
+ case EnumToken.AtRuleNodeType: {
490
+ // the private variables are substituted
491
+ if (arena.stringEquals(arena.name[child], "private")) {
492
+ break;
493
+ }
494
+ if (arena.stringEquals(arena.name[child], "apply")) {
495
+ result += serializeApply(arena, child, scope);
496
+ break;
497
+ }
498
+ // the content of `@result` is the result of the mixin
499
+ if (arena.stringEquals(arena.name[child], "result")) {
500
+ result += serializeBlock(arena, child, scope);
501
+ break;
502
+ }
503
+ if (arena.stringEquals(arena.name[child], "contents")) {
504
+ result += serializeContents(arena, child, scope);
505
+ break;
506
+ }
507
+ const prelude = arena.resolveString(arena.stringValue[child]);
508
+ result +=
509
+ "@" +
510
+ arena.resolveString(arena.name[child]) +
511
+ (prelude === "" ? "" : " " + prelude) +
512
+ (arena.flags[child] & EnumAstNodeStatus.HasChildren
513
+ ? "{" + serializeBlock(arena, child, scope) + "}"
514
+ : ";");
515
+ break;
516
+ }
517
+ }
518
+ }
519
+ return result;
520
+ }
521
+ /**
522
+ * the generated nodes are located at the `@apply` rule
523
+ * @param arena
524
+ * @param node
525
+ * @param location
526
+ */
527
+ function locate(arena, node, location) {
528
+ arena.copyLocation(node, location);
529
+ if (arena.flags[node] & EnumAstNodeStatus.HasChildren) {
530
+ for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) {
531
+ locate(arena, child, location);
532
+ }
533
+ }
534
+ }
535
+ /**
536
+ * parse a mixin definition. null if the prelude is not valid
537
+ * @param arena
538
+ * @param node
539
+ */
540
+ function parseMixin(arena, node) {
541
+ const reference = firstToken(arena, arena.tokens(node));
542
+ if (reference == null) {
543
+ return null;
544
+ }
545
+ let parameters = [];
546
+ if (arena.dataTypes[reference] === EnumToken.CustomFunctionTokenType) {
547
+ parameters = parseParameters(arena, reference);
548
+ if (parameters == null) {
549
+ return null;
550
+ }
551
+ }
552
+ else if (arena.dataTypes[reference] !== EnumToken.DashedIdenTokenType) {
553
+ return null;
554
+ }
555
+ return {
556
+ node,
557
+ name: arena.resolveString(arena.stringValue[reference]),
558
+ parameters,
559
+ };
560
+ }
561
+ /**
562
+ * parse the prelude of an `@apply` rule: the name of the mixin and the arguments. the comments and the whitespace
563
+ * are ignored: `@apply --mixin( /* comment *\/ )` has no argument
564
+ * @param arena
565
+ * @param node
566
+ */
567
+ function parseApply(arena, node) {
568
+ const reference = firstToken(arena, arena.tokens(node));
569
+ if (reference == null) {
570
+ return null;
571
+ }
572
+ if (arena.dataTypes[reference] === EnumToken.DashedIdenTokenType) {
573
+ return { name: arena.resolveString(arena.stringValue[reference]), args: [] };
574
+ }
575
+ if (arena.dataTypes[reference] !== EnumToken.CustomFunctionTokenType) {
576
+ return null;
577
+ }
578
+ return { name: arena.resolveString(arena.stringValue[reference]), args: parseArguments(arena, reference) };
579
+ }
580
+ /**
581
+ * bind the arguments to the mixin parameters. false when the arguments do not match the parameters:
582
+ * - more arguments than parameters
583
+ * - a parameter without default value has no argument
584
+ * - an argument or a default value does not match the type of the parameter, or is invalid
585
+ * @param arena
586
+ * @param definition
587
+ * @param args argument tokens
588
+ * @param caller scope of the `@apply` rule, the arguments are evaluated in this scope
589
+ * @param scope scope of the mixin body, the default values are evaluated in this scope
590
+ * @param options
591
+ */
592
+ function bindParameters(arena, definition, args, caller, scope, options) {
593
+ const application = scope.application;
594
+ if (args.length > definition.parameters.length) {
595
+ return false;
596
+ }
597
+ for (let index = 0; index < definition.parameters.length; index++) {
598
+ const parameter = definition.parameters[index];
599
+ if (index < args.length) {
600
+ application.args.set(parameter.name, {
601
+ tokens: null,
602
+ text: substitute(arena, args[index], caller, false),
603
+ scope,
604
+ });
605
+ }
606
+ else if (parameter.defaultValue != null) {
607
+ // the default value may reference the other variables: it is resolved once the variables are declared
608
+ application.args.set(parameter.name, { tokens: parameter.defaultValue, scope });
609
+ }
610
+ else {
611
+ return false;
612
+ }
613
+ }
614
+ // the private variables may be referenced by the default values
615
+ declarePrivates(arena, definition.node, scope);
616
+ for (const parameter of definition.parameters) {
617
+ const value = resolve(arena, application.args.get(parameter.name), false);
618
+ if (value === null || !matchesType(arena, parameter.syntax, value, options)) {
619
+ return false;
620
+ }
621
+ // the value of a typed argument is computed on the element the mixin is applied to
622
+ if (parameter.syntax != null) {
623
+ application.typed.set(parameter.name, { value, syntax: parameter.syntax, property: null, entry: null });
624
+ }
625
+ }
626
+ return true;
627
+ }
628
+ /**
629
+ * create the registered custom property of a typed argument
630
+ * ```css
631
+ * @property --same-size-size-1 { syntax: "<length>"; inherits: true; initial-value: 0px }
632
+ * ```
633
+ * @param arena
634
+ * @param property
635
+ */
636
+ function registerProperty(arena, property) {
637
+ const node = arena.createAtRule(EnumToken.AtRuleNodeType, "property", property.name, true, [arena.createToken(EnumToken.DashedIdenTokenType, property.name)], EnumAstNodeStatus.Validated, null);
638
+ arena.appendChildList(node, parseDeclarations(`syntax:${JSON.stringify(property.syntax)};inherits:true;initial-value:${property.initialValue}`, arena).nodes);
639
+ return node;
640
+ }
641
+ /**
642
+ * true if a mixin applies itself, directly or through the mixins it applies: it cannot be evaluated
643
+ * @param arena
644
+ * @param name
645
+ * @param state
646
+ * @param stack mixins being checked
647
+ */
648
+ function isRecursive(arena, name, state, stack = []) {
649
+ if (stack.includes(name)) {
650
+ return true;
651
+ }
652
+ if (state.recursive.has(name)) {
653
+ return state.recursive.get(name);
654
+ }
655
+ const definitions = state.definitions.get(name) ?? [];
656
+ let result = false;
657
+ stack.push(name);
658
+ for (const definition of definitions) {
659
+ for (const id of arena.walk(definition.node)) {
660
+ if (id !== definition.node && isAtRule(arena, id, "apply")) {
661
+ const reference = parseApply(arena, id);
662
+ if (reference != null && isRecursive(arena, reference.name, state, stack)) {
663
+ result = true;
664
+ break;
665
+ }
666
+ }
667
+ }
668
+ if (result) {
669
+ break;
670
+ }
671
+ }
672
+ stack.pop();
673
+ // a mixin that reaches one of the mixins being checked is part of a cycle
674
+ state.recursive.set(name, result);
675
+ return result;
676
+ }
677
+ /**
678
+ * replace an `@apply` rule with the evaluated body of the mixin. the `@apply` rule is left as is when it cannot be
679
+ * evaluated
680
+ * @param arena
681
+ * @param node
682
+ * @param state
683
+ * @returns the inserted nodes, null when the `@apply` rule is not evaluated
684
+ */
685
+ function apply(arena, node, state) {
686
+ const reference = parseApply(arena, node);
687
+ if (reference == null) {
688
+ return null;
689
+ }
690
+ // the mixins visible from the `@apply` rule: a mixin defined in a rule or an at-rule is not visible outside of it.
691
+ // the mixin is defined only once in the innermost scope that defines it
692
+ const definitions = resolveDefinitions(arena, state.definitions.get(reference.name), node);
693
+ const definition = definitions.length === 1 ? definitions[0] : null;
694
+ const properties = ruleProperties(arena, node);
695
+ const chain = state.chains.get(node) ?? [];
696
+ if (definition == null ||
697
+ properties == null ||
698
+ // a mixin that applies itself
699
+ isRecursive(arena, reference.name, state) ||
700
+ chain.includes(reference.name) ||
701
+ chain.length >= MAX_DEPTH) {
702
+ // the visible definitions are kept
703
+ for (const visible of definitions) {
704
+ state.pending.add(visible.node);
705
+ }
706
+ return null;
707
+ }
708
+ // the contents block is a declaration list. its variables are not private variables: they are not substituted
709
+ const contents = arena.flags[node] & EnumAstNodeStatus.HasChildren
710
+ ? serializeDeclarations(arena, node, new MixinScope([{ privates: new Map(), relation: SELF }], new MixinApplication(reference.name, new Map(), null, null), new Set()))
711
+ : null;
712
+ const application = new MixinApplication(reference.name, properties, contents, state.names, state.registry);
713
+ // the arguments are evaluated in the context of the `@apply` rule
714
+ const caller = new MixinScope([{ privates: new Map(), relation: SELF }], new MixinApplication(reference.name, properties, null, null), new Set());
715
+ const scope = new MixinScope([{ privates: new Map(), relation: SELF }], application, collectMasked(arena, definition.node));
716
+ if (!bindParameters(arena, definition, reference.args, caller, scope, state.options)) {
717
+ state.pending.add(definition.node);
718
+ return null;
719
+ }
720
+ // the custom functions called by the mixin body are evaluated in the context of the `@apply` rule
721
+ state.registry.site = node;
722
+ const failed = state.registry.failed;
723
+ let css = serializeBlock(arena, definition.node, scope);
724
+ // a typed argument cannot be registered, or a custom function call is not evaluated
725
+ if (application.failed || state.registry.failed !== failed) {
726
+ state.pending.add(definition.node);
727
+ return null;
728
+ }
729
+ if (application.registered.length > 0) {
730
+ // the top level node that contains the `@apply` rule
731
+ let top = node;
732
+ while (arena.parents[top] !== state.ast && arena.parents[top] !== 0) {
733
+ top = arena.parents[top];
734
+ }
735
+ let declarations = "";
736
+ for (const property of application.registered) {
737
+ const registered = registerProperty(arena, property);
738
+ locate(arena, registered, node);
739
+ arena.insertBefore(top, registered);
740
+ // the value is computed on the element the mixin is applied to
741
+ declarations += property.name + ":" + property.value + ";";
742
+ }
743
+ css = declarations + css;
744
+ }
745
+ // the body is parsed as the content of the rule the mixin is applied to: '&' is that rule
746
+ const nodes = parseRuleContent(css, arena, state.options);
747
+ const nested = chain.concat(reference.name);
748
+ for (const child of nodes) {
749
+ locate(arena, child, node);
750
+ arena.insertBefore(node, child);
751
+ // the `@apply` rules of the mixin body
752
+ for (const id of arena.walk(child)) {
753
+ if (isAtRule(arena, id, "apply")) {
754
+ state.chains.set(id, nested);
755
+ }
756
+ }
757
+ }
758
+ arena.detach(node);
759
+ return nodes;
760
+ }
761
+ /**
762
+ * the definitions that are kept:
763
+ * - the mixins and the custom functions referenced by an `@apply` rule or a call that is not evaluated
764
+ * - the custom functions that are not called
765
+ * - the definitions referenced by the definitions that are kept or not valid: a mixin that is kept may apply a mixin or
766
+ * call a function that is evaluated. the references are resolved from their location, see {@link resolveDefinitions}
767
+ *
768
+ * the mixins that are not referenced are dropped
769
+ * @param arena
770
+ * @param state
771
+ * @param registry
772
+ */
773
+ function keptDefinitions(arena, state, registry) {
774
+ const kept = new Set([...state.pending, ...registry.pending]);
775
+ for (const definitions of registry.definitions.values()) {
776
+ for (const definition of definitions) {
777
+ if (!registry.evaluated.has(definition.node)) {
778
+ kept.add(definition.node);
779
+ }
780
+ }
781
+ }
782
+ const queue = [...kept, ...state.invalid];
783
+ while (queue.length > 0) {
784
+ const node = queue.pop();
785
+ const referenced = [];
786
+ for (const id of arena.walk(node)) {
787
+ if (id !== node && isAtRule(arena, id, "apply")) {
788
+ const reference = parseApply(arena, id);
789
+ if (reference != null) {
790
+ for (const definition of resolveDefinitions(arena, state.definitions.get(reference.name), id)) {
791
+ referenced.push(definition.node);
792
+ }
793
+ }
794
+ }
795
+ for (const call of findCalls(arena, arena.tokens(id))) {
796
+ const name = arena.resolveString(arena.stringValue[call]);
797
+ for (const definition of resolveDefinitions(arena, registry.definitions.get(name), id)) {
798
+ referenced.push(definition.node);
799
+ }
800
+ }
801
+ }
802
+ for (const definition of referenced) {
803
+ if (!kept.has(definition)) {
804
+ kept.add(definition);
805
+ queue.push(definition);
806
+ }
807
+ }
808
+ }
809
+ return kept;
810
+ }
811
+ /**
812
+ * evaluate the mixins and the custom functions of a stylesheet
813
+ * @param arena
814
+ * @param ast
815
+ * @param options
816
+ */
817
+ function evaluate(arena, ast, options) {
818
+ const invalidMixins = [];
819
+ const invalidFunctions = [];
820
+ const registry = new FunctionRegistry(collectDefinitions(arena, ast, "function", parseFunction, new Map(), invalidFunctions), options);
821
+ const state = {
822
+ definitions: collectDefinitions(arena, ast, "mixin", parseMixin, new Map(), invalidMixins),
823
+ invalid: invalidMixins,
824
+ pending: new Set(),
825
+ chains: new Map(),
826
+ recursive: new Map(),
827
+ ast,
828
+ registry,
829
+ names: new Set(),
830
+ options,
831
+ };
832
+ // the custom functions that are not valid are dropped
833
+ for (const node of invalidFunctions) {
834
+ arena.detach(node);
835
+ }
836
+ if (state.definitions.size === 0 && registry.definitions.size === 0) {
837
+ return;
838
+ }
839
+ if (state.definitions.size > 0) {
840
+ for (const id of arena.walk(ast)) {
841
+ if (isCustomProperty(arena, id)) {
842
+ state.names.add(arena.resolveString(arena.name[id]));
843
+ }
844
+ else if (isAtRule(arena, id, "property")) {
845
+ state.names.add(arena.resolveString(arena.stringValue[id]).trim());
846
+ }
847
+ }
848
+ // depth first traversal, in document order
849
+ const stack = [];
850
+ for (let child = arena.lastChild[ast]; child !== 0; child = arena.previousSibling[child]) {
851
+ stack.push(child);
852
+ }
853
+ while (stack.length > 0) {
854
+ const node = stack.pop();
855
+ if (arena.dataTypes[node] === EnumToken.AtRuleNodeType) {
856
+ // the mixin and the function bodies are evaluated when they are used
857
+ if (isAtRule(arena, node, "mixin") || isAtRule(arena, node, "function")) {
858
+ continue;
859
+ }
860
+ if (isAtRule(arena, node, "apply")) {
861
+ const nodes = apply(arena, node, state);
862
+ if (nodes != null) {
863
+ // the mixin body may apply other mixins
864
+ for (let i = nodes.length - 1; i >= 0; i--) {
865
+ stack.push(nodes[i]);
866
+ }
867
+ continue;
868
+ }
869
+ }
870
+ }
871
+ if (arena.flags[node] & EnumAstNodeStatus.HasChildren) {
872
+ for (let child = arena.lastChild[node]; child !== 0; child = arena.previousSibling[child]) {
873
+ stack.push(child);
874
+ }
875
+ }
876
+ }
877
+ }
878
+ // the custom function calls, including the calls of the evaluated mixins
879
+ if (registry.definitions.size > 0) {
880
+ evaluateFunctions(arena, ast, registry);
881
+ }
882
+ const kept = keptDefinitions(arena, state, registry);
883
+ finalizeDefinitions(arena, ast, "mixin", kept, !!options.keepMixins, invalidMixins);
884
+ finalizeDefinitions(arena, ast, "function", kept, !!options.keepMixins, []);
885
+ }
886
+ /**
887
+ * Evaluate the css mixins and the custom functions: the `@apply` rules are replaced by the body of the mixin they
888
+ * reference, the custom function calls are replaced by the result of the function.
889
+ * the feature is enabled with the {@link ParserOptions.evaluateMixins} option.
890
+ *
891
+ * https://drafts.csswg.org/css-mixins-1/
892
+ *
893
+ * ```ts
894
+ * import {transform} from '@tbela99/css-parser';
895
+ *
896
+ * const css = `
897
+ * @mixin --only-descs(--arg) {
898
+ * color: var(--arg);
899
+ * & * { color: var(--arg, red); }
900
+ * & + * { color: var(--arg, red); }
901
+ * }
902
+ * .foo {
903
+ * @apply --only-descs(green);
904
+ * }
905
+ * `;
906
+ *
907
+ * const result = await transform(css, {evaluateMixins: true, expandNestingRules: true, beautify: true});
908
+ *
909
+ * console.log(result.code);
910
+ * // .foo,.foo * {
911
+ * // color: green
912
+ * // }
913
+ * // .foo+* {
914
+ * // color: red
915
+ * // }
916
+ * ```
917
+ */
918
+ class EvaluateMixinFeature {
919
+ accept = new Set([EnumToken.StyleSheetNodeType]);
920
+ get ordering() {
921
+ return 0;
922
+ }
923
+ get processMode() {
924
+ return FeatureWalkMode.Pre;
925
+ }
926
+ static register(options) {
927
+ if (options.evaluateMixins) {
928
+ // @ts-ignore
929
+ options.features.push(new EvaluateMixinFeature());
930
+ }
931
+ }
932
+ /**
933
+ * evaluate the mixins of a stylesheet
934
+ * @param arena
935
+ * @param ast
936
+ * @param options
937
+ */
938
+ static evaluate(arena, ast, options = {}) {
939
+ evaluate(arena, ast, options);
940
+ }
941
+ /**
942
+ *
943
+ * @param arena
944
+ * @param ast
945
+ * @param options
946
+ */
947
+ run(arena, ast, options = {}) {
948
+ evaluate(arena, ast, options);
949
+ return null;
950
+ }
951
+ }
952
+
953
+ export { EvaluateMixinFeature };