rainbowindex 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.d.ts CHANGED
@@ -1,1323 +1,5 @@
1
- /**
2
- * Rainbow Index AST Types
3
- *
4
- * Defines the Abstract Syntax Tree structure for CSS parsing and generation.
5
- */
6
- /** Source location tracking for source maps */
7
- interface Source {
8
- file: string | null;
9
- code: string;
10
- }
11
- type SourceLocation = [source: Source, start: number, end: number];
12
- /** CSS Style Rule: selector { declarations } */
13
- interface StyleRule {
14
- kind: "rule";
15
- selector: string;
16
- nodes: AstNode[];
17
- src?: SourceLocation;
18
- dst?: SourceLocation;
19
- }
20
- /** CSS At-Rule: @name params { nodes } */
21
- interface AtRule {
22
- kind: "at-rule";
23
- name: string;
24
- params: string;
25
- nodes: AstNode[];
26
- src?: SourceLocation;
27
- dst?: SourceLocation;
28
- }
29
- /** CSS Declaration: property: value */
30
- interface Declaration {
31
- kind: "declaration";
32
- property: string;
33
- value: string | undefined;
34
- important: boolean;
35
- src?: SourceLocation;
36
- dst?: SourceLocation;
37
- }
38
- /** CSS Comment */
39
- interface Comment {
40
- kind: "comment";
41
- value: string;
42
- src?: SourceLocation;
43
- dst?: SourceLocation;
44
- }
45
- /** Internal context node for tracking metadata during compilation */
46
- interface Context {
47
- kind: "context";
48
- context: Record<string, string | boolean>;
49
- nodes: AstNode[];
50
- }
51
- /** At-root node for hoisting content outside current rule */
52
- interface AtRoot {
53
- kind: "at-root";
54
- nodes: AstNode[];
55
- }
56
- /** Union of all AST node types */
57
- type AstNode = StyleRule | AtRule | Declaration | Comment | Context | AtRoot;
1
+ export { C as ColorDefinition, a as CompilationContext, b as CompilationSnapshot, D as DEFAULT_TEXT_SIZES, F as FluidConfig, T as TextSize, c as Theme, d as createCompilationContext, e as createRi, f as defaultTheme, g as finalizeCompilationContext, r as registerColorNames, h as registerCustomFontFamilies, i as registerCustomTextSizes, j as registerCustomUtility, k as ri, s as safelist } from './safelist-DRk1XXxi.js';
58
2
 
59
- /**
60
- * Source Map Generator
61
- *
62
- * Generates source maps in the standard v3 format with VLQ encoding.
63
- * Also provides ECMA-426 decoded source map types for structured access.
64
- *
65
- * ## Pipeline Stages and Source Map Flow
66
- *
67
- * The Rainbow Index build pipeline generates source maps through multiple stages:
68
- *
69
- * 1. **Parser** (parse.ts)
70
- * - Input: Raw CSS/Rainbow syntax
71
- * - Output: AST with `src[]` location metadata
72
- * - Source Map: Implicit via SourceLocation tuples on nodes
73
- *
74
- * 2. **Compiler** (compile.ts)
75
- * - Input: AST with `src[]`
76
- * - Output: Transformed AST with `dst[]` added
77
- * - Source Map: `createSourceMap({ ast })` generates DecodedSourceMap
78
- *
79
- * 3. **Printer** (print.ts)
80
- * - Input: Compiled AST
81
- * - Output: CSS string
82
- * - Source Map: `generateSourceMap()` produces v3 SourceMap
83
- *
84
- * 4. **Optimizer** (optimize.ts in @rainbowindex/node)
85
- * - Input: CSS string + optional source map
86
- * - Output: Optimized CSS + composed source map
87
- * - Source Map: Uses `@jridgewell/remapping` for composition
88
- *
89
- * ## Composition Functions
90
- *
91
- * - `chainSourceMaps(original, transformed)`: Chains two sequential maps.
92
- * Maps from final output -> intermediate -> original source.
93
- *
94
- * - `mergeSourceMaps(maps[])`: Combines maps from parallel sources.
95
- * Used when concatenating CSS from multiple input files.
96
- *
97
- * - `@jridgewell/remapping`: External library used in optimizer for
98
- * composing maps through Lightning CSS and MagicString transformations.
99
- *
100
- * ## Example Usage
101
- *
102
- * ```typescript
103
- * // Chain maps through a 3-stage pipeline
104
- * const map1 = chainSourceMaps(parseMap, compileMap);
105
- * const finalMap = chainSourceMaps(map1, optimizeMap);
106
- *
107
- * // Merge maps from multiple input files
108
- * const bundleMap = mergeSourceMaps([resetMap, utilsMap, componentsMap]);
109
- * ```
110
- */
3
+ declare function browserEntryUnavailable(): never;
111
4
 
