@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
package/README.md CHANGED
@@ -9,8 +9,7 @@ configuration file (`chikx.config.json`) and diagnostic codes (`CHIKX####`) keep
9
9
 
10
10
  ## Install
11
11
 
12
- Not on npm yet — the 0.1.0 publication is parked; use the source checkout in the repository README
13
- until then.
12
+ Published on npm as **0.1.0** (2026-11-26):
14
13
 
15
14
  ```sh
16
15
  npm install @chikx/compiler
@@ -18,17 +17,18 @@ npm install @chikx/compiler
18
17
 
19
18
  ## Use
20
19
 
20
+ `compile()` is async; await it. It returns artifacts and never writes files.
21
+
21
22
  ```ts
22
23
  import { compile } from "@chikx/compiler";
23
24
 
24
- const result = compile(source, { sourceFile: "src/button.cssx" });
25
+ const result = await compile(source, { sourceFile: "src/button.cssx" });
25
26
  if (result.diagnostics.some((diagnostic) => diagnostic.severity === "error")) {
26
27
  throw new Error(result.diagnostics.map((diagnostic) => diagnostic.message).join("\n"));
27
28
  }
28
29
  ```
29
30
 
30
- `compile` returns artifacts and never writes files. Project builds, output planning, the CLI and the
31
- VS Code extension are built on the same entry points.
31
+ Project builds, output planning, the CLI and the VS Code extension are built on the same entry points.
32
32
 
33
33
  ## Documentation
34
34
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chikx/compiler",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Chikx lexer, parser, resolver, transformer and CSS/JS generators. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,10 +28,10 @@
28
28
  "default": "./dist/index.js"
29
29
  }
30
30
  },
31
- "files": ["dist"],
31
+ "files": ["dist", "src"],
32
32
  "sideEffects": false,
33
33
  "scripts": {
34
34
  "typecheck": "tsc -p tsconfig.json --noEmit",
35
- "build": "tsc -p tsconfig.json"
35
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json"
36
36
  }
37
37
  }
@@ -0,0 +1,658 @@
1
+ import type {
2
+ AtRuleContextIr,
3
+ DeclarationIr,
4
+ MediaConditionIr,
5
+ NativeBlockIr,
6
+ RuleIr,
7
+ StylesheetIr,
8
+ } from "../ir/types.js";
9
+ import { flattenSelector } from "../selectors/index.js";
10
+ import {
11
+ generateSourceMap,
12
+ offsetToLineColumn,
13
+ serializeSourceMap,
14
+ sourceMapComment,
15
+ } from "../sourcemaps/index.js";
16
+ import type { SourceMapping } from "../sourcemaps/index.js";
17
+ import type { Diagnostic } from "../types/diagnostics.js";
18
+ import { error } from "../types/diagnostics.js";
19
+ import type { Span } from "../types/span.js";
20
+
21
+ /**
22
+ * Deterministic CSS text emission from the lowered stylesheet IR
23
+ * (SPECIFICATION.md §9 `minify`, §5 cascade contract).
24
+ *
25
+ * The emitter is pure: it never reads the filesystem, never mutates the IR and
26
+ * never throws. It emits nodes in IR order, never reorders, merges or
27
+ * deduplicates declarations, and never propagates `!important`: the raw
28
+ * `DeclarationIr.value` already contains the authored `!important` text
29
+ * (ADR-0003), so appending the flag would duplicate it.
30
+ *
31
+ * Formatting conventions:
32
+ *
33
+ * - Pretty mode uses two-space indentation, one declaration per line with a
34
+ * trailing `;` on every declaration, and one blank line between sibling
35
+ * rules or at-rules. The stylesheet ends with one `\n`.
36
+ * - `minify: true` compacts only structural whitespace (indentation, newlines,
37
+ * the space after `:` and spaces around braces). Selector text, declaration
38
+ * values, quoted strings, `url(...)`, `calc(...)` internals and at-rule
39
+ * preludes are emitted exactly as they appear in the IR. The output is
40
+ * therefore the pretty output with structural whitespace removed.
41
+ * - Output uses `\n` for structural newlines on every platform; CRLF or other
42
+ * bytes inside raw IR values are emitted unchanged.
43
+ *
44
+ * Native wrappers: a {@link NativeBlockIr} emits its own at-rule once, and
45
+ * child rules pass the already-emitted wrapper chain so their `context` is not
46
+ * emitted a second time. For a rule whose context is not represented by an
47
+ * ancestor native block (normal lowering always represents it), the remaining
48
+ * media contexts and the resolved Chikx condition are ANDed into one `@media`
49
+ * wrapper when the parts can form a valid single query (plain conditions plus
50
+ * at most one media type, which is placed first); `not`, comma lists and
51
+ * top-level `or` nest as separate wrappers. Non-media contexts nest outside the
52
+ * media wrapper (SPECIFICATION.md §3.5).
53
+ */
54
+
55
+ /** Emitter options; `minify` is the opt-in compact output flag from §9. */
56
+ export interface EmitOptions {
57
+ /** Compact structural whitespace only; authored tokens are preserved. */
58
+ readonly minify: boolean;
59
+ /** When present, emit a standard v3 source map and the trailing URL comment. */
60
+ readonly sourceMap?: EmitSourceMapOptions;
61
+ }
62
+
63
+ /**
64
+ * Source-map emission options.
65
+ *
66
+ * `file` is the **planned CSS output basename** (for example `button.css`), not
67
+ * the map path: the trailing comment becomes
68
+ * `/*# sourceMappingURL=button.css.map */` and the v3 `file` field records
69
+ * the CSS basename. `sourceText` supplies the authored text a span belongs to
70
+ * so UTF-16 offsets can become one-based line/column pairs; spans carry no
71
+ * source copy. Sources whose text is unavailable are skipped (their mappings
72
+ * are dropped, never guessed).
73
+ */
74
+ export interface EmitSourceMapOptions {
75
+ /** Planned CSS output basename, for example `button.css`. */
76
+ readonly file: string;
77
+ /** Authored text lookup keyed by a span's file path (absolute in pipeline IR). */
78
+ readonly sourceText: (file: string) => string | undefined;
79
+ /**
80
+ * Optional normalization from a span's `file` to the map `sources` entry.
81
+ * Pipeline spans carry canonical absolute paths; pass a workspace-relative
82
+ * POSIX projection here to satisfy §6 and keep maps portable.
83
+ */
84
+ readonly sourcePath?: (file: string) => string;
85
+ /** Optional `sourceRoot` applied by consumers that relocate sources. */
86
+ readonly sourceRoot?: string;
87
+ /** Include `sourcesContent` (default `false`) so maps are self-contained. */
88
+ readonly includeSourcesContent?: boolean;
89
+ }
90
+
91
+ /** Emitted CSS plus any structural diagnostics. */
92
+ export interface EmitResult {
93
+ /** Complete stylesheet text; empty when nothing emitted. */
94
+ readonly css: string;
95
+ /** Serialized v3 source map when `sourceMap` was requested. */
96
+ readonly map?: string;
97
+ /** CHIKX1001 diagnostics for rejected selectors and invalid declarations. */
98
+ readonly diagnostics: readonly Diagnostic[];
99
+ }
100
+
101
+ /** One deferred mapping: the authored span recorded at a marker. */
102
+ interface DeferredMapping {
103
+ readonly span: Span;
104
+ }
105
+
106
+ /**
107
+ * Mutable marker bookkeeping used only while a source map is requested.
108
+ *
109
+ * Instead of threading a writer through every recursive renderer, the emitter
110
+ * inserts a zero-width NUL-delimited marker at each mapped position. Markers
111
+ * contain no newline, so indentation, joining and minification are unchanged;
112
+ * after the final text is assembled, {@link resolveMappings} replaces each
113
+ * marker with nothing while recording its real generated line/column. With
114
+ * source maps OFF no marker is ever inserted and output is byte-identical.
115
+ */
116
+ interface MarkState {
117
+ readonly marks: DeferredMapping[];
118
+ readonly sourceText: (file: string) => string | undefined;
119
+ readonly sourcePath: (file: string) => string;
120
+ }
121
+
122
+ /** Return the marker for one mapped span, or an empty string when maps are off. */
123
+ function mark(state: MarkState | undefined, span: Span): string {
124
+ if (state === undefined) return "";
125
+ const id = state.marks.length;
126
+ state.marks.push({ span });
127
+ return `\u0000${id}\u0000`;
128
+ }
129
+
130
+ /** Text with markers removed plus the mappings resolved at their real positions. */
131
+ interface ResolvedBody {
132
+ readonly text: string;
133
+ readonly mappings: readonly SourceMapping[];
134
+ readonly content: Readonly<Record<string, string>>;
135
+ }
136
+
137
+ /** Replace markers with nothing, recording generated and authored positions. */
138
+ function resolveMappings(body: string, state: MarkState): ResolvedBody {
139
+ let text = "";
140
+ let generatedLine = 0;
141
+ let generatedColumn = 0;
142
+ let index = 0;
143
+ const mappings: SourceMapping[] = [];
144
+ const content: Record<string, string> = {};
145
+
146
+ while (index < body.length) {
147
+ const character = body.charAt(index);
148
+ if (character === "\u0000") {
149
+ const close = body.indexOf("\u0000", index + 1);
150
+ if (close < 0) {
151
+ text += character;
152
+ index += 1;
153
+ continue;
154
+ }
155
+ const id = Number(body.slice(index + 1, close));
156
+ const entry = state.marks[id];
157
+ if (entry !== undefined) {
158
+ const sourceText = state.sourceText(entry.span.file);
159
+ if (sourceText !== undefined) {
160
+ const source = state.sourcePath(entry.span.file);
161
+ const position = offsetToLineColumn(sourceText, entry.span.start);
162
+ mappings.push({
163
+ generatedLine,
164
+ generatedColumn,
165
+ source,
166
+ sourceLine: position.line - 1,
167
+ sourceColumn: position.column - 1,
168
+ });
169
+ content[source] = sourceText;
170
+ }
171
+ }
172
+ index = close + 1;
173
+ continue;
174
+ }
175
+ text += character;
176
+ if (character === "\n") {
177
+ generatedLine += 1;
178
+ generatedColumn = 0;
179
+ } else {
180
+ generatedColumn += 1;
181
+ }
182
+ index += 1;
183
+ }
184
+
185
+ return { text, mappings, content };
186
+ }
187
+
188
+ /** One validated declaration ready for formatting. */
189
+ interface RenderedDeclaration {
190
+ readonly property: string;
191
+ readonly value: string;
192
+ /** Origin of the authored value segment, used for source-map mappings. */
193
+ readonly span: Span;
194
+ }
195
+
196
+ /** A rendered child inside a native at-rule block. */
197
+ interface RenderedChild {
198
+ readonly kind: "declaration" | "block";
199
+ readonly text: string;
200
+ }
201
+
202
+ /** A native wrapper that has already been emitted by an ancestor block. */
203
+ interface EmittedAtRule {
204
+ readonly name: string;
205
+ readonly prelude: string;
206
+ }
207
+
208
+ /** Media composition state for one rule. */
209
+ interface MediaParts {
210
+ readonly media: readonly EmittedAtRule[];
211
+ readonly other: readonly EmittedAtRule[];
212
+ }
213
+
214
+ function indent(text: string, levels: number): string {
215
+ const padding = " ".repeat(levels);
216
+ return text
217
+ .split("\n")
218
+ .map((line) => (line.length === 0 ? line : padding + line))
219
+ .join("\n");
220
+ }
221
+
222
+ function atRuleHeader(name: string, prelude: string): string {
223
+ const trimmed = prelude.trim();
224
+ return trimmed.length === 0 ? `@${name}` : `@${name} ${trimmed}`;
225
+ }
226
+
227
+ /** Structural whitespace flags of one media prelude. */
228
+ interface MediaFlags {
229
+ readonly comma: boolean;
230
+ readonly or: boolean;
231
+ }
232
+
233
+ /** Scan a media prelude for top-level commas and the `or` keyword. */
234
+ function mediaFlags(text: string): MediaFlags {
235
+ let depth = 0;
236
+ let quote: '"' | "'" | null = null;
237
+ let inComment = false;
238
+ let escaped = false;
239
+ let comma = false;
240
+ let or = false;
241
+
242
+ const isNameCharacter = (character: string): boolean =>
243
+ character !== "" && /[A-Za-z0-9_-]/.test(character);
244
+
245
+ for (let index = 0; index < text.length; index += 1) {
246
+ const character = text.charAt(index);
247
+ if (inComment) {
248
+ if (character === "*" && text.charAt(index + 1) === "/") {
249
+ inComment = false;
250
+ index += 1;
251
+ }
252
+ continue;
253
+ }
254
+ if (quote !== null) {
255
+ if (escaped) {
256
+ escaped = false;
257
+ continue;
258
+ }
259
+ if (character === "\\") {
260
+ escaped = true;
261
+ continue;
262
+ }
263
+ if (character === quote) quote = null;
264
+ continue;
265
+ }
266
+ if (escaped) {
267
+ escaped = false;
268
+ continue;
269
+ }
270
+ if (character === "\\") {
271
+ escaped = true;
272
+ continue;
273
+ }
274
+ if (character === "/" && text.charAt(index + 1) === "*") {
275
+ inComment = true;
276
+ index += 1;
277
+ continue;
278
+ }
279
+ if (character === '"' || character === "'") {
280
+ quote = character;
281
+ continue;
282
+ }
283
+ if (character === "(" || character === "[") {
284
+ depth += 1;
285
+ continue;
286
+ }
287
+ if (character === ")" || character === "]") {
288
+ depth = Math.max(0, depth - 1);
289
+ continue;
290
+ }
291
+ if (depth > 0) continue;
292
+
293
+ if (character === ",") comma = true;
294
+ if (character === "o" || character === "O") {
295
+ const word = text.slice(index, index + 2).toLowerCase();
296
+ const before = text.charAt(index - 1);
297
+ const after = text.charAt(index + 2);
298
+ if (word === "or" && !isNameCharacter(before) && !isNameCharacter(after)) {
299
+ or = true;
300
+ }
301
+ }
302
+ }
303
+
304
+ return { comma, or };
305
+ }
306
+
307
+ /**
308
+ * Combine media parts with `and` when the result is valid and meaning-preserving.
309
+ *
310
+ * A plain parenthesized condition can always be ANDed. A single media type (or
311
+ * `only <type>`) may join too and is placed first, because media query grammar
312
+ * requires the media type at the start; AND is commutative so this is a query
313
+ * normalization, not declaration reordering. `not`, comma lists and top-level
314
+ * `or` return `null` so the caller nests separate wrappers instead
315
+ * (SPECIFICATION.md §4.3: native media lists pass through unchanged).
316
+ */
317
+ function combineMediaParts(parts: readonly string[]): string | null {
318
+ if (parts.length === 0) return null;
319
+ if (parts.length === 1) return parts[0] ?? null;
320
+
321
+ let mediaType: string | null = null;
322
+ let hasOnly = false;
323
+ const conditions: string[] = [];
324
+
325
+ for (const part of parts) {
326
+ const trimmed = part.trim();
327
+ if (trimmed === "") return null;
328
+ const flags = mediaFlags(trimmed);
329
+ if (flags.comma || flags.or) return null;
330
+ if (/^not\s/i.test(trimmed)) return null;
331
+
332
+ const onlyMatch = /^only\s+/i.exec(trimmed);
333
+ if (onlyMatch !== null) {
334
+ if (hasOnly || mediaType !== null) return null;
335
+ hasOnly = true;
336
+ mediaType = trimmed.slice(onlyMatch[0].length).trim();
337
+ continue;
338
+ }
339
+
340
+ if (trimmed.startsWith("(")) {
341
+ conditions.push(trimmed);
342
+ continue;
343
+ }
344
+
345
+ if (/^[A-Za-z][A-Za-z0-9-]*(?:\s|$)/.test(trimmed)) {
346
+ if (mediaType !== null) return null;
347
+ mediaType = trimmed;
348
+ continue;
349
+ }
350
+
351
+ return null;
352
+ }
353
+
354
+ const pieces: string[] = [];
355
+ if (mediaType !== null) pieces.push(`${hasOnly ? "only " : ""}${mediaType}`);
356
+ pieces.push(...conditions);
357
+ return pieces.join(" and ");
358
+ }
359
+
360
+ function effectiveDeclarations(
361
+ declarations: readonly DeclarationIr[],
362
+ diagnostics: Diagnostic[],
363
+ ): readonly RenderedDeclaration[] {
364
+ const rendered: RenderedDeclaration[] = [];
365
+ for (const declaration of declarations) {
366
+ if (declaration.property.trim().length === 0) {
367
+ diagnostics.push(
368
+ error(
369
+ "CHIKX1001",
370
+ "Empty declaration property: the declaration was omitted.",
371
+ declaration.span,
372
+ ),
373
+ );
374
+ continue;
375
+ }
376
+ if (declaration.value.trim().length === 0) {
377
+ diagnostics.push(
378
+ error(
379
+ "CHIKX1001",
380
+ `Empty declaration value for "${declaration.property}": inline variants require a base value (SPECIFICATION.md §3.1); the declaration was omitted.`,
381
+ declaration.span,
382
+ ),
383
+ );
384
+ continue;
385
+ }
386
+ rendered.push({
387
+ property: declaration.property,
388
+ value: declaration.value,
389
+ span: declaration.span,
390
+ });
391
+ }
392
+ return rendered;
393
+ }
394
+
395
+ function renderRuleBlock(
396
+ selector: string,
397
+ selectorSpan: Span,
398
+ declarations: readonly RenderedDeclaration[],
399
+ minify: boolean,
400
+ marks: MarkState | undefined,
401
+ ): string {
402
+ const markedSelector = `${mark(marks, selectorSpan)}${selector}`;
403
+ if (minify) {
404
+ const body = declarations
405
+ .map(
406
+ (declaration) =>
407
+ `${mark(marks, declaration.span)}${declaration.property}:${declaration.value};`,
408
+ )
409
+ .join("");
410
+ return `${markedSelector}{${body}}`;
411
+ }
412
+ const body = declarations
413
+ .map(
414
+ (declaration) =>
415
+ ` ${mark(marks, declaration.span)}${declaration.property}: ${declaration.value};`,
416
+ )
417
+ .join("\n");
418
+ return `${markedSelector} {\n${body}\n}`;
419
+ }
420
+
421
+ function renderDeclaration(
422
+ declaration: RenderedDeclaration,
423
+ minify: boolean,
424
+ marks: MarkState | undefined,
425
+ ): string {
426
+ const marker = mark(marks, declaration.span);
427
+ return minify
428
+ ? `${marker}${declaration.property}:${declaration.value};`
429
+ : `${marker}${declaration.property}: ${declaration.value};`;
430
+ }
431
+
432
+ function wrapAtRule(name: string, prelude: string, inner: string, minify: boolean): string {
433
+ const header = atRuleHeader(name, prelude);
434
+ return minify ? `${header}{${inner}}` : `${header} {\n${indent(inner, 1)}\n}`;
435
+ }
436
+
437
+ function pendingContext(
438
+ context: readonly AtRuleContextIr[],
439
+ emitted: readonly EmittedAtRule[],
440
+ ): readonly AtRuleContextIr[] {
441
+ let prefix = 0;
442
+ while (prefix < emitted.length && prefix < context.length) {
443
+ const emittedEntry = emitted[prefix];
444
+ const contextEntry = context[prefix];
445
+ if (
446
+ emittedEntry === undefined ||
447
+ contextEntry === undefined ||
448
+ emittedEntry.name !== contextEntry.name ||
449
+ emittedEntry.prelude !== contextEntry.prelude
450
+ ) {
451
+ break;
452
+ }
453
+ prefix += 1;
454
+ }
455
+ return context.slice(prefix);
456
+ }
457
+
458
+ function splitMediaContexts(context: readonly AtRuleContextIr[]): MediaParts {
459
+ const media: EmittedAtRule[] = [];
460
+ const other: EmittedAtRule[] = [];
461
+ for (const entry of context) {
462
+ const wrapper = { name: entry.name, prelude: entry.prelude };
463
+ if (entry.name.toLowerCase() === "media") {
464
+ media.push(wrapper);
465
+ } else {
466
+ other.push(wrapper);
467
+ }
468
+ }
469
+ return { media, other };
470
+ }
471
+
472
+ function wrapRule(
473
+ block: string,
474
+ context: readonly AtRuleContextIr[],
475
+ condition: MediaConditionIr | null,
476
+ emitted: readonly EmittedAtRule[],
477
+ minify: boolean,
478
+ ): string {
479
+ const pending = splitMediaContexts(pendingContext(context, emitted));
480
+ const parts: string[] = pending.media.map((entry) => entry.prelude);
481
+ if (condition !== null) parts.push(condition.query);
482
+
483
+ let content = block;
484
+ if (parts.length > 0) {
485
+ const combined = combineMediaParts(parts);
486
+ if (combined !== null) {
487
+ content = wrapAtRule("media", combined, content, minify);
488
+ } else {
489
+ for (let index = parts.length - 1; index >= 0; index -= 1) {
490
+ const part = parts[index];
491
+ if (part === undefined) continue;
492
+ content = wrapAtRule("media", part, content, minify);
493
+ }
494
+ }
495
+ }
496
+
497
+ for (let index = pending.other.length - 1; index >= 0; index -= 1) {
498
+ const entry = pending.other[index];
499
+ if (entry === undefined) continue;
500
+ content = wrapAtRule(entry.name, entry.prelude, content, minify);
501
+ }
502
+
503
+ return content;
504
+ }
505
+
506
+ function renderRule(
507
+ rule: RuleIr,
508
+ minify: boolean,
509
+ diagnostics: Diagnostic[],
510
+ emitted: readonly EmittedAtRule[],
511
+ marks: MarkState | undefined,
512
+ ): string | null {
513
+ const flattened = flattenSelector(rule.selector, rule.ancestors);
514
+ if (!flattened.ok) {
515
+ diagnostics.push(
516
+ error(
517
+ "CHIKX1001",
518
+ `Cannot flatten selector "${rule.selector}": ${flattened.reason}`,
519
+ rule.span,
520
+ ),
521
+ );
522
+ return null;
523
+ }
524
+
525
+ const declarations = effectiveDeclarations(rule.declarations, diagnostics);
526
+ if (declarations.length === 0) return null;
527
+
528
+ const block = renderRuleBlock(flattened.selector, rule.span, declarations, minify, marks);
529
+ return wrapRule(block, rule.context, rule.condition, emitted, minify);
530
+ }
531
+
532
+ function joinRenderedChildren(children: readonly RenderedChild[]): string {
533
+ let output = "";
534
+ for (let index = 0; index < children.length; index += 1) {
535
+ const child = children[index];
536
+ if (child === undefined) continue;
537
+ if (index > 0) {
538
+ const previous = children[index - 1];
539
+ const bothDeclarations =
540
+ previous !== undefined && previous.kind === "declaration" && child.kind === "declaration";
541
+ output += bothDeclarations ? "\n" : "\n\n";
542
+ }
543
+ output += child.text;
544
+ }
545
+ return output;
546
+ }
547
+
548
+ function renderNativeBlock(
549
+ block: NativeBlockIr,
550
+ minify: boolean,
551
+ diagnostics: Diagnostic[],
552
+ emitted: readonly EmittedAtRule[],
553
+ marks: MarkState | undefined,
554
+ ): string {
555
+ const header = atRuleHeader(block.name, block.prelude);
556
+ if (block.statement === true) return `${header};`;
557
+
558
+ const emittedHere: readonly EmittedAtRule[] = [
559
+ ...emitted,
560
+ { name: block.name, prelude: block.prelude },
561
+ ];
562
+ const children: RenderedChild[] = [];
563
+
564
+ for (const child of block.children) {
565
+ if ("children" in child) {
566
+ children.push({
567
+ kind: "block",
568
+ text: renderNativeBlock(child, minify, diagnostics, emittedHere, marks),
569
+ });
570
+ continue;
571
+ }
572
+ if ("declarations" in child) {
573
+ const text = renderRule(child, minify, diagnostics, emittedHere, marks);
574
+ if (text !== null) children.push({ kind: "block", text });
575
+ continue;
576
+ }
577
+ const declarations = effectiveDeclarations([child], diagnostics);
578
+ const declaration = declarations[0];
579
+ if (declaration !== undefined) {
580
+ children.push({ kind: "declaration", text: renderDeclaration(declaration, minify, marks) });
581
+ }
582
+ }
583
+
584
+ if (children.length === 0) return minify ? `${header}{}` : `${header} {}`;
585
+ if (minify) return `${header}{${children.map((child) => child.text).join("")}}`;
586
+ return `${header} {\n${indent(joinRenderedChildren(children), 1)}\n}`;
587
+ }
588
+
589
+ function renderTopLevel(
590
+ nodes: readonly (RuleIr | NativeBlockIr)[],
591
+ minify: boolean,
592
+ diagnostics: Diagnostic[],
593
+ emitted: readonly EmittedAtRule[],
594
+ marks: MarkState | undefined,
595
+ ): string {
596
+ const rendered: string[] = [];
597
+ for (const node of nodes) {
598
+ const text =
599
+ "declarations" in node
600
+ ? renderRule(node, minify, diagnostics, emitted, marks)
601
+ : renderNativeBlock(node, minify, diagnostics, emitted, marks);
602
+ if (text !== null) rendered.push(text);
603
+ }
604
+ return minify ? rendered.join("") : rendered.join("\n\n");
605
+ }
606
+
607
+ /**
608
+ * Emit a stylesheet IR as CSS text.
609
+ *
610
+ * Pure and deterministic: identical IR and options produce byte-identical
611
+ * output on every platform. Rules whose selector cannot be flattened or whose
612
+ * only declarations are structurally invalid are omitted with CHIKX1001
613
+ * diagnostics; valid rules keep authored declaration order, selectors,
614
+ * conditions and native wrapper order. `minify` defaults to `false`.
615
+ *
616
+ * Source maps are opt-in through `sourceMap`; when active the emitted CSS gains
617
+ * a trailing `/*# sourceMappingURL=… *&#47;` comment and `map` carries the v3
618
+ * JSON text. Mapping granularity is one entry per emitted rule selector and one
619
+ * per emitted declaration property, both taken from the node's `Span` start;
620
+ * minified output repositions every marker so the same generator stays correct.
621
+ * With `sourceMap` unset, output bytes and diagnostics are unchanged.
622
+ */
623
+ export function emitCss(ir: StylesheetIr, options: Partial<EmitOptions> = {}): EmitResult {
624
+ const minify = options.minify === true;
625
+ const sourceMap = options.sourceMap;
626
+ const diagnostics: Diagnostic[] = [];
627
+ const marks: MarkState | undefined =
628
+ sourceMap === undefined
629
+ ? undefined
630
+ : {
631
+ marks: [],
632
+ sourceText: sourceMap.sourceText,
633
+ sourcePath: sourceMap.sourcePath ?? ((file) => file),
634
+ };
635
+ const body = renderTopLevel(ir.rules, minify, diagnostics, [], marks);
636
+ const resolved = marks === undefined ? undefined : resolveMappings(body, marks);
637
+
638
+ const text = resolved === undefined ? body : resolved.text;
639
+ let css = text.length === 0 ? "" : minify ? text : `${text}\n`;
640
+
641
+ if (sourceMap === undefined || resolved === undefined) {
642
+ return { css, diagnostics: Object.freeze(diagnostics) };
643
+ }
644
+
645
+ const comment = sourceMapComment(sourceMap.file);
646
+ css = css.length === 0 ? `${comment}\n` : `${css}${css.endsWith("\n") ? "" : "\n"}${comment}\n`;
647
+ const map = generateSourceMap(resolved.mappings, {
648
+ file: sourceMap.file,
649
+ ...(sourceMap.sourceRoot === undefined ? {} : { sourceRoot: sourceMap.sourceRoot }),
650
+ ...(sourceMap.includeSourcesContent === true ? { sourcesContent: resolved.content } : {}),
651
+ });
652
+
653
+ return {
654
+ css,
655
+ map: serializeSourceMap(map),
656
+ diagnostics: Object.freeze(diagnostics),
657
+ };
658
+ }