@chikx/compiler 0.1.0 → 0.1.1

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 (85) hide show
  1. package/README.md +5 -5
  2. package/package.json +3 -3
  3. package/src/emitter/index.ts +658 -0
  4. package/src/formatter/index.ts +544 -0
  5. package/src/host/node.ts +85 -0
  6. package/src/index.ts +1021 -0
  7. package/src/ir/factories.ts +85 -0
  8. package/src/ir/index.ts +28 -0
  9. package/src/ir/types.ts +145 -0
  10. package/src/lexer/at-keywords.ts +35 -0
  11. package/src/lexer/characters.ts +82 -0
  12. package/src/lexer/comments.ts +27 -0
  13. package/src/lexer/diagnostics.ts +42 -0
  14. package/src/lexer/dollar-refs.ts +23 -0
  15. package/src/lexer/index.ts +37 -0
  16. package/src/lexer/names.ts +49 -0
  17. package/src/lexer/numbers.ts +59 -0
  18. package/src/lexer/scanner.ts +199 -0
  19. package/src/lexer/strings.ts +52 -0
  20. package/src/lexer/urls.ts +63 -0
  21. package/src/lowering/expand-groups.ts +206 -0
  22. package/src/lowering/group.ts +119 -0
  23. package/src/lowering/index.ts +43 -0
  24. package/src/lowering/lower.ts +441 -0
  25. package/src/lowering/media.ts +314 -0
  26. package/src/lowering/merge.ts +163 -0
  27. package/src/lowering/property-families.ts +194 -0
  28. package/src/lowering/spans.ts +118 -0
  29. package/src/naming/index.ts +44 -0
  30. package/src/naming/mapgen.ts +252 -0
  31. package/src/naming/merge.ts +114 -0
  32. package/src/naming/rewrite.ts +333 -0
  33. package/src/naming/scan.ts +267 -0
  34. package/src/naming/table.ts +153 -0
  35. package/src/naming/types.ts +100 -0
  36. package/src/output/import-path.ts +30 -0
  37. package/src/output/index.ts +213 -0
  38. package/src/output/manifest.ts +28 -0
  39. package/src/output/paths.ts +200 -0
  40. package/src/output/resolve.ts +401 -0
  41. package/src/output/validate.ts +251 -0
  42. package/src/parser/cursor.ts +138 -0
  43. package/src/parser/declaration.ts +247 -0
  44. package/src/parser/diagnostics.ts +75 -0
  45. package/src/parser/group.ts +303 -0
  46. package/src/parser/index.ts +50 -0
  47. package/src/parser/modifier.ts +60 -0
  48. package/src/parser/recovery.ts +88 -0
  49. package/src/parser/rule.ts +370 -0
  50. package/src/parser/statement.ts +47 -0
  51. package/src/parser/statements.ts +667 -0
  52. package/src/parser/value.ts +265 -0
  53. package/src/resolver/graph.ts +467 -0
  54. package/src/resolver/groups.ts +177 -0
  55. package/src/resolver/index.ts +68 -0
  56. package/src/resolver/keyframes.ts +131 -0
  57. package/src/resolver/paths.ts +142 -0
  58. package/src/resolver/rules.ts +54 -0
  59. package/src/resolver/scopes.ts +342 -0
  60. package/src/resolver/types.ts +259 -0
  61. package/src/selectors/flatten.ts +448 -0
  62. package/src/selectors/index.ts +14 -0
  63. package/src/selectors/scan.ts +227 -0
  64. package/src/selectors/specificity.ts +319 -0
  65. package/src/setup-list.ts +172 -0
  66. package/src/sourcemaps/index.ts +25 -0
  67. package/src/sourcemaps/mappings.ts +190 -0
  68. package/src/sourcemaps/vlq.ts +29 -0
  69. package/src/types/ast.ts +318 -0
  70. package/src/types/diagnostics.ts +124 -0
  71. package/src/types/options.ts +286 -0
  72. package/src/types/result.ts +121 -0
  73. package/src/types/span.ts +18 -0
  74. package/src/types/token.ts +77 -0
  75. package/src/variables/ast.ts +182 -0
  76. package/src/variables/expand.ts +319 -0
  77. package/src/variables/index.ts +38 -0
  78. package/src/variables/naming.ts +46 -0
  79. package/src/variables/runtime.ts +336 -0
  80. package/src/variables/substitute.ts +148 -0
  81. package/src/variables/walk.ts +147 -0
  82. package/dist/output/importPath.d.ts +0 -27
  83. package/dist/output/importPath.d.ts.map +0 -1
  84. package/dist/output/importPath.js +0 -84
  85. package/dist/output/importPath.js.map +0 -1
