@tbela99/css-parser 1.8.1 → 2.0.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 (105) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +129 -31
  3. package/dist/index-umd-web.js +27382 -24086
  4. package/dist/index.d.ts +2737 -2200
  5. package/dist/package.json.js +2 -2
  6. package/dist/src/data/properties.json.js +1 -1
  7. package/dist/src/data/validation.json.js +1 -1
  8. package/dist/src/lib/ast/arena-node.js +548 -0
  9. package/dist/src/lib/ast/arena.js +3198 -0
  10. package/dist/src/lib/ast/features/calc.js +85 -76
  11. package/dist/src/lib/ast/features/if.js +155 -115
  12. package/dist/src/lib/ast/features/index.js +1 -1
  13. package/dist/src/lib/ast/features/inlinecssvariables.js +77 -84
  14. package/dist/src/lib/ast/features/prefix.js +184 -183
  15. package/dist/src/lib/ast/features/shorthand.js +40 -46
  16. package/dist/src/lib/ast/features/transform.js +24 -24
  17. package/dist/src/lib/ast/features/type.js +1 -1
  18. package/dist/src/lib/ast/fingerprint.js +333 -0
  19. package/dist/src/lib/ast/math/expression.js +458 -543
  20. package/dist/src/lib/ast/math/math.js +19 -41
  21. package/dist/src/lib/ast/minify.js +590 -647
  22. package/dist/src/lib/ast/transform/compute.js +82 -85
  23. package/dist/src/lib/ast/transform/matrix.js +21 -38
  24. package/dist/src/lib/ast/transform/minify.js +82 -193
  25. package/dist/src/lib/ast/transform/perspective.js +2 -3
  26. package/dist/src/lib/ast/transform/rotate.js +1 -1
  27. package/dist/src/lib/ast/transform/scale.js +1 -1
  28. package/dist/src/lib/ast/transform/skew.js +1 -1
  29. package/dist/src/lib/ast/transform/translate.js +1 -1
  30. package/dist/src/lib/ast/transform/utils.js +2 -2
  31. package/dist/src/lib/ast/types.js +263 -258
  32. package/dist/src/lib/ast/walk.js +246 -610
  33. package/dist/src/lib/fs/resolve.js +1 -1
  34. package/dist/src/lib/parser/declaration/list.js +223 -139
  35. package/dist/src/lib/parser/declaration/map.js +251 -238
  36. package/dist/src/lib/parser/declaration/set.js +74 -66
  37. package/dist/src/lib/parser/linesmap.js +1 -1
  38. package/dist/src/lib/parser/parse.js +1379 -1662
  39. package/dist/src/lib/parser/source.js +7 -4
  40. package/dist/src/lib/parser/tokenize.js +406 -199
  41. package/dist/src/lib/parser/utils/angle.js +11 -13
  42. package/dist/src/lib/parser/utils/at-rule-container.js +183 -168
  43. package/dist/src/lib/parser/utils/at-rule-font-feature-values.js +5 -5
  44. package/dist/src/lib/parser/utils/at-rule-generic.js +31 -24
  45. package/dist/src/lib/parser/utils/at-rule-import.js +44 -44
  46. package/dist/src/lib/parser/utils/at-rule-media.js +216 -205
  47. package/dist/src/lib/parser/utils/at-rule-support.js +83 -88
  48. package/dist/src/lib/parser/utils/at-rule-when-else.js +47 -47
  49. package/dist/src/lib/parser/utils/at-rule.js +5 -5
  50. package/dist/src/lib/parser/utils/base64.js +2 -2
  51. package/dist/src/lib/parser/utils/cache.js +1 -1
  52. package/dist/src/lib/parser/utils/config.js +1 -1
  53. package/dist/src/lib/parser/utils/declaration.js +233 -234
  54. package/dist/src/lib/parser/utils/eq.js +50 -3
  55. package/dist/src/lib/parser/utils/hash.js +2 -35
  56. package/dist/src/lib/parser/utils/selector.js +309 -387
  57. package/dist/src/lib/parser/utils/text.js +18 -4
  58. package/dist/src/lib/parser/utils/token.js +16 -69
  59. package/dist/src/lib/parser/utils/type.js +37 -24
  60. package/dist/src/lib/printer/render.js +965 -511
  61. package/dist/src/lib/printer/sourcemap/lib/codec.js +1 -1
  62. package/dist/src/lib/printer/sourcemap/sourcemap.js +1 -1
  63. package/dist/src/lib/syntax/color/a98rgb.js +1 -1
  64. package/dist/src/lib/syntax/color/alpha.js +36 -37
  65. package/dist/src/lib/syntax/color/cmyk.js +35 -52
  66. package/dist/src/lib/syntax/color/color-mix.js +96 -132
  67. package/dist/src/lib/syntax/color/color.js +222 -231
  68. package/dist/src/lib/syntax/color/hex.js +45 -55
  69. package/dist/src/lib/syntax/color/hsl.js +54 -62
  70. package/dist/src/lib/syntax/color/hwb.js +60 -68
  71. package/dist/src/lib/syntax/color/lab.js +59 -67
  72. package/dist/src/lib/syntax/color/lch.js +59 -67
  73. package/dist/src/lib/syntax/color/oklab.js +60 -68
  74. package/dist/src/lib/syntax/color/oklch.js +60 -67
  75. package/dist/src/lib/syntax/color/p3.js +1 -1
  76. package/dist/src/lib/syntax/color/prophotorgb.js +1 -1
  77. package/dist/src/lib/syntax/color/rec2020.js +1 -1
  78. package/dist/src/lib/syntax/color/relative-color.js +94 -144
  79. package/dist/src/lib/syntax/color/rgb.js +54 -57
  80. package/dist/src/lib/syntax/color/srgb.js +55 -53
  81. package/dist/src/lib/syntax/color/utils/color-type.js +13 -10
  82. package/dist/src/lib/syntax/color/utils/colorspace.js +11 -11
  83. package/dist/src/lib/syntax/color/utils/components.js +19 -20
  84. package/dist/src/lib/syntax/color/utils/distance.js +15 -13
  85. package/dist/src/lib/syntax/color/utils/make-color.js +15 -19
  86. package/dist/src/lib/syntax/color/utils/matrix.js +2 -2
  87. package/dist/src/lib/syntax/color/xyz.js +1 -1
  88. package/dist/src/lib/syntax/color/xyzd50.js +1 -1
  89. package/dist/src/lib/syntax/constants.js +2 -16
  90. package/dist/src/lib/syntax/syntax.js +301 -407
  91. package/dist/src/lib/validation/config.js +1 -1
  92. package/dist/src/lib/validation/match.js +959 -723
  93. package/dist/src/lib/validation/parser/parse.js +230 -112
  94. package/dist/src/lib/validation/parser/typedef.js +1 -1
  95. package/dist/src/lib/validation/utils/list.js +27 -12
  96. package/dist/src/node.js +12 -72
  97. package/dist/src/types.js +1 -1
  98. package/dist/src/utils/sync.js +9 -6
  99. package/dist/src/web.js +11 -73
  100. package/package.json +9 -10
  101. package/dist/index.cjs +0 -35874
  102. package/dist/src/lib/ast/clone.js +0 -51
  103. package/dist/src/lib/ast/expand.js +0 -311
  104. package/dist/src/lib/ast/find.js +0 -192
  105. package/dist/src/lib/ast/node.js +0 -59