112
- /**
113
- * Standard source map format (JSON v3 specification).
114
- * @see https://sourcemaps.info/spec.html
115
- */
116
- interface SourceMap {
117
- version: 3;
118
- file?: string;
119
- sourceRoot?: string;
120
- sources: string[];
121
- sourcesContent: (string | null)[];
122
- names: string[];
123
- mappings: string;
124
- }
125
-
126
- /**
127
- * AST Printer
128
- *
129
- * Converts AST nodes back to CSS strings.
130
- * Optimized following tailwindcss patterns:
131
- * - Pre-computed indentation array
132
- * - Separate CSS generation from source map tracking
133
- * - ECMA-426 decoded source maps with deferred VLQ encoding
134
- * - Binary search position lookups via line tables
135
- */
136
-
137
- interface PrintOptions {
138
- /** Use minified output (no whitespace) */
139
- minify?: boolean;
140
- /** Indentation string (default: " ") */
141
- indent?: string;
142
- /** Generate source map */
143
- sourceMap?: boolean;
144
- /**
145
- * Return decoded source map (ECMA-426 format) instead of V3.
146
- * This is faster as it skips VLQ encoding.
147
- * Use encodeSourceMap() to convert to V3 when needed.
148
- */
149
- decodedSourceMap?: boolean;
150
- /** Output file name for source map */
151
- file?: string;
152
- }
153
- /**
154
- * Convert AST to CSS string.
155
- */
156
- declare function print(ast: AstNode[], options?: PrintOptions): string;
157
- /**
158
- * Minify CSS by removing whitespace and comments.
159
- */
160
- declare function minify(css: string): string;
161
-
162
- /**
163
- * Candidate Types
164
- *
165
- * Defines the structure of parsed utility class candidates.
166
- * A candidate like "hover:bg-red-500/75" is parsed into its constituent parts.
167
- */
168
- /** A named value like "red-500" in "bg-red-500" */
169
- interface NamedValue {
170
- kind: "named";
171
- /** The value name, e.g., "red-500" */
172
- value: string;
173
- /** Fraction part if present, e.g., "1/2" in "w-1/2" */
174
- fraction: string | null;
175
- }
176
- /** An arbitrary value like "[#ff0000]" in "bg-[#ff0000]" */
177
- interface ArbitraryValue {
178
- kind: "arbitrary";
179
- /** The raw value inside brackets */
180
- value: string;
181
- /** Optional data type hint, e.g., "color" in "bg-[color:#ff0000]" */
182
- dataType: string | null;
183
- }
184
- type CandidateValue = NamedValue | ArbitraryValue;
185
- /** A named modifier like "75" in "bg-red-500/75" */
186
- interface NamedModifier {
187
- kind: "named";
188
- value: string;
189
- }
190
- /** An arbitrary modifier like "[0.5]" in "bg-red-500/[0.5]" */
191
- interface ArbitraryModifier {
192
- kind: "arbitrary";
193
- value: string;
194
- dashedIdent: string | null;
195
- }
196
- type CandidateModifier = NamedModifier | ArbitraryModifier;
197
- /** A static variant like "hover" */
198
- interface StaticVariant {
199
- kind: "static";
200
- root: string;
201
- }
202
- /** A functional variant like "aria-disabled" or "md" */
203
- interface FunctionalVariant {
204
- kind: "functional";
205
- root: string;
206
- value: CandidateValue | null;
207
- modifier: CandidateModifier | null;
208
- }
209
- /** An arbitrary variant like "[&_p]" */
210
- interface ArbitraryVariant {
211
- kind: "arbitrary";
212
- selector: string;
213
- relative: boolean;
214
- }
215
- /** A compound variant like "group-hover" */
216
- interface CompoundVariant {
217
- kind: "compound";
218
- root: string;
219
- modifier: CandidateModifier | null;
220
- variant: Variant;
221
- }
222
- type Variant = StaticVariant | FunctionalVariant | ArbitraryVariant | CompoundVariant;
223
- /** A static candidate like "flex" or "hidden" */
224
- interface StaticCandidate {
225
- kind: "static";
226
- /** The utility name */
227
- root: string;
228
- /** Applied variants in order */
229
- variants: Variant[];
230
- /** Whether !important is applied */
231
- important: boolean;
232
- /** Original raw string */
233
- raw: string;
234
- }
235
- /** A functional candidate like "bg-red-500" or "p-4" */
236
- interface FunctionalCandidate {
237
- kind: "functional";
238
- /** The utility prefix, e.g., "bg" */
239
- root: string;
240
- /** The value part */
241
- value: CandidateValue | null;
242
- /** The modifier part (e.g., opacity) */
243
- modifier: CandidateModifier | null;
244
- /** Applied variants in order */
245
- variants: Variant[];
246
- /** Whether !important is applied */
247
- important: boolean;
248
- /** Original raw string */
249
- raw: string;
250
- }
251
- /** An arbitrary property candidate like "[color:red]" */
252
- interface ArbitraryCandidate {
253
- kind: "arbitrary";
254
- /** CSS property name */
255
- property: string;
256
- /** CSS value */
257
- value: string;
258
- /** The modifier part */
259
- modifier: CandidateModifier | null;
260
- /** Applied variants in order */
261
- variants: Variant[];
262
- /** Whether !important is applied */
263
- important: boolean;
264
- /** Original raw string */
265
- raw: string;
266
- }
267
- type Candidate = StaticCandidate | FunctionalCandidate | ArbitraryCandidate;
268
-
269
- /**
270
- * Theme System
271
- *
272
- * Manages CSS custom property definitions and resolution.
273
- * Handles @theme declarations and provides lookups for utilities.
274
- */
275
-
276
- declare const enum ThemeOptions {
277
- /** No special options */
278
- NONE = 0,
279
- /** Inline in :root (not registered via @property) */
280
- INLINE = 1,
281
- /** Reference only - don't output the declaration */
282
- REFERENCE = 2,
283
- /** Default value that can be overridden */
284
- DEFAULT = 4,
285
- /** Static value that cannot use var() */
286
- STATIC = 8,
287
- /** Mark as used (for tree-shaking) */
288
- USED = 16
289
- }
290
- /** Theme keys always start with -- */
291
- type ThemeKey = `--${string}`;
292
- interface ThemeEntry {
293
- value: string;
294
- options: ThemeOptions;
295
- src?: SourceLocation;
296
- }
297
- declare class Theme {
298
- /** Stored theme values */
299
- private values;
300
- /** Keyframe animations */
301
- private keyframes;
302
- /** Theme prefix (e.g., "ri" for --ri-*) */
303
- prefix: string | null;
304
- /** Track which variables are used */
305
- private usedVariables;
306
- /**
307
- * Create a new Theme with the same values/keyframes.
308
- * Used to speed up cold starts without sharing mutation state.
309
- */
310
- clone(): Theme;
311
- /**
312
- * Add a theme value.
313
- */
314
- add(key: string, value: string, options?: ThemeOptions, src?: SourceLocation): void;
315
- /**
316
- * Get a raw theme value by key.
317
- */
318
- get(key: string): string | null;
319
- /**
320
- * Check if a theme key exists.
321
- */
322
- has(key: string): boolean;
323
- /**
324
- * Resolve a candidate value against theme keys.
325
- *
326
- * For example, resolve("red-500", ["--background-color", "--color"])
327
- * will look for --background-color-red-500 or --color-red-500.
328
- *
329
- * Returns a var() reference or the inline value based on ThemeOptions:
330
- * - STATIC: always inlines the value (no var())
331
- * - INLINE: inlines the value (no var())
332
- * - REFERENCE: returns var() with fallback value
333
- * - Default: returns var() without fallback
334
- *
335
- * When a prefix is set, applies it to the emitted var() key.
336
- */
337
- resolve(candidateValue: string | null, themeKeys: ThemeKey[]): string | null;
338
- /**
339
- * Get all values in a namespace.
340
- * E.g., namespace("--color") returns all --color-* values.
341
- */
342
- namespace(namespace: ThemeKey): Map<string | null, string>;
343
- /**
344
- * Add a keyframe animation.
345
- */
346
- addKeyframes(name: string, keyframes: AtRule): void;
347
- /**
348
- * Get a keyframe animation.
349
- */
350
- getKeyframes(name: string): AtRule | null;
351
- /**
352
- * Get all keyframe animations.
353
- */
354
- getAllKeyframes(): Map<string, AtRule>;
355
- /**
356
- * Mark a variable as used.
357
- */
358
- markUsed(key: string): void;
359
- /**
360
- * Check if a variable has been used.
361
- */
362
- isUsed(key: string): boolean;
363
- /**
364
- * Get all theme entries (for output generation).
365
- */
366
- entries(): IterableIterator<[string, ThemeEntry]>;
367
- /**
368
- * Get all used theme entries.
369
- */
370
- usedEntries(): [string, ThemeEntry][];
371
- /**
372
- * Create a child theme that inherits from this one.
373
- */
374
- child(): Theme;
375
- /**
376
- * Merge another theme into this one.
377
- */
378
- merge(other: Theme): void;
379
- }
380
-
381
- /**
382
- * Utility Trie
383
- *
384
- * A segment-based trie data structure for O(k) utility prefix matching.
385
- * Instead of character-by-character traversal, we split by dashes and
386
- * traverse segment-by-segment, reducing Map lookups significantly.
387
- *
388
- * Example:
389
- * - "bg-gradient-to-r-500" with right-to-left: 5 Map lookups
390
- * - "bg-gradient-to-r-500" with segment trie: 5 segment lookups (same, but left-to-right)
391
- *
392
- * The key advantage is we find the LONGEST match in one forward pass,
393
- * without needing to backtrack.
394
- */
395
- /**
396
- * A segment-based trie optimized for finding the longest matching utility prefix.
397
- * Stores dash-separated segments instead of individual characters.
398
- */
399
- declare class UtilityTrie {
400
- private root;
401
- private size;
402
- /**
403
- * Insert a utility name into the trie.
404
- * @param utility - The utility name (e.g., "bg", "bg-gradient-to")
405
- */
406
- insert(utility: string): void;
407
- /**
408
- * Check if a utility exists in the trie.
409
- * @param utility - The utility name to check
410
- */
411
- has(utility: string): boolean;
412
- /**
413
- * Find the longest matching utility prefix in the input string.
414
- * Uses inline segment extraction to avoid array allocations.
415
- *
416
- * @param input - The candidate string (e.g., "bg-red-500")
417
- * @returns [root, value] tuple if found, null if no match or entire string is a utility
418
- *
419
- * @example
420
- * ```ts
421
- * trie.insert("bg");
422
- * trie.insert("bg-gradient-to");
423
- *
424
- * trie.findLongestPrefix("bg-red-500")
425
- * // Returns ["bg", "red-500"]
426
- *
427
- * trie.findLongestPrefix("bg-gradient-to-r")
428
- * // Returns ["bg-gradient-to", "r"]
429
- *
430
- * trie.findLongestPrefix("flex")
431
- * // Returns null (entire string is utility or no match)
432
- * ```
433
- */
434
- findLongestPrefix(input: string): [string, string] | null;
435
- /**
436
- * Find all utilities that match as prefixes of the input.
437
- * Useful for debugging and testing.
438
- *
439
- * @param input - The candidate string
440
- * @returns Array of matching utility prefixes
441
- */
442
- findAllPrefixes(input: string): string[];
443
- /**
444
- * Get the number of utilities in the trie.
445
- */
446
- getSize(): number;
447
- /**
448
- * Clear all utilities from the trie.
449
- */
450
- clear(): void;
451
- }
452
-
453
- /**
454
- * Utilities Registry
455
- *
456
- * Manages utility definitions and compilation.
457
- * Utilities are functions that convert candidates to CSS declarations.
458
- */
459
-
460
- /** Options for utility registration */
461
- interface UtilityOptions {
462
- /** Data types this utility accepts (for Intellisense) */
463
- types?: string[];
464
- }
465
- /** Compile function for static utilities */
466
- type StaticCompileFn = (candidate: StaticCandidate, theme: Theme) => AstNode[] | null | undefined;
467
- /** Compile function for functional utilities */
468
- type FunctionalCompileFn = (candidate: FunctionalCandidate, theme: Theme) => AstNode[] | null | undefined;
469
- /**
470
- * Stored utility definition.
471
- *
472
- * PERFORMANCE: All fields are always present (never undefined) to ensure
473
- * consistent V8 hidden class shapes. This allows the engine to optimize
474
- * property access without polymorphic inline caches.
475
- */
476
- interface UtilityDef {
477
- kind: "static" | "functional";
478
- /** Static compile function (null for functional utilities) */
479
- staticFn: StaticCompileFn | null;
480
- /** Functional compile function (null for static utilities) */
481
- functionalFn: FunctionalCompileFn | null;
482
- /** Utility options (null if none) */
483
- options: UtilityOptions | null;
484
- }
485
- /** Suggestion group for Intellisense */
486
- interface SuggestionGroup {
487
- name: string;
488
- values: string[];
489
- }
490
- declare class Utilities {
491
- /** Registered utilities by name */
492
- private utilities;
493
- /** Completion suggestions by utility name */
494
- private completions;
495
- /** Trie for O(n) utility prefix lookup (lazily built) */
496
- private _trie;
497
- /** Whether native utility set has been loaded */
498
- private _nativeLoaded;
499
- /** Cache for findRoot results (per utilities instance) */
500
- private _findRootCache;
501
- /**
502
- * Get or build the utility trie for fast prefix matching.
503
- * The trie is lazily built on first access and cached.
504
- * Also loads utility set into native Rust for even faster lookups.
505
- */
506
- getTrie(): UtilityTrie;
507
- /**
508
- * Find the longest matching utility root for a candidate string.
509
- * Uses native Rust when available, falls back to TypeScript trie.
510
- *
511
- * @param input - The utility part of the candidate (without variants)
512
- * @returns [root, value] tuple if found, null otherwise
513
- */
514
- findRoot(input: string): [string, string] | null;
515
- /**
516
- * Invalidate the trie cache (call after registering new utilities).
517
- */
518
- invalidateTrie(): void;
519
- /**
520
- * Create a new Utilities instance with the same registered utilities.
521
- * Keeps caches empty to avoid sharing mutable state.
522
- */
523
- clone(): Utilities;
524
- /**
525
- * Register a static utility (no value, like "flex" or "hidden").
526
- */
527
- static(name: string, compileFn: StaticCompileFn): void;
528
- /**
529
- * Register a functional utility (with value, like "bg-*" or "p-*").
530
- */
531
- functional(name: string, compileFn: FunctionalCompileFn, options?: UtilityOptions): void;
532
- /**
533
- * Check if a utility exists.
534
- */
535
- has(name: string, kind?: "static" | "functional"): boolean;
536
- /**
537
- * Get utility definitions by name.
538
- */
539
- get(name: string): UtilityDef[];
540
- /**
541
- * Compile a candidate to AST nodes.
542
- */
543
- compile(candidate: Candidate, theme: Theme): AstNode[] | null;
544
- /**
545
- * Negate numeric values in declarations.
546
- * Only negates CSS custom properties (--*) and simple numeric values.
547
- */
548
- private negateDeclarations;
549
- /**
550
- * Check if a value can be simply negated.
551
- * Returns true for numeric values (length, percentage, angle, time) and calc()/var().
552
- * Uses inferDataType for robust type detection.
553
- */
554
- private isSimpleNegatable;
555
- /**
556
- * Register completion suggestions for a utility.
557
- */
558
- suggest(name: string, groups: () => SuggestionGroup[]): void;
559
- /**
560
- * Get completion suggestions for a utility.
561
- */
562
- getCompletions(name: string): SuggestionGroup[];
563
- /**
564
- * Get all registered utility names.
565
- */
566
- names(): IterableIterator<string>;
567
- }
568
-
569
- /**
570
- * Variants Registry
571
- *
572
- * Manages variant definitions for conditional styling.
573
- * Variants wrap utilities in selectors or at-rules.
574
- */
575
-
576
- /** Compound behavior flags */
577
- declare const enum Compounds {
578
- /** Cannot compound with other variants */
579
- Never = 0,
580
- /** Can compound with at-rules (media, supports, etc.) */
581
- AtRules = 1,
582
- /** Can compound with style rules (selectors) */
583
- StyleRules = 2
584
- }
585
- /** Apply function for static variants */
586
- type StaticApplyFn = (rule: StyleRule, variant: StaticVariant, theme: Theme) => void | null;
587
- /** Apply function for functional variants */
588
- type FunctionalApplyFn = (rule: StyleRule, variant: FunctionalVariant, theme: Theme) => void | null;
589
- /** Variant configuration */
590
- interface VariantConfig {
591
- kind: "static" | "functional";
592
- order: number;
593
- applyFn: StaticApplyFn | FunctionalApplyFn;
594
- compoundsWith: Compounds;
595
- }
596
- declare class Variants {
597
- /** Registered variants */
598
- private variants;
599
- /** Special pattern-based variants (like numeric breakpoints) */
600
- private patterns;
601
- /** Optional class prefix (e.g., "tw-") for compound marker classes */
602
- classPrefix: string | null;
603
- /** Current ordering index */
604
- private orderIndex;
605
- /** Current group comparison function */
606
- private currentCompareFn?;
607
- /**
608
- * Pre-computed order map for bitmask operations.
609
- * PERFORMANCE: Updated incrementally during registration to avoid
610
- * rebuilding the entire map on each access.
611
- */
612
- private _orderMap;
613
- /** Tracks if order map needs rebuilding (variants registered out of order) */
614
- private _orderMapDirty;
615
- /**
616
- * Register a static variant.
617
- */
618
- static(name: string, applyFn: StaticApplyFn, options?: {
619
- compoundsWith?: Compounds;
620
- order?: number;
621
- }): void;
622
- /**
623
- * Register a functional variant.
624
- */
625
- functional(name: string | RegExp, applyFn: FunctionalApplyFn, options?: {
626
- compoundsWith?: Compounds;
627
- order?: number;
628
- }): void;
629
- /**
630
- * Check if a variant exists.
631
- */
632
- has(name: string): boolean;
633
- /**
634
- * Get variant configuration.
635
- */
636
- get(name: string): VariantConfig | undefined;
637
- /**
638
- * Apply a variant to a rule.
639
- */
640
- apply(rule: StyleRule, variant: Variant, theme: Theme): AstNode[] | null;
641
- /**
642
- * Apply a non-compound variant to a rule.
643
- * Used internally by applyCompoundVariant for the `not` variant.
644
- */
645
- private applyInnerVariant;
646
- /**
647
- * Get the sort order for a variant.
648
- */
649
- getOrder(variant: Variant): number;
650
- /**
651
- * Compare two variants for sorting.
652
- * Uses breakpoint comparison for media query variants.
653
- *
654
- * @returns negative if a < b, 0 if equal, positive if a > b
655
- */
656
- compareVariants(a: Variant, b: Variant, theme?: Theme): number;
657
- /**
658
- * Get all registered variant names.
659
- */
660
- names(): IterableIterator<string>;
661
- /**
662
- * Create a new Variants instance with the same registered variants.
663
- * Keeps caches empty to avoid sharing mutable state.
664
- */
665
- clone(): Variants;
666
- /**
667
- * Get a map of variant names to their order indices.
668
- * Used for bitmask-based sorting (O(1) comparisons).
669
- *
670
- * PERFORMANCE: Pre-computed during registration for most cases.
671
- * Only rebuilds when custom order values were specified.
672
- */
673
- getOrderMap(): Map<string, number>;
674
- /**
675
- * Invalidate the order map (call after registering new variants with custom order).
676
- */
677
- invalidateOrderMap(): void;
678
- /**
679
- * Group variants for ordering.
680
- */
681
- group(fn: () => void): void;
682
- /**
683
- * Apply a compound variant (group-hover, peer-focus, etc.)
684
- *
685
- * Compound variants create selectors that target elements based on
686
- * the state of a parent/sibling with a matching marker class.
687
- *
688
- * Examples:
689
- * - group-hover:text-paper -> .group:hover .group-hover\:text-paper
690
- * - peer-focus:text-paper -> .peer:focus ~ .peer-focus\:text-paper
691
- * - group/sidebar-hover:text-paper -> .group\/sidebar:hover .group\/sidebar-hover\:text-paper
692
- */
693
- private applyCompoundVariant;
694
- }
695
-
696
- /**
697
- * Plugin API
698
- *
699
- * The API passed to plugin functions for extending the design system.
700
- */
701
-
702
- /**
703
- * The API object passed to plugin functions.
704
- */
705
- interface PluginAPI {
706
- /**
707
- * Add a static utility class.
708
- * @example
709
- * addUtility('truncate', {
710
- * overflow: 'hidden',
711
- * 'text-overflow': 'ellipsis',
712
- * 'white-space': 'nowrap',
713
- * })
714
- */
715
- addUtility(name: string, declarations: Record<string, string>): void;
716
- /**
717
- * Add a functional utility that accepts values.
718
- * @example
719
- * addFunctionalUtility('custom-spacing', (value, theme) => ({
720
- * '--custom-spacing': theme.get(`--spacing-${value}`) ?? `${value}rem`,
721
- * }))
722
- */
723
- addFunctionalUtility(name: string, handler: (value: string, theme: Theme) => Record<string, string> | null): void;
724
- /**
725
- * Add a static variant.
726
- * @example
727
- * addVariant('hocus', '&:hover, &:focus')
728
- */
729
- addVariant(name: string, selector: string | ((selector: string) => string)): void;
730
- /**
731
- * Add a functional variant that accepts values.
732
- * @example
733
- * addFunctionalVariant('nth', (value) => `&:nth-child(${value})`)
734
- */
735
- addFunctionalVariant(name: string, handler: (value: string) => string | null): void;
736
- /**
737
- * Extend the theme with custom values.
738
- * @example
739
- * extendTheme({
740
- * '--color-brand': '#ff0000',
741
- * '--spacing-huge': '100rem',
742
- * })
743
- */
744
- extendTheme(values: Record<string, string>): void;
745
- /**
746
- * Add raw CSS to the output.
747
- * This CSS will be included in the final output.
748
- * @example
749
- * addBase({
750
- * 'html': { 'font-size': '16px' },
751
- * 'body': { 'line-height': '1.5' },
752
- * })
753
- */
754
- addBase(styles: Record<string, Record<string, string>>): void;
755
- /**
756
- * Add component styles.
757
- * Similar to addBase but intended for component-level styles.
758
- * @example
759
- * addComponents({
760
- * '.btn': {
761
- * padding: '0.5rem 1rem',
762
- * 'border-radius': '0.25rem',
763
- * },
764
- * })
765
- */
766
- addComponents(styles: Record<string, Record<string, string>>): void;
767
- /**
768
- * Get a value from the theme.
769
- * @example
770
- * theme('--color-red-500') // => 'oklch(0.637 0.237 25.331)'
771
- */
772
- theme(key: string): string | undefined;
773
- /**
774
- * Access the design system's theme instance.
775
- */
776
- readonly themeInstance: Theme;
777
- /**
778
- * Access the design system's utilities instance.
779
- */
780
- readonly utilitiesInstance: Utilities;
781
- /**
782
- * Access the design system's variants instance.
783
- */
784
- readonly variantsInstance: Variants;
785
- }
786
-
787
- /**
788
- * Plugin System
789
- *
790
- * Core plugin types and loading functionality.
791
- */
792
-
793
- /**
794
- * A plugin function that extends the design system.
795
- */
796
- type PluginFunction = (api: PluginAPI) => void;
797
- /**
798
- * A plugin with configuration options.
799
- */
800
- interface PluginWithOptions<T = Record<string, unknown>> {
801
- (options?: T): PluginFunction;
802
- __isPluginWithOptions: true;
803
- }
804
- /**
805
- * A plugin can be either a function or a plugin with options.
806
- */
807
- type Plugin = PluginFunction | PluginWithOptions<any>;
808
-
809
- /**
810
- * Constant Folding Optimizer
811
- *
812
- * Simplifies calc() expressions at compile time:
813
- * - calc(2 * 4px) -> 8px
814
- * - calc(100% - 0px) -> 100%
815
- * - calc(1rem + 0) -> 1rem
816
- *
817
- * ## Supported Operations
818
- *
819
- * - **Multiplication**: `calc(N * value)` or `calc(value * N)` where N is unitless
820
- * - **Division**: `calc(value / N)` where N is unitless and non-zero
821
- * - **Addition/Subtraction**: `calc(value + value)` with compatible units
822
- *
823
- * ## Known Limitations
824
- *
825
- * ### Not Folded (Intentionally Preserved)
826
- *
827
- * - **`min()`, `max()`, `clamp()`**: CSS comparison functions require runtime
828
- * viewport/container context and cannot be evaluated at compile time.
829
- * Example: `calc(min(10px, 20px) + 5px)` is preserved as-is.
830
- *
831
- * - **`var()` references**: CSS custom properties cannot be evaluated at compile time.
832
- * Controlled via `preserveVars` option (default: true).
833
- *
834
- * - **Viewport units**: `vw`, `vh`, `vmin`, `vmax`, `svw`, `svh`, `lvw`, `lvh`, `dvw`, `dvh`
835
- * require runtime viewport dimensions.
836
- *
837
- * - **Container query units**: `cqw`, `cqh`, `cqi`, `cqb`, `cqmin`, `cqmax`
838
- * require runtime container context.
839
- *
840
- * - **Percentage + length**: `calc(50% + 10px)` cannot be folded because
841
- * percentage depends on the containing block.
842
- *
843
- * - **Nested calc()**: Complex nested expressions like `calc(calc(1 + 2) * 3)`
844
- * are not currently supported.
845
- *
846
- * ### Tokenizer Constraints
847
- *
848
- * The tokenizer uses simple parsing. Some edge cases may not fold:
849
- * - Expressions with multiple operators: `calc(1px + 2px + 3px)` (3+ operands)
850
- * - Complex whitespace patterns
851
- *
852
- * ## Unit Compatibility
853
- *
854
- * - **Length units** (px, rem, em, cm, mm, in, pt, pc) are compatible with each other
855
- * - **Angle units** (deg, grad, rad, turn) are compatible with each other
856
- * - **Time units** (s, ms) are compatible with each other
857
- * - **Percentage + length**: NOT compatible (preserved as-is)
858
- *
859
- * @example
860
- * // Folded
861
- * foldCalc("calc(2 * 4px)") // "8px"
862
- * foldCalc("calc(10px / 2)") // "5px"
863
- * foldCalc("calc(1rem + 1rem)") // "2rem"
864
- *
865
- * // Preserved (not folded)
866
- * foldCalc("calc(min(10px, 20px))") // unchanged
867
- * foldCalc("calc(50% + 10px)") // unchanged
868
- * foldCalc("calc(100vw - 20px)") // unchanged
869
- * foldCalc("calc(var(--size) * 2)") // unchanged (default)
870
- */
871
-
872
- interface FoldOptions {
873
- /** Root font size for rem calculations (default: 16) */
874
- rem?: number;
875
- /** Preserve calc() for var() references (default: true) */
876
- preserveVars?: boolean;
877
- }
878
-
879
- /**
880
- * CSS Compilation
881
- *
882
- * Main compilation pipeline that transforms CSS with utilities.
883
- */
884
-
885
- interface DesignSystem {
886
- theme: Theme;
887
- utilities: Utilities;
888
- variants: Variants;
889
- /** Base styles added by plugins */
890
- baseStyles: AstNode[];
891
- /** Component styles added by plugins */
892
- componentStyles: AstNode[];
893
- /** Optional prefix for all utility classes (e.g., "tw-") */
894
- prefix: string | null;
895
- /**
896
- * Whether to apply !important to all generated utilities.
897
- * Set by @import "tailwindcss" important or @media important.
898
- */
899
- important: boolean;
900
- /** Set of candidates that failed to compile (for diagnostics) */
901
- invalidCandidates: Set<string>;
902
- /** Set of candidates that are explicitly blocked from use */
903
- blockedCandidates: Set<string>;
904
- /** Record a candidate as invalid (failed to compile) */
905
- recordInvalid(candidate: string): void;
906
- /** Check if a candidate is valid (not blocked and has prefix if required) */
907
- isValidCandidate(candidate: string): boolean;
908
- /** Check if a candidate has the required prefix */
909
- hasValidPrefix(candidate: string): boolean;
910
- /** Strip the prefix from a candidate if present */
911
- stripPrefix(candidate: string): string;
912
- /**
913
- * Parse a candidate with caching.
914
- * Returns cached results for repeated calls with the same input.
915
- */
916
- parseCandidate(candidate: string): readonly Candidate[];
917
- /**
918
- * Track CSS variables used in a value.
919
- * Marks variables as used in the theme for tree-shaking.
920
- */
921
- trackUsedVariables(raw: string): void;
922
- /**
923
- * Get all tracked used variables.
924
- */
925
- getUsedVariables(): Set<string>;
926
- /**
927
- * Compile a candidate to AST nodes with caching.
928
- * Returns cached results for repeated calls with the same candidate.
929
- */
930
- compileCandidate(candidate: Candidate): AstNode[] | null;
931
- /**
932
- * Compile classes to AST nodes (for IntelliSense).
933
- * Returns an array of AST nodes for each class, or empty array if invalid.
934
- */
935
- candidatesToAst(classes: string[]): AstNode[][];
936
- /**
937
- * Compile classes to CSS strings (for IntelliSense).
938
- * Returns CSS string for each class, or null if invalid.
939
- */
940
- candidatesToCss(classes: string[]): (string | null)[];
941
- /**
942
- * Symbol-keyed storage for plugin data.
943
- * Used for plugin extensibility without polluting the main interface.
944
- */
945
- storage: Record<symbol, unknown>;
946
- /**
947
- * Clear all internal caches.
948
- * Call this when theme values change, plugins are reloaded,
949
- * or when you need to ensure fresh compilation results.
950
- *
951
- * This invalidates:
952
- * - Parsed candidate cache
953
- * - Compiled AST cache
954
- * - Invalid candidate tracking
955
- */
956
- clearCaches(): void;
957
- /**
958
- * Get cache statistics for debugging and monitoring.
959
- * Includes hit/miss ratios for performance analysis.
960
- */
961
- getCacheStats(): {
962
- parsedCandidates: {
963
- size: number;
964
- hits: number;
965
- misses: number;
966
- hitRate: number;
967
- };
968
- compiledAst: number;
969
- };
970
- }
971
- interface DesignSystemOptions {
972
- /** List of plugins to load */
973
- plugins?: Plugin[];
974
- /** Optional prefix for all utility classes (e.g., "tw-") */
975
- prefix?: string | null;
976
- /** Candidates to explicitly block from use */
977
- blockedCandidates?: string[];
978
- }
979
- /**
980
- * Create a design system with default configuration.
981
- */
982
- declare function createDesignSystem(options?: DesignSystemOptions): DesignSystem;
983
- interface CompileOptions {
984
- /** Design system to use (creates default if not provided) */
985
- designSystem?: DesignSystem;
986
- /** Whether to minify output */
987
- minify?: boolean;
988
- /** Whether to include base styles from plugins */
989
- includeBase?: boolean;
990
- /** Whether to include component styles from plugins */
991
- includeComponents?: boolean;
992
- /** Generate source map */
993
- sourceMap?: boolean;
994
- /** Source file path for source map */
995
- from?: string;
996
- /**
997
- * Fold calc() expressions at compile time.
998
- * - calc(2 * 4px) -> 8px
999
- * - calc(100% - 0px) -> 100%
1000
- * - calc(1rem + 1rem) -> 2rem
1001
- */
1002
- foldConstants?: boolean | FoldOptions;
1003
- /**
1004
- * Substitute custom CSS functions:
1005
- * - --alpha(color / opacity) -> color-mix()
1006
- * - --spacing(multiplier) -> calc()
1007
- * - --theme(variable) -> var() or inlined value
1008
- */
1009
- substituteFunctions?: boolean;
1010
- /**
1011
- * Sort CSS declarations by property order for consistent output.
1012
- * (position > display > box model > typography > visual)
1013
- */
1014
- sortDeclarations?: boolean;
1015
- }
1016
- interface CompileResult {
1017
- /** Generated CSS */
1018
- css: string;
1019
- /** List of generated class names */
1020
- classes: string[];
1021
- /** Source map (when sourceMap option is true) */
1022
- map?: SourceMap;
1023
- }
1024
- /**
1025
- * Compile a list of utility classes to CSS.
1026
- */
1027
- declare function compileClasses(classes: string[], options?: CompileOptions): CompileResult;
1028
- /**
1029
- * Apply !important to all declarations in the AST.
1030
- * Used by both Node compile and browser build when @media important is set.
1031
- */
1032
- declare function applyImportant(nodes: AstNode[]): AstNode[];
1033
-
1034
- interface CSSParseOptions {
1035
- /** Source file path for error messages */
1036
- from?: string;
1037
- /**
1038
- * Force tracking of source locations for source map generation.
1039
- * When true, always uses TypeScript parser (which tracks locations)
1040
- * instead of the faster native Rust parser (which doesn't track locations).
1041
- */
1042
- trackSourceLocations?: boolean;
1043
- }
1044
- interface ParseResult {
1045
- /** Parsed AST nodes */
1046
- ast: AstNode[];
1047
- /** License comments found in the CSS */
1048
- licenseComments: Comment[];
1049
- /** Source object for source map generation */
1050
- source: Source;
1051
- }
1052
- /**
1053
- * Parse CSS string into an AST.
1054
- *
1055
- * Uses native Rust parser when available (3-10x faster),
1056
- * falling back to TypeScript implementation otherwise.
1057
- *
1058
- * Key optimizations:
1059
- * - Native Rust parser with SIMD optimizations
1060
- * - Index-based buffer tracking (single slice at flush time)
1061
- * - Escape sequences tracked separately (rare case)
1062
- * - Inline trim via trimSlice (avoids extra string creation)
1063
- * - Pre-sizes arrays based on input length
1064
- */
1065
- declare function parse(input: string, options?: CSSParseOptions): ParseResult;
1066
-
1067
- /**
1068
- * Directive Error Classes
1069
- *
1070
- * This module contains all error classes used by the directives system.
1071
- * Each error class provides specific context about what went wrong.
1072
- *
1073
- * @module
1074
- */
1075
- /**
1076
- * Available preflight modules.
1077
- *
1078
- * These control which parts of the CSS reset are included:
1079
- * - box-sizing: Universal box-sizing: border-box
1080
- * - document: HTML/body defaults
1081
- * - typography: Text rendering, heading margins
1082
- * - tables: Table border-collapse
1083
- * - forms: Form element normalization
1084
- * - lists: List style reset for ul, ol
1085
- * - media: Image/video responsiveness
1086
- * - spacing: Default margin/padding reset
1087
- * - accessibility: sr-only and reduced-motion
1088
- */
1089
- declare const PREFLIGHT_MODULES: readonly ["box-sizing", "document", "typography", "tables", "forms", "lists", "media", "spacing", "accessibility"];
1090
- type PreflightModule = (typeof PREFLIGHT_MODULES)[number];
1091
-
1092
- /**
1093
- * @rainbowindex Directive
1094
- *
1095
- * Processes the @rainbowindex directive for marking injection points.
1096
- *
1097
- * @module
1098
- */
1099
-
1100
- type RainbowIndexDirectiveType = "base" | "utilities" | "components";
1101
- interface RainbowIndexDirective {
1102
- /** Type of directive: base, utilities, or components */
1103
- type: RainbowIndexDirectiveType;
1104
- /** Source pattern for utilities (optional) */
1105
- source?: {
1106
- base: string;
1107
- pattern: string;
1108
- } | "none";
1109
- /** The original AST node (used as a placeholder for utility injection) */
1110
- node: AtRule;
1111
- }
1112
-
1113
- /**
1114
- * @preflight Directive
1115
- *
1116
- * Processes the @preflight directive for CSS reset configuration.
1117
- *
1118
- * @module
1119
- */
1120
-
1121
- /**
1122
- * Preflight configuration from @preflight directive.
1123
- *
1124
- * @preflight; // Full preflight (default)
1125
- * @preflight none; // No preflight
1126
- * @preflight not lists; // Exclude specific modules
1127
- * @preflight not lists, media; // Exclude multiple modules
1128
- * @preflight only box-sizing; // Include only specific modules
1129
- * @preflight only box-sizing, forms; // Include only multiple modules
1130
- */
1131
- interface PreflightConfig {
1132
- /** Mode: full (default), none, include (only), or exclude (not) */
1133
- mode: "full" | "none" | "include" | "exclude";
1134
- /** Modules to include or exclude (depending on mode) */
1135
- modules: PreflightModule[];
1136
- }
1137
- /**
1138
- * Filter preflight styles in a @layer base block.
1139
- *
1140
- * This handles the case where preflight is wrapped in @layer base { ... }
1141
- * and filters the inner nodes based on the PreflightConfig.
1142
- */
1143
- declare function filterPreflightInLayer(ast: AstNode[], config: PreflightConfig): AstNode[];
1144
-
1145
- /**
1146
- * @source Directive
1147
- *
1148
- * Processes the @source directive for candidate source configuration.
1149
- *
1150
- * @module
1151
- */
1152
-
1153
- interface SourceDirective {
1154
- /** Type of source directive */
1155
- kind: "glob" | "inline" | "not-inline";
1156
- /** Glob pattern (for kind: "glob") */
1157
- pattern?: string;
1158
- /** Base directory for the pattern */
1159
- base?: string;
1160
- /** Whether this is a negated pattern */
1161
- negated?: boolean;
1162
- /** Inline candidates (for kind: "inline" or "not-inline") */
1163
- candidates?: string[];
1164
- }
1165
-
1166
- /**
1167
- * @font Directive
1168
- *
1169
- * Processes the @font directive for web font loading configuration.
1170
- *
1171
- * @module
1172
- */
1173
-
1174
- /**
1175
- * Options for @font directive.
1176
- */
1177
- interface FontDirectiveOptions {
1178
- /** Specific weights to include */
1179
- weights?: number[];
1180
- /** Include italic variants */
1181
- italic?: boolean;
1182
- /** Force variable or static font mode */
1183
- variable?: boolean;
1184
- /** Font display strategy */
1185
- display?: "auto" | "block" | "swap" | "fallback" | "optional";
1186
- /** Hosting mode: cdn (default) or self */
1187
- host?: "cdn" | "self";
1188
- /** URL path for self-hosted fonts */
1189
- path?: string;
1190
- /** Set theme font family (sans, serif, mono) */
1191
- set?: "sans" | "serif" | "mono";
1192
- }
1193
- /**
1194
- * Parsed @font directive.
1195
- */
1196
- interface FontDirective {
1197
- /** Font family name */
1198
- family: string;
1199
- /** Provider (currently only "google") */
1200
- provider: "google";
1201
- /** Font options */
1202
- options: FontDirectiveOptions;
1203
- }
1204
-
1205
- /**
1206
- * Utility Injection
1207
- *
1208
- * Functions for injecting compiled utilities into the AST and cleaning up
1209
- * internal nodes after processing.
1210
- *
1211
- * @module
1212
- */
1213
-
1214
- /**
1215
- * Remove @utility nodes from AST.
1216
- *
1217
- * Call this AFTER @apply processing to clean up @utility nodes that were
1218
- * kept for dependency resolution.
1219
- */
1220
- declare function removeUtilityNodes(ast: AstNode[]): AstNode[];
1221
-
1222
- /**
1223
- * Directive Handlers
1224
- *
1225
- * Processes special CSS directives: @rainbowindex, @theme, @color, @apply, @utility, @variant, @source, @layer
1226
- */
1227
-
1228
- type CompileFeaturesFlags = number;
1229
- interface TransformOptions {
1230
- designSystem: DesignSystem;
1231
- /** Base directory for @source patterns */
1232
- base?: string;
1233
- }
1234
- interface TransformResult {
1235
- /** Transformed AST nodes */
1236
- ast: AstNode[];
1237
- /** Collected @source directives */
1238
- sources: SourceDirective[];
1239
- /** Inline candidates from @source inline() */
1240
- inlineCandidates: string[];
1241
- /** Ignored candidates from @source not inline() */
1242
- ignoredCandidates: string[];
1243
- /** Reference imports (path -> true) */
1244
- referenceImports: Set<string>;
1245
- /** @rainbowindex directives found (for utility injection) */
1246
- rainbowIndexDirectives: RainbowIndexDirective[];
1247
- /** Layers declared via @layer */
1248
- layers: string[];
1249
- /** Custom utility registration functions (call with DesignSystem to register and process @apply) */
1250
- customUtilities: Array<(designSystem: DesignSystem) => void>;
1251
- /**
1252
- * Process deferred @apply directives after custom utilities are registered.
1253
- * Call this after registering customUtilities to expand @apply references
1254
- * to utilities defined later in the CSS.
1255
- * Returns a new AST with deferred @apply directives expanded.
1256
- */
1257
- processDeferredApply: (ast: AstNode[]) => AstNode[];
1258
- /** Preflight configuration from @preflight directive */
1259
- preflightConfig: PreflightConfig;
1260
- /** Bitmask of detected Rainbow Index features */
1261
- features: CompileFeaturesFlags;
1262
- /** @font directives found (for font import generation) */
1263
- fontDirectives: FontDirective[];
1264
- }
1265
- /**
1266
- * Transform CSS by processing all directives.
1267
- */
1268
- declare function transformCSS(ast: AstNode[], options: TransformOptions): TransformResult;
1269
-
1270
- /**
1271
- * Rainbow Index Browser Entry Point
1272
- *
1273
- * Focused entry point for browser environments with tree-shaking in mind.
1274
- * Only exports functions that are safe and useful in browser contexts.
1275
- *
1276
- * Node.js-specific functionality (file I/O, native modules) is excluded.
1277
- *
1278
- * IMPORTANT: This file must NOT import from "./index" or any barrel exports
1279
- * that include Node.js-specific code. Import directly from specific modules.
1280
- */
1281
-
1282
- /** Feature flags for Lightning CSS integration */
1283
- declare const Features: {
1284
- /** Enable CSS nesting transformation */
1285
- readonly Nesting: number;
1286
- /** Enable media query transformations */
1287
- readonly MediaQueries: number;
1288
- /** Transform logical properties */
1289
- readonly LogicalProperties: number;
1290
- /** Transform :dir() selector */
1291
- readonly DirSelector: number;
1292
- /** Transform light-dark() function */
1293
- readonly LightDark: number;
1294
- /** Transform oklch/oklab colors */
1295
- readonly OklabColors: number;
1296
- /** Transform lab/lch colors */
1297
- readonly LabColors: number;
1298
- /** Transform display-p3 colors */
1299
- readonly P3Colors: number;
1300
- /** Transform color() function */
1301
- readonly ColorFunction: number;
1302
- /** No features enabled */
1303
- readonly None: 0;
1304
- /** All features enabled */
1305
- readonly All: number;
1306
- };
1307
- type FeatureFlags = number;
1308
- /**
1309
- * Validate that a value is a valid feature flags bitmask.
1310
- * Returns true if the value is a non-negative integer within the valid range.
1311
- */
1312
- declare function isValidFeatureFlags(value: unknown): value is FeatureFlags;
1313
- /**
1314
- * Validate feature flags and return a safe value.
1315
- * If the input is invalid, returns Features.None.
1316
- */
1317
- declare function validateFeatureFlags(value: unknown): FeatureFlags;
1318
- /**
1319
- * Check if specific feature flags are enabled in a bitmask.
1320
- */
1321
- declare function hasFeature(flags: FeatureFlags, feature: FeatureFlags): boolean;
1322
-
1323
- export { type CompileOptions, type CompileResult, type DesignSystem, type FeatureFlags, Features, type ParseResult, type PrintOptions, applyImportant, compileClasses, createDesignSystem, filterPreflightInLayer, hasFeature, isValidFeatureFlags, minify, parse, print, removeUtilityNodes, transformCSS, validateFeatureFlags };
5
+ export { browserEntryUnavailable as default };