@@ -0,0 +1,448 @@
1
+ import { nativeBlockIr, ruleIr, stylesheetIr } from "../ir/factories.js";
2
+ import type {
3
+ DeclarationIr,
4
+ NativeBlockChild,
5
+ NativeBlockIr,
6
+ RuleIr,
7
+ StylesheetIr,
8
+ } from "../ir/types.js";
9
+ import type { Diagnostic } from "../types/diagnostics.js";
10
+ import { error } from "../types/diagnostics.js";
11
+ import type { Span } from "../types/span.js";
12
+ import { scanSelector, splitSelectorList } from "./scan.js";
13
+ import type { Specificity } from "./specificity.js";
14
+ import { addSpecificity, compareSpecificity, specificityOfItem } from "./specificity.js";
15
+
16
+ /**
17
+ * Nested-selector flattening (ADR-0002, ADR-0012, SPECIFICATION.md §7.1).
18
+ *
19
+ * `flattenSelector` is pure: it takes the raw authored selector of one rule
20
+ * and the raw authored selectors of its enclosing rules (outermost-first) and
21
+ * returns a flat selector list. It never reads the AST, mutates its input or
22
+ * throws.
23
+ *
24
+ * Policy summary:
25
+ *
26
+ * - A nested selector without `&` is a descendant: `parent + " " + child`
27
+ * (ADR-0002).
28
+ * - `&` is substituted in any position, including trailing and repeated
29
+ * (ADR-0012). A backslash-escaped `\&` stays literal, and `&` inside strings,
30
+ * comments and attribute selectors is never rewritten.
31
+ * - A parent that resolves to one selector substitutes directly. A complex
32
+ * parent (contains a top-level combinator) is wrapped in `:is(...)` when `&`
33
+ * is attached to a prefix such as `.x&` or `&&`, because plain concatenation
34
+ * would change meaning.
35
+ * - A parent selector list with equal, known specificity expands as the CSS
36
+ * cross-product in authored order. A parent list with mixed or unknown
37
+ * specificity substitutes `:is(list)`, which is exactly native nesting
38
+ * specificity. Mixed-specificity lists containing pseudo-elements are
39
+ * rejected because `:is()` cannot accept them.
40
+ * - A nested rule's own selector list expands as a cross-product: each child
41
+ * item is expanded against every parent alternative in authored order.
42
+ * - Rejected cases return a reason: `&` outside a nested rule, empty selector
43
+ * list items, unbalanced structures, leading combinators (relative nested
44
+ * selectors need an explicit `&` per §7.1) and the pseudo-element case
45
+ * above. The emitter turns a rejection into CHIKX1001.
46
+ * - Expansion is bounded per rule by {@link FLATTEN_LIMITS}. A level that
47
+ * carries repeated `&` duplicates the selector product (and its character
48
+ * count) at every step, so a pathological but syntactically valid document
49
+ * would otherwise grow without bound; the bound rejects that rule with the
50
+ * same CHIKX1001 diagnostic while legal nesting is unaffected.
51
+ */
52
+
53
+ /**
54
+ * Per-rule bounds on flattened-selector expansion.
55
+ *
56
+ * A nesting level carrying two `&`s squares the selector product, and a `&`
57
+ * pair against a single parent doubles the selector length, so adversarial
58
+ * input grows exponentially. These limits cap one rule's flattened selector
59
+ * list; exceeding either aborts flattening with a CHIKX1001 diagnostic instead
60
+ * of hanging or exhausting memory.
61
+ *
62
+ * The defaults are deliberately generous: the committed scale case (a
63
+ * 1 000-level `&.m<n>` chain ending in a 500-item selector list) flattens to
64
+ * ~2.45 M characters in 500 alternatives, well inside the budget, while a
65
+ * 1 000-level `& &` chain aborts after roughly two dozen levels.
66
+ */
67
+ export const FLATTEN_LIMITS = Object.freeze({
68
+ /** Maximum characters in one rule's flattened selector list (joined by `", "`). */
69
+ maxSelectorChars: 8_388_608,
70
+ /** Maximum number of flat alternatives in one rule's selector list. */
71
+ maxSelectors: 100_000,
72
+ });
73
+
74
+ /** One flat alternative plus its estimated specificity. */
75
+ interface Alternative {
76
+ readonly selector: string;
77
+ readonly specificity: Specificity | null;
78
+ }
79
+
80
+ /** Successful flattening. */
81
+ export interface FlattenedSelector {
82
+ readonly ok: true;
83
+ /** Flat selector list, items joined with `", "`. */
84
+ readonly selector: string;
85
+ }
86
+
87
+ /** Rejected flattening with a user-facing reason for the emitter diagnostic. */
88
+ export interface FlattenFailure {
89
+ readonly ok: false;
90
+ readonly reason: string;
91
+ }
92
+
93
+ /** Result of {@link flattenSelector}. */
94
+ export type FlattenResult = FlattenedSelector | FlattenFailure;
95
+
96
+ type ItemResult = { readonly ok: true; readonly items: readonly Alternative[] } | FlattenFailure;
97
+
98
+ function failure(reason: string): FlattenFailure {
99
+ return { ok: false, reason };
100
+ }
101
+
102
+ function diagnosticFor(selector: string, reason: string, span: Span): Diagnostic {
103
+ return error("CHIKX1001", `Cannot flatten selector "${selector}": ${reason}`, span);
104
+ }
105
+
106
+ /** Human-readable bound used in the expansion-limit reason. */
107
+ function limitFailure(depth: number): FlattenFailure {
108
+ return failure(
109
+ `selector expansion exceeded the flattening limit of ${FLATTEN_LIMITS.maxSelectorChars} characters and ${FLATTEN_LIMITS.maxSelectors} selectors at nesting depth ${depth}; reduce repeated "&" or nested selector lists`,
110
+ );
111
+ }
112
+
113
+ /** Exact joined-list size check (`items.join(", ")`). */
114
+ function exceedsLimits(selectors: readonly string[]): boolean {
115
+ if (selectors.length > FLATTEN_LIMITS.maxSelectors) return true;
116
+ let chars = selectors.length === 0 ? 0 : (selectors.length - 1) * 2;
117
+ for (const selector of selectors) {
118
+ chars += selector.length;
119
+ if (chars > FLATTEN_LIMITS.maxSelectorChars) return true;
120
+ }
121
+ return false;
122
+ }
123
+
124
+ /** True when `parent` has no top-level combinator and is therefore one compound. */
125
+ function isCompound(parent: string): boolean {
126
+ const scan = scanSelector(parent);
127
+ return scan.ok && !scan.hasTopLevelCombinator;
128
+ }
129
+
130
+ /**
131
+ * True when the `&` at `position` is attached to a preceding simple selector
132
+ * (for example `.x&`, `:not(.y)&` or `&&`) rather than starting a compound.
133
+ */
134
+ function isPrefixAttached(text: string, position: number): boolean {
135
+ if (position === 0) return false;
136
+ const previous = text.charAt(position - 1);
137
+ return previous !== "" && !/[\s>+~|,(]/.test(previous);
138
+ }
139
+
140
+ function substitute(
141
+ item: string,
142
+ ampersands: readonly number[],
143
+ parent: readonly Alternative[],
144
+ depth: number,
145
+ ): ItemResult {
146
+ if (parent.length === 0) return failure('"&" has no enclosing rule to resolve against');
147
+
148
+ const first = parent[0];
149
+ if (first === undefined) return failure('"&" has no enclosing rule to resolve against');
150
+ if (parent.length === 1) {
151
+ const needsIs =
152
+ !isCompound(first.selector) &&
153
+ ampersands.some((position) => isPrefixAttached(item, position));
154
+ const replacement = needsIs ? `:is(${first.selector})` : first.selector;
155
+ const projected = item.length - ampersands.length + ampersands.length * replacement.length;
156
+ if (projected > FLATTEN_LIMITS.maxSelectorChars) return limitFailure(depth);
157
+ let result = "";
158
+ let cursor = 0;
159
+ for (const position of ampersands) {
160
+ result += item.slice(cursor, position) + replacement;
161
+ cursor = position + 1;
162
+ if (result.length > FLATTEN_LIMITS.maxSelectorChars) return limitFailure(depth);
163
+ }
164
+ result += item.slice(cursor);
165
+ if (result.length > FLATTEN_LIMITS.maxSelectorChars) return limitFailure(depth);
166
+ return {
167
+ ok: true,
168
+ items: [{ selector: result, specificity: specificityOfItem(result) }],
169
+ };
170
+ }
171
+
172
+ let partial: string[] = [""];
173
+ let cursor = 0;
174
+ for (const position of ampersands) {
175
+ const literal = item.slice(cursor, position);
176
+ const choices: string[] = [];
177
+ for (const alternative of parent) {
178
+ const wrap = !isCompound(alternative.selector) && isPrefixAttached(item, position);
179
+ choices.push(wrap ? `:is(${alternative.selector})` : alternative.selector);
180
+ }
181
+ if (partial.length * choices.length > FLATTEN_LIMITS.maxSelectors) return limitFailure(depth);
182
+ const next: string[] = [];
183
+ let nextChars = 0;
184
+ for (const prefix of partial) {
185
+ for (const choice of choices) {
186
+ const projected = prefix.length + literal.length + choice.length;
187
+ if (projected > FLATTEN_LIMITS.maxSelectorChars) return limitFailure(depth);
188
+ next.push(prefix + literal + choice);
189
+ nextChars += projected;
190
+ if (nextChars + (next.length - 1) * 2 > FLATTEN_LIMITS.maxSelectorChars) {
191
+ return limitFailure(depth);
192
+ }
193
+ }
194
+ }
195
+ partial = next;
196
+ cursor = position + 1;
197
+ }
198
+
199
+ const tail = item.slice(cursor);
200
+ const items: Alternative[] = [];
201
+ let chars = partial.length === 0 ? 0 : (partial.length - 1) * 2;
202
+ for (const prefix of partial) {
203
+ const selector = prefix + tail;
204
+ chars += selector.length;
205
+ if (chars > FLATTEN_LIMITS.maxSelectorChars) return limitFailure(depth);
206
+ items.push({ selector, specificity: specificityOfItem(selector) });
207
+ }
208
+ return { ok: true, items };
209
+ }
210
+
211
+ function descend(item: string, parent: readonly Alternative[], depth: number): ItemResult {
212
+ const childSpecificity = specificityOfItem(item);
213
+ const items: Alternative[] = [];
214
+ let chars = parent.length === 0 ? 0 : (parent.length - 1) * 2;
215
+ for (const alternative of parent) {
216
+ const selector = `${alternative.selector} ${item}`;
217
+ chars += selector.length;
218
+ if (chars > FLATTEN_LIMITS.maxSelectorChars) return limitFailure(depth);
219
+ items.push({
220
+ selector,
221
+ specificity: addSpecificity(alternative.specificity, childSpecificity),
222
+ });
223
+ }
224
+ return { ok: true, items };
225
+ }
226
+
227
+ function flattenAgainstParent(
228
+ text: string,
229
+ parent: readonly Alternative[] | null,
230
+ depth: number,
231
+ ): ItemResult {
232
+ if (text.length > FLATTEN_LIMITS.maxSelectorChars) return limitFailure(depth);
233
+ const list = splitSelectorList(text);
234
+ if (!list.ok) return failure(list.reason);
235
+
236
+ const results: Alternative[] = [];
237
+ let chars = 0;
238
+ const append = (items: readonly Alternative[]): FlattenFailure | null => {
239
+ for (const item of items) {
240
+ results.push(item);
241
+ chars += item.selector.length + (results.length === 1 ? 0 : 2);
242
+ if (results.length > FLATTEN_LIMITS.maxSelectors || chars > FLATTEN_LIMITS.maxSelectorChars) {
243
+ return limitFailure(depth);
244
+ }
245
+ }
246
+ return null;
247
+ };
248
+ for (const item of list.items) {
249
+ const scan = scanSelector(item);
250
+ if (!scan.ok) return failure(scan.reason);
251
+ if (scan.leadingCombinator) {
252
+ return failure(
253
+ 'a selector starting with a combinator requires an explicit "&" (SPECIFICATION.md §7.1)',
254
+ );
255
+ }
256
+
257
+ if (parent === null) {
258
+ if (scan.ampersands.length > 0) {
259
+ return failure('"&" has no enclosing rule to resolve against');
260
+ }
261
+ const overflow = append([{ selector: item, specificity: specificityOfItem(item) }]);
262
+ if (overflow !== null) return overflow;
263
+ continue;
264
+ }
265
+
266
+ if (scan.ampersands.length > 0) {
267
+ const substituted = substitute(item, scan.ampersands, parent, depth);
268
+ if (!substituted.ok) return substituted;
269
+ const overflow = append(substituted.items);
270
+ if (overflow !== null) return overflow;
271
+ } else {
272
+ const descended = descend(item, parent, depth);
273
+ if (!descended.ok) return descended;
274
+ const overflow = append(descended.items);
275
+ if (overflow !== null) return overflow;
276
+ }
277
+ }
278
+
279
+ return { ok: true, items: results };
280
+ }
281
+
282
+ /**
283
+ * Normalize a resolved ancestor list before it is used as a substitution
284
+ * parent. Equal, known specificity may stay a list (cross-product); a mixed or
285
+ * unknown list collapses to one `:is(...)` alternative.
286
+ */
287
+ function normalizeParent(
288
+ parent: readonly Alternative[],
289
+ ): { readonly ok: true; readonly parent: readonly Alternative[] } | FlattenFailure {
290
+ if (parent.length <= 1) return { ok: true, parent };
291
+
292
+ const firstSpecificity = parent[0]?.specificity ?? null;
293
+ const equal =
294
+ firstSpecificity !== null &&
295
+ parent.every(
296
+ (alternative) =>
297
+ alternative.specificity !== null &&
298
+ compareSpecificity(alternative.specificity, firstSpecificity) === 0,
299
+ );
300
+ if (equal) return { ok: true, parent };
301
+
302
+ for (const alternative of parent) {
303
+ const scan = scanSelector(alternative.selector);
304
+ if (scan.ok && scan.hasPseudoElement) {
305
+ return failure(
306
+ "mixed-specificity parent selector lists containing pseudo-elements cannot be represented with :is(...)",
307
+ );
308
+ }
309
+ }
310
+
311
+ let maximum: Specificity | null = null;
312
+ let unknown = false;
313
+ for (const alternative of parent) {
314
+ if (alternative.specificity === null) {
315
+ unknown = true;
316
+ break;
317
+ }
318
+ if (maximum === null || compareSpecificity(alternative.specificity, maximum) > 0) {
319
+ maximum = alternative.specificity;
320
+ }
321
+ }
322
+
323
+ const joined = parent.map((alternative) => alternative.selector).join(", ");
324
+ return {
325
+ ok: true,
326
+ parent: [{ selector: `:is(${joined})`, specificity: unknown ? null : maximum }],
327
+ };
328
+ }
329
+
330
+ function resolveAncestors(
331
+ ancestors: readonly string[],
332
+ ): { readonly ok: true; readonly parent: readonly Alternative[] | null } | FlattenFailure {
333
+ const depth = ancestors.length + 1;
334
+ let resolved: readonly Alternative[] | null = null;
335
+ for (const ancestor of ancestors) {
336
+ const normalized = resolved === null ? null : normalizeParent(resolved);
337
+ if (normalized !== null && !normalized.ok) return normalized;
338
+ const folded = flattenAgainstParent(
339
+ ancestor,
340
+ normalized === null ? null : normalized.parent,
341
+ depth,
342
+ );
343
+ if (!folded.ok) return folded;
344
+ resolved = folded.items;
345
+ }
346
+ if (resolved === null) return { ok: true, parent: null };
347
+ const normalized = normalizeParent(resolved);
348
+ if (!normalized.ok) return normalized;
349
+ if (exceedsLimits(normalized.parent.map((alternative) => alternative.selector))) {
350
+ return limitFailure(depth);
351
+ }
352
+ return { ok: true, parent: normalized.parent };
353
+ }
354
+
355
+ /**
356
+ * Flatten one authored selector against its authored ancestor selectors.
357
+ *
358
+ * Pure and deterministic: the returned selector list preserves authored item
359
+ * order, cross-product order and all non-`&` tokens. A rejection carries a
360
+ * reason suitable for a CHIKX1001-family diagnostic. Expansion is bounded by
361
+ * {@link FLATTEN_LIMITS}; a document that exceeds it fails with one rejection
362
+ * instead of hanging or exhausting memory.
363
+ */
364
+ export function flattenSelector(selector: string, ancestors: readonly string[]): FlattenResult {
365
+ const depth = ancestors.length + 1;
366
+ const resolved = resolveAncestors(ancestors);
367
+ if (!resolved.ok) return resolved;
368
+ const folded = flattenAgainstParent(selector, resolved.parent, depth);
369
+ if (!folded.ok) return folded;
370
+ const selectors = folded.items.map((item) => item.selector);
371
+ if (exceedsLimits(selectors)) return limitFailure(depth);
372
+ return {
373
+ ok: true,
374
+ selector: selectors.join(", "),
375
+ };
376
+ }
377
+
378
+ function flattenRuleNode(rule: RuleIr, diagnostics: Diagnostic[]): RuleIr | null {
379
+ const flattened = flattenSelector(rule.selector, rule.ancestors);
380
+ if (!flattened.ok) {
381
+ diagnostics.push(diagnosticFor(rule.selector, flattened.reason, rule.span));
382
+ return null;
383
+ }
384
+ return ruleIr({
385
+ selector: flattened.selector,
386
+ ancestors: [],
387
+ declarations: rule.declarations,
388
+ condition: rule.condition,
389
+ context: rule.context,
390
+ span: rule.span,
391
+ });
392
+ }
393
+
394
+ function flattenNativeNode(block: NativeBlockIr, diagnostics: Diagnostic[]): NativeBlockIr {
395
+ return nativeBlockIr({
396
+ name: block.name,
397
+ prelude: block.prelude,
398
+ ...(block.statement === true ? { statement: true } : {}),
399
+ children: flattenChildren(block.children, diagnostics),
400
+ span: block.span,
401
+ });
402
+ }
403
+
404
+ function flattenChildren(
405
+ children: readonly NativeBlockChild[],
406
+ diagnostics: Diagnostic[],
407
+ ): readonly NativeBlockChild[] {
408
+ const flattened: NativeBlockChild[] = [];
409
+ for (const child of children) {
410
+ if ("children" in child) {
411
+ flattened.push(flattenNativeNode(child, diagnostics));
412
+ continue;
413
+ }
414
+ if ("declarations" in child) {
415
+ const rule = flattenRuleNode(child, diagnostics);
416
+ if (rule !== null) flattened.push(rule);
417
+ continue;
418
+ }
419
+ flattened.push(child as DeclarationIr);
420
+ }
421
+ return flattened;
422
+ }
423
+
424
+ /**
425
+ * Flatten every rule selector in a stylesheet IR and clear `ancestors`.
426
+ *
427
+ * This is the explicit pipeline step between `groupRuns` and `emitCss`. Rules
428
+ * whose selector cannot be flattened are omitted with a CHIKX1001 diagnostic;
429
+ * callers that emit the original IR instead get the same rejection from
430
+ * `emitCss` directly. Declaration, condition, context and span data are
431
+ * preserved unchanged.
432
+ */
433
+ export function flattenIr(ir: StylesheetIr): {
434
+ readonly ir: StylesheetIr;
435
+ readonly diagnostics: readonly Diagnostic[];
436
+ } {
437
+ const diagnostics: Diagnostic[] = [];
438
+ const rules: (RuleIr | NativeBlockIr)[] = [];
439
+ for (const node of ir.rules) {
440
+ if ("children" in node) {
441
+ rules.push(flattenNativeNode(node, diagnostics));
442
+ continue;
443
+ }
444
+ const rule = flattenRuleNode(node, diagnostics);
445
+ if (rule !== null) rules.push(rule);
446
+ }
447
+ return { ir: stylesheetIr(rules), diagnostics: Object.freeze(diagnostics) };
448
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Selector flattening: nested authored selectors to flat CSS selector lists.
3
+ *
4
+ * The module is pure and zero-dependency. `flattenSelector` implements the
5
+ * nesting contract of ADR-0002 (bare nested selector = descendant) and
6
+ * ADR-0012 (`&` substitution in any position, escaped ampersands and strings
7
+ * untouched). `flattenIr` applies the same logic to a lowered stylesheet IR as
8
+ * the explicit pipeline step before `emitCss`.
9
+ *
10
+ * Class naming, prefixing and `:global(...)` removal are not performed here;
11
+ * they belong to P4/A09 and run after flattening.
12
+ */
13
+ export { FLATTEN_LIMITS, flattenIr, flattenSelector } from "./flatten.js";
14
+ export type { FlattenFailure, FlattenResult, FlattenedSelector } from "./flatten.js";
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Structural scanning of authored selector text.
3
+ *
4
+ * Selectors are raw source slices (ADR-0005), so every consumer that wants to
5
+ * split, rewrite or measure them must understand strings, comments, escapes,
6
+ * functional pseudos and attribute selectors. This module is the single
7
+ * scanner used by selector flattening and specificity estimation: it never
8
+ * rewrites text, never throws and reports a reason instead of failing.
9
+ */
10
+
11
+ /** Result of scanning one selector (or selector list) slice. */
12
+ export interface SelectorScan {
13
+ /** `false` when the text is structurally malformed; every array is then empty. */
14
+ readonly ok: boolean;
15
+ /** Human-readable rejection reason; empty when {@link ok} is `true`. */
16
+ readonly reason: string;
17
+ /** Offsets of unescaped `&` characters outside strings, comments and attribute selectors. */
18
+ readonly ampersands: readonly number[];
19
+ /** Offsets of top-level commas (selector-list separators). */
20
+ readonly commas: readonly number[];
21
+ /** `true` when the trimmed text starts with `>`, `+`, `~` or `||`. */
22
+ readonly leadingCombinator: boolean;
23
+ /** `true` when a top-level combinator separates compounds (`a b`, `a > b`). */
24
+ readonly hasTopLevelCombinator: boolean;
25
+ /** `true` when a `::` sequence occurs outside strings and comments. */
26
+ readonly hasPseudoElement: boolean;
27
+ }
28
+
29
+ function failure(reason: string): SelectorScan {
30
+ return {
31
+ ok: false,
32
+ reason,
33
+ ampersands: [],
34
+ commas: [],
35
+ leadingCombinator: false,
36
+ hasTopLevelCombinator: false,
37
+ hasPseudoElement: false,
38
+ };
39
+ }
40
+
41
+ /** Legacy single-colon pseudo-elements, which `:is(...)` cannot contain either. */
42
+ const LEGACY_PSEUDO_ELEMENTS: ReadonlySet<string> = new Set([
43
+ "before",
44
+ "after",
45
+ "first-line",
46
+ "first-letter",
47
+ ]);
48
+
49
+ /** Read a plain name without decoding escapes (pseudo-element names are plain). */
50
+ function readPlainName(text: string, start: number): string {
51
+ let index = start;
52
+ while (index < text.length) {
53
+ const character = text.charAt(index);
54
+ if (!/[A-Za-z0-9_-]/.test(character)) break;
55
+ index += 1;
56
+ }
57
+ return text.slice(start, index).toLowerCase();
58
+ }
59
+
60
+ /** True for CSS whitespace characters (selector whitespace is only these). */
61
+ export function isWhitespace(character: string): boolean {
62
+ return (
63
+ character === " " ||
64
+ character === "\t" ||
65
+ character === "\n" ||
66
+ character === "\r" ||
67
+ character === "\f"
68
+ );
69
+ }
70
+
71
+ /** True when `text` (already trimmed) begins with an explicit combinator. */
72
+ function startsWithCombinator(text: string): boolean {
73
+ const first = text.charAt(0);
74
+ if (first === ">" || first === "+" || first === "~") return true;
75
+ return first === "|" && text.charAt(1) === "|";
76
+ }
77
+
78
+ /**
79
+ * Scan selector text for structural validity, ampersands and top-level commas.
80
+ *
81
+ * A backslash escapes the following character (CSS escapes are never decoded),
82
+ * quoted strings and comments stay opaque, attribute selectors are opaque to
83
+ * `&` search, and parentheses are balanced but do not hide ampersands because
84
+ * `&` may legally appear inside functional pseudos such as `:is(&)`.
85
+ */
86
+ export function scanSelector(text: string): SelectorScan {
87
+ const ampersands: number[] = [];
88
+ const commas: number[] = [];
89
+ const closers: Array<")" | "]"> = [];
90
+ let quote: '"' | "'" | null = null;
91
+ let inComment = false;
92
+ let escaped = false;
93
+ let hasTopLevelCombinator = false;
94
+ let hasPseudoElement = false;
95
+
96
+ for (let index = 0; index < text.length; index += 1) {
97
+ const character = text.charAt(index);
98
+
99
+ if (inComment) {
100
+ if (character === "*" && text.charAt(index + 1) === "/") {
101
+ inComment = false;
102
+ index += 1;
103
+ }
104
+ continue;
105
+ }
106
+
107
+ if (quote !== null) {
108
+ if (escaped) {
109
+ escaped = false;
110
+ continue;
111
+ }
112
+ if (character === "\\") {
113
+ escaped = true;
114
+ continue;
115
+ }
116
+ if (character === quote) quote = null;
117
+ continue;
118
+ }
119
+
120
+ if (escaped) {
121
+ escaped = false;
122
+ continue;
123
+ }
124
+ if (character === "\\") {
125
+ escaped = true;
126
+ continue;
127
+ }
128
+ if (character === "/" && text.charAt(index + 1) === "*") {
129
+ inComment = true;
130
+ index += 1;
131
+ continue;
132
+ }
133
+ if (character === '"' || character === "'") {
134
+ quote = character;
135
+ continue;
136
+ }
137
+ if (character === "(") {
138
+ closers.push(")");
139
+ continue;
140
+ }
141
+ if (character === "[") {
142
+ closers.push("]");
143
+ continue;
144
+ }
145
+ if (character === ")" || character === "]") {
146
+ if (closers.pop() !== character) {
147
+ return failure(`unbalanced "${character}"`);
148
+ }
149
+ continue;
150
+ }
151
+
152
+ if (character === ":" && text.charAt(index + 1) === ":") {
153
+ hasPseudoElement = true;
154
+ }
155
+
156
+ const insideAttribute = closers.length > 0 && closers[closers.length - 1] === "]";
157
+ if (character === ":" && !insideAttribute && text.charAt(index + 1) !== ":") {
158
+ if (LEGACY_PSEUDO_ELEMENTS.has(readPlainName(text, index + 1))) {
159
+ hasPseudoElement = true;
160
+ }
161
+ }
162
+ if (character === "&" && !insideAttribute) {
163
+ ampersands.push(index);
164
+ }
165
+
166
+ if (closers.length === 0) {
167
+ if (character === ",") {
168
+ commas.push(index);
169
+ } else if (
170
+ character === ">" ||
171
+ character === "+" ||
172
+ character === "~" ||
173
+ (character === "|" && text.charAt(index + 1) === "|") ||
174
+ isWhitespace(character)
175
+ ) {
176
+ hasTopLevelCombinator = true;
177
+ }
178
+ }
179
+ }
180
+
181
+ if (quote !== null) return failure("unterminated string");
182
+ if (inComment) return failure("unterminated comment");
183
+ if (escaped) return failure("trailing escape");
184
+ if (closers.length > 0) {
185
+ return failure(`unbalanced "${closers[closers.length - 1] ?? ")"}"`);
186
+ }
187
+
188
+ return {
189
+ ok: true,
190
+ reason: "",
191
+ ampersands,
192
+ commas,
193
+ leadingCombinator: startsWithCombinator(text.trimStart()),
194
+ hasTopLevelCombinator,
195
+ hasPseudoElement,
196
+ };
197
+ }
198
+
199
+ /** Result of splitting a selector list at top-level commas. */
200
+ export type SelectorListSplit =
201
+ | { readonly ok: true; readonly items: readonly string[] }
202
+ | { readonly ok: false; readonly reason: string };
203
+
204
+ /**
205
+ * Split authored selector text at top-level commas and trim each item.
206
+ *
207
+ * Commas inside strings, comments, attribute selectors and functional pseudos
208
+ * are ignored. Empty items are rejected because the emitter cannot produce a
209
+ * valid selector list from them.
210
+ */
211
+ export function splitSelectorList(text: string): SelectorListSplit {
212
+ const scan = scanSelector(text);
213
+ if (!scan.ok) return { ok: false, reason: scan.reason };
214
+
215
+ const items: string[] = [];
216
+ let start = 0;
217
+ for (const comma of scan.commas) {
218
+ items.push(text.slice(start, comma).trim());
219
+ start = comma + 1;
220
+ }
221
+ items.push(text.slice(start).trim());
222
+
223
+ if (items.some((item) => item.length === 0)) {
224
+ return { ok: false, reason: "empty selector list item" };
225
+ }
226
+ return { ok: true, items };
227
+ }