0
# Core Engine
1
2
Core UnoCSS engine functionality providing generator creation, configuration management, utility functions, and the fundamental CSS generation system.
3
4
## Capabilities
5
6
### Configuration Functions
7
8
Helper functions for defining and managing UnoCSS configuration.
9
10
```typescript { .api }
11
/**
12
* Define UnoCSS configuration with type safety
13
* @param config - User configuration object
14
* @returns Validated configuration object
15
*/
16
function defineConfig<Theme>(config: UserConfig<Theme>): UserConfig<Theme>;
17
18
/**
19
* Resolve user configuration with defaults
20
* @param userConfig - User-provided configuration
21
* @param defaults - Default configuration to merge with
22
* @returns Resolved configuration
23
*/
24
function resolveConfig<Theme>(
25
userConfig: UserConfig<Theme>,
26
defaults?: UserConfig<Theme>
27
): Promise<ResolvedConfig<Theme>>;
28
29
/**
30
* Merge multiple configurations into one
31
* @param configs - Array of configurations to merge
32
* @returns Merged configuration
33
*/
34
function mergeConfigs<Theme>(configs: UserConfig<Theme>[]): UserConfig<Theme>;
35
36
/**
37
* Helper to define presets with proper typing
38
* @param preset - Preset configuration
39
* @returns Typed preset object
40
*/
41
function definePreset<Theme>(preset: Preset<Theme>): Preset<Theme>;
42
```
43
44
### Generator Functions
45
46
Core generator creation and management functions.
47
48
```typescript { .api }
49
/**
50
* Creates a UnoCSS generator instance asynchronously
51
* @param config - Optional user configuration
52
* @param defaults - Optional default configuration
53
* @returns Promise that resolves to UnoGenerator instance
54
*/
55
function createGenerator<Theme>(
56
config?: UserConfig<Theme>,
57
defaults?: UserConfig<Theme>
58
): Promise<UnoGenerator<Theme>>;
59
60
interface UnoGenerator<Theme = object> {
61
/** Current resolved configuration */
62
config: ResolvedConfig<Theme>;
63
64
/** Generate CSS from tokens */
65
generate(
66
tokens: string | string[],
67
options?: GenerateOptions<Theme>
68
): Promise<GenerateResult<Theme>>;
69
70
/** Parse and match tokens */
71
parseToken(token: string): Promise<ExtendedTokenInfo<Theme>[]>;
72
73
/** Get all CSS for given tokens */
74
getCSS(options?: GenerateOptions<Theme>): Promise<string>;
75
76
/** Apply safelist patterns */
77
applyExtractors(
78
code: string,
79
filename?: string,
80
extractors?: Extractor[]
81
): Promise<Set<string>>;
82
}
83
84
interface GenerateOptions<Theme = object> {
85
/** File ID for context */
86
id?: string;
87
/** Tokens to generate CSS for */
88
tokens?: Set<string>;
89
/** Whether to include preflights */
90
preflights?: boolean;
91
/** Whether to include safelist */
92
safelist?: boolean;
93
/** Minimum layers to include */
94
minify?: boolean;
95
}
96
97
interface GenerateResult<Theme = object> {
98
/** Generated CSS string */
99
css: string;
100
/** Layer information */
101
layers: string[];
102
/** Matched tokens information */
103
matched: Set<string>;
104
/** Processing time */
105
time: number;
106
}
107
```
108
109
### Core Symbols and Constants
110
111
Special control symbols and constants for CSS manipulation.
112
113
```typescript { .api }
114
/** Special control symbols for CSS manipulation */
115
declare const symbols: {
116
/** Prevent merging in shortcuts */
117
readonly shortcutsNoMerge: unique symbol;
118
/** Prevent merging in rules */
119
readonly noMerge: unique symbol;
120
/** Additional variants for rules */
121
readonly variants: unique symbol;
122
/** Parent selector (@media, @supports, etc.) */
123
readonly parent: unique symbol;
124
/** Selector modifier */
125
readonly selector: unique symbol;
126
/** Layer modifier */
127
readonly layer: unique symbol;
128
/** Sort modifier */
129
readonly sort: unique symbol;
130
/** Custom CSS body modifier */
131
readonly body: unique symbol;
132
};
133
134
/** Default layer name ('default') */
135
declare const LAYER_DEFAULT: string;
136
/** Preflights layer name ('preflights') */
137
declare const LAYER_PREFLIGHTS: string;
138
/** Shortcuts layer name ('shortcuts') */
139
declare const LAYER_SHORTCUTS: string;
140
/** Imports layer name ('imports') */
141
declare const LAYER_IMPORTS: string;
142
/** Default layer configuration object */
143
declare const DEFAULT_LAYERS: Record<string, number>;
144
```
145
146
### Utility Functions
147
148
General utility functions for common operations.
149
150
```typescript { .api }
151
/**
152
* Converts value to array
153
* @param value - Value to convert
154
* @returns Array containing the value(s)
155
*/
156
function toArray<T>(value: T | T[]): T[];
157
158
/**
159
* Returns array with unique values
160
* @param array - Input array
161
* @returns Array with duplicates removed
162
*/
163
function uniq<T>(array: T[]): T[];
164
165
/**
166
* Returns unique array using equality function
167
* @param array - Input array
168
* @param equalFn - Function to determine equality
169
* @returns Array with duplicates removed based on equalFn
170
*/
171
function uniqueBy<T>(array: T[], equalFn: (a: T, b: T) => boolean): T[];
172
173
/**
174
* Type guard for strings
175
* @param value - Value to check
176
* @returns True if value is string
177
*/
178
function isString(value: any): value is string;
179
180
/**
181
* Type guard for objects
182
* @param item - Item to check
183
* @returns True if item is object
184
*/
185
function isObject(item: any): item is object;
186
187
/**
188
* Deep merge objects
189
* @param original - Original object
190
* @param patch - Patch to apply
191
* @param mergeArray - Whether to merge arrays
192
* @returns Merged object
193
*/
194
function mergeDeep<T>(original: T, patch: DeepPartial<T>, mergeArray?: boolean): T;
195
196
/**
197
* Deep clone values
198
* @param val - Value to clone
199
* @returns Cloned value
200
*/
201
function clone<T>(val: T): T;
202
203
/**
204
* Type guard to filter null/undefined
205
* @param value - Value to check
206
* @returns True if value is not null/undefined
207
*/
208
function notNull<T>(value: T | null | undefined): value is T;
209
210
/**
211
* No-operation function
212
*/
213
function noop(): void;
214
215
/**
216
* Warn once per message
217
* @param msg - Warning message
218
*/
219
function warnOnce(msg: string): void;
220
```
221
222
### CSS Utilities
223
224
Functions for working with CSS objects and strings.
225
226
```typescript { .api }
227
/**
228
* Normalize CSS entries
229
* @param obj - CSS object to normalize
230
* @returns Normalized CSS entries
231
*/
232
function normalizeCSSEntries(obj: CSSObject): CSSEntries;
233
234
/**
235
* Normalize CSS values
236
* @param obj - Object with CSS values
237
* @returns Object with normalized values
238
*/
239
function normalizeCSSValues(obj: Record<string, any>): Record<string, string>;
240
241
/**
242
* Convert entries to CSS string
243
* @param entries - CSS entries to convert
244
* @returns CSS string
245
*/
246
function entriesToCss(entries: CSSEntries): string;
247
248
/**
249
* Remove duplicate entries
250
* @param entries - CSS entries
251
* @returns Entries with duplicates removed
252
*/
253
function clearIdenticalEntries(entries: CSSEntries): CSSEntries;
254
255
/**
256
* Escape CSS selector
257
* @param str - Selector string to escape
258
* @returns Escaped selector
259
*/
260
function escapeSelector(str: string): string;
261
262
/**
263
* Short alias for escapeSelector
264
*/
265
declare const e: typeof escapeSelector;
266
267
/**
268
* Escape CSS selector for safe use
269
* @param raw - Raw selector
270
* @returns Escaped selector
271
*/
272
function toEscapedSelector(raw: string): string;
273
274
/**
275
* Check if CSS has scope placeholder
276
* @param css - CSS string to check
277
* @returns True if has scope placeholder
278
*/
279
function hasScopePlaceholder(css: string): boolean;
280
```
281
282
### Advanced Data Structures
283
284
Enhanced data structures for internal UnoCSS operations.
285
286
```typescript { .api }
287
/**
288
* Set that tracks element counts
289
*/
290
class CountableSet<K> extends Set<K> {
291
getCount(key: K): number;
292
setCount(key: K, count: number): this;
293
increaseCount(key: K, delta?: number): number;
294
decreaseCount(key: K, delta?: number): number;
295
}
296
297
/**
298
* Type guard for CountableSet
299
* @param value - Value to check
300
* @returns True if value is CountableSet
301
*/
302
function isCountableSet<T>(value: any): value is CountableSet<T>;
303
304
/**
305
* Map with two keys
306
*/
307
class TwoKeyMap<K1, K2, V> {
308
set(key1: K1, key2: K2, value: V): this;
309
get(key1: K1, key2: K2): V | undefined;
310
has(key1: K1, key2: K2): boolean;
311
delete(key1: K1, key2: K2): boolean;
312
clear(): void;
313
}
314
315
/**
316
* Enhanced Map class with additional utilities
317
*/
318
class BetterMap<K, V> extends Map<K, V> {
319
ensure(key: K, defaultValue: V): V;
320
approach(key: K, defaultValue: V): V;
321
}
322
323
/**
324
* Create nano event emitter
325
* @returns Event emitter instance
326
*/
327
function createNanoEvents<Events>(): {
328
emit<E extends keyof Events>(event: E, ...args: Events[E] extends (...args: infer A) => any ? A : []): void;
329
on<E extends keyof Events>(event: E, callback: Events[E]): () => void;
330
};
331
```
332
333
### Extractors and Parsing
334
335
Functions for extracting and parsing CSS tokens from source code.
336
337
```typescript { .api }
338
/**
339
* Default split extractor
340
*/
341
declare const extractorSplit: Extractor;
342
343
/**
344
* Default split regex
345
*/
346
declare const defaultSplitRE: RegExp;
347
348
/**
349
* Split regex with variant groups
350
*/
351
declare const splitWithVariantGroupRE: RegExp;
352
353
/**
354
* Split code into tokens
355
* @param code - Source code to split
356
* @returns Array of tokens
357
*/
358
function splitCode(code: string): string[];
359
360
/**
361
* Parse variant group syntax
362
* @param str - String to parse
363
* @param separators - Optional separators
364
* @param depth - Optional parsing depth
365
* @returns Parsed variant group
366
*/
367
function parseVariantGroup(str: string, separators?: string[], depth?: number): any;
368
369
/**
370
* Expand variant group syntax
371
* @param str - String to expand
372
* @param separators - Optional separators
373
* @param depth - Optional expansion depth
374
* @returns Expanded variant group
375
*/
376
function expandVariantGroup(str: string, separators?: string[], depth?: number): string[];
377
378
/**
379
* Collapse variant group syntax
380
* @param str - String to collapse
381
* @param prefixes - Prefixes to use
382
* @returns Collapsed variant group
383
*/
384
function collapseVariantGroup(str: string, prefixes: string[]): string;
385
```
386
387
## Types
388
389
### Context Types
390
391
```typescript { .api }
392
interface RuleContext<Theme = object> {
393
/** Current theme */
394
theme: Theme;
395
/** Raw CSS selector */
396
rawSelector: string;
397
/** Current CSS selector */
398
currentSelector: string;
399
/** Available variants */
400
variants: Set<Variant<Theme>>;
401
/** Generator instance */
402
generator: UnoGenerator<Theme>;
403
}
404
405
interface VariantContext<Theme = object> {
406
/** Current theme */
407
theme: Theme;
408
/** Generator instance */
409
generator: UnoGenerator<Theme>;
410
}
411
412
interface ExtractorContext {
413
/** Original code */
414
original: string;
415
/** Code to extract from */
416
code: string;
417
/** File ID */
418
id?: string;
419
}
420
```
421
422
### Extended Token Information
423
424
```typescript { .api }
425
interface ExtendedTokenInfo<Theme = object> {
426
/** Parsed token */
427
token: string;
428
/** Raw token */
429
raw: string;
430
/** CSS body */
431
body: CSSObject;
432
/** Parent selectors */
433
parent: string;
434
/** Selector transformations */
435
selector: string;
436
/** Layer name */
437
layer: string;
438
/** Sort value */
439
sort: number;
440
/** Associated rule */
441
rule?: Rule<Theme>;
442
/** Associated shortcut */
443
shortcut?: Shortcut<Theme>;
444
}
445
```