@@ -0,0 +1,3198 @@
1
+ /*
2
+ CSS parser, minifier and validator for node and the browser
3
+
4
+ Author(s): Thierry Bela
5
+ Version: 2.0.0
6
+ License: MIT
7
+ */
8
+ import { EnumToken, EnumAstNodeStatus, ColorType } from './types.js';
9
+ import { NodeWalker, ValueWalker } from './walk.js';
10
+ import { ARENA, isNodeObjectType, AstArenaNode, ARENAID } from './arena-node.js';
11
+ import { splitRule } from './minify.js';
12
+ import { combinators } from '../syntax/constants.js';
13
+ import { parseString } from '../parser/parse.js';
14
+ import { renderValue } from '../printer/render.js';
15
+ import { equalsIgnoreCase } from '../parser/utils/text.js';
16
+
17
+ /**
18
+ * position of the structured token fields in the children list
19
+ */
20
+ var TokenField;
21
+ (function (TokenField) {
22
+ /**
23
+ * left hand side (`l`)
24
+ */
25
+ TokenField[TokenField["L"] = 0] = "L";
26
+ /**
27
+ * right hand side (`r`)
28
+ */
29
+ TokenField[TokenField["R"] = 1] = "R";
30
+ /**
31
+ * operator (`op`, `op1`)
32
+ */
33
+ TokenField[TokenField["Op"] = 2] = "Op";
34
+ /**
35
+ * second operator (`op2`)
36
+ */
37
+ TokenField[TokenField["Op2"] = 3] = "Op2";
38
+ /**
39
+ * value (`val`)
40
+ */
41
+ TokenField[TokenField["Val"] = 4] = "Val";
42
+ })(TokenField || (TokenField = {}));
43
+ /**
44
+ * numeric token types: the value is stored in the `numericValue` column
45
+ */
46
+ const numericTokenTypes = new Set([
47
+ EnumToken.NumberTokenType,
48
+ EnumToken.DimensionTokenType,
49
+ EnumToken.LengthTokenType,
50
+ EnumToken.AngleTokenType,
51
+ EnumToken.TimeTokenType,
52
+ EnumToken.FrequencyTokenType,
53
+ EnumToken.ResolutionTokenType,
54
+ EnumToken.PercentageTokenType,
55
+ EnumToken.FlexTokenType,
56
+ EnumToken.UserDefinedDimensionTokenType,
57
+ ]);
58
+ /**
59
+ * token types whose fields are stored as list children (see {@link TokenField})
60
+ */
61
+ const structuredTokenTypes = new Set([
62
+ EnumToken.BinaryExpressionTokenType,
63
+ EnumToken.MatchExpressionTokenType,
64
+ EnumToken.MediaQueryConditionTokenType,
65
+ EnumToken.MediaQueryUnaryFeatureTokenType,
66
+ EnumToken.SupportsQueryConditionTokenType,
67
+ EnumToken.SupportsQueryUnaryConditionTokenType,
68
+ EnumToken.WhenElseQueryConditionTokenType,
69
+ EnumToken.WhenElseUnaryConditionTokenType,
70
+ EnumToken.IfConditionTokenType,
71
+ EnumToken.IfElseConditionTokenType,
72
+ EnumToken.ContainerStyleRangeTokenType,
73
+ EnumToken.MediaRangeQueryTokenType,
74
+ EnumToken.ComposesSelectorNodeType,
75
+ EnumToken.NameSpaceAttributeTokenType,
76
+ ]);
77
+ // structuredFields() results, by token type
78
+ const structuredFieldsCache = [];
79
+ const noFields = [];
80
+ /**
81
+ * fields of a structured token type: the plain object key (`l`, `r`, `op`, `op1`, `op2`, `val`), the field index and
82
+ * whether the field holds a single token. empty for the other token types
83
+ * @param typ
84
+ * @internal
85
+ */
86
+ function structuredFields(typ) {
87
+ let fields = structuredFieldsCache[typ];
88
+ if (fields != null) {
89
+ return fields;
90
+ }
91
+ if (!structuredTokenTypes.has(typ)) {
92
+ fields = noFields;
93
+ }
94
+ else {
95
+ const single = typ == EnumToken.BinaryExpressionTokenType ||
96
+ typ == EnumToken.IfElseConditionTokenType ||
97
+ typ == EnumToken.MatchExpressionTokenType ||
98
+ typ == EnumToken.NameSpaceAttributeTokenType;
99
+ const singleLeft = single ||
100
+ typ == EnumToken.MediaQueryConditionTokenType ||
101
+ typ == EnumToken.MediaQueryUnaryFeatureTokenType ||
102
+ typ == EnumToken.SupportsQueryUnaryConditionTokenType ||
103
+ typ == EnumToken.WhenElseUnaryConditionTokenType;
104
+ const singleRight = single || typ == EnumToken.ComposesSelectorNodeType;
105
+ fields = [
106
+ ["l", TokenField.L, singleLeft],
107
+ ["r", TokenField.R, singleRight],
108
+ [
109
+ typ == EnumToken.MediaRangeQueryTokenType ? "op1" : "op",
110
+ TokenField.Op,
111
+ typ != EnumToken.ContainerStyleRangeTokenType,
112
+ ],
113
+ ["op2", TokenField.Op2, true],
114
+ ["val", TokenField.Val, false],
115
+ ];
116
+ }
117
+ structuredFieldsCache[typ] = fields;
118
+ return fields;
119
+ }
120
+ /**
121
+ * little endian platform
122
+ */
123
+ const littleEndian = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1;
124
+ /**
125
+ * arena columns stored as typed arrays, in the order of the transferable buffers
126
+ */
127
+ const arenaColumns = [
128
+ "dataTypes",
129
+ "parents",
130
+ "nextSibling",
131
+ "previousSibling",
132
+ "firstToken",
133
+ "lastToken",
134
+ "firstChild",
135
+ "lastChild",
136
+ "name",
137
+ "stringValue",
138
+ "numericValue",
139
+ "unit",
140
+ "flags",
141
+ "colorType",
142
+ "spans",
143
+ ];
144
+ /**
145
+ * typed array constructor of each column
146
+ */
147
+ const arenaColumnTypes = {
148
+ dataTypes: Uint8Array,
149
+ parents: Uint32Array,
150
+ nextSibling: Uint32Array,
151
+ previousSibling: Uint32Array,
152
+ firstToken: Uint32Array,
153
+ lastToken: Uint32Array,
154
+ firstChild: Uint32Array,
155
+ lastChild: Uint32Array,
156
+ name: Uint32Array,
157
+ stringValue: Uint32Array,
158
+ numericValue: Float64Array,
159
+ unit: Uint32Array,
160
+ flags: Uint32Array,
161
+ colorType: Uint8Array,
162
+ spans: BigUint64Array,
163
+ };
164
+ // the nesting rules of these nodes are not expanded
165
+ const skipStates = EnumAstNodeStatus.Invalid |
166
+ EnumAstNodeStatus.Disallowed |
167
+ EnumAstNodeStatus.Unknown |
168
+ EnumAstNodeStatus.Unparsed |
169
+ EnumAstNodeStatus.Malformed;
170
+ // stack of visitValues(), shared by the nested calls: each call uses the entries above its base. the entries are
171
+ // written by index and the array never shrinks
172
+ const visitStack = [];
173
+ let visitTop = 0;
174
+ /**
175
+ * Arena memory manager.
176
+ *
177
+ * The node data is stored column-wise in typed arrays allocated for the capacity of the arena ({@link getCapacity},
178
+ * 62 bytes per node). The arena grows by doubling its capacity and never frees memory by itself: detached nodes keep
179
+ * their memory and their ids stay valid. {@link release}, {@link compact}, {@link trim} and {@link compactStrings}
180
+ * reclaim the memory, `compact()` and `trim()` renumber the nodes. See the Arena Memory guide (files/arena.md).
181
+ */
182
+ class Arena {
183
+ /**
184
+ * string interner identifiers
185
+ */
186
+ stringIds = new Map();
187
+ /**
188
+ * string interner values
189
+ */
190
+ strings = [];
191
+ /**
192
+ * root node
193
+ */
194
+ root = 1;
195
+ /**
196
+ * last allocated node id. the next node is allocated with the id current + 1 (unless a recycled id is available).
197
+ * 0 is never allocated: it means "no node"
198
+ */
199
+ current = 1;
200
+ /**
201
+ * head of the list of recycled node ids. the list is linked through the `nextSibling` column, see {@link recycle}
202
+ */
203
+ freeList = 0;
204
+ /**
205
+ * node EnumToken type array
206
+ */
207
+ dataTypes;
208
+ /**
209
+ * parent node id array
210
+ */
211
+ parents;
212
+ /**
213
+ * next sibling node id array
214
+ */
215
+ nextSibling;
216
+ /**
217
+ * previous sibling node id array
218
+ */
219
+ previousSibling;
220
+ /**
221
+ * first token node id array
222
+ */
223
+ firstToken;
224
+ /**
225
+ * last token node id array
226
+ */
227
+ lastToken;
228
+ /**
229
+ * first child node id array
230
+ */
231
+ firstChild;
232
+ /**
233
+ * last child node id array
234
+ */
235
+ lastChild;
236
+ /**
237
+ * node name string interner id array. used to store (node as AstRule | AstDeclaration | AstKeyframesAtRule).nam and (node as AstRule | AstKeyframesRule).sel
238
+ */
239
+ name;
240
+ /**
241
+ * node string value index array.
242
+ */
243
+ stringValue;
244
+ /**
245
+ * node numeric value array. previously used as (node as NumberToken | DimensionToken).val
246
+ */
247
+ numericValue;
248
+ /**
249
+ * node unit string interner id array. previously used as (node as DimensionToken).unit
250
+ */
251
+ unit;
252
+ /**
253
+ * node flags
254
+ */
255
+ flags;
256
+ /**
257
+ * color type. previously use as (node as ColorToken).kin
258
+ */
259
+ colorType;
260
+ /**
261
+ * token spans. 8 bits for source type. 28 bits for start position, 28 bits for end position. This allows us to store the start and end positions of tokens in a single 64-bit integer, which is more efficient than storing them separately.
262
+ */
263
+ spans;
264
+ /**
265
+ * 32 bits view of the spans: the low word holds the end position and the 4 low bits of the start position,
266
+ * the high word holds the 24 high bits of the start position and the source
267
+ */
268
+ spans32;
269
+ /**
270
+ * error cache
271
+ */
272
+ errors = new Map();
273
+ constructor(size = 4096) {
274
+ this.dataTypes = new Uint8Array(size);
275
+ this.parents = new Uint32Array(size);
276
+ this.nextSibling = new Uint32Array(size);
277
+ this.previousSibling = new Uint32Array(size);
278
+ this.lastToken = new Uint32Array(size);
279
+ this.firstToken = new Uint32Array(size);
280
+ this.firstChild = new Uint32Array(size);
281
+ this.lastChild = new Uint32Array(size);
282
+ this.name = new Uint32Array(size);
283
+ this.stringValue = new Uint32Array(size);
284
+ this.numericValue = new Float64Array(size);
285
+ this.unit = new Uint32Array(size);
286
+ this.flags = new Uint32Array(size);
287
+ this.colorType = new Uint8Array(size);
288
+ this.spans = new BigUint64Array(size);
289
+ this.spans32 = new Uint32Array(this.spans.buffer);
290
+ this.dataTypes[this.root] = EnumToken.StyleSheetNodeType;
291
+ }
292
+ /**
293
+ * Export the arena as a structured-cloneable object and the list of its column buffers, to send an arena
294
+ * to a worker (or back to the main thread) without copying the node data.
295
+ *
296
+ * The properties (strings, errors, ...) are cloned by `postMessage()`, the column buffers are moved when they are
297
+ * passed as the transfer list: the source arena must not be used afterwards (its columns are detached).
298
+ * The buffers are copied instead when the transfer list is omitted.
299
+ *
300
+ * ```ts
301
+ * // main thread
302
+ * const [properties, transferables] = AstArena.toTransferableArenaObject(result.arena);
303
+ *
304
+ * worker.postMessage({ ast: result.ast, properties, transferables }, transferables);
305
+ *
306
+ * // worker
307
+ * const { ast, properties, transferables } = event.data;
308
+ * const arena = AstArena.fromTransferableArenaObjects(properties, transferables);
309
+ * ```
310
+ *
311
+ * @param arena
312
+ * @returns the arena properties and the column buffers, see {@link ArenaProperties} and {@link ArenaTransferables}
313
+ */
314
+ static toTransferableArenaObject(arena) {
315
+ return [arena.exportProperties(), arena.exportTransferables()];
316
+ }
317
+ /**
318
+ * Create an arena from the objects produced by {@link Arena.toTransferableArenaObject}. The column buffers are
319
+ * used as is (zero copy): the typed arrays are views on the given buffers.
320
+ *
321
+ * @param properties arena properties
322
+ * @param transferables column buffers
323
+ * @returns an `Arena` or an `AstArena` depending on the class the method is called on
324
+ */
325
+ static fromTransferableArenaObjects(properties, transferables) {
326
+ const arena = new this(0);
327
+ arena.importProperties(properties, transferables);
328
+ return arena;
329
+ }
330
+ /**
331
+ * true when the column buffers have been transferred to another thread: the arena can no longer be used
332
+ */
333
+ get transferred() {
334
+ return this.dataTypes.length == 0 && this.current > 0;
335
+ }
336
+ /**
337
+ * structured-cloneable properties of the arena
338
+ */
339
+ exportProperties() {
340
+ return {
341
+ kind: "Arena",
342
+ current: this.current,
343
+ strings: this.strings,
344
+ errors: [...this.errors.entries()],
345
+ };
346
+ }
347
+ /**
348
+ * column buffers, in the order of {@link arenaColumns}. the `spans` buffer is shared with the `spans32` view
349
+ */
350
+ exportTransferables() {
351
+ const buffers = [];
352
+ for (const column of arenaColumns) {
353
+ const array = this[column];
354
+ // the columns always own their buffer: no offset or partial view
355
+ buffers.push(array.buffer);
356
+ }
357
+ return buffers;
358
+ }
359
+ /**
360
+ * initialize the arena from exported properties and column buffers
361
+ * @param properties
362
+ * @param transferables
363
+ */
364
+ importProperties(properties, transferables) {
365
+ if (transferables.length != arenaColumns.length) {
366
+ throw new TypeError(`expected ${arenaColumns.length} column buffers, got ${transferables.length}`);
367
+ }
368
+ for (let i = 0; i < arenaColumns.length; i++) {
369
+ const column = arenaColumns[i];
370
+ // @ts-ignore
371
+ this[column] = new arenaColumnTypes[column](transferables[i]);
372
+ }
373
+ this.spans32 = new Uint32Array(this.spans.buffer);
374
+ this.current = properties.current;
375
+ this.strings = properties.strings.slice();
376
+ this.stringIds = new Map(this.strings.map((str, index) => [str, index]));
377
+ this.errors = new Map(properties.errors);
378
+ }
379
+ allocate() {
380
+ let id = this.freeList;
381
+ if (id != 0) {
382
+ // reuse a recycled node: its record is already zeroed, except the free list link
383
+ this.freeList = this.nextSibling[id];
384
+ this.nextSibling[id] = 0;
385
+ return id;
386
+ }
387
+ id = ++this.current;
388
+ if (id >= this.dataTypes.length) {
389
+ this.resize(this.dataTypes.length * 2);
390
+ }
391
+ return id;
392
+ }
393
+ /**
394
+ * recycle a detached leaf node (no parent, no children, no tokens) that is no longer referenced:
395
+ * its id is reused by the next allocation. the record is zeroed, so a stale reference reads an empty node
396
+ * @param id
397
+ */
398
+ recycle(id) {
399
+ this.dataTypes[id] = 0;
400
+ this.name[id] = 0;
401
+ this.stringValue[id] = 0;
402
+ this.numericValue[id] = 0;
403
+ this.unit[id] = 0;
404
+ this.flags[id] = 0;
405
+ this.colorType[id] = 0;
406
+ this.spans[id] = 0n;
407
+ if (this.errors.size > 0) {
408
+ this.errors.delete(id);
409
+ }
410
+ this.nextSibling[id] = this.freeList;
411
+ this.freeList = id;
412
+ }
413
+ /**
414
+ * Interns a string and returns its unique ID. If the string has already been interned, it returns the existing ID.
415
+ * @param str
416
+ * @returns
417
+ */
418
+ internString(str) {
419
+ let id = this.stringIds.get(str);
420
+ if (id != null) {
421
+ return id;
422
+ }
423
+ id = this.strings.length;
424
+ this.stringIds.set(str, id);
425
+ this.strings.push(str);
426
+ return id;
427
+ }
428
+ /**
429
+ * set node data for a given id. The first argument is the id, the second is the type, the third is the string value, the fourth is the numeric value, and the fifth is the unit.
430
+ * @param id
431
+ * @param args
432
+ */
433
+ set(id, ...args) {
434
+ this.dataTypes[id] = args[0];
435
+ if (args.length > 1) {
436
+ // 0 is null string, so we can use it to indicate that there is no string value for this node.
437
+ this.stringValue[id] = args[1];
438
+ }
439
+ if (args.length > 2) {
440
+ this.numericValue[id] = args[2];
441
+ }
442
+ if (args.length > 3) {
443
+ this.unit[id] = args[3];
444
+ }
445
+ }
446
+ getType(id) {
447
+ return this.dataTypes[id];
448
+ }
449
+ /**
450
+ * type of a node or a token. null when the id is null
451
+ * @param id
452
+ */
453
+ typeOf(id) {
454
+ return id == null ? null : this.dataTypes[id];
455
+ }
456
+ setType(id, type) {
457
+ this.dataTypes[id] = type;
458
+ }
459
+ setName(id, nameId) {
460
+ this.name[id] = nameId;
461
+ }
462
+ getName(id) {
463
+ return this.strings[this.name[id]] ?? null;
464
+ }
465
+ setValue(id, valueId) {
466
+ this.stringValue[id] = valueId;
467
+ }
468
+ getValue(id) {
469
+ return this.strings[this.stringValue[id]] ?? null;
470
+ }
471
+ setNumericValue(id, numericValue) {
472
+ this.numericValue[id] = numericValue;
473
+ }
474
+ setUnit(id, unit) {
475
+ this.unit[id] = unit;
476
+ }
477
+ getUnit(id) {
478
+ return this.strings[this.unit[id]] ?? null;
479
+ }
480
+ getNumericValue(id) {
481
+ return this.numericValue[id];
482
+ }
483
+ setParent(id, parentId) {
484
+ this.parents[id] = parentId;
485
+ }
486
+ /**
487
+ * first child of a node. 0 when the node has no children
488
+ * @param id
489
+ */
490
+ getFirstChild(id) {
491
+ return this.firstChild[id];
492
+ }
493
+ /**
494
+ * next sibling of a node or of a token. 0 for the last node / token of the list
495
+ * @param id
496
+ */
497
+ getNextSibling(id) {
498
+ return this.nextSibling[id];
499
+ }
500
+ /**
501
+ * previous sibling of a node or of a token. 0 for the first node / token of the list
502
+ * @param id
503
+ */
504
+ getPreviousSibling(id) {
505
+ return this.previousSibling[id];
506
+ }
507
+ /**
508
+ * first token of the token list of a node or of a token (declaration value, selector / prelude tokens, function
509
+ * arguments). 0 when the list is empty
510
+ * @param id
511
+ */
512
+ getFirstToken(id) {
513
+ return this.firstToken[id];
514
+ }
515
+ /**
516
+ * last token of the token list of a node or of a token. 0 when the list is empty
517
+ * @param id
518
+ */
519
+ getLastToken(id) {
520
+ return this.lastToken[id];
521
+ }
522
+ /**
523
+ * number of nodes the columns can hold before the arena grows. see {@link getLastId} for the last allocated id
524
+ */
525
+ getCapacity() {
526
+ return this.dataTypes.length;
527
+ }
528
+ /**
529
+ * last allocated node id. the ids of the arena are in the range 1 ... getLastId(), the detached nodes included
530
+ */
531
+ getLastId() {
532
+ return this.current;
533
+ }
534
+ /**
535
+ * number of interned strings
536
+ */
537
+ getStringCount() {
538
+ return this.strings.length;
539
+ }
540
+ /**
541
+ * replace the first child
542
+ * @param id
543
+ * @param firstChildId
544
+ */
545
+ setFirstChild(id, firstChildId) {
546
+ const firstChild = this.firstChild[id];
547
+ if (firstChild == firstChildId) {
548
+ return;
549
+ }
550
+ this.detach(firstChildId);
551
+ if (firstChild != 0) {
552
+ this.#insertBefore(id, firstChild, firstChildId);
553
+ this.detach(firstChild);
554
+ }
555
+ else {
556
+ // inlined: this.appendChildren(id, firstChildId)
557
+ this.appendChildList(id, [firstChildId]);
558
+ }
559
+ }
560
+ getLastChild(id) {
561
+ return this.lastChild[id];
562
+ }
563
+ /**
564
+ * replace the last child
565
+ * @param id
566
+ * @param lastChildId
567
+ */
568
+ setLastChild(id, lastChildId) {
569
+ const lastChild = this.lastChild[id];
570
+ if (lastChild == lastChildId) {
571
+ return;
572
+ }
573
+ this.detach(lastChildId);
574
+ if (lastChild != 0) {
575
+ this.detach(lastChild);
576
+ }
577
+ // inlined: this.appendChildren(id, lastChildId)
578
+ this.appendChildList(id, [lastChildId]);
579
+ }
580
+ /**
581
+ * insert a node after another one
582
+ * @param id
583
+ * @param nextSiblingId
584
+ */
585
+ setNextSibling(id, nextSiblingId) {
586
+ if (id == nextSiblingId) {
587
+ return;
588
+ }
589
+ this.detach(nextSiblingId);
590
+ const parent = this.parents[id];
591
+ const next = this.nextSibling[id];
592
+ this.nextSibling[nextSiblingId] = next;
593
+ this.previousSibling[nextSiblingId] = id;
594
+ this.nextSibling[id] = nextSiblingId;
595
+ this.parents[nextSiblingId] = parent;
596
+ if (next != 0) {
597
+ this.previousSibling[next] = nextSiblingId;
598
+ }
599
+ else if (this.lastChild[parent] == id) {
600
+ this.lastChild[parent] = nextSiblingId;
601
+ }
602
+ else if (this.lastToken[parent] == id) {
603
+ this.lastToken[parent] = nextSiblingId;
604
+ }
605
+ }
606
+ /**
607
+ * insert a node before another one
608
+ * @param id
609
+ * @param previousSiblingId
610
+ */
611
+ setPreviousSibling(id, previousSiblingId) {
612
+ if (id == previousSiblingId) {
613
+ return;
614
+ }
615
+ this.detach(previousSiblingId);
616
+ this.#insertBefore(this.parents[id], id, previousSiblingId);
617
+ }
618
+ /**
619
+ * replace the first token
620
+ * @param id
621
+ * @param firstTokenId
622
+ */
623
+ setFirstToken(id, firstTokenId) {
624
+ const firstToken = this.firstToken[id];
625
+ if (firstToken == firstTokenId) {
626
+ return;
627
+ }
628
+ this.detach(firstTokenId);
629
+ if (firstToken != 0) {
630
+ this.#insertBefore(id, firstToken, firstTokenId);
631
+ this.detach(firstToken);
632
+ }
633
+ else {
634
+ // inlined: this.appendTokens(id, firstTokenId)
635
+ this.appendTokenList(id, [firstTokenId]);
636
+ }
637
+ }
638
+ setColorType(id, colorType) {
639
+ this.colorType[id] = colorType;
640
+ }
641
+ getColorType(id) {
642
+ return this.colorType[id];
643
+ }
644
+ setFlags(id, flags) {
645
+ this.flags[id] = flags;
646
+ }
647
+ getFlags(id) {
648
+ return this.flags[id];
649
+ }
650
+ hasFlags(id, flag) {
651
+ return (this.flags[id] & flag) == flag;
652
+ }
653
+ getChildAt(id, index) {
654
+ let child = this.firstChild[id];
655
+ while (index > 0 && child != 0) {
656
+ child = this.nextSibling[child];
657
+ index--;
658
+ }
659
+ return child == 0 ? null : child;
660
+ }
661
+ /**
662
+ * token at the given position of the token list
663
+ * @param id
664
+ * @param index
665
+ */
666
+ getTokenAt(id, index) {
667
+ let token = this.firstToken[id];
668
+ while (index > 0 && token != 0) {
669
+ token = this.nextSibling[token];
670
+ index--;
671
+ }
672
+ return token == 0 ? null : token;
673
+ }
674
+ /**
675
+ * replace the child at the given index. the node is appended when the index is out of range
676
+ * @param id
677
+ * @param index
678
+ * @param child
679
+ */
680
+ setChildAt(id, index, child) {
681
+ const current = this.getChildAt(id, index);
682
+ if (current == child) {
683
+ return;
684
+ }
685
+ this.detach(child);
686
+ if (current == null) {
687
+ // inlined: this.appendChildren(id, child)
688
+ this.appendChildList(id, [child]);
689
+ return;
690
+ }
691
+ this.#insertBefore(id, current, child);
692
+ this.detach(current);
693
+ }
694
+ /**
695
+ * link a node before a reference node of the given parent
696
+ * @param parent
697
+ * @param reference
698
+ * @param node
699
+ */
700
+ #insertBefore(parent, reference, node) {
701
+ const previous = this.previousSibling[reference];
702
+ this.previousSibling[node] = previous;
703
+ this.nextSibling[node] = reference;
704
+ this.previousSibling[reference] = node;
705
+ this.parents[node] = parent;
706
+ if (previous != 0) {
707
+ this.nextSibling[previous] = node;
708
+ }
709
+ else if (this.firstChild[parent] == reference) {
710
+ this.firstChild[parent] = node;
711
+ }
712
+ else if (this.firstToken[parent] == reference) {
713
+ this.firstToken[parent] = node;
714
+ }
715
+ }
716
+ // ---- structured token fields ---------------------------------------------------------
717
+ /**
718
+ * list node holding the tokens of a structured token field. created when missing
719
+ * @param id
720
+ * @param field
721
+ */
722
+ fieldList(id, field) {
723
+ let child = this.firstChild[id];
724
+ let index = 0;
725
+ while (index < field) {
726
+ if (child == 0) {
727
+ break;
728
+ }
729
+ child = this.nextSibling[child];
730
+ index++;
731
+ }
732
+ if (child != 0) {
733
+ return child;
734
+ }
735
+ // create the missing slots
736
+ let count = this.childCount(id);
737
+ while (count <= field) {
738
+ child = this.allocate();
739
+ this.dataTypes[child] = EnumToken.ListTokenType;
740
+ // inlined: this.appendChildren(id, child)
741
+ this.appendChildList(id, [child]);
742
+ count++;
743
+ }
744
+ return child;
745
+ }
746
+ /**
747
+ * true if the field exists and is not empty
748
+ * @param id
749
+ * @param field
750
+ */
751
+ hasField(id, field) {
752
+ const list = this.getChildAt(id, field);
753
+ return list != null && this.firstToken[list] != 0;
754
+ }
755
+ /**
756
+ * first token of a structured token field (single token fields: `l` and `r` of binary expressions, `op`, ...)
757
+ * @param id
758
+ * @param field
759
+ */
760
+ field(id, field) {
761
+ const list = this.getChildAt(id, field);
762
+ return list == null ? 0 : this.firstToken[list];
763
+ }
764
+ /**
765
+ * tokens of a structured token field
766
+ * @param id
767
+ * @param field
768
+ */
769
+ fieldTokens(id, field) {
770
+ const list = this.getChildAt(id, field);
771
+ return list == null ? [] : this.tokens(list);
772
+ }
773
+ /**
774
+ * set the tokens of a structured token field
775
+ * @param id
776
+ * @param field
777
+ * @param tokens
778
+ */
779
+ setField(id, field, ...tokens) {
780
+ this.setTokenList(this.fieldList(id, field), tokens);
781
+ }
782
+ /**
783
+ * append tokens to a structured token field
784
+ * @param id
785
+ * @param field
786
+ * @param tokens
787
+ */
788
+ appendField(id, field, ...tokens) {
789
+ this.appendTokenList(this.fieldList(id, field), tokens);
790
+ }
791
+ setLeft(id, ...children) {
792
+ // inlined: this.setField(id, TokenField.L, ...children)
793
+ this.setTokenList(this.fieldList(id, TokenField.L), children);
794
+ }
795
+ getLeft(id) {
796
+ return this.getChildAt(id, TokenField.L) == null ? null : this.fieldTokens(id, TokenField.L);
797
+ }
798
+ setRight(id, ...rightId) {
799
+ // inlined: this.setField(id, TokenField.R, ...(rightId == null || rightId[0] == null ? [] : (rightId as number[])))
800
+ this.setTokenList(this.fieldList(id, TokenField.R), (rightId == null || rightId[0] == null ? [] : rightId));
801
+ }
802
+ getRight(id) {
803
+ return this.getChildAt(id, TokenField.R) == null ? null : this.fieldTokens(id, TokenField.R);
804
+ }
805
+ setOp(id, opId) {
806
+ // inlined: this.setField(id, TokenField.Op, opId)
807
+ this.setTokenList(this.fieldList(id, TokenField.Op), [opId]);
808
+ }
809
+ getOp(id) {
810
+ return this.field(id, TokenField.Op);
811
+ }
812
+ setOp2(id, op2Id) {
813
+ // inlined: this.setField(id, TokenField.Op2, op2Id)
814
+ this.setTokenList(this.fieldList(id, TokenField.Op2), [op2Id]);
815
+ }
816
+ getOp2(id) {
817
+ return this.field(id, TokenField.Op2);
818
+ }
819
+ // ---- spans ---------------------------------------------------------------------
820
+ setSpan(id, sourceId, start, end) {
821
+ if (littleEndian) {
822
+ const index = id << 1;
823
+ this.spans32[index] = ((end & 0xfffffff) | ((start & 0xf) << 28)) >>> 0;
824
+ this.spans32[index + 1] = (((start >>> 4) & 0xffffff) | ((sourceId & 0xff) << 24)) >>> 0;
825
+ return;
826
+ }
827
+ this.spans[id] =
828
+ (BigInt(sourceId & 0xff) << 56n) | (BigInt(start & 0xfffffff) << 28n) | BigInt(end & 0xfffffff);
829
+ }
830
+ /**
831
+ * copy the packed location of a node
832
+ * @param target
833
+ * @param source
834
+ */
835
+ copySpan(target, source) {
836
+ const t = target << 1;
837
+ const s = source << 1;
838
+ this.spans32[t] = this.spans32[s];
839
+ this.spans32[t + 1] = this.spans32[s + 1];
840
+ }
841
+ getSourceId(id) {
842
+ if (littleEndian) {
843
+ return this.spans32[(id << 1) + 1] >>> 24;
844
+ }
845
+ return Number((this.spans[id] >> 56n) & 0xffn);
846
+ }
847
+ getSpanStart(id) {
848
+ if (littleEndian) {
849
+ const index = id << 1;
850
+ return ((this.spans32[index + 1] & 0xffffff) << 4) | (this.spans32[index] >>> 28);
851
+ }
852
+ return Number((this.spans[id] >> 28n) & 0xfffffffn);
853
+ }
854
+ setSpandStart(id, start) {
855
+ this.setSpan(id, this.getSourceId(id), start, this.getSpanEnd(id));
856
+ }
857
+ getSpanEnd(id) {
858
+ if (littleEndian) {
859
+ return this.spans32[id << 1] & 0xfffffff;
860
+ }
861
+ return Number(this.spans[id] & 0xfffffffn);
862
+ }
863
+ setSpanEnd(id, end) {
864
+ this.setSpan(id, this.getSourceId(id), this.getSpanStart(id), end);
865
+ }
866
+ getParent(id) {
867
+ return this.parents[id];
868
+ }
869
+ resolveString(id) {
870
+ return this.strings[id];
871
+ }
872
+ /**
873
+ * detach a node from its parent
874
+ * @param id
875
+ */
876
+ detach(id) {
877
+ if (id == 0 || this.parents[id] == 0) {
878
+ return;
879
+ }
880
+ const parent = this.parents[id];
881
+ const next = this.nextSibling[id];
882
+ const previous = this.previousSibling[id];
883
+ if (previous != 0) {
884
+ this.nextSibling[previous] = next;
885
+ }
886
+ else if (this.firstChild[parent] == id) {
887
+ this.firstChild[parent] = next;
888
+ }
889
+ else if (this.firstToken[parent] == id) {
890
+ this.firstToken[parent] = next;
891
+ }
892
+ if (next != 0) {
893
+ this.previousSibling[next] = previous;
894
+ }
895
+ else if (this.lastChild[parent] == id) {
896
+ this.lastChild[parent] = previous;
897
+ }
898
+ else if (this.lastToken[parent] == id) {
899
+ this.lastToken[parent] = previous;
900
+ }
901
+ this.nextSibling[id] = 0;
902
+ this.previousSibling[id] = 0;
903
+ this.parents[id] = 0;
904
+ }
905
+ /**
906
+ * Walk the ast nodes: the node and its descendants, in document order. The iterator returns node ids (and value
907
+ * tokens when `attributes` is set). The children of a node are read when the next node is requested: the current
908
+ * node can be modified or detached by the caller.
909
+ *
910
+ * ```ts
911
+ * import {EnumToken, transform, WalkerOptionEnum} from '@tbela99/css-parser';
912
+ *
913
+ * const result = await transform(css);
914
+ * const arena = result.arena;
915
+ *
916
+ * for (const node of arena.walk(result.ast)) {
917
+ *
918
+ * console.log(EnumToken[arena.getType(node)], arena.getParent(node));
919
+ * }
920
+ *
921
+ * // the filter controls the walk, see WalkerOptionEnum
922
+ * function filter(arena: AstArena, node: number) {
923
+ *
924
+ * if (arena.getType(node) == EnumToken.RuleNodeType && arena.getSelector(node).includes('html')) {
925
+ *
926
+ * // skip the children of the current node
927
+ * return WalkerOptionEnum.IgnoreChildren;
928
+ * }
929
+ * }
930
+ *
931
+ * for (const node of arena.walk(result.ast, filter)) {
932
+ *
933
+ * console.log(EnumToken[arena.getType(node)]);
934
+ * }
935
+ * ```
936
+ *
937
+ * @param node initial node id (or value token)
938
+ * @param filter filter function or walker options
939
+ * @param reverse walk in reverse order
940
+ */
941
+ walk(node, filter, reverse) {
942
+ return new NodeWalker(this, node, filter, reverse);
943
+ }
944
+ /**
945
+ * Walk value tokens and their descendants (function arguments, structured token fields, ...), in document
946
+ * order. The iterator returns token ids. The children of a token are read when the next token is requested: the
947
+ * current token can be modified or replaced by the caller.
948
+ *
949
+ * ```ts
950
+ * import {EnumToken, transform} from '@tbela99/css-parser';
951
+ *
952
+ * const css = `
953
+ * body { color: color(from var(--base-color) display-p3 r calc(g + 0.24) calc(b + 0.15)); }
954
+ * `;
955
+ *
956
+ * const result = await transform(css);
957
+ * const arena = result.arena;
958
+ * const declaration = arena.getFirstChild(arena.getFirstChild(result.ast));
959
+ *
960
+ * // walk the value tokens of the declaration in reverse order
961
+ * for (const value of arena.walkValues(declaration, null, true)) {
962
+ *
963
+ * console.error([EnumToken[arena.getType(value)], arena.getValue(value)]);
964
+ * }
965
+ * ```
966
+ *
967
+ * @param tokens token ids, or a node / token id: its value tokens are walked
968
+ * @param filter filter function, called with the arena, the token id and the event, or filter options
969
+ * @param reverse walk in reverse order
970
+ */
971
+ walkValues(tokens, filter, reverse) {
972
+ return new ValueWalker(this, tokens, filter, reverse);
973
+ }
974
+ /**
975
+ * call the visitor for the tokens and their children, in the order of {@link walkValues} (the children of a
976
+ * token are read after the visitor returns). no iterator or stack is created: use it when the visitor is not a
977
+ * closure
978
+ * @param tokens
979
+ * @param visitor
980
+ * @internal
981
+ */
982
+ visitValues(tokens, visitor) {
983
+ const stack = visitStack;
984
+ const base = visitTop;
985
+ let top = base;
986
+ for (let i = tokens.length - 1; i >= 0; i--) {
987
+ stack[top++] = tokens[i];
988
+ }
989
+ try {
990
+ while (top > base) {
991
+ const value = stack[--top];
992
+ // nested calls use the entries above top
993
+ visitTop = top;
994
+ visitor(this, value);
995
+ // the children, in reverse order
996
+ const first = top;
997
+ let token = this.firstToken[value];
998
+ while (token != 0) {
999
+ stack[top++] = token;
1000
+ token = this.nextSibling[token];
1001
+ }
1002
+ if ((this.flags[value] & EnumAstNodeStatus.HasChildren) == 0) {
1003
+ let child = this.firstChild[value];
1004
+ while (child != 0) {
1005
+ if (this.dataTypes[child] == EnumToken.ListTokenType) {
1006
+ token = this.firstToken[child];
1007
+ while (token != 0) {
1008
+ stack[top++] = token;
1009
+ token = this.nextSibling[token];
1010
+ }
1011
+ }
1012
+ else {
1013
+ stack[top++] = child;
1014
+ }
1015
+ child = this.nextSibling[child];
1016
+ }
1017
+ }
1018
+ for (let i = first, j = top - 1; i < j; i++, j--) {
1019
+ const swap = stack[i];
1020
+ stack[i] = stack[j];
1021
+ stack[j] = swap;
1022
+ }
1023
+ }
1024
+ }
1025
+ finally {
1026
+ visitTop = base;
1027
+ }
1028
+ }
1029
+ /**
1030
+ * parent of a value token: the node or the token that owns the token list, or the structured token that owns the
1031
+ * field (the field list token is skipped). 0 when the token is detached
1032
+ * @param id
1033
+ */
1034
+ getValueParent(id) {
1035
+ const parent = this.parents[id];
1036
+ return parent != 0 && this.dataTypes[parent] == EnumToken.ListTokenType ? this.parents[parent] : parent;
1037
+ }
1038
+ /**
1039
+ * node that owns a value token: the declaration, the rule or the at-rule. 0 when the token is detached
1040
+ * @param id
1041
+ */
1042
+ getValueOwner(id) {
1043
+ let parent = this.parents[id];
1044
+ while (parent != 0 && (this.flags[parent] & (EnumAstNodeStatus.HasChildren | EnumAstNodeStatus.HasValues)) == 0) {
1045
+ parent = this.parents[parent];
1046
+ }
1047
+ return parent;
1048
+ }
1049
+ /**
1050
+ * Search the ast subtree and return the first match, in document order
1051
+ *
1052
+ * ```ts
1053
+ * // find the first declaration which name is 'aspect-ratio'
1054
+ * import { EnumToken, transform } from "@tbela99/css-parser";
1055
+ *
1056
+ * const result = await transform(css);
1057
+ * const arena = result.arena;
1058
+ *
1059
+ * const node = arena.find(result.ast, (arena, node) =>
1060
+ * arena.getType(node) == EnumToken.DeclarationNodeType && arena.getName(node) == 'aspect-ratio');
1061
+ *
1062
+ * console.log(node == null ? null : arena.toObject(node));
1063
+ * ```
1064
+ *
1065
+ * @param node node id
1066
+ * @param matcher called with the arena and the node id
1067
+ * @returns the node id or null
1068
+ */
1069
+ find(node, matcher) {
1070
+ const walker = new NodeWalker(this, node);
1071
+ for (let r = walker.next(); !r.done; r = walker.next()) {
1072
+ if (matcher(this, r.value)) {
1073
+ walker.return();
1074
+ return r.value;
1075
+ }
1076
+ }
1077
+ return null;
1078
+ }
1079
+ /**
1080
+ * Search the ast subtree and return all matches, in document order
1081
+ *
1082
+ * @param node node id
1083
+ * @param matcher called with the arena and the node id
1084
+ */
1085
+ findAll(node, matcher) {
1086
+ const result = [];
1087
+ const walker = new NodeWalker(this, node);
1088
+ for (let r = walker.next(); !r.done; r = walker.next()) {
1089
+ if (matcher(this, r.value)) {
1090
+ result.push(r.value);
1091
+ }
1092
+ }
1093
+ return result;
1094
+ }
1095
+ /**
1096
+ * Search the ast subtree in reverse order and return the first match (the last node in document order)
1097
+ *
1098
+ * @param node node id
1099
+ * @param matcher called with the arena and the node id
1100
+ */
1101
+ findLast(node, matcher) {
1102
+ const walker = new NodeWalker(this, node, null, true);
1103
+ for (let r = walker.next(); !r.done; r = walker.next()) {
1104
+ if (matcher(this, r.value)) {
1105
+ walker.return();
1106
+ return r.value;
1107
+ }
1108
+ }
1109
+ return null;
1110
+ }
1111
+ /**
1112
+ * Search the value tokens of the ast subtree and return the first match: the node that owns the token and the
1113
+ * token
1114
+ *
1115
+ * ```ts
1116
+ * // find the first node which contains the length token '30px'
1117
+ * import { EnumToken, transform } from "@tbela99/css-parser";
1118
+ *
1119
+ * const result = await transform(css);
1120
+ * const {node, value} = result.arena.findByValue(result.ast, (arena, value) =>
1121
+ * arena.getType(value) == EnumToken.LengthTokenType && arena.getNumericValue(value) == 30 && arena.getUnit(value) == 'px') ?? {};
1122
+ * ```
1123
+ *
1124
+ * @param node node id
1125
+ * @param matcher called with the arena and the token id
1126
+ */
1127
+ findByValue(node, matcher) {
1128
+ const walker = new NodeWalker(this, node);
1129
+ for (let r = walker.next(); !r.done; r = walker.next()) {
1130
+ const current = r.value;
1131
+ if (this.firstToken[current] == 0) {
1132
+ continue;
1133
+ }
1134
+ const values = new ValueWalker(this, this.tokens(current));
1135
+ for (let v = values.next(); !v.done; v = values.next()) {
1136
+ if (matcher(this, v.value)) {
1137
+ walker.return();
1138
+ return { node: current, value: v.value };
1139
+ }
1140
+ }
1141
+ }
1142
+ return null;
1143
+ }
1144
+ /**
1145
+ * Search a token and its descendants, or the value tokens of a node and their descendants, and return the first
1146
+ * match
1147
+ *
1148
+ * @param node node or token id
1149
+ * @param matcher called with the arena and the token id
1150
+ * @returns the token id or null
1151
+ */
1152
+ findValue(node, matcher) {
1153
+ if (node == null || node == 0) {
1154
+ return null;
1155
+ }
1156
+ if ((this.flags[node] & (EnumAstNodeStatus.HasChildren | EnumAstNodeStatus.HasValues)) == 0) {
1157
+ // token: the token itself is tested first
1158
+ if (matcher(this, node)) {
1159
+ return node;
1160
+ }
1161
+ }
1162
+ // prelude tokens, declaration values or token children
1163
+ const values = new ValueWalker(this, node);
1164
+ for (let v = values.next(); !v.done; v = values.next()) {
1165
+ if (matcher(this, v.value)) {
1166
+ values.return();
1167
+ return v.value;
1168
+ }
1169
+ }
1170
+ return null;
1171
+ }
1172
+ /**
1173
+ * direct value tokens of a node or a token: the token list, then the tokens of the structured fields
1174
+ * and the child tokens (fractions, unary expressions)
1175
+ * @param id
1176
+ */
1177
+ subTokens(id) {
1178
+ const result = [];
1179
+ let token = this.firstToken[id];
1180
+ while (token != 0) {
1181
+ result.push(token);
1182
+ token = this.nextSibling[token];
1183
+ }
1184
+ if (this.flags[id] & EnumAstNodeStatus.HasChildren) {
1185
+ // ast node: the children are nodes
1186
+ return result;
1187
+ }
1188
+ let child = this.firstChild[id];
1189
+ while (child != 0) {
1190
+ if (this.dataTypes[child] == EnumToken.ListTokenType) {
1191
+ token = this.firstToken[child];
1192
+ while (token != 0) {
1193
+ result.push(token);
1194
+ token = this.nextSibling[token];
1195
+ }
1196
+ }
1197
+ else {
1198
+ result.push(child);
1199
+ }
1200
+ child = this.nextSibling[child];
1201
+ }
1202
+ return result;
1203
+ }
1204
+ findChild(id, predicate) {
1205
+ let child = this.firstChild[id];
1206
+ while (child != 0) {
1207
+ if (predicate(child)) {
1208
+ return child;
1209
+ }
1210
+ child = this.nextSibling[child];
1211
+ }
1212
+ return null;
1213
+ }
1214
+ /**
1215
+ * find a token in the token list
1216
+ * @param id
1217
+ * @param predicate called with the arena and the token id
1218
+ */
1219
+ findToken(id, predicate) {
1220
+ let token = this.firstToken[id];
1221
+ while (token != 0) {
1222
+ if (predicate(this, token)) {
1223
+ return token;
1224
+ }
1225
+ token = this.nextSibling[token];
1226
+ }
1227
+ return null;
1228
+ }
1229
+ /**
1230
+ * the children of the parent of a node, the node included
1231
+ * @param id
1232
+ * @param filter called with the arena and the node id
1233
+ */
1234
+ siblings(id, filter) {
1235
+ let siblings = [];
1236
+ let child = this.firstChild[this.parents[id]];
1237
+ while (child != 0) {
1238
+ if (filter == null || filter(this, child)) {
1239
+ siblings.push(child);
1240
+ }
1241
+ child = this.nextSibling[child];
1242
+ }
1243
+ return siblings;
1244
+ }
1245
+ /**
1246
+ * child node ids
1247
+ * @param id
1248
+ * @param filter called with the arena and the node id
1249
+ */
1250
+ children(id, filter) {
1251
+ let children = [];
1252
+ let child = this.firstChild[id];
1253
+ while (child != 0) {
1254
+ if (filter != null && !filter(this, child)) {
1255
+ child = this.nextSibling[child];
1256
+ continue;
1257
+ }
1258
+ children.push(child);
1259
+ child = this.nextSibling[child];
1260
+ }
1261
+ return children;
1262
+ }
1263
+ /**
1264
+ * token ids of the token list: the declaration values, the selector / prelude tokens, the function arguments
1265
+ * @param id
1266
+ * @param filter called with the arena and the token id
1267
+ */
1268
+ tokens(id, filter) {
1269
+ let tokens = [];
1270
+ let token = this.firstToken[id];
1271
+ while (token != 0) {
1272
+ if (filter != null && !filter(this, token)) {
1273
+ token = this.nextSibling[token];
1274
+ continue;
1275
+ }
1276
+ tokens.push(token);
1277
+ token = this.nextSibling[token];
1278
+ }
1279
+ return tokens;
1280
+ }
1281
+ /**
1282
+ * number of tokens in the token list
1283
+ * @param id
1284
+ */
1285
+ tokenCount(id) {
1286
+ let count = 0;
1287
+ let token = this.firstToken[id];
1288
+ while (token != 0) {
1289
+ count++;
1290
+ token = this.nextSibling[token];
1291
+ }
1292
+ return count;
1293
+ }
1294
+ setChildren(id, ...children) {
1295
+ this.setChildList(id, children);
1296
+ }
1297
+ /**
1298
+ * replace the children. same as {@link setChildren} with an array
1299
+ * @param id
1300
+ * @param children
1301
+ */
1302
+ setChildList(id, children) {
1303
+ let child = this.firstChild[id];
1304
+ while (child != 0) {
1305
+ const next = this.nextSibling[child];
1306
+ this.nextSibling[child] = 0;
1307
+ this.previousSibling[child] = 0;
1308
+ this.parents[child] = 0;
1309
+ child = next;
1310
+ }
1311
+ this.firstChild[id] = 0;
1312
+ this.lastChild[id] = 0;
1313
+ this.appendChildList(id, children);
1314
+ }
1315
+ setTokens(id, ...children) {
1316
+ this.setTokenList(id, children);
1317
+ }
1318
+ /**
1319
+ * replace the token list. same as {@link setTokens} with an array
1320
+ * @param id
1321
+ * @param tokens
1322
+ */
1323
+ setTokenList(id, tokens) {
1324
+ let token = this.firstToken[id];
1325
+ while (token != 0) {
1326
+ const next = this.nextSibling[token];
1327
+ this.nextSibling[token] = 0;
1328
+ this.previousSibling[token] = 0;
1329
+ this.parents[token] = 0;
1330
+ token = next;
1331
+ }
1332
+ this.firstToken[id] = 0;
1333
+ this.lastToken[id] = 0;
1334
+ this.appendTokenList(id, tokens);
1335
+ }
1336
+ /**
1337
+ * move the children of a node into another node, in order
1338
+ * @param from
1339
+ * @param to
1340
+ * @param before the children are inserted before this child of `to`. they are appended when 0
1341
+ */
1342
+ moveChildren(from, to, before = 0) {
1343
+ if (from == to) {
1344
+ return;
1345
+ }
1346
+ let child = this.firstChild[from];
1347
+ while (child != 0) {
1348
+ const next = this.nextSibling[child];
1349
+ this.detach(child);
1350
+ if (before == 0) {
1351
+ this.appendChild(to, child);
1352
+ }
1353
+ else {
1354
+ this.#insertBefore(to, before, child);
1355
+ }
1356
+ child = next;
1357
+ }
1358
+ }
1359
+ appendChildren(id, ...children) {
1360
+ this.appendChildList(id, children);
1361
+ }
1362
+ /**
1363
+ * append children. same as {@link appendChildren} with an array
1364
+ * @param id
1365
+ * @param children
1366
+ */
1367
+ appendChildList(id, children) {
1368
+ if (children.length == 0) {
1369
+ return;
1370
+ }
1371
+ let lastChild;
1372
+ for (let i = 0; i < children.length; i++) {
1373
+ const child = children[i];
1374
+ if (child == id || child == 0) {
1375
+ continue;
1376
+ }
1377
+ // the child may already be the last child: detach before reading the last child
1378
+ this.detach(child);
1379
+ lastChild = this.lastChild[id];
1380
+ if (lastChild == 0) {
1381
+ this.firstChild[id] = child;
1382
+ }
1383
+ else {
1384
+ this.nextSibling[lastChild] = child;
1385
+ }
1386
+ this.previousSibling[child] = lastChild;
1387
+ this.nextSibling[child] = 0;
1388
+ this.parents[child] = id;
1389
+ this.lastChild[id] = child;
1390
+ }
1391
+ }
1392
+ appendTokens(id, ...children) {
1393
+ this.appendTokenList(id, children);
1394
+ }
1395
+ /**
1396
+ * append tokens. same as {@link appendTokens} with an array
1397
+ * @param id
1398
+ * @param children
1399
+ */
1400
+ appendTokenList(id, children) {
1401
+ if (children.length == 0) {
1402
+ return;
1403
+ }
1404
+ let lastToken;
1405
+ for (let i = 0; i < children.length; i++) {
1406
+ const token = children[i];
1407
+ if (token == id || token == 0) {
1408
+ continue;
1409
+ }
1410
+ // the token may already be the last token: detach before reading the last token
1411
+ this.detach(token);
1412
+ lastToken = this.lastToken[id];
1413
+ if (lastToken == 0) {
1414
+ this.firstToken[id] = token;
1415
+ }
1416
+ else {
1417
+ this.nextSibling[lastToken] = token;
1418
+ }
1419
+ this.previousSibling[token] = lastToken;
1420
+ this.nextSibling[token] = 0;
1421
+ this.parents[token] = id;
1422
+ this.lastToken[id] = token;
1423
+ }
1424
+ }
1425
+ /**
1426
+ * append a single child node. faster than appendChildren()
1427
+ * @param id
1428
+ * @param child
1429
+ */
1430
+ appendChild(id, child) {
1431
+ if (child == id || child == 0) {
1432
+ return;
1433
+ }
1434
+ if (this.parents[child] != 0) {
1435
+ this.detach(child);
1436
+ }
1437
+ const lastChild = this.lastChild[id];
1438
+ if (lastChild == 0) {
1439
+ this.firstChild[id] = child;
1440
+ }
1441
+ else {
1442
+ this.nextSibling[lastChild] = child;
1443
+ }
1444
+ this.previousSibling[child] = lastChild;
1445
+ this.nextSibling[child] = 0;
1446
+ this.parents[child] = id;
1447
+ this.lastChild[id] = child;
1448
+ }
1449
+ /**
1450
+ * append a single token. faster than appendTokens()
1451
+ * @param id
1452
+ * @param token
1453
+ */
1454
+ appendToken(id, token) {
1455
+ if (token == id || token == 0) {
1456
+ return;
1457
+ }
1458
+ if (this.parents[token] != 0) {
1459
+ this.detach(token);
1460
+ }
1461
+ const lastToken = this.lastToken[id];
1462
+ if (lastToken == 0) {
1463
+ this.firstToken[id] = token;
1464
+ }
1465
+ else {
1466
+ this.nextSibling[lastToken] = token;
1467
+ }
1468
+ this.previousSibling[token] = lastToken;
1469
+ this.nextSibling[token] = 0;
1470
+ this.parents[token] = id;
1471
+ this.lastToken[id] = token;
1472
+ }
1473
+ /**
1474
+ * prepend tokens to the token list
1475
+ * @param id
1476
+ * @param tokens
1477
+ */
1478
+ prependTokens(id, ...tokens) {
1479
+ const first = this.firstToken[id];
1480
+ if (first == 0) {
1481
+ this.appendTokenList(id, tokens);
1482
+ return;
1483
+ }
1484
+ for (const token of tokens) {
1485
+ if (token == id || token == 0) {
1486
+ continue;
1487
+ }
1488
+ this.setPreviousSibling(first, token);
1489
+ }
1490
+ }
1491
+ equalsIgnoreCase(node, key, string) {
1492
+ const id = key == "nam" ? this.name[node] : this.stringValue[node];
1493
+ const stringId = this.stringIds.get(string);
1494
+ if (stringId != null && id == stringId) {
1495
+ return true;
1496
+ }
1497
+ const value = this.strings[id];
1498
+ if (value == null || string.length != value.length) {
1499
+ return false;
1500
+ }
1501
+ return equalsIgnoreCase(value, string);
1502
+ }
1503
+ startsWith(node, key, string) {
1504
+ const id = key == "nam" ? this.name[node] : this.stringValue[node];
1505
+ const stringId = this.stringIds.get(string);
1506
+ if (stringId != null && id == stringId) {
1507
+ return true;
1508
+ }
1509
+ const value = this.strings[id];
1510
+ if (value == null || string.length > value.length) {
1511
+ return false;
1512
+ }
1513
+ return value.startsWith(string);
1514
+ }
1515
+ resize(newSize) {
1516
+ if (newSize <= this.dataTypes.length) {
1517
+ return;
1518
+ }
1519
+ const newDataTypes = new Uint8Array(newSize);
1520
+ newDataTypes.set(this.dataTypes);
1521
+ this.dataTypes = newDataTypes;
1522
+ const newParents = new Uint32Array(newSize);
1523
+ newParents.set(this.parents);
1524
+ this.parents = newParents;
1525
+ const newNextSibling = new Uint32Array(newSize);
1526
+ newNextSibling.set(this.nextSibling);
1527
+ this.nextSibling = newNextSibling;
1528
+ const newPreviousSibling = new Uint32Array(newSize);
1529
+ newPreviousSibling.set(this.previousSibling);
1530
+ this.previousSibling = newPreviousSibling;
1531
+ const newFirstToken = new Uint32Array(newSize);
1532
+ newFirstToken.set(this.firstToken);
1533
+ this.firstToken = newFirstToken;
1534
+ const newLastToken = new Uint32Array(newSize);
1535
+ newLastToken.set(this.lastToken);
1536
+ this.lastToken = newLastToken;
1537
+ const newFirstChild = new Uint32Array(newSize);
1538
+ newFirstChild.set(this.firstChild);
1539
+ this.firstChild = newFirstChild;
1540
+ const newLastChild = new Uint32Array(newSize);
1541
+ newLastChild.set(this.lastChild);
1542
+ this.lastChild = newLastChild;
1543
+ const newName = new Uint32Array(newSize);
1544
+ newName.set(this.name);
1545
+ this.name = newName;
1546
+ const newStringValue = new Uint32Array(newSize);
1547
+ newStringValue.set(this.stringValue);
1548
+ this.stringValue = newStringValue;
1549
+ const newNumericValue = new Float64Array(newSize);
1550
+ newNumericValue.set(this.numericValue);
1551
+ this.numericValue = newNumericValue;
1552
+ const newUnit = new Uint32Array(newSize);
1553
+ newUnit.set(this.unit);
1554
+ this.unit = newUnit;
1555
+ const newFlags = new Uint32Array(newSize);
1556
+ newFlags.set(this.flags);
1557
+ this.flags = newFlags;
1558
+ const newColorType = new Uint8Array(newSize);
1559
+ newColorType.set(this.colorType);
1560
+ this.colorType = newColorType;
1561
+ const newSpans = new BigUint64Array(newSize);
1562
+ newSpans.set(this.spans);
1563
+ this.spans = newSpans;
1564
+ this.spans32 = new Uint32Array(this.spans.buffer);
1565
+ }
1566
+ /**
1567
+ * drop the interned strings that are no longer referenced by any node
1568
+ */
1569
+ compactStrings() {
1570
+ const used = new Uint8Array(this.strings.length);
1571
+ const size = this.current + 1;
1572
+ let count = 0;
1573
+ // the empty string is always kept
1574
+ used[0] = 1;
1575
+ for (let id = 1; id < size; id++) {
1576
+ used[this.name[id]] = 1;
1577
+ used[this.stringValue[id]] = 1;
1578
+ used[this.unit[id]] = 1;
1579
+ }
1580
+ for (let i = 0; i < used.length; i++) {
1581
+ count += used[i];
1582
+ }
1583
+ if (count == this.strings.length) {
1584
+ return;
1585
+ }
1586
+ // remap the string ids
1587
+ const mapping = new Uint32Array(this.strings.length);
1588
+ const strings = new Array(count);
1589
+ const stringIds = new Map();
1590
+ let next = 0;
1591
+ for (let i = 0; i < used.length; i++) {
1592
+ if (used[i]) {
1593
+ mapping[i] = next;
1594
+ strings[next] = this.strings[i];
1595
+ stringIds.set(this.strings[i], next);
1596
+ next++;
1597
+ }
1598
+ }
1599
+ for (let id = 1; id < size; id++) {
1600
+ this.name[id] = mapping[this.name[id]];
1601
+ this.stringValue[id] = mapping[this.stringValue[id]];
1602
+ this.unit[id] = mapping[this.unit[id]];
1603
+ }
1604
+ this.strings = strings;
1605
+ this.stringIds = stringIds;
1606
+ }
1607
+ /**
1608
+ * drop the nodes that are not reachable from the root and renumber the remaining nodes in document order.
1609
+ * the node ids change: ids obtained before the call (from visitors for instance) are no longer valid.
1610
+ * the unused strings are dropped too
1611
+ * @param errors error descriptions whose `node` is remapped
1612
+ * @returns mapping of the old ids to the new ids (0 when the node was dropped)
1613
+ */
1614
+ compact(errors) {
1615
+ const size = this.current + 1;
1616
+ const mapping = new Uint32Array(size);
1617
+ const order = new Uint32Array(size);
1618
+ const stack = [this.root];
1619
+ let next = 1;
1620
+ // document order: a node, its tokens then its children
1621
+ while (stack.length > 0) {
1622
+ const id = stack.pop();
1623
+ order[next] = id;
1624
+ mapping[id] = next++;
1625
+ for (let child = this.lastChild[id]; child != 0; child = this.previousSibling[child]) {
1626
+ stack.push(child);
1627
+ }
1628
+ for (let token = this.lastToken[id]; token != 0; token = this.previousSibling[token]) {
1629
+ stack.push(token);
1630
+ }
1631
+ }
1632
+ const capacity = next + Math.max(64, next >> 5);
1633
+ const dataTypes = new Uint8Array(capacity);
1634
+ const parents = new Uint32Array(capacity);
1635
+ const nextSibling = new Uint32Array(capacity);
1636
+ const previousSibling = new Uint32Array(capacity);
1637
+ const firstToken = new Uint32Array(capacity);
1638
+ const lastToken = new Uint32Array(capacity);
1639
+ const firstChild = new Uint32Array(capacity);
1640
+ const lastChild = new Uint32Array(capacity);
1641
+ const name = new Uint32Array(capacity);
1642
+ const stringValue = new Uint32Array(capacity);
1643
+ const numericValue = new Float64Array(capacity);
1644
+ const unit = new Uint32Array(capacity);
1645
+ const flags = new Uint32Array(capacity);
1646
+ const colorType = new Uint8Array(capacity);
1647
+ const spans = new BigUint64Array(capacity);
1648
+ const spans32 = new Uint32Array(spans.buffer);
1649
+ const nodeErrors = new Map();
1650
+ const used = new Uint8Array(this.strings.length);
1651
+ // the empty string is always kept
1652
+ used[0] = 1;
1653
+ for (let target = 1; target < next; target++) {
1654
+ const id = order[target];
1655
+ dataTypes[target] = this.dataTypes[id];
1656
+ parents[target] = mapping[this.parents[id]];
1657
+ nextSibling[target] = mapping[this.nextSibling[id]];
1658
+ previousSibling[target] = mapping[this.previousSibling[id]];
1659
+ firstToken[target] = mapping[this.firstToken[id]];
1660
+ lastToken[target] = mapping[this.lastToken[id]];
1661
+ firstChild[target] = mapping[this.firstChild[id]];
1662
+ lastChild[target] = mapping[this.lastChild[id]];
1663
+ name[target] = this.name[id];
1664
+ stringValue[target] = this.stringValue[id];
1665
+ numericValue[target] = this.numericValue[id];
1666
+ unit[target] = this.unit[id];
1667
+ flags[target] = this.flags[id];
1668
+ colorType[target] = this.colorType[id];
1669
+ spans32[target << 1] = this.spans32[id << 1];
1670
+ spans32[(target << 1) + 1] = this.spans32[(id << 1) + 1];
1671
+ used[name[target]] = 1;
1672
+ used[stringValue[target]] = 1;
1673
+ used[unit[target]] = 1;
1674
+ }
1675
+ // drop the unused strings
1676
+ let count = 0;
1677
+ for (let i = 0; i < used.length; i++) {
1678
+ count += used[i];
1679
+ }
1680
+ if (count < this.strings.length) {
1681
+ const stringMapping = new Uint32Array(this.strings.length);
1682
+ const strings = new Array(count);
1683
+ const stringIds = new Map();
1684
+ let index = 0;
1685
+ for (let i = 0; i < used.length; i++) {
1686
+ if (used[i]) {
1687
+ stringMapping[i] = index;
1688
+ strings[index] = this.strings[i];
1689
+ stringIds.set(this.strings[i], index);
1690
+ index++;
1691
+ }
1692
+ }
1693
+ for (let id = 1; id < next; id++) {
1694
+ name[id] = stringMapping[name[id]];
1695
+ stringValue[id] = stringMapping[stringValue[id]];
1696
+ unit[id] = stringMapping[unit[id]];
1697
+ }
1698
+ this.strings = strings;
1699
+ this.stringIds = stringIds;
1700
+ }
1701
+ for (const [id, list] of this.errors) {
1702
+ if (mapping[id] != 0) {
1703
+ nodeErrors.set(mapping[id], list);
1704
+ }
1705
+ }
1706
+ if (errors != null) {
1707
+ for (const error of errors) {
1708
+ if (typeof error.node == "number") {
1709
+ error.node = mapping[error.node] || null;
1710
+ }
1711
+ }
1712
+ }
1713
+ this.dataTypes = dataTypes;
1714
+ this.parents = parents;
1715
+ this.nextSibling = nextSibling;
1716
+ this.previousSibling = previousSibling;
1717
+ this.firstToken = firstToken;
1718
+ this.lastToken = lastToken;
1719
+ this.firstChild = firstChild;
1720
+ this.lastChild = lastChild;
1721
+ this.name = name;
1722
+ this.stringValue = stringValue;
1723
+ this.numericValue = numericValue;
1724
+ this.unit = unit;
1725
+ this.flags = flags;
1726
+ this.colorType = colorType;
1727
+ this.spans = spans;
1728
+ this.spans32 = new Uint32Array(spans.buffer);
1729
+ this.errors = nodeErrors;
1730
+ this.current = next - 1;
1731
+ this.freeList = 0;
1732
+ return mapping;
1733
+ }
1734
+ /**
1735
+ * mark nodes to be released or trimmed later, see {@link release} and {@link trim}.
1736
+ * the library never releases nor trims the arena by itself
1737
+ * @param ids
1738
+ */
1739
+ mark(...ids) {
1740
+ for (const id of ids) {
1741
+ if (id != 0 && id != this.root) {
1742
+ this.flags[id] |= EnumAstNodeStatus.Marked;
1743
+ }
1744
+ }
1745
+ }
1746
+ /**
1747
+ * true if the node is marked, see {@link mark}
1748
+ * @param id
1749
+ */
1750
+ isMarked(id) {
1751
+ return (this.flags[id] & EnumAstNodeStatus.Marked) != 0;
1752
+ }
1753
+ /**
1754
+ * release nodes: detach them and drop their data (interned strings, errors). node ids are never reused:
1755
+ * the memory is reclaimed by {@link trim}
1756
+ * @param id the node to release. every marked node (and its descendants) is released when omitted
1757
+ * @param deep release the children and the tokens too
1758
+ */
1759
+ release(id, deep = false) {
1760
+ if (id == null) {
1761
+ for (let node = 1; node <= this.current; node++) {
1762
+ if (this.flags[node] & EnumAstNodeStatus.Marked) {
1763
+ this.flags[node] &= ~EnumAstNodeStatus.Marked;
1764
+ this.release(node, true);
1765
+ }
1766
+ }
1767
+ return;
1768
+ }
1769
+ if (id == 0 || id == this.root) {
1770
+ return;
1771
+ }
1772
+ if (deep) {
1773
+ let child = this.firstChild[id];
1774
+ while (child != 0) {
1775
+ const next = this.nextSibling[child];
1776
+ this.release(child, true);
1777
+ child = next;
1778
+ }
1779
+ let token = this.firstToken[id];
1780
+ while (token != 0) {
1781
+ const next = this.nextSibling[token];
1782
+ this.release(token, true);
1783
+ token = next;
1784
+ }
1785
+ }
1786
+ this.detach(id);
1787
+ this.name[id] = 0;
1788
+ this.stringValue[id] = 0;
1789
+ this.unit[id] = 0;
1790
+ this.errors.delete(id);
1791
+ }
1792
+ /**
1793
+ * reclaim the memory: release the marked nodes, then drop the nodes that are not reachable from the root and
1794
+ * renumber the remaining ones, see {@link compact}. the ids obtained before the call are no longer valid
1795
+ * @param errors error descriptions whose `node` is remapped
1796
+ * @returns mapping of the old ids to the new ids (0 when the node was dropped)
1797
+ */
1798
+ trim(errors) {
1799
+ this.release();
1800
+ return this.compact(errors);
1801
+ }
1802
+ setErrors(id, errors) {
1803
+ // empty error lists are not stored
1804
+ if (errors == null || errors.length == 0) {
1805
+ this.errors.delete(id);
1806
+ }
1807
+ else {
1808
+ this.errors.set(id, errors);
1809
+ }
1810
+ }
1811
+ getErrors(id) {
1812
+ return this.errors.get(id) ?? null;
1813
+ }
1814
+ /**
1815
+ * number of children
1816
+ * @param id
1817
+ */
1818
+ childCount(id) {
1819
+ let count = 0;
1820
+ let child = this.firstChild[id];
1821
+ while (child != 0) {
1822
+ count++;
1823
+ child = this.nextSibling[child];
1824
+ }
1825
+ return count;
1826
+ }
1827
+ }
1828
+ /**
1829
+ * Css ast arena: ast nodes and value tokens.
1830
+ *
1831
+ * The node data is read and written with the methods of the arena ({@link getType}, {@link getName},
1832
+ * {@link getFirstChild}, {@link tokens}, ...). See {@link Arena} and the Arena Memory guide for the memory usage.
1833
+ */
1834
+ class AstArena extends Arena {
1835
+ /**
1836
+ * raw selector (minification cache). sparse: only rules have an entry
1837
+ */
1838
+ raw = [];
1839
+ /**
1840
+ * optimized selector (minification cache). sparse: only rules have an entry
1841
+ */
1842
+ optimized = [];
1843
+ /**
1844
+ * source ids. `spans` store the index in this table (8 bits)
1845
+ */
1846
+ sources = [];
1847
+ constructor(size = 4096) {
1848
+ super(size);
1849
+ // string id 0 is the null / empty string
1850
+ this.internString("");
1851
+ this.flags[this.root] = EnumAstNodeStatus.HasChildren;
1852
+ }
1853
+ /**
1854
+ * @inheritDoc
1855
+ */
1856
+ exportProperties() {
1857
+ return {
1858
+ ...super.exportProperties(),
1859
+ kind: "AstArena",
1860
+ sources: this.sources,
1861
+ raw: this.raw,
1862
+ optimized: this.optimized,
1863
+ };
1864
+ }
1865
+ /**
1866
+ * @inheritDoc
1867
+ */
1868
+ importProperties(properties, transferables) {
1869
+ super.importProperties(properties, transferables);
1870
+ this.sources = properties.sources?.slice() ?? [];
1871
+ this.raw = properties.raw?.slice() ?? [];
1872
+ this.optimized = properties.optimized?.slice() ?? [];
1873
+ }
1874
+ /**
1875
+ * @inheritDoc
1876
+ */
1877
+ release(id, deep = false) {
1878
+ super.release(id, deep);
1879
+ if (id != null) {
1880
+ // drop the minification caches
1881
+ if (this.raw[id] != null) {
1882
+ this.raw[id] = undefined;
1883
+ }
1884
+ if (this.optimized[id] != null) {
1885
+ this.optimized[id] = undefined;
1886
+ }
1887
+ }
1888
+ }
1889
+ /**
1890
+ * @inheritDoc
1891
+ */
1892
+ compact(errors) {
1893
+ const mapping = super.compact(errors);
1894
+ // the minification caches are dropped
1895
+ this.raw = [];
1896
+ this.optimized = [];
1897
+ return mapping;
1898
+ }
1899
+ // ---- state ---------------------------------------------------------------------
1900
+ /**
1901
+ * validation state bits
1902
+ * @param id
1903
+ */
1904
+ getState(id) {
1905
+ return this.flags[id] & EnumAstNodeStatus.StateMask;
1906
+ }
1907
+ /**
1908
+ * set the validation state bits
1909
+ * @param id
1910
+ * @param state
1911
+ */
1912
+ setState(id, state) {
1913
+ this.flags[id] = (this.flags[id] & ~EnumAstNodeStatus.StateMask) | ((state ?? 0) & EnumAstNodeStatus.StateMask);
1914
+ }
1915
+ /**
1916
+ * true if the node is invalid
1917
+ * @param id
1918
+ */
1919
+ isInvalid(id) {
1920
+ return (this.flags[id] & EnumAstNodeStatus.Invalid) != 0;
1921
+ }
1922
+ // ---- location ------------------------------------------------------------------
1923
+ /**
1924
+ * index of a source id in the sources table
1925
+ * @param srcId
1926
+ */
1927
+ sourceIndex(srcId) {
1928
+ let index = this.sources.indexOf(srcId);
1929
+ if (index == -1) {
1930
+ index = this.sources.length;
1931
+ this.sources.push(srcId);
1932
+ }
1933
+ return index;
1934
+ }
1935
+ /**
1936
+ * set the source location
1937
+ * @param id
1938
+ * @param srcId source id
1939
+ * @param sta start offset
1940
+ * @param end end offset
1941
+ */
1942
+ setLocation(id, srcId, sta, end) {
1943
+ if (srcId == null && sta == null) {
1944
+ this.flags[id] &= ~EnumAstNodeStatus.HasLocation;
1945
+ this.spans32[id << 1] = 0;
1946
+ this.spans32[(id << 1) + 1] = 0;
1947
+ return;
1948
+ }
1949
+ this.flags[id] |= EnumAstNodeStatus.HasLocation;
1950
+ this.setSpan(id, this.sourceIndex(srcId ?? 0), sta ?? 0, end ?? 0);
1951
+ }
1952
+ /**
1953
+ * set the location of a token from the tokenizer values. the source index is the index of the source id in the sources table
1954
+ * @param id
1955
+ * @param sourceIndex
1956
+ * @param sta
1957
+ * @param end
1958
+ */
1959
+ setTokenLocation(id, sourceIndex, sta, end) {
1960
+ this.flags[id] |= EnumAstNodeStatus.HasLocation;
1961
+ this.setSpan(id, sourceIndex, sta, end);
1962
+ }
1963
+ /**
1964
+ * copy the source location of another node
1965
+ * @param id
1966
+ * @param source node id
1967
+ */
1968
+ copyLocation(id, source) {
1969
+ this.copySpan(id, source);
1970
+ this.flags[id] =
1971
+ (this.flags[id] & ~EnumAstNodeStatus.HasLocation) | (this.flags[source] & EnumAstNodeStatus.HasLocation);
1972
+ }
1973
+ /**
1974
+ * set the location from the start of a node to the end of another one
1975
+ * @param id
1976
+ * @param start
1977
+ * @param end
1978
+ */
1979
+ spanLocation(id, start, end) {
1980
+ if ((this.flags[start] & EnumAstNodeStatus.HasLocation) == 0) {
1981
+ this.copyLocation(id, end);
1982
+ return;
1983
+ }
1984
+ this.flags[id] |= EnumAstNodeStatus.HasLocation;
1985
+ this.setSpan(id, this.getSourceId(start), this.getSpanStart(start), this.flags[end] & EnumAstNodeStatus.HasLocation ? this.getSpanEnd(end) : this.getSpanEnd(start));
1986
+ }
1987
+ /**
1988
+ * true if the node has a source location
1989
+ * @param id
1990
+ */
1991
+ hasLocation(id) {
1992
+ return (this.flags[id] & EnumAstNodeStatus.HasLocation) != 0;
1993
+ }
1994
+ /**
1995
+ * source location
1996
+ * @param id
1997
+ */
1998
+ getLocation(id) {
1999
+ if ((this.flags[id] & EnumAstNodeStatus.HasLocation) == 0) {
2000
+ return null;
2001
+ }
2002
+ return {
2003
+ sta: this.getSpanStart(id),
2004
+ end: this.getSpanEnd(id),
2005
+ srcId: this.sources[this.getSourceId(id)] ?? 0,
2006
+ };
2007
+ }
2008
+ /**
2009
+ * source id of the node location
2010
+ * @param id
2011
+ */
2012
+ getSource(id) {
2013
+ return this.sources[this.getSourceId(id)] ?? 0;
2014
+ }
2015
+ // ---- ast nodes -------------------------------------------------------------------
2016
+ /**
2017
+ * allocate a stylesheet node
2018
+ */
2019
+ createStyleSheet() {
2020
+ const id = this.allocate();
2021
+ this.dataTypes[id] = EnumToken.StyleSheetNodeType;
2022
+ this.flags[id] = EnumAstNodeStatus.HasChildren;
2023
+ return id;
2024
+ }
2025
+ /**
2026
+ * allocate a rule node
2027
+ * @param typ
2028
+ * @param sel
2029
+ * @param tokens prelude tokens
2030
+ * @param state
2031
+ * @param errors
2032
+ */
2033
+ createRule(typ, sel, tokens, state, errors) {
2034
+ const id = this.allocate();
2035
+ this.dataTypes[id] = typ;
2036
+ this.name[id] = this.internString(sel);
2037
+ this.flags[id] = EnumAstNodeStatus.HasChildren | ((state ?? 0) & EnumAstNodeStatus.StateMask);
2038
+ if (tokens != null) {
2039
+ this.appendTokenList(id, tokens);
2040
+ }
2041
+ if (errors != null && errors.length > 0) {
2042
+ this.errors.set(id, errors);
2043
+ }
2044
+ return id;
2045
+ }
2046
+ /**
2047
+ * allocate an at-rule node
2048
+ * @param typ
2049
+ * @param nam
2050
+ * @param val
2051
+ * @param block true if the at-rule has a block
2052
+ * @param tokens prelude tokens
2053
+ * @param state
2054
+ * @param errors
2055
+ */
2056
+ createAtRule(typ, nam, val, block, tokens, state, errors) {
2057
+ const id = this.allocate();
2058
+ this.dataTypes[id] = typ;
2059
+ this.name[id] = this.internString(nam);
2060
+ this.stringValue[id] = this.internString(val);
2061
+ this.flags[id] = (block ? EnumAstNodeStatus.HasChildren : 0) | ((state ?? 0) & EnumAstNodeStatus.StateMask);
2062
+ if (tokens != null) {
2063
+ this.appendTokenList(id, tokens);
2064
+ }
2065
+ if (errors != null && errors.length > 0) {
2066
+ this.errors.set(id, errors);
2067
+ }
2068
+ return id;
2069
+ }
2070
+ /**
2071
+ * allocate a declaration node
2072
+ * @param typ
2073
+ * @param nam
2074
+ * @param val value tokens
2075
+ * @param state
2076
+ * @param errors
2077
+ */
2078
+ createDeclaration(typ, nam, val, state, errors) {
2079
+ const id = this.allocate();
2080
+ this.dataTypes[id] = typ;
2081
+ this.name[id] = this.internString(nam);
2082
+ this.flags[id] = EnumAstNodeStatus.HasValues | ((state ?? 0) & EnumAstNodeStatus.StateMask);
2083
+ if (val != null) {
2084
+ this.appendTokenList(id, val);
2085
+ }
2086
+ if (errors != null && errors.length > 0) {
2087
+ this.errors.set(id, errors);
2088
+ }
2089
+ return id;
2090
+ }
2091
+ /**
2092
+ * allocate a comment node
2093
+ * @param typ
2094
+ * @param val
2095
+ */
2096
+ createComment(typ, val) {
2097
+ const id = this.allocate();
2098
+ this.dataTypes[id] = typ;
2099
+ this.stringValue[id] = this.internString(val);
2100
+ this.flags[id] = 0;
2101
+ return id;
2102
+ }
2103
+ // ---- tokens ----------------------------------------------------------------------
2104
+ /**
2105
+ * allocate a token. string values are interned, numeric values are stored in the `numericValue` column
2106
+ * @param typ
2107
+ * @param val
2108
+ * @param unit
2109
+ */
2110
+ createToken(typ, val, unit) {
2111
+ const id = this.allocate();
2112
+ this.dataTypes[id] = typ;
2113
+ if (typeof val == "string") {
2114
+ this.stringValue[id] = this.internString(val);
2115
+ }
2116
+ else if (typeof val == "number") {
2117
+ this.numericValue[id] = val;
2118
+ }
2119
+ if (unit != null) {
2120
+ this.unit[id] = this.internString(unit);
2121
+ }
2122
+ return id;
2123
+ }
2124
+ /**
2125
+ * allocate a color token
2126
+ * @param val color name, hex value or color function name
2127
+ * @param kin
2128
+ * @param tokens color function arguments
2129
+ */
2130
+ createColor(val, kin, tokens) {
2131
+ const id = this.allocate();
2132
+ this.dataTypes[id] = EnumToken.ColorTokenType;
2133
+ this.stringValue[id] = this.internString(val);
2134
+ // inlined: this.setColorType(id, kin)
2135
+ this.colorType[id] = kin;
2136
+ if (tokens != null) {
2137
+ this.appendTokenList(id, tokens);
2138
+ }
2139
+ return id;
2140
+ }
2141
+ /**
2142
+ * allocate a function token
2143
+ * @param typ function token type
2144
+ * @param name function name
2145
+ * @param tokens arguments
2146
+ */
2147
+ createFunction(typ, name, tokens) {
2148
+ const id = this.allocate();
2149
+ this.dataTypes[id] = typ;
2150
+ this.stringValue[id] = this.internString(name);
2151
+ if (tokens != null) {
2152
+ this.appendTokenList(id, tokens);
2153
+ }
2154
+ return id;
2155
+ }
2156
+ /**
2157
+ * allocate a list token (parens, attribute, wrapped values, ...)
2158
+ * @param typ
2159
+ * @param tokens
2160
+ */
2161
+ createList(typ, tokens) {
2162
+ const id = this.allocate();
2163
+ this.dataTypes[id] = typ;
2164
+ if (tokens != null) {
2165
+ this.appendTokenList(id, tokens);
2166
+ }
2167
+ return id;
2168
+ }
2169
+ /**
2170
+ * allocate a binary expression token. the operator is stored in the `numericValue` column
2171
+ * @param op
2172
+ * @param l
2173
+ * @param r
2174
+ */
2175
+ createBinaryExpression(op, l, r) {
2176
+ const id = this.allocate();
2177
+ this.dataTypes[id] = EnumToken.BinaryExpressionTokenType;
2178
+ this.numericValue[id] = op;
2179
+ // inlined: this.setField(id, TokenField.L, l)
2180
+ this.setTokenList(this.fieldList(id, TokenField.L), [l]);
2181
+ // inlined: this.setField(id, TokenField.R, r)
2182
+ this.setTokenList(this.fieldList(id, TokenField.R), [r]);
2183
+ return id;
2184
+ }
2185
+ /**
2186
+ * allocate a fraction token
2187
+ * @param l numerator
2188
+ * @param r denominator
2189
+ */
2190
+ createFraction(l, r) {
2191
+ const id = this.allocate();
2192
+ this.dataTypes[id] = EnumToken.FractionTokenType;
2193
+ // inlined: this.appendChildren(id, l, r)
2194
+ this.appendChildList(id, [l, r]);
2195
+ return id;
2196
+ }
2197
+ /**
2198
+ * true if the numeric token value is a fraction
2199
+ * @param id
2200
+ */
2201
+ hasFraction(id) {
2202
+ const child = this.firstChild[id];
2203
+ return child != 0 && this.dataTypes[child] == EnumToken.FractionTokenType;
2204
+ }
2205
+ /**
2206
+ * fraction token of a numeric token
2207
+ * @param id
2208
+ */
2209
+ getFraction(id) {
2210
+ const child = this.firstChild[id];
2211
+ return child != 0 && this.dataTypes[child] == EnumToken.FractionTokenType ? child : 0;
2212
+ }
2213
+ /**
2214
+ * set the fraction value of a numeric token. the numeric value is set to the fraction value
2215
+ * @param id
2216
+ * @param fraction fraction token id or null
2217
+ */
2218
+ setFraction(id, fraction) {
2219
+ const child = this.getFraction(id);
2220
+ if (child != 0) {
2221
+ this.detach(child);
2222
+ }
2223
+ if (fraction != null && fraction != 0) {
2224
+ // inlined: this.appendChildren(id, fraction)
2225
+ this.appendChildList(id, [fraction]);
2226
+ this.numericValue[id] =
2227
+ this.numericValue[this.firstChild[fraction]] / this.numericValue[this.lastChild[fraction]];
2228
+ }
2229
+ }
2230
+ /**
2231
+ * numerator of a fraction token
2232
+ * @param id
2233
+ */
2234
+ numerator(id) {
2235
+ return this.firstChild[id];
2236
+ }
2237
+ /**
2238
+ * denominator of a fraction token
2239
+ * @param id
2240
+ */
2241
+ denominator(id) {
2242
+ return this.lastChild[id];
2243
+ }
2244
+ /**
2245
+ * string value of a token (`val`)
2246
+ * @param id
2247
+ */
2248
+ str(id) {
2249
+ return this.strings[this.stringValue[id]];
2250
+ }
2251
+ /**
2252
+ * set the string value of a token (`val`)
2253
+ * @param id
2254
+ * @param value
2255
+ */
2256
+ setStr(id, value) {
2257
+ this.stringValue[id] = this.internString(value);
2258
+ }
2259
+ /**
2260
+ * set the unit of a token
2261
+ * @param id
2262
+ * @param unit
2263
+ */
2264
+ setUnitString(id, unit) {
2265
+ this.unit[id] = unit == null ? 0 : this.internString(unit);
2266
+ }
2267
+ /**
2268
+ * true if the token is a numeric token (number, dimension, percentage, ...)
2269
+ * @param id
2270
+ */
2271
+ isNumeric(id) {
2272
+ return numericTokenTypes.has(this.dataTypes[id]);
2273
+ }
2274
+ /**
2275
+ * replace a token by other tokens in its parent token list
2276
+ * @param id
2277
+ * @param tokens
2278
+ */
2279
+ replaceToken(id, ...tokens) {
2280
+ if (this.parents[id] == 0) {
2281
+ return;
2282
+ }
2283
+ const index = tokens.indexOf(id);
2284
+ if (index == -1) {
2285
+ this.insertBefore(id, ...tokens);
2286
+ this.detach(id);
2287
+ return;
2288
+ }
2289
+ this.insertBefore(id, ...tokens.slice(0, index));
2290
+ this.insertAfter(id, ...tokens.slice(index + 1));
2291
+ }
2292
+ /**
2293
+ * get a token that can be attached to a new parent: the token itself when it is detached, a deep clone otherwise.
2294
+ * a token can only belong to one token list
2295
+ * @param token
2296
+ */
2297
+ take(token) {
2298
+ return this.parents[token] == 0 ? token : this.clone(token, true);
2299
+ }
2300
+ /**
2301
+ * copy the data columns of a token (type, values, unit, color type, location)
2302
+ * @param target
2303
+ * @param source
2304
+ */
2305
+ copyToken(target, source) {
2306
+ this.dataTypes[target] = this.dataTypes[source];
2307
+ this.name[target] = this.name[source];
2308
+ this.stringValue[target] = this.stringValue[source];
2309
+ this.numericValue[target] = this.numericValue[source];
2310
+ this.unit[target] = this.unit[source];
2311
+ this.colorType[target] = this.colorType[source];
2312
+ this.copySpan(target, source);
2313
+ this.flags[target] = this.flags[source] & ~(EnumAstNodeStatus.HasChildren | EnumAstNodeStatus.HasValues);
2314
+ }
2315
+ /**
2316
+ * reset a token to a new type. the values, the token list and the fields are dropped
2317
+ * @param id
2318
+ * @param typ
2319
+ * @param val
2320
+ * @param unit
2321
+ */
2322
+ resetToken(id, typ, val, unit) {
2323
+ this.dataTypes[id] = typ;
2324
+ this.stringValue[id] = 0;
2325
+ this.numericValue[id] = 0;
2326
+ this.unit[id] = 0;
2327
+ this.colorType[id] = 0;
2328
+ this.name[id] = 0;
2329
+ if (typeof val == "string") {
2330
+ this.stringValue[id] = this.internString(val);
2331
+ }
2332
+ else if (typeof val == "number") {
2333
+ this.numericValue[id] = val;
2334
+ }
2335
+ if (unit != null) {
2336
+ this.unit[id] = this.internString(unit);
2337
+ }
2338
+ // inlined: this.setTokens(id)
2339
+ this.setTokenList(id, []);
2340
+ // inlined: this.setChildren(id)
2341
+ this.setChildList(id, []);
2342
+ }
2343
+ // ---- plain objects -----------------------------------------------------------------
2344
+ /**
2345
+ * Import an object: an {@link AstArenaNode} or a plain object ({@link PlainAstNode}, {@link PlainToken}).
2346
+ *
2347
+ * - importing a view of this arena is a noop: its node id is returned, the node is not copied,
2348
+ * - a view of another arena is copied with its descendants (see {@link import}),
2349
+ * - a plain object is allocated in the arena. `chi`, `val`, `l`, `r`, ... are created recursively, they can be
2350
+ * node ids, views or plain objects.
2351
+ *
2352
+ * @param node
2353
+ * @returns the node id
2354
+ */
2355
+ fromObject(node) {
2356
+ const id = node[ARENAID];
2357
+ if (id !== undefined) {
2358
+ // no copy for the nodes of this arena
2359
+ return this.import(node[ARENA], id);
2360
+ }
2361
+ return isNodeObjectType(node.typ)
2362
+ ? this.nodeFromObject(node)
2363
+ : this.tokenFromObject(node);
2364
+ }
2365
+ /**
2366
+ * create an ast node from a plain object
2367
+ * @param node
2368
+ */
2369
+ nodeFromObject(node) {
2370
+ const id = this.allocate();
2371
+ const typ = node.typ;
2372
+ this.dataTypes[id] = typ;
2373
+ switch (typ) {
2374
+ case EnumToken.StyleSheetNodeType:
2375
+ this.flags[id] = EnumAstNodeStatus.HasChildren;
2376
+ break;
2377
+ case EnumToken.RuleNodeType:
2378
+ case EnumToken.KeyframesRuleNodeType:
2379
+ this.name[id] = this.internString((node.sel ?? node.nam ?? ""));
2380
+ this.flags[id] = EnumAstNodeStatus.HasChildren;
2381
+ if (node.raw != null) {
2382
+ this.raw[id] = node.raw;
2383
+ }
2384
+ if (node.optimized != null) {
2385
+ this.optimized[id] = node.optimized;
2386
+ }
2387
+ if (typeof node.val == "string") {
2388
+ this.stringValue[id] = this.internString(node.val);
2389
+ }
2390
+ break;
2391
+ case EnumToken.AtRuleNodeType:
2392
+ case EnumToken.KeyframesAtRuleNodeType:
2393
+ this.name[id] = this.internString(node.nam ?? "");
2394
+ this.stringValue[id] = this.internString(node.val ?? "");
2395
+ this.flags[id] = node.chi != null ? EnumAstNodeStatus.HasChildren : 0;
2396
+ break;
2397
+ case EnumToken.CommentNodeType:
2398
+ case EnumToken.CDOCOMMNodeType:
2399
+ this.stringValue[id] = this.internString(node.val ?? "");
2400
+ this.flags[id] = 0;
2401
+ break;
2402
+ default:
2403
+ // declaration like nodes
2404
+ this.name[id] = this.internString(node.nam ?? "");
2405
+ this.flags[id] = EnumAstNodeStatus.HasValues;
2406
+ if (Array.isArray(node.val)) {
2407
+ for (const token of node.val) {
2408
+ this.appendToken(id, typeof token == "number" ? token : this.fromObject(token));
2409
+ }
2410
+ }
2411
+ break;
2412
+ }
2413
+ if (Array.isArray(node.tokens)) {
2414
+ for (const token of node.tokens) {
2415
+ this.appendToken(id, typeof token == "number" ? token : this.fromObject(token));
2416
+ }
2417
+ }
2418
+ // inlined: this.setState(id, node.state)
2419
+ this.flags[id] = (this.flags[id] & ~EnumAstNodeStatus.StateMask) | ((node.state ?? 0) & EnumAstNodeStatus.StateMask);
2420
+ const loc = node.loc;
2421
+ if (loc != null) {
2422
+ this.setLocation(id, loc.srcId, loc.sta, loc.end);
2423
+ }
2424
+ const errors = node.errors;
2425
+ if (errors != null && errors.length > 0) {
2426
+ this.errors.set(id, errors);
2427
+ }
2428
+ if (Array.isArray(node.chi) && this.flags[id] & EnumAstNodeStatus.HasChildren) {
2429
+ for (const child of node.chi) {
2430
+ // inlined: this.appendChildren(id, typeof child == "number" ? child : this.fromObject(child))
2431
+ this.appendChildList(id, [(typeof child == "number" ? child : this.fromObject(child))]);
2432
+ }
2433
+ }
2434
+ return id;
2435
+ }
2436
+ /**
2437
+ * create a token from a plain object
2438
+ * @param token
2439
+ */
2440
+ tokenFromObject(token) {
2441
+ const id = this.allocate();
2442
+ const typ = token.typ;
2443
+ const plain = token;
2444
+ this.dataTypes[id] = typ;
2445
+ if (typeof plain.nam == "string") {
2446
+ this.name[id] = this.internString(plain.nam);
2447
+ }
2448
+ if (typeof plain.unit == "string") {
2449
+ this.unit[id] = this.internString(plain.unit);
2450
+ }
2451
+ if (typeof plain.kin == "number") {
2452
+ // inlined: this.setColorType(id, plain.kin)
2453
+ this.colorType[id] = plain.kin;
2454
+ }
2455
+ if (typeof plain.cal == "string") {
2456
+ this.unit[id] = this.internString(plain.cal);
2457
+ }
2458
+ if (typeof plain.attr == "string") {
2459
+ this.unit[id] = this.internString(plain.attr);
2460
+ }
2461
+ if (typ == EnumToken.BinaryExpressionTokenType) {
2462
+ this.numericValue[id] = plain.op;
2463
+ }
2464
+ else if (typ == EnumToken.UnaryExpressionTokenType) {
2465
+ this.numericValue[id] = plain.sign;
2466
+ // inlined: this.appendChildren(id, typeof plain.val == "number" ? plain.val : this.fromObject(plain.val))
2467
+ this.appendChildList(id, [(typeof plain.val == "number" ? plain.val : this.fromObject(plain.val))]);
2468
+ }
2469
+ else if (typ == EnumToken.FractionTokenType) {
2470
+ // inlined: this.appendChildren(id, typeof plain.l == "number" ? plain.l : this.fromObject(plain.l), typeof plain.r == "number" ? plain.r : this.fromObject(plain.r))
2471
+ this.appendChildList(id, [(typeof plain.l == "number" ? plain.l : this.fromObject(plain.l)), (typeof plain.r == "number" ? plain.r : this.fromObject(plain.r))]);
2472
+ }
2473
+ else if (typeof plain.val == "string") {
2474
+ if (numericTokenTypes.has(typ)) {
2475
+ // numeric value as a string
2476
+ this.numericValue[id] = +plain.val;
2477
+ }
2478
+ else {
2479
+ this.stringValue[id] = this.internString(plain.val);
2480
+ }
2481
+ }
2482
+ else if (typeof plain.val == "number") {
2483
+ this.numericValue[id] = plain.val;
2484
+ }
2485
+ else if (plain.val != null && typeof plain.val == "object" && !Array.isArray(plain.val)) {
2486
+ // fraction value
2487
+ this.setFraction(id, this.fromObject(plain.val));
2488
+ }
2489
+ else if (Array.isArray(plain.val) && typ != EnumToken.MediaRangeQueryTokenType) {
2490
+ // declaration like tokens
2491
+ for (const child of plain.val) {
2492
+ this.appendToken(id, typeof child == "number" ? child : this.fromObject(child));
2493
+ }
2494
+ }
2495
+ if (Array.isArray(plain.chi)) {
2496
+ for (const child of plain.chi) {
2497
+ this.appendToken(id, typeof child == "number" ? child : this.fromObject(child));
2498
+ }
2499
+ }
2500
+ if (structuredTokenTypes.has(typ)) {
2501
+ const fields = [
2502
+ ["l", TokenField.L],
2503
+ ["r", TokenField.R],
2504
+ ["op", TokenField.Op],
2505
+ ["op1", TokenField.Op],
2506
+ ["op2", TokenField.Op2],
2507
+ ["val", TokenField.Val],
2508
+ ];
2509
+ for (const [key, field] of fields) {
2510
+ if (plain[key] == null) {
2511
+ continue;
2512
+ }
2513
+ const values = Array.isArray(plain[key]) ? plain[key] : [plain[key]];
2514
+ const fieldTokens = [];
2515
+ for (const value of values) {
2516
+ fieldTokens.push(typeof value == "number" ? value : this.fromObject(value));
2517
+ }
2518
+ // inlined: this.setField(id, field, ...fieldTokens)
2519
+ this.setTokenList(this.fieldList(id, field), fieldTokens);
2520
+ }
2521
+ }
2522
+ const loc = plain.loc;
2523
+ if (loc != null) {
2524
+ this.setLocation(id, loc.srcId, loc.sta, loc.end);
2525
+ }
2526
+ return id;
2527
+ }
2528
+ /**
2529
+ * Object view of a node or a token: an {@link AstArenaNode}. The view does not copy the node: its properties read
2530
+ * and write the arena. Importing the view in this arena ({@link fromObject}, visitor results, setters of the
2531
+ * views) is a noop
2532
+ *
2533
+ * ```ts
2534
+ * function visitor(arena: AstArena, id: number) {
2535
+ *
2536
+ * const node = arena.toObject(id);
2537
+ *
2538
+ * console.log(node.typ, node.nam, node.val);
2539
+ * }
2540
+ * ```
2541
+ *
2542
+ * @param id node or token id
2543
+ */
2544
+ toObject(id) {
2545
+ return new AstArenaNode(this, id);
2546
+ }
2547
+ /**
2548
+ * export a node or a token as a plain object (deep copy). `JSON.stringify()` of an {@link AstArenaNode} returns
2549
+ * the plain object
2550
+ * @param id
2551
+ */
2552
+ toPlainObject(id) {
2553
+ const typ = this.dataTypes[id];
2554
+ const flags = this.flags[id];
2555
+ if (!isNodeObjectType(typ)) {
2556
+ return this.tokenToObject(id);
2557
+ }
2558
+ const node = { typ };
2559
+ switch (typ) {
2560
+ case EnumToken.StyleSheetNodeType:
2561
+ break;
2562
+ case EnumToken.RuleNodeType:
2563
+ case EnumToken.KeyframesRuleNodeType:
2564
+ node.sel = this.strings[this.name[id]];
2565
+ break;
2566
+ case EnumToken.AtRuleNodeType:
2567
+ case EnumToken.KeyframesAtRuleNodeType:
2568
+ node.nam = this.strings[this.name[id]];
2569
+ node.val = this.strings[this.stringValue[id]];
2570
+ break;
2571
+ case EnumToken.CommentNodeType:
2572
+ case EnumToken.CDOCOMMNodeType:
2573
+ node.val = this.strings[this.stringValue[id]];
2574
+ break;
2575
+ default:
2576
+ node.nam = this.strings[this.name[id]];
2577
+ node.val = [];
2578
+ for (const token of this.tokens(id)) {
2579
+ node.val.push(this.tokenToObject(token));
2580
+ }
2581
+ break;
2582
+ }
2583
+ if (flags & EnumAstNodeStatus.HasChildren) {
2584
+ node.chi = [];
2585
+ for (const child of this.children(id)) {
2586
+ node.chi.push(this.toPlainObject(child));
2587
+ }
2588
+ }
2589
+ if (flags & EnumAstNodeStatus.HasLocation) {
2590
+ node.loc = this.getLocation(id);
2591
+ }
2592
+ if (flags & EnumAstNodeStatus.StateMask) {
2593
+ node.state = flags & EnumAstNodeStatus.StateMask;
2594
+ }
2595
+ if ((flags & EnumAstNodeStatus.HasValues) == 0 && this.firstToken[id] != 0) {
2596
+ node.tokens = [];
2597
+ for (const token of this.tokens(id)) {
2598
+ node.tokens.push(this.tokenToObject(token));
2599
+ }
2600
+ }
2601
+ if (this.errors.has(id)) {
2602
+ node.errors = this.errors.get(id);
2603
+ }
2604
+ if (this.raw[id] != null) {
2605
+ node.raw = this.raw[id];
2606
+ }
2607
+ if (this.optimized[id] != null) {
2608
+ node.optimized = this.optimized[id];
2609
+ }
2610
+ return node;
2611
+ }
2612
+ /**
2613
+ * export a token as a plain object (deep copy)
2614
+ * @param id
2615
+ */
2616
+ tokenToObject(id) {
2617
+ const typ = this.dataTypes[id];
2618
+ const token = { typ };
2619
+ if (this.name[id] != 0) {
2620
+ token.nam = this.strings[this.name[id]];
2621
+ }
2622
+ if (typ == EnumToken.BinaryExpressionTokenType) {
2623
+ token.op = this.numericValue[id];
2624
+ }
2625
+ else if (typ == EnumToken.UnaryExpressionTokenType) {
2626
+ token.sign = this.numericValue[id];
2627
+ token.val = this.firstChild[id] == 0 ? null : this.tokenToObject(this.firstChild[id]);
2628
+ }
2629
+ else if (typ == EnumToken.FractionTokenType) {
2630
+ token.l = this.tokenToObject(this.firstChild[id]);
2631
+ token.r = this.tokenToObject(this.lastChild[id]);
2632
+ }
2633
+ else if (numericTokenTypes.has(typ)) {
2634
+ const fraction = this.getFraction(id);
2635
+ token.val = fraction == 0 ? this.numericValue[id] : this.tokenToObject(fraction);
2636
+ }
2637
+ else if (this.stringValue[id] != 0 || typ == EnumToken.IdenTokenType || typ == EnumToken.StringTokenType) {
2638
+ token.val = this.strings[this.stringValue[id]];
2639
+ }
2640
+ if (this.unit[id] != 0) {
2641
+ if (typ == EnumToken.ColorTokenType) {
2642
+ token.cal = this.strings[this.unit[id]];
2643
+ }
2644
+ else if (typ == EnumToken.MatchExpressionTokenType) {
2645
+ token.attr = this.strings[this.unit[id]];
2646
+ }
2647
+ else {
2648
+ token.unit = this.strings[this.unit[id]];
2649
+ }
2650
+ }
2651
+ if (typ == EnumToken.ColorTokenType && this.colorType[id] != ColorType.NONE) {
2652
+ token.kin = this.colorType[id];
2653
+ }
2654
+ if (this.firstToken[id] != 0) {
2655
+ const tokens = [];
2656
+ for (const child of this.tokens(id)) {
2657
+ tokens.push(this.tokenToObject(child));
2658
+ }
2659
+ if (typ == EnumToken.DeclarationNodeType ||
2660
+ typ == EnumToken.CssVariableTokenType ||
2661
+ typ == EnumToken.CssVariableImportTokenType) {
2662
+ token.val = tokens;
2663
+ }
2664
+ else {
2665
+ token.chi = tokens;
2666
+ }
2667
+ }
2668
+ if (structuredTokenTypes.has(typ)) {
2669
+ for (const [key, field, isSingle] of structuredFields(typ)) {
2670
+ const list = this.getChildAt(id, field);
2671
+ if (list == null) {
2672
+ continue;
2673
+ }
2674
+ const values = [];
2675
+ for (const child of this.tokens(list)) {
2676
+ values.push(this.tokenToObject(child));
2677
+ }
2678
+ token[key] = isSingle ? (values[0] ?? null) : values;
2679
+ }
2680
+ }
2681
+ if (this.flags[id] & EnumAstNodeStatus.HasLocation) {
2682
+ token.loc = this.getLocation(id);
2683
+ }
2684
+ return token;
2685
+ }
2686
+ // ---- clone / import ----------------------------------------------------------------
2687
+ /**
2688
+ * clone a node or a token. tokens are always cloned deeply
2689
+ * @param id
2690
+ * @param deep also clone the children (rules) or the value tokens (declarations)
2691
+ * @param cloneMap map of the source ids to their clones
2692
+ */
2693
+ clone(id, deep = false, cloneMap = null) {
2694
+ const target = this.allocate();
2695
+ const flags = this.flags[id];
2696
+ cloneMap?.set(id, target);
2697
+ this.dataTypes[target] = this.dataTypes[id];
2698
+ this.name[target] = this.name[id];
2699
+ this.stringValue[target] = this.stringValue[id];
2700
+ this.numericValue[target] = this.numericValue[id];
2701
+ this.unit[target] = this.unit[id];
2702
+ this.colorType[target] = this.colorType[id];
2703
+ this.flags[target] = flags;
2704
+ this.copySpan(target, id);
2705
+ if (this.raw[id] != null) {
2706
+ this.raw[target] = this.raw[id];
2707
+ }
2708
+ if (this.optimized[id] != null) {
2709
+ this.optimized[target] = this.optimized[id];
2710
+ }
2711
+ if (this.errors.size > 0 && this.errors.has(id)) {
2712
+ this.errors.set(target, this.errors.get(id));
2713
+ }
2714
+ const isNode = (flags & (EnumAstNodeStatus.HasChildren | EnumAstNodeStatus.HasValues)) != 0;
2715
+ // declaration values are cloned only when requested
2716
+ if (!isNode || deep || (flags & EnumAstNodeStatus.HasValues) == 0) {
2717
+ let token = this.firstToken[id];
2718
+ while (token != 0) {
2719
+ this.appendToken(target, this.clone(token, true, cloneMap));
2720
+ token = this.nextSibling[token];
2721
+ }
2722
+ }
2723
+ if (!isNode || deep) {
2724
+ let child = this.firstChild[id];
2725
+ while (child != 0) {
2726
+ this.appendChild(target, this.clone(child, true, cloneMap));
2727
+ child = this.nextSibling[child];
2728
+ }
2729
+ }
2730
+ return target;
2731
+ }
2732
+ /**
2733
+ * copy a node or a token of another arena into this arena
2734
+ * @param source
2735
+ * @param id
2736
+ * @param deep copy the children. defaults to true
2737
+ */
2738
+ import(source, id, deep = true) {
2739
+ if (source === this) {
2740
+ return id;
2741
+ }
2742
+ const target = this.allocate();
2743
+ const flags = source.flags[id];
2744
+ this.dataTypes[target] = source.dataTypes[id];
2745
+ this.name[target] = this.internString(source.strings[source.name[id]] ?? "");
2746
+ this.stringValue[target] = this.internString(source.strings[source.stringValue[id]] ?? "");
2747
+ this.numericValue[target] = source.numericValue[id];
2748
+ this.unit[target] = this.internString(source.strings[source.unit[id]] ?? "");
2749
+ this.colorType[target] = source.colorType[id];
2750
+ this.flags[target] = flags & ~EnumAstNodeStatus.HasLocation;
2751
+ if (source.raw[id] != null) {
2752
+ this.raw[target] = source.raw[id];
2753
+ }
2754
+ if (source.optimized[id] != null) {
2755
+ this.optimized[target] = source.optimized[id];
2756
+ }
2757
+ if (flags & EnumAstNodeStatus.HasLocation) {
2758
+ // inlined: source.getSource(id)
2759
+ this.setLocation(target, source.sources[source.getSourceId(id)] ?? 0, source.getSpanStart(id), source.getSpanEnd(id));
2760
+ }
2761
+ if (source.errors.has(id)) {
2762
+ this.errors.set(target, source.errors.get(id));
2763
+ }
2764
+ let token = source.firstToken[id];
2765
+ while (token != 0) {
2766
+ this.appendToken(target, this.import(source, token));
2767
+ token = source.nextSibling[token];
2768
+ }
2769
+ if (deep || (flags & EnumAstNodeStatus.HasChildren) == 0) {
2770
+ let child = source.firstChild[id];
2771
+ while (child != 0) {
2772
+ this.appendChild(target, this.import(source, child));
2773
+ child = source.nextSibling[child];
2774
+ }
2775
+ }
2776
+ return target;
2777
+ }
2778
+ // ---- tree helpers --------------------------------------------------------------
2779
+ /**
2780
+ * index of a child in its parent's children (or tokens) list
2781
+ * @param id
2782
+ */
2783
+ indexOf(id) {
2784
+ let index = 0;
2785
+ let child = this.previousSibling[id];
2786
+ if (this.parents[id] == 0) {
2787
+ return -1;
2788
+ }
2789
+ while (child != 0) {
2790
+ index++;
2791
+ child = this.previousSibling[child];
2792
+ }
2793
+ return index;
2794
+ }
2795
+ /**
2796
+ * insert nodes before a child
2797
+ * @param reference
2798
+ * @param nodes
2799
+ */
2800
+ insertBefore(reference, ...nodes) {
2801
+ for (const node of nodes) {
2802
+ if (node == reference || node == 0) {
2803
+ continue;
2804
+ }
2805
+ this.setPreviousSibling(reference, node);
2806
+ }
2807
+ }
2808
+ /**
2809
+ * insert nodes after a child
2810
+ * @param reference
2811
+ * @param nodes
2812
+ */
2813
+ insertAfter(reference, ...nodes) {
2814
+ for (const node of nodes) {
2815
+ if (node == reference || node == 0) {
2816
+ continue;
2817
+ }
2818
+ this.setNextSibling(reference, node);
2819
+ reference = node;
2820
+ }
2821
+ }
2822
+ /**
2823
+ * prepend children
2824
+ * @param id
2825
+ * @param nodes
2826
+ */
2827
+ prependChildren(id, ...nodes) {
2828
+ const first = this.firstChild[id];
2829
+ if (first == 0) {
2830
+ this.appendChildList(id, nodes);
2831
+ }
2832
+ else {
2833
+ this.insertBefore(first, ...nodes);
2834
+ }
2835
+ }
2836
+ /**
2837
+ * replace a child with other nodes. the node itself may be part of the replacement
2838
+ * @param id
2839
+ * @param nodes
2840
+ */
2841
+ replaceChild(id, ...nodes) {
2842
+ if (this.parents[id] == 0) {
2843
+ return;
2844
+ }
2845
+ const index = nodes.indexOf(id);
2846
+ if (index == -1) {
2847
+ this.insertBefore(id, ...nodes);
2848
+ this.detach(id);
2849
+ return;
2850
+ }
2851
+ this.insertBefore(id, ...nodes.slice(0, index));
2852
+ this.insertAfter(id, ...nodes.slice(index + 1));
2853
+ }
2854
+ /**
2855
+ * true if the node has a block (at-rules) or a children list
2856
+ * @param id
2857
+ */
2858
+ hasChildren(id) {
2859
+ return (this.flags[id] & EnumAstNodeStatus.HasChildren) != 0;
2860
+ }
2861
+ /**
2862
+ * rule selector
2863
+ * @param id
2864
+ */
2865
+ getSelector(id) {
2866
+ return this.strings[this.name[id]];
2867
+ }
2868
+ /**
2869
+ * set the rule selector
2870
+ * @param id
2871
+ * @param sel
2872
+ */
2873
+ setSelector(id, sel) {
2874
+ this.name[id] = this.internString(sel);
2875
+ }
2876
+ /**
2877
+ * set the at-rule / declaration name
2878
+ * @param id
2879
+ * @param nam
2880
+ */
2881
+ setNameString(id, nam) {
2882
+ this.name[id] = this.internString(nam);
2883
+ }
2884
+ /**
2885
+ * set the at-rule prelude / comment string value
2886
+ * @param id
2887
+ * @param val
2888
+ */
2889
+ setValueString(id, val) {
2890
+ this.stringValue[id] = this.internString(val);
2891
+ }
2892
+ // ---- nesting rules expansion ---------------------------------------------------------------
2893
+ /**
2894
+ * Expand the css nesting rules of a stylesheet, a rule or an at-rule. The tree is expanded in place: the nested rules
2895
+ * are moved into the parent of their rule and their selectors are resolved
2896
+ *
2897
+ * ```ts
2898
+ * const result = await parse(`.foo { color: red; .bar & { color: blue } }`);
2899
+ *
2900
+ * result.arena.expand(result.ast);
2901
+ * console.log(render(result.arena, result.ast).code);
2902
+ * ```
2903
+ *
2904
+ * @param ast node id
2905
+ * @returns the node id
2906
+ */
2907
+ expand(ast) {
2908
+ if (this.flags[ast] & skipStates) {
2909
+ return ast;
2910
+ }
2911
+ let node = this.firstChild[ast];
2912
+ while (node != 0) {
2913
+ const next = this.nextSibling[node];
2914
+ const typ = this.dataTypes[node];
2915
+ if (typ === EnumToken.RuleNodeType) {
2916
+ // the expanded rules are inserted after the rule
2917
+ this.expandRule(node, ast, next);
2918
+ }
2919
+ else if (typ == EnumToken.AtRuleNodeType && this.flags[node] & EnumAstNodeStatus.HasChildren) {
2920
+ let j = this.lastChild[node];
2921
+ while (j != 0) {
2922
+ if (this.dataTypes[j] == EnumToken.RuleNodeType || this.dataTypes[j] == EnumToken.AtRuleNodeType) {
2923
+ this.expand(node);
2924
+ break;
2925
+ }
2926
+ j = this.previousSibling[j];
2927
+ }
2928
+ }
2929
+ node = next;
2930
+ }
2931
+ return ast;
2932
+ }
2933
+ /**
2934
+ * expand a rule: the nested rules and at-rules are moved out of the rule, into `parent` before `before`.
2935
+ * the rule is detached when it has no children left
2936
+ * @param node
2937
+ * @param parent
2938
+ * @param before the expanded nodes are inserted before this child of parent. they are appended when 0
2939
+ */
2940
+ expandRule(node, parent, before) {
2941
+ if (this.flags[node] & skipStates) {
2942
+ return;
2943
+ }
2944
+ const ast = node;
2945
+ const sel = this.strings[this.name[ast]];
2946
+ const place = (child) => {
2947
+ if (before == 0) {
2948
+ this.appendChild(parent, child);
2949
+ }
2950
+ else {
2951
+ this.insertBefore(before, child);
2952
+ }
2953
+ };
2954
+ if (this.dataTypes[ast] == EnumToken.RuleNodeType) {
2955
+ let child = this.firstChild[ast];
2956
+ while (child != 0) {
2957
+ const next = this.nextSibling[child];
2958
+ const typ = this.dataTypes[child];
2959
+ if (typ == EnumToken.RuleNodeType) {
2960
+ const rule = child;
2961
+ const ruleSel = this.strings[this.name[rule]];
2962
+ if (!ruleSel.includes("&")) {
2963
+ const selRule = splitRule(ruleSel);
2964
+ const arSelf = splitRule(sel)
2965
+ .filter((r) => r.every((t) => t != ":before" && t != ":after" && !t.startsWith("::")))
2966
+ .reduce((acc, curr) => acc.concat([curr.join("")]), [])
2967
+ .join(",");
2968
+ if (arSelf.length == 0) {
2969
+ this.detach(rule);
2970
+ child = next;
2971
+ continue;
2972
+ }
2973
+ for (let i1 = 0; i1 < selRule.length; i1++) {
2974
+ const arr = selRule[i1];
2975
+ combinators.includes(arr[0].charAt(0)) ? arr.unshift(arSelf) : arr.unshift(arSelf, " ");
2976
+ }
2977
+ // inlined: this.setSelector(rule, selRule .reduce((acc: string[], curr: string[]) => { acc.push(curr.join("")); return acc; }, <string[]>[]) .join(","))
2978
+ this.name[rule] = this.internString(selRule
2979
+ .reduce((acc, curr) => {
2980
+ acc.push(curr.join(""));
2981
+ return acc;
2982
+ }, [])
2983
+ .join(","));
2984
+ }
2985
+ else {
2986
+ let childSelectorCompound = [];
2987
+ let withCompound = [];
2988
+ let withoutCompound = [];
2989
+ // pseudo elements cannot be used with '&'
2990
+ // https://www.w3.org/TR/css-nesting-1/#example-7145ff1e
2991
+ const rules = splitRule(sel).filter((r) => r.every((t) => t != ":before" && t != ":after" && !t.startsWith("::")));
2992
+ const parentSelector = !sel.includes("&");
2993
+ if (rules.length == 0) {
2994
+ this.detach(rule);
2995
+ child = next;
2996
+ continue;
2997
+ }
2998
+ for (const sel of this.raw[rule] ?? splitRule(ruleSel)) {
2999
+ const s = sel.join("");
3000
+ if (s.includes("&") || parentSelector) {
3001
+ if (s.indexOf("&", 1) == -1) {
3002
+ if (s.at(0) == "&") {
3003
+ if (s.at(1) == " ") {
3004
+ childSelectorCompound.push(s.slice(2));
3005
+ }
3006
+ else {
3007
+ if (s == "&" || parentSelector) {
3008
+ withCompound.push(s);
3009
+ }
3010
+ }
3011
+ }
3012
+ else {
3013
+ withoutCompound.push(s);
3014
+ }
3015
+ }
3016
+ else {
3017
+ withCompound.push(s);
3018
+ }
3019
+ }
3020
+ }
3021
+ const selectors = [];
3022
+ const selector = rules.length > 1 ? ":is(" + rules.map((a) => a.join("")).join(",") + ")" : rules[0].join("");
3023
+ if (childSelectorCompound.length > 0) {
3024
+ if (childSelectorCompound.length == 1) {
3025
+ selectors.push(this.replaceCompound("& " + childSelectorCompound[0].trim(), selector));
3026
+ }
3027
+ else {
3028
+ selectors.push(this.replaceCompound("& :is(" +
3029
+ childSelectorCompound.reduce((acc, curr) => acc + (acc.length > 0 ? "," : "") + curr.trim(), "") +
3030
+ ")", selector));
3031
+ }
3032
+ }
3033
+ if (withCompound.length > 0) {
3034
+ if (withCompound.every((t) => t[0] == "&" && t.indexOf("&", 1) == -1)) {
3035
+ withoutCompound.push(...withCompound.map((t) => t.slice(1)));
3036
+ withCompound.length = 0;
3037
+ }
3038
+ }
3039
+ if (withoutCompound.length > 0) {
3040
+ if (withoutCompound.length == 1) {
3041
+ const useIs = rules.length == 1 &&
3042
+ selector.match(/^[a-zA-Z.:]/) != null &&
3043
+ selector.includes(" ") &&
3044
+ withoutCompound.length == 1 &&
3045
+ withoutCompound[0].match(/^[a-zA-Z]+$/) != null;
3046
+ const compound = useIs ? ":is(&)" : "&";
3047
+ selectors.push(this.replaceCompound(rules.length == 1
3048
+ ? useIs
3049
+ ? withoutCompound[0] + ":is(&)"
3050
+ : selector.match(/^[.:]/) && withoutCompound[0].match(/^[a-zA-Z]+$/)
3051
+ ? withoutCompound[0] + compound
3052
+ : compound + withoutCompound[0]
3053
+ : withoutCompound[0].match(/^[a-zA-Z:]+$/)
3054
+ ? withoutCompound[0].trim() + compound
3055
+ : "&" +
3056
+ (withoutCompound[0].match(/^\S+$/)
3057
+ ? withoutCompound[0].trim()
3058
+ : ":is(" + withoutCompound[0].trim() + ")"), selector));
3059
+ }
3060
+ else {
3061
+ selectors.push(this.replaceCompound("&:is(" +
3062
+ withoutCompound.reduce((acc, curr) => acc + (acc.length > 0 ? "," : "") + curr.trim(), "") +
3063
+ ")", selector));
3064
+ }
3065
+ }
3066
+ if (withCompound.length > 0) {
3067
+ if (withCompound.length == 1) {
3068
+ selectors.push(this.replaceCompound(withCompound[0], selector));
3069
+ }
3070
+ }
3071
+ // inlined: this.setSelector(rule, selectors.reduce((acc, curr) => (curr.length == 0 ? acc : acc + (acc.length > 0 ? "," : "") + curr), ""))
3072
+ this.name[rule] = this.internString(selectors.reduce((acc, curr) => (curr.length == 0 ? acc : acc + (acc.length > 0 ? "," : "") + curr), ""));
3073
+ }
3074
+ place(rule);
3075
+ this.expandRule(rule, parent, before);
3076
+ }
3077
+ else if (typ == EnumToken.AtRuleNodeType) {
3078
+ const astAtRule = child;
3079
+ const atRuleName = this.strings[this.name[astAtRule]];
3080
+ if (atRuleName === "scope") {
3081
+ const atRuleValue = this.strings[this.stringValue[astAtRule]];
3082
+ if (atRuleValue.includes("&")) {
3083
+ // inlined: this.setValueString(astAtRule, this.replaceCompound(atRuleValue, sel))
3084
+ this.stringValue[astAtRule] = this.internString(this.replaceCompound(atRuleValue, sel));
3085
+ }
3086
+ let hasNesting = false;
3087
+ for (let t = this.firstChild[astAtRule]; t != 0; t = this.nextSibling[t]) {
3088
+ if (this.dataTypes[t] == EnumToken.RuleNodeType &&
3089
+ this.strings[this.name[t]].includes("&")) {
3090
+ hasNesting = true;
3091
+ break;
3092
+ }
3093
+ }
3094
+ if (hasNesting) {
3095
+ // expand the nested rules against the parent selector
3096
+ const clone = this.clone(node);
3097
+ this.moveChildren(astAtRule, clone);
3098
+ this.expandRule(clone, astAtRule, 0);
3099
+ // declarations stay in the at-rule, before the expanded rules
3100
+ this.moveChildren(clone, astAtRule, this.firstChild[astAtRule]);
3101
+ }
3102
+ place(astAtRule);
3103
+ }
3104
+ else {
3105
+ const clone = this.clone(ast);
3106
+ // the rules are expanded inside the at-rule: [clone, ...expanded nodes]
3107
+ this.moveChildren(astAtRule, clone);
3108
+ this.expandRule(clone, astAtRule, 0);
3109
+ if (this.firstChild[clone] != 0) {
3110
+ // the rule declarations are wrapped in the clone, before the expanded nodes
3111
+ if (this.firstChild[astAtRule] == 0) {
3112
+ this.appendChild(astAtRule, clone);
3113
+ }
3114
+ else {
3115
+ this.insertBefore(this.firstChild[astAtRule], clone);
3116
+ }
3117
+ }
3118
+ place(astAtRule);
3119
+ // the expanded at-rules are moved after the at-rule
3120
+ let r = this.firstChild[astAtRule];
3121
+ while (r != 0) {
3122
+ const nextRule = this.nextSibling[r];
3123
+ if (this.dataTypes[r] == EnumToken.AtRuleNodeType) {
3124
+ if (this.flags[r] & EnumAstNodeStatus.HasChildren) {
3125
+ const val = this.strings[this.stringValue[astAtRule]];
3126
+ const rVal = this.strings[this.stringValue[r]];
3127
+ if (val !== "" && rVal !== "") {
3128
+ const rName = this.strings[this.name[r]];
3129
+ if (atRuleName === "media" && rName === "media") {
3130
+ // inlined: this.setValueString(r, val + " and " + rVal)
3131
+ this.stringValue[r] = this.internString((val + " and " + rVal));
3132
+ }
3133
+ else if (atRuleName == "layer" && rName == "layer") {
3134
+ // inlined: this.setValueString(r, val + "." + rVal)
3135
+ this.stringValue[r] = this.internString((val + "." + rVal));
3136
+ }
3137
+ }
3138
+ place(r);
3139
+ }
3140
+ else {
3141
+ this.detach(r);
3142
+ }
3143
+ }
3144
+ r = nextRule;
3145
+ }
3146
+ }
3147
+ if (this.firstChild[astAtRule] == 0) {
3148
+ this.detach(astAtRule);
3149
+ }
3150
+ }
3151
+ child = next;
3152
+ }
3153
+ }
3154
+ if (this.firstChild[ast] == 0) {
3155
+ this.detach(ast);
3156
+ }
3157
+ }
3158
+ /**
3159
+ * replace the nesting selector '&' of a selector
3160
+ * @internal
3161
+ * @param input
3162
+ * @param replace
3163
+ */
3164
+ replaceCompound(input, replace) {
3165
+ const tokens = parseString(this, input);
3166
+ // inlined: this.walkValues(tokens)
3167
+ for (const t of new ValueWalker(this, tokens)) {
3168
+ if (this.dataTypes[t] == EnumToken.NestingSelectorTokenType) {
3169
+ if (tokens.length == 2) {
3170
+ this.resetToken(t, EnumToken.LiteralTokenType, this.replaceCompoundLiteral(this.strings[this.stringValue[t]], replace));
3171
+ continue;
3172
+ }
3173
+ const rule = splitRule(replace);
3174
+ this.resetToken(t, EnumToken.LiteralTokenType, rule.length > 1 ? ":is(" + replace + ")" : replace);
3175
+ }
3176
+ }
3177
+ return tokens.reduce((acc, curr) => acc + renderValue(this, curr), "");
3178
+ }
3179
+ replaceCompoundLiteral(selector, replace) {
3180
+ const tokens = [""];
3181
+ let i = 0;
3182
+ for (; i < selector.length; i++) {
3183
+ if (selector.charAt(i) == "&") {
3184
+ tokens.push("&", "");
3185
+ }
3186
+ }
3187
+ return tokens
3188
+ .sort((a, b) => {
3189
+ if (a == "&") {
3190
+ return 1;
3191
+ }
3192
+ return b == "&" ? -1 : 0;
3193
+ })
3194
+ .reduce((acc, curr) => acc + (curr == "&" ? replace : curr), "");
3195
+ }
3196
+ }
3197
+
3198
+ export { Arena, AstArena, TokenField, arenaColumns, numericTokenTypes, structuredFields, structuredTokenTypes };