nitrowind 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +44 -2
  4. package/css.d.ts +6 -0
  5. package/dist/color.d.ts +24 -0
  6. package/dist/color.d.ts.map +1 -0
  7. package/dist/color.js +158 -0
  8. package/dist/color.js.map +1 -0
  9. package/dist/core.d.ts +121 -0
  10. package/dist/core.d.ts.map +1 -0
  11. package/dist/core.js +1026 -0
  12. package/dist/core.js.map +1 -0
  13. package/dist/css/compile.d.ts +18 -0
  14. package/dist/css/compile.d.ts.map +1 -0
  15. package/dist/css/compile.js +1018 -0
  16. package/dist/css/compile.js.map +1 -0
  17. package/dist/css/declarations.d.ts +18 -0
  18. package/dist/css/declarations.d.ts.map +1 -0
  19. package/dist/css/declarations.js +1173 -0
  20. package/dist/css/declarations.js.map +1 -0
  21. package/dist/css/index.d.ts +7 -0
  22. package/dist/css/index.d.ts.map +1 -0
  23. package/dist/css/index.js +7 -0
  24. package/dist/css/index.js.map +1 -0
  25. package/dist/css/parser.d.ts +9 -0
  26. package/dist/css/parser.d.ts.map +1 -0
  27. package/dist/css/parser.js +188 -0
  28. package/dist/css/parser.js.map +1 -0
  29. package/dist/css/tokenizer.d.ts +14 -0
  30. package/dist/css/tokenizer.d.ts.map +1 -0
  31. package/dist/css/tokenizer.js +200 -0
  32. package/dist/css/tokenizer.js.map +1 -0
  33. package/dist/css/types.d.ts +128 -0
  34. package/dist/css/types.d.ts.map +1 -0
  35. package/dist/css/types.js +19 -0
  36. package/dist/css/types.js.map +1 -0
  37. package/dist/css/values.d.ts +37 -0
  38. package/dist/css/values.d.ts.map +1 -0
  39. package/dist/css/values.js +343 -0
  40. package/dist/css/values.js.map +1 -0
  41. package/dist/environment.d.ts +5 -0
  42. package/dist/environment.d.ts.map +1 -0
  43. package/dist/environment.js +99 -0
  44. package/dist/environment.js.map +1 -0
  45. package/dist/hooks.d.ts +22 -0
  46. package/dist/hooks.d.ts.map +1 -0
  47. package/dist/hooks.js +140 -0
  48. package/dist/hooks.js.map +1 -0
  49. package/dist/index.d.ts +26 -0
  50. package/dist/index.d.ts.map +1 -0
  51. package/dist/index.js +16 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/jsx-dev-runtime.d.ts +17 -0
  54. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  55. package/dist/jsx-dev-runtime.js +12 -0
  56. package/dist/jsx-dev-runtime.js.map +1 -0
  57. package/dist/jsx-namespace.d.ts +29 -0
  58. package/dist/jsx-namespace.d.ts.map +1 -0
  59. package/dist/jsx-namespace.js +2 -0
  60. package/dist/jsx-namespace.js.map +1 -0
  61. package/dist/jsx-runtime.d.ts +22 -0
  62. package/dist/jsx-runtime.d.ts.map +1 -0
  63. package/dist/jsx-runtime.js +21 -0
  64. package/dist/jsx-runtime.js.map +1 -0
  65. package/dist/math.d.ts +50 -0
  66. package/dist/math.d.ts.map +1 -0
  67. package/dist/math.js +442 -0
  68. package/dist/math.js.map +1 -0
  69. package/dist/plugin.d.ts +45 -0
  70. package/dist/plugin.d.ts.map +1 -0
  71. package/dist/plugin.js +172 -0
  72. package/dist/plugin.js.map +1 -0
  73. package/dist/props.d.ts +29 -0
  74. package/dist/props.d.ts.map +1 -0
  75. package/dist/props.js +163 -0
  76. package/dist/props.js.map +1 -0
  77. package/dist/scope.d.ts +99 -0
  78. package/dist/scope.d.ts.map +1 -0
  79. package/dist/scope.js +228 -0
  80. package/dist/scope.js.map +1 -0
  81. package/dist/store.d.ts +18 -0
  82. package/dist/store.d.ts.map +1 -0
  83. package/dist/store.js +244 -0
  84. package/dist/store.js.map +1 -0
  85. package/dist/tokens/index.d.ts +12 -0
  86. package/dist/tokens/index.d.ts.map +1 -0
  87. package/dist/tokens/index.js +237 -0
  88. package/dist/tokens/index.js.map +1 -0
  89. package/dist/tokens/tailwind.generated.d.ts +3 -0
  90. package/dist/tokens/tailwind.generated.d.ts.map +1 -0
  91. package/dist/tokens/tailwind.generated.js +610 -0
  92. package/dist/tokens/tailwind.generated.js.map +1 -0
  93. package/dist/tokens/types.d.ts +95 -0
  94. package/dist/tokens/types.d.ts.map +1 -0
  95. package/dist/tokens/types.js +2 -0
  96. package/dist/tokens/types.js.map +1 -0
  97. package/dist/transform.d.ts +22 -0
  98. package/dist/transform.d.ts.map +1 -0
  99. package/dist/transform.js +79 -0
  100. package/dist/transform.js.map +1 -0
  101. package/dist/transition.d.ts +7 -0
  102. package/dist/transition.d.ts.map +1 -0
  103. package/dist/transition.js +355 -0
  104. package/dist/transition.js.map +1 -0
  105. package/dist/types.d.ts +214 -0
  106. package/dist/types.d.ts.map +1 -0
  107. package/dist/types.js +2 -0
  108. package/dist/types.js.map +1 -0
  109. package/dist/utilities.d.ts +109 -0
  110. package/dist/utilities.d.ts.map +1 -0
  111. package/dist/utilities.js +2000 -0
  112. package/dist/utilities.js.map +1 -0
  113. package/dist/variables.d.ts +65 -0
  114. package/dist/variables.d.ts.map +1 -0
  115. package/dist/variables.js +408 -0
  116. package/dist/variables.js.map +1 -0
  117. package/dist/version.d.ts +3 -0
  118. package/dist/version.d.ts.map +1 -0
  119. package/dist/version.js +3 -0
  120. package/dist/version.js.map +1 -0
  121. package/dist/withNitroWind.d.ts +11 -0
  122. package/dist/withNitroWind.d.ts.map +1 -0
  123. package/dist/withNitroWind.js +27 -0
  124. package/dist/withNitroWind.js.map +1 -0
  125. package/package.json +89 -4
  126. package/src/color.ts +164 -0
  127. package/src/core.ts +1248 -0
  128. package/src/css/compile.ts +1198 -0
  129. package/src/css/declarations.ts +1141 -0
  130. package/src/css/index.ts +22 -0
  131. package/src/css/parser.ts +196 -0
  132. package/src/css/tokenizer.ts +227 -0
  133. package/src/css/types.ts +178 -0
  134. package/src/css/values.ts +330 -0
  135. package/src/environment.ts +112 -0
  136. package/src/hooks.ts +190 -0
  137. package/src/index.ts +61 -0
  138. package/src/jsx-dev-runtime.ts +43 -0
  139. package/src/jsx-namespace.ts +23 -0
  140. package/src/jsx-runtime.ts +39 -0
  141. package/src/math.ts +488 -0
  142. package/src/plugin.ts +230 -0
  143. package/src/props.ts +173 -0
  144. package/src/scope.ts +331 -0
  145. package/src/store.ts +288 -0
  146. package/src/tokens/index.ts +252 -0
  147. package/src/tokens/tailwind.generated.ts +613 -0
  148. package/src/tokens/types.ts +99 -0
  149. package/src/transform.ts +115 -0
  150. package/src/transition.ts +414 -0
  151. package/src/types.ts +248 -0
  152. package/src/utilities.ts +1992 -0
  153. package/src/variables.ts +509 -0
  154. package/src/version.ts +2 -0
  155. package/src/withNitroWind.ts +36 -0
@@ -0,0 +1,1198 @@
1
+ import type { PackedColor } from '../color'
2
+ import { tailwindTokens } from '../tokens/tailwind.generated'
3
+ import type {
4
+ NitroFontWeight,
5
+ TokenBoxShadow,
6
+ TokenDropShadow,
7
+ TokenFontSize,
8
+ TokenLineHeight,
9
+ Tokens,
10
+ TokensConfig,
11
+ TokensInput,
12
+ } from '../tokens/types'
13
+ import type { ColorScheme, CSSVariableValue } from '../types'
14
+ import { hasVarCall } from '../variables'
15
+ import { validateRawDeclaration } from './declarations'
16
+ import { parseStylesheet } from './parser'
17
+ import {
18
+ type CSSAtRuleNode,
19
+ type CSSCustomClassDefinition,
20
+ type CSSCustomClassEntry,
21
+ type CSSCustomClassRank,
22
+ type CSSDeclarationNode,
23
+ type CSSLocation,
24
+ type CSSNode,
25
+ CSSParseError,
26
+ type CSSRuleNode,
27
+ type CSSThemeEntry,
28
+ type CSSTokenNamespace,
29
+ type CSSTokenResets,
30
+ type CSSWarning,
31
+ type CSSWarningCode,
32
+ type NitroWindCSSConfig,
33
+ type ParseCSSOptions,
34
+ } from './types'
35
+ import {
36
+ parseCSSBoxShadows,
37
+ parseCSSBreakpoint,
38
+ parseCSSColor,
39
+ parseCSSDropShadows,
40
+ parseCSSFontWeight,
41
+ parseCSSLength,
42
+ parseCSSLengthOrPercent,
43
+ parseCSSLineHeight,
44
+ parseCSSRatio,
45
+ parseImportSpecifier,
46
+ resolveRelativeImportKey,
47
+ } from './values'
48
+
49
+ const PRESET_IMPORTS = new Set(['tailwindcss', 'nitrowind', 'uniwind'])
50
+
51
+ const ALL_TOKEN_NAMESPACES: readonly CSSTokenNamespace[] = [
52
+ 'colors',
53
+ 'fontSize',
54
+ 'fontWeight',
55
+ 'leading',
56
+ 'radius',
57
+ 'shadow',
58
+ 'insetShadow',
59
+ 'dropShadow',
60
+ 'container',
61
+ 'aspect',
62
+ 'breakpoints',
63
+ 'spacingScale',
64
+ ]
65
+
66
+ interface TokenPrefixSpec {
67
+ readonly prefix: string
68
+ readonly namespace: CSSTokenNamespace
69
+ }
70
+
71
+ /** Ordered longest-prefix first so `--inset-shadow-` matches before `--shadow-`, etc. */
72
+ const TOKEN_PREFIXES: readonly TokenPrefixSpec[] = [
73
+ { prefix: '--inset-shadow-', namespace: 'insetShadow' },
74
+ { prefix: '--drop-shadow-', namespace: 'dropShadow' },
75
+ { prefix: '--font-weight-', namespace: 'fontWeight' },
76
+ { prefix: '--breakpoint-', namespace: 'breakpoints' },
77
+ { prefix: '--container-', namespace: 'container' },
78
+ { prefix: '--spacing-', namespace: 'spacingScale' },
79
+ { prefix: '--leading-', namespace: 'leading' },
80
+ { prefix: '--shadow-', namespace: 'shadow' },
81
+ { prefix: '--radius-', namespace: 'radius' },
82
+ { prefix: '--aspect-', namespace: 'aspect' },
83
+ { prefix: '--color-', namespace: 'colors' },
84
+ { prefix: '--text-', namespace: 'fontSize' },
85
+ ]
86
+
87
+ interface MatchedTokenVar {
88
+ readonly namespace: CSSTokenNamespace
89
+ readonly key: string
90
+ readonly lineHeightFor?: string
91
+ }
92
+
93
+ function matchTokenVariable(name: string): MatchedTokenVar | null {
94
+ if (!name.startsWith('--')) return null
95
+ for (const { prefix, namespace } of TOKEN_PREFIXES) {
96
+ if (!name.startsWith(prefix)) continue
97
+ const suffix = name.slice(prefix.length)
98
+ if (!suffix) return null
99
+ if (namespace === 'fontSize') {
100
+ if (suffix.startsWith('shadow-')) return null
101
+ if (suffix.endsWith('--line-height')) {
102
+ const sizeKey = suffix.slice(0, -'--line-height'.length)
103
+ return sizeKey ? { namespace: 'fontSize', key: sizeKey, lineHeightFor: sizeKey } : null
104
+ }
105
+ if (suffix.includes('--')) return null
106
+ }
107
+ return { namespace, key: suffix }
108
+ }
109
+ return null
110
+ }
111
+
112
+ interface PendingInlineLineHeight {
113
+ readonly raw: string
114
+ readonly location: CSSLocation
115
+ }
116
+
117
+ interface MutableThemeEntry {
118
+ colorScheme?: ColorScheme
119
+ readonly variables: Record<string, CSSVariableValue>
120
+ readonly location?: CSSLocation
121
+ }
122
+
123
+ interface MutableCustomClassEntry {
124
+ rank: CSSCustomClassRank
125
+ readonly entries: CSSCustomClassEntry[]
126
+ readonly applyLocations: Map<string, CSSLocation>
127
+ }
128
+
129
+ interface CompilerState {
130
+ readonly imports: string[]
131
+ readonly warnings: CSSWarning[]
132
+ readonly variables: Record<string, CSSVariableValue>
133
+ readonly themes: Record<string, MutableThemeEntry>
134
+ readonly customClasses: Record<string, MutableCustomClassEntry>
135
+ readonly themeVarLocations: Map<string, CSSLocation>
136
+ readonly resetNamespaces: Set<CSSTokenNamespace>
137
+ readonly resetKeys: Map<CSSTokenNamespace, Set<string>>
138
+ readonly resetPrefixes: Map<CSSTokenNamespace, Set<string>>
139
+ spacing?: number | string
140
+ readonly spacingScale: Record<string, number | string>
141
+ readonly colors: Record<string, PackedColor | string>
142
+ readonly fontSize: Record<string, TokenFontSize | string>
143
+ readonly inlineLineHeights: Map<string, PendingInlineLineHeight>
144
+ readonly varLineHeights: Set<string>
145
+ readonly fontWeight: Record<string, NitroFontWeight | string>
146
+ readonly leading: Record<string, TokenLineHeight>
147
+ readonly radius: Record<string, number | string>
148
+ readonly shadow: Record<string, TokenBoxShadow[] | string>
149
+ readonly insetShadow: Record<string, TokenBoxShadow[] | string>
150
+ readonly dropShadow: Record<string, TokenDropShadow[] | string>
151
+ readonly container: Record<string, number | string>
152
+ readonly aspect: Record<string, number | string>
153
+ readonly breakpoints: Record<string, number>
154
+ readonly importStack: string[]
155
+ warn(code: CSSWarningCode, message: string, location: CSSLocation): void
156
+ }
157
+
158
+ function getNamespaceBucket(state: CompilerState, namespace: CSSTokenNamespace): Record<string, unknown> {
159
+ switch (namespace) {
160
+ case 'colors':
161
+ return state.colors
162
+ case 'fontSize':
163
+ return state.fontSize
164
+ case 'fontWeight':
165
+ return state.fontWeight
166
+ case 'leading':
167
+ return state.leading
168
+ case 'radius':
169
+ return state.radius
170
+ case 'shadow':
171
+ return state.shadow
172
+ case 'insetShadow':
173
+ return state.insetShadow
174
+ case 'dropShadow':
175
+ return state.dropShadow
176
+ case 'container':
177
+ return state.container
178
+ case 'aspect':
179
+ return state.aspect
180
+ case 'breakpoints':
181
+ return state.breakpoints
182
+ case 'spacingScale':
183
+ return state.spacingScale
184
+ }
185
+ }
186
+
187
+ function deleteVariablesForPrefix(variables: Record<string, CSSVariableValue>, varPrefix: string): void {
188
+ for (const key of Object.keys(variables)) {
189
+ if (key.startsWith(varPrefix)) delete variables[key]
190
+ }
191
+ }
192
+
193
+ function clearNamespace(state: CompilerState, namespace: CSSTokenNamespace, varPrefix?: string): void {
194
+ state.resetNamespaces.add(namespace)
195
+ state.resetKeys.delete(namespace)
196
+ state.resetPrefixes.delete(namespace)
197
+ const bucket = getNamespaceBucket(state, namespace)
198
+ for (const key of Object.keys(bucket)) delete bucket[key]
199
+ if (namespace === 'fontSize') {
200
+ state.inlineLineHeights.clear()
201
+ state.varLineHeights.clear()
202
+ }
203
+ if (varPrefix !== undefined) {
204
+ deleteVariablesForPrefix(state.variables, varPrefix)
205
+ }
206
+ }
207
+
208
+ function clearNamespacePrefix(
209
+ state: CompilerState,
210
+ namespace: CSSTokenNamespace,
211
+ keyPrefix: string,
212
+ varPrefix: string,
213
+ ): void {
214
+ let set = state.resetPrefixes.get(namespace)
215
+ if (set === undefined) {
216
+ set = new Set()
217
+ state.resetPrefixes.set(namespace, set)
218
+ }
219
+ set.add(keyPrefix)
220
+ const bucket = getNamespaceBucket(state, namespace)
221
+ for (const key of Object.keys(bucket)) {
222
+ if (key.startsWith(keyPrefix)) delete bucket[key]
223
+ }
224
+ deleteVariablesForPrefix(state.variables, varPrefix)
225
+ }
226
+
227
+ function clearNamespaceKey(state: CompilerState, namespace: CSSTokenNamespace, key: string, varName: string): void {
228
+ let set = state.resetKeys.get(namespace)
229
+ if (set === undefined) {
230
+ set = new Set()
231
+ state.resetKeys.set(namespace, set)
232
+ }
233
+ set.add(key)
234
+ const bucket = getNamespaceBucket(state, namespace)
235
+ delete bucket[key]
236
+ if (namespace === 'fontSize') {
237
+ state.inlineLineHeights.delete(key)
238
+ state.varLineHeights.delete(key)
239
+ }
240
+ delete state.variables[varName]
241
+ }
242
+
243
+ function unmarkResetKey(state: CompilerState, namespace: CSSTokenNamespace, key: string): void {
244
+ state.resetKeys.get(namespace)?.delete(key)
245
+ }
246
+
247
+ function applyInitialReset(state: CompilerState, property: string, location: CSSLocation): boolean {
248
+ if (property === '--*') {
249
+ for (const ns of ALL_TOKEN_NAMESPACES) {
250
+ clearNamespace(state, ns)
251
+ }
252
+ for (const spec of TOKEN_PREFIXES) {
253
+ deleteVariablesForPrefix(state.variables, spec.prefix)
254
+ }
255
+ return true
256
+ }
257
+ for (const { prefix, namespace } of TOKEN_PREFIXES) {
258
+ if (!property.startsWith(prefix)) continue
259
+ const suffix = property.slice(prefix.length)
260
+ if (suffix === '*') {
261
+ clearNamespace(state, namespace, prefix)
262
+ return true
263
+ }
264
+ if (suffix.endsWith('-*')) {
265
+ const keyPrefix = suffix.slice(0, -1) // e.g. 'red-'
266
+ clearNamespacePrefix(state, namespace, keyPrefix, `${prefix}${keyPrefix}`)
267
+ return true
268
+ }
269
+ if (namespace === 'fontSize' && suffix.startsWith('shadow-')) return false
270
+ if (namespace === 'fontSize' && suffix.endsWith('--line-height')) {
271
+ const sizeKey = suffix.slice(0, -'--line-height'.length)
272
+ if (!sizeKey) return false
273
+ state.inlineLineHeights.delete(sizeKey)
274
+ state.varLineHeights.delete(sizeKey)
275
+ delete state.variables[property]
276
+ const existing = state.fontSize[sizeKey]
277
+ if (existing && typeof existing === 'object') {
278
+ state.fontSize[sizeKey] = { fontSize: existing.fontSize }
279
+ }
280
+ return true
281
+ }
282
+ clearNamespaceKey(state, namespace, suffix, property)
283
+ return true
284
+ }
285
+ state.warn('unsupported-declaration', `Unsupported initial reset "${property}: initial"`, location)
286
+ return true
287
+ }
288
+
289
+ function registerVarBackedToken(
290
+ state: CompilerState,
291
+ property: string,
292
+ value: string,
293
+ location: CSSLocation,
294
+ fromVariant = false,
295
+ ): void {
296
+ if (property === '--spacing') {
297
+ state.spacing = 'var(--spacing)'
298
+ return
299
+ }
300
+ const matched = matchTokenVariable(property)
301
+ if (matched === null) return
302
+
303
+ const { namespace, key, lineHeightFor } = matched
304
+ unmarkResetKey(state, namespace, key)
305
+
306
+ if (namespace === 'breakpoints') {
307
+ if (fromVariant) {
308
+ state.warn(
309
+ 'unsupported-declaration',
310
+ `Breakpoint "${property}" cannot be scoped to @variant; declare it in @theme or :root`,
311
+ location,
312
+ )
313
+ return
314
+ }
315
+ const bp = parseCSSBreakpoint(value)
316
+ if (bp === null) {
317
+ state.warn('invalid-token-value', `Invalid breakpoint length "${value}" for "${property}"`, location)
318
+ return
319
+ }
320
+ state.breakpoints[key] = bp
321
+ return
322
+ }
323
+
324
+ if (namespace === 'fontSize') {
325
+ if (lineHeightFor !== undefined) {
326
+ state.varLineHeights.add(lineHeightFor)
327
+ state.inlineLineHeights.delete(lineHeightFor)
328
+ const existing = state.fontSize[lineHeightFor]
329
+ if (existing !== undefined) {
330
+ const fontSize = typeof existing === 'string' ? existing : existing.fontSize
331
+ state.fontSize[lineHeightFor] = { fontSize, lineHeight: `var(${property})` }
332
+ } else if (!state.resetNamespaces.has('fontSize') && !state.resetKeys.get('fontSize')?.has(lineHeightFor)) {
333
+ const fallback = tailwindTokens.fontSize[lineHeightFor]
334
+ if (fallback !== undefined) {
335
+ const fontSize = typeof fallback === 'string' ? fallback : fallback.fontSize
336
+ state.fontSize[lineHeightFor] = { fontSize, lineHeight: `var(${property})` }
337
+ }
338
+ }
339
+ return
340
+ }
341
+ state.inlineLineHeights.delete(key)
342
+ const lhVar = `--text-${key}--line-height`
343
+ if (state.varLineHeights.has(key)) {
344
+ state.fontSize[key] = { fontSize: `var(${property})`, lineHeight: `var(${lhVar})` }
345
+ } else {
346
+ state.fontSize[key] = `var(${property})`
347
+ }
348
+ return
349
+ }
350
+
351
+ const bucket = getNamespaceBucket(state, namespace)
352
+ bucket[key] = `var(${property})`
353
+ }
354
+
355
+ function registerInlineToken(state: CompilerState, property: string, value: string, location: CSSLocation): void {
356
+ const isVarExpr = hasVarCall(value)
357
+
358
+ if (property === '--spacing') {
359
+ if (isVarExpr) {
360
+ state.spacing = value
361
+ return
362
+ }
363
+ const len = parseCSSLength(value)
364
+ if (len === null) {
365
+ state.warn('invalid-token-value', `Invalid spacing value "${value}" for "--spacing"`, location)
366
+ return
367
+ }
368
+ state.spacing = len
369
+ return
370
+ }
371
+
372
+ const matched = matchTokenVariable(property)
373
+ if (matched === null) return
374
+
375
+ const { namespace, key, lineHeightFor } = matched
376
+ unmarkResetKey(state, namespace, key)
377
+
378
+ if (namespace === 'fontSize' && lineHeightFor !== undefined) {
379
+ state.varLineHeights.delete(lineHeightFor)
380
+ state.inlineLineHeights.set(lineHeightFor, { raw: value, location })
381
+ return
382
+ }
383
+
384
+ if (isVarExpr && namespace !== 'breakpoints') {
385
+ if (namespace === 'fontSize') {
386
+ state.varLineHeights.delete(key)
387
+ state.fontSize[key] = value
388
+ } else {
389
+ getNamespaceBucket(state, namespace)[key] = value
390
+ }
391
+ return
392
+ }
393
+
394
+ switch (namespace) {
395
+ case 'colors': {
396
+ const color = parseCSSColor(value)
397
+ if (color === null) {
398
+ state.warn('invalid-token-value', `Invalid color "${value}" for "${property}"`, location)
399
+ return
400
+ }
401
+ state.colors[key] = color
402
+ return
403
+ }
404
+ case 'fontSize': {
405
+ const len = parseCSSLength(value)
406
+ if (len === null) {
407
+ state.warn('invalid-token-value', `Invalid font size "${value}" for "${property}"`, location)
408
+ return
409
+ }
410
+ state.varLineHeights.delete(key)
411
+ state.fontSize[key] = { fontSize: len }
412
+ return
413
+ }
414
+ case 'fontWeight': {
415
+ const weight = parseCSSFontWeight(value)
416
+ if (weight === null) {
417
+ state.warn('invalid-token-value', `Invalid font weight "${value}" for "${property}"`, location)
418
+ return
419
+ }
420
+ state.fontWeight[key] = weight
421
+ return
422
+ }
423
+ case 'leading': {
424
+ const lh = parseCSSLineHeight(value)
425
+ if (lh === null) {
426
+ state.warn('invalid-token-value', `Invalid line height "${value}" for "${property}"`, location)
427
+ return
428
+ }
429
+ state.leading[key] = lh.kind === 'points' ? { points: lh.value } : lh.value
430
+ return
431
+ }
432
+ case 'radius': {
433
+ const len = parseCSSLength(value)
434
+ if (len === null) {
435
+ state.warn('invalid-token-value', `Invalid radius "${value}" for "${property}"`, location)
436
+ return
437
+ }
438
+ state.radius[key] = len
439
+ return
440
+ }
441
+ case 'spacingScale': {
442
+ const len = parseCSSLengthOrPercent(value)
443
+ if (len === null) {
444
+ state.warn('invalid-token-value', `Invalid spacing "${value}" for "${property}"`, location)
445
+ return
446
+ }
447
+ state.spacingScale[key] = len
448
+ return
449
+ }
450
+ case 'shadow': {
451
+ const shadows = parseCSSBoxShadows(value, false)
452
+ if (shadows === null) {
453
+ state.warn('invalid-token-value', `Invalid box-shadow "${value}" for "${property}"`, location)
454
+ return
455
+ }
456
+ state.shadow[key] = shadows
457
+ return
458
+ }
459
+ case 'insetShadow': {
460
+ const shadows = parseCSSBoxShadows(value, true)
461
+ if (shadows === null) {
462
+ state.warn('invalid-token-value', `Invalid inset box-shadow "${value}" for "${property}"`, location)
463
+ return
464
+ }
465
+ state.insetShadow[key] = shadows
466
+ return
467
+ }
468
+ case 'dropShadow': {
469
+ const shadows = parseCSSDropShadows(value)
470
+ if (shadows === null) {
471
+ state.warn('invalid-token-value', `Invalid drop-shadow "${value}" for "${property}"`, location)
472
+ return
473
+ }
474
+ state.dropShadow[key] = shadows
475
+ return
476
+ }
477
+ case 'container': {
478
+ const len = parseCSSLength(value)
479
+ if (len === null) {
480
+ state.warn('invalid-token-value', `Invalid container width "${value}" for "${property}"`, location)
481
+ return
482
+ }
483
+ state.container[key] = len
484
+ return
485
+ }
486
+ case 'aspect': {
487
+ const ratio = parseCSSRatio(value)
488
+ if (ratio === null) {
489
+ state.warn('invalid-token-value', `Invalid aspect ratio "${value}" for "${property}"`, location)
490
+ return
491
+ }
492
+ state.aspect[key] = ratio
493
+ return
494
+ }
495
+ case 'breakpoints': {
496
+ const bp = parseCSSBreakpoint(value)
497
+ if (bp === null) {
498
+ state.warn('invalid-token-value', `Invalid breakpoint length "${value}" for "${property}"`, location)
499
+ return
500
+ }
501
+ state.breakpoints[key] = bp
502
+ return
503
+ }
504
+ }
505
+ }
506
+
507
+ function compileThemeBlock(state: CompilerState, node: CSSAtRuleNode): void {
508
+ const mode = node.prelude.trim().toLowerCase()
509
+ const isInline = mode === 'inline'
510
+ if (mode !== '' && !isInline) {
511
+ state.warn('unsupported-at-rule', `Unsupported @theme modifier "${node.prelude}"`, node.location)
512
+ return
513
+ }
514
+ if (!node.nodes) {
515
+ state.warn('unsupported-at-rule', 'Expected "{ ... }" block for @theme', node.location)
516
+ return
517
+ }
518
+
519
+ for (const child of node.nodes) {
520
+ if (child.kind !== 'declaration') {
521
+ state.warn(
522
+ child.kind === 'at-rule' ? 'unsupported-at-rule' : 'unsupported-rule',
523
+ `Unexpected ${child.kind === 'at-rule' ? `@${child.name}` : child.selector} inside @theme`,
524
+ child.location,
525
+ )
526
+ continue
527
+ }
528
+ compileThemeDeclaration(state, child, isInline)
529
+ }
530
+ }
531
+
532
+ function compileThemeDeclaration(state: CompilerState, decl: CSSDeclarationNode, isInline: boolean): void {
533
+ const { property, value, location } = decl
534
+ if (!property.startsWith('--')) {
535
+ state.warn('unsupported-declaration', `Expected CSS variable ("--*") inside @theme, got "${property}"`, location)
536
+ return
537
+ }
538
+ if (value.trim().toLowerCase() === 'initial') {
539
+ applyInitialReset(state, property, location)
540
+ return
541
+ }
542
+ if (isInline) {
543
+ registerInlineToken(state, property, value, location)
544
+ return
545
+ }
546
+ state.variables[property] = value
547
+ registerVarBackedToken(state, property, value, location)
548
+ }
549
+
550
+ function compileImport(
551
+ state: CompilerState,
552
+ node: CSSAtRuleNode,
553
+ currentFile: string | undefined,
554
+ options: ParseCSSOptions,
555
+ ): void {
556
+ const specifier = parseImportSpecifier(node.prelude)
557
+ if (specifier === null) {
558
+ state.warn('unresolved-import', `Invalid @import specifier "${node.prelude}"`, node.location)
559
+ return
560
+ }
561
+
562
+ if (PRESET_IMPORTS.has(specifier)) {
563
+ state.imports.push(specifier)
564
+ return
565
+ }
566
+
567
+ const isRelative = specifier.startsWith('./') || specifier.startsWith('../')
568
+ if (!options.resolveImport) {
569
+ const hint = isRelative
570
+ ? `Relative @import "${specifier}" cannot be resolved without a "resolveImport" hook or the "nitrowind/plugin" bundler plugin`
571
+ : `Unsupported @import "${specifier}"`
572
+ state.warn('unresolved-import', hint, node.location)
573
+ return
574
+ }
575
+
576
+ const resolved = options.resolveImport(specifier, currentFile)
577
+ const importedCss = typeof resolved === 'string' ? resolved : resolved.css
578
+ const importedFile =
579
+ typeof resolved === 'string'
580
+ ? resolveRelativeImportKey(specifier, currentFile)
581
+ : (resolved.filename ?? resolveRelativeImportKey(specifier, currentFile))
582
+
583
+ if (state.importStack.includes(importedFile)) {
584
+ const chain = [...state.importStack, importedFile].join(' -> ')
585
+ throw new CSSParseError(`Circular @import detected: ${chain}`, node.location)
586
+ }
587
+
588
+ state.imports.push(specifier)
589
+ state.importStack.push(importedFile)
590
+ try {
591
+ const ast = parseStylesheet(importedCss, { filename: importedFile })
592
+ compileNodes(state, ast.nodes, importedFile, options)
593
+ } finally {
594
+ state.importStack.pop()
595
+ }
596
+ }
597
+
598
+ function compileVariantBlock(state: CompilerState, node: CSSAtRuleNode): void {
599
+ const themeName = node.prelude.trim()
600
+ if (!themeName || /[\s:[\]]/.test(themeName)) {
601
+ throw new CSSParseError(`Invalid theme name "${themeName}" in @variant`, node.location)
602
+ }
603
+ if (!node.nodes) {
604
+ state.warn('unsupported-at-rule', `Expected "{ ... }" block for @variant ${themeName}`, node.location)
605
+ return
606
+ }
607
+
608
+ let entry = state.themes[themeName]
609
+ if (entry === undefined) {
610
+ entry = {
611
+ colorScheme: themeName === 'light' ? 'light' : themeName === 'dark' ? 'dark' : undefined,
612
+ variables: {},
613
+ location: node.location,
614
+ }
615
+ state.themes[themeName] = entry
616
+ }
617
+
618
+ for (const child of node.nodes) {
619
+ if (child.kind !== 'declaration') {
620
+ state.warn(
621
+ child.kind === 'at-rule' ? 'unsupported-at-rule' : 'unsupported-rule',
622
+ `Unexpected ${child.kind === 'at-rule' ? `@${child.name}` : child.selector} inside @variant ${themeName}`,
623
+ child.location,
624
+ )
625
+ continue
626
+ }
627
+ const propLower = child.property.toLowerCase()
628
+ if (propLower === 'color-scheme') {
629
+ const scheme = child.value.trim().toLowerCase()
630
+ if (scheme !== 'light' && scheme !== 'dark') {
631
+ throw new CSSParseError(
632
+ `Invalid color-scheme "${child.value}" for @variant ${themeName}; expected "light" or "dark"`,
633
+ child.location,
634
+ )
635
+ }
636
+ if (themeName === 'light' && scheme !== 'light') {
637
+ throw new CSSParseError('Built-in theme "light" must have color-scheme "light"', child.location)
638
+ }
639
+ if (themeName === 'dark' && scheme !== 'dark') {
640
+ throw new CSSParseError('Built-in theme "dark" must have color-scheme "dark"', child.location)
641
+ }
642
+ entry.colorScheme = scheme
643
+ continue
644
+ }
645
+ if (!child.property.startsWith('--')) {
646
+ state.warn(
647
+ 'unsupported-declaration',
648
+ `Unsupported property "${child.property}" inside @variant ${themeName}`,
649
+ child.location,
650
+ )
651
+ continue
652
+ }
653
+ entry.variables[child.property] = child.value
654
+ if (!state.themeVarLocations.has(child.property)) {
655
+ state.themeVarLocations.set(child.property, child.location)
656
+ }
657
+ registerVarBackedToken(state, child.property, child.value, child.location, true)
658
+ }
659
+ }
660
+
661
+ function compileRootRule(state: CompilerState, rule: CSSRuleNode): void {
662
+ for (const child of rule.nodes) {
663
+ if (child.kind === 'at-rule' && child.name === 'variant') {
664
+ compileVariantBlock(state, child)
665
+ continue
666
+ }
667
+ if (child.kind === 'declaration') {
668
+ if (!child.property.startsWith('--')) {
669
+ state.warn('unsupported-declaration', `Unsupported property "${child.property}" inside :root`, child.location)
670
+ continue
671
+ }
672
+ state.variables[child.property] = child.value
673
+ registerVarBackedToken(state, child.property, child.value, child.location)
674
+ continue
675
+ }
676
+ state.warn(
677
+ child.kind === 'at-rule' ? 'unsupported-at-rule' : 'unsupported-rule',
678
+ `Unexpected ${child.kind === 'at-rule' ? `@${child.name}` : child.selector} inside :root`,
679
+ child.location,
680
+ )
681
+ }
682
+ }
683
+
684
+ const CLASS_SELECTOR_RE = /^\.(-?[A-Za-z_][A-Za-z0-9_-]*)$/
685
+ const UTILITY_NAME_RE = /^-?[A-Za-z0-9_][A-Za-z0-9_-]*$/
686
+
687
+ function extractBareClassName(rawToken: string): string {
688
+ let bracketDepth = 0
689
+ let parenDepth = 0
690
+ let start = 0
691
+ for (let i = 0; i < rawToken.length; i++) {
692
+ const ch = rawToken[i]
693
+ if (ch === '[') bracketDepth++
694
+ else if (ch === ']') bracketDepth = Math.max(0, bracketDepth - 1)
695
+ else if (ch === '(') parenDepth++
696
+ else if (ch === ')') parenDepth = Math.max(0, parenDepth - 1)
697
+ else if (ch === ':' && bracketDepth === 0 && parenDepth === 0) {
698
+ start = i + 1
699
+ }
700
+ }
701
+ let bare = rawToken.slice(start)
702
+ if (bare.startsWith('!')) bare = bare.slice(1)
703
+ else if (bare.endsWith('!')) bare = bare.slice(0, -1)
704
+ return bare
705
+ }
706
+
707
+ function compileCustomClassBody(
708
+ state: CompilerState,
709
+ nodes: readonly CSSNode[],
710
+ applyLocations: Map<string, CSSLocation>,
711
+ ): CSSCustomClassEntry[] {
712
+ const entries: CSSCustomClassEntry[] = []
713
+ for (const child of nodes) {
714
+ if (child.kind === 'at-rule') {
715
+ if (child.name === 'apply') {
716
+ if (child.nodes !== undefined) {
717
+ state.warn('unsupported-at-rule', 'Unexpected "{ ... }" block on @apply', child.location)
718
+ continue
719
+ }
720
+ const classes = child.prelude.split(/\s+/).filter(Boolean)
721
+ if (classes.length === 0) continue
722
+ for (const cls of classes) {
723
+ const target = extractBareClassName(cls)
724
+ if (target && !applyLocations.has(target)) {
725
+ applyLocations.set(target, child.location)
726
+ }
727
+ }
728
+ entries.push({ kind: 'apply', classes })
729
+ continue
730
+ }
731
+ if (child.name === 'variant') {
732
+ const variant = child.prelude.trim()
733
+ if (!variant || /[\s:]/.test(variant)) {
734
+ state.warn('unsupported-at-rule', `Unsupported @variant "${child.prelude}"`, child.location)
735
+ continue
736
+ }
737
+ if (!child.nodes) {
738
+ state.warn('unsupported-at-rule', `Expected "{ ... }" block for @variant ${variant}`, child.location)
739
+ continue
740
+ }
741
+ const nested = compileCustomClassBody(state, child.nodes, applyLocations)
742
+ if (nested.length > 0) {
743
+ entries.push({ kind: 'variant', variant, entries: nested })
744
+ }
745
+ continue
746
+ }
747
+ state.warn('unsupported-at-rule', `Unsupported at-rule "@${child.name}" inside custom class`, child.location)
748
+ continue
749
+ }
750
+ if (child.kind === 'rule') {
751
+ state.warn('unsupported-rule', `Unsupported nested selector "${child.selector}"`, child.location)
752
+ continue
753
+ }
754
+ const validated = validateRawDeclaration(child.property, child.value)
755
+ if (!validated.ok) {
756
+ state.warn('unsupported-declaration', validated.reason, child.location)
757
+ continue
758
+ }
759
+ if (!validated.noop) {
760
+ entries.push({
761
+ kind: 'declaration',
762
+ property: child.property.toLowerCase(),
763
+ value: child.value.trim(),
764
+ })
765
+ }
766
+ }
767
+ return entries
768
+ }
769
+
770
+ function registerCustomClass(
771
+ state: CompilerState,
772
+ className: string,
773
+ rank: CSSCustomClassRank,
774
+ entries: readonly CSSCustomClassEntry[],
775
+ applyLocations: ReadonlyMap<string, CSSLocation>,
776
+ ): void {
777
+ let target = state.customClasses[className]
778
+ if (target === undefined) {
779
+ target = { rank, entries: [], applyLocations: new Map() }
780
+ state.customClasses[className] = target
781
+ } else if (rank === 'utility') {
782
+ target.rank = 'utility'
783
+ }
784
+ for (const entry of entries) {
785
+ target.entries.push(entry)
786
+ }
787
+ for (const [applied, loc] of applyLocations) {
788
+ if (!target.applyLocations.has(applied)) {
789
+ target.applyLocations.set(applied, loc)
790
+ }
791
+ }
792
+ }
793
+
794
+ function compileCustomClassRule(state: CompilerState, rule: CSSRuleNode, rank: CSSCustomClassRank): void {
795
+ const parts = rule.selector
796
+ .split(',')
797
+ .map((part) => part.trim())
798
+ .filter(Boolean)
799
+ const validNames: string[] = []
800
+ for (const part of parts) {
801
+ const match = CLASS_SELECTOR_RE.exec(part)
802
+ if (match) {
803
+ validNames.push(match[1]!)
804
+ } else {
805
+ state.warn('unsupported-rule', `Unsupported selector "${part}"`, rule.location)
806
+ }
807
+ }
808
+ if (validNames.length === 0) return
809
+ const applyLocations = new Map<string, CSSLocation>()
810
+ const compiled = compileCustomClassBody(state, rule.nodes, applyLocations)
811
+ for (const name of validNames) {
812
+ registerCustomClass(state, name, rank, compiled, applyLocations)
813
+ }
814
+ }
815
+
816
+ function compileUtilityBlock(state: CompilerState, node: CSSAtRuleNode): void {
817
+ const name = node.prelude.trim()
818
+ if (!UTILITY_NAME_RE.test(name)) {
819
+ state.warn('unsupported-at-rule', `Unsupported @utility name "${node.prelude}"`, node.location)
820
+ return
821
+ }
822
+ if (!node.nodes) {
823
+ state.warn('unsupported-at-rule', `Expected "{ ... }" block for @utility ${name}`, node.location)
824
+ return
825
+ }
826
+ const applyLocations = new Map<string, CSSLocation>()
827
+ const compiled = compileCustomClassBody(state, node.nodes, applyLocations)
828
+ registerCustomClass(state, name, 'utility', compiled, applyLocations)
829
+ }
830
+
831
+ function collectApplyTargets(entries: readonly CSSCustomClassEntry[], out: Set<string>): void {
832
+ for (const entry of entries) {
833
+ if (entry.kind === 'apply') {
834
+ for (const cls of entry.classes) {
835
+ const bare = extractBareClassName(cls)
836
+ if (bare) out.add(bare)
837
+ }
838
+ } else if (entry.kind === 'variant') {
839
+ collectApplyTargets(entry.entries, out)
840
+ }
841
+ }
842
+ }
843
+
844
+ /**
845
+ * Validates that no custom class transitively `@apply`s itself.
846
+ * Throws `CSSParseError` (with source location when available) on the first cycle found.
847
+ */
848
+ export function detectCustomClassCycles(
849
+ customClasses: Readonly<Record<string, CSSCustomClassDefinition>>,
850
+ applyLocations?: Readonly<Record<string, ReadonlyMap<string, CSSLocation>>>,
851
+ ): void {
852
+ const state = new Map<string, 'visiting' | 'done'>()
853
+ const stack: string[] = []
854
+
855
+ const visit = (name: string): void => {
856
+ state.set(name, 'visiting')
857
+ stack.push(name)
858
+ const def = customClasses[name]
859
+ if (def !== undefined) {
860
+ const targets = new Set<string>()
861
+ collectApplyTargets(def.entries, targets)
862
+ for (const target of targets) {
863
+ if (!Object.prototype.hasOwnProperty.call(customClasses, target)) continue
864
+ const targetState = state.get(target)
865
+ if (targetState === 'visiting') {
866
+ const cycleStart = stack.indexOf(target)
867
+ const chain = [...stack.slice(cycleStart), target].join(' -> ')
868
+ const loc = applyLocations?.[name]?.get(target) ?? { line: 1, column: 1 }
869
+ throw new CSSParseError(`Circular @apply detected: ${chain}`, loc)
870
+ }
871
+ if (targetState === undefined) {
872
+ visit(target)
873
+ }
874
+ }
875
+ }
876
+ stack.pop()
877
+ state.set(name, 'done')
878
+ }
879
+
880
+ for (const name of Object.keys(customClasses)) {
881
+ if (state.get(name) === undefined) visit(name)
882
+ }
883
+ }
884
+
885
+ function compileLayerBlock(state: CompilerState, node: CSSAtRuleNode): void {
886
+ const layerName = node.prelude.trim().toLowerCase()
887
+ if (layerName === 'components' || layerName === 'utilities') {
888
+ if (!node.nodes) {
889
+ state.warn('unsupported-at-rule', `Expected "{ ... }" block for @layer ${layerName}`, node.location)
890
+ return
891
+ }
892
+ const rank: CSSCustomClassRank = layerName === 'utilities' ? 'utility' : 'component'
893
+ for (const child of node.nodes) {
894
+ if (child.kind === 'rule') {
895
+ compileCustomClassRule(state, child, rank)
896
+ continue
897
+ }
898
+ if (child.kind === 'at-rule' && child.name === 'utility') {
899
+ compileUtilityBlock(state, child)
900
+ continue
901
+ }
902
+ state.warn(
903
+ child.kind === 'at-rule' ? 'unsupported-at-rule' : 'unsupported-declaration',
904
+ `Unexpected ${child.kind === 'at-rule' ? `@${child.name}` : child.property} inside @layer ${layerName}`,
905
+ child.location,
906
+ )
907
+ }
908
+ return
909
+ }
910
+ if (layerName !== 'theme') {
911
+ state.warn('unsupported-at-rule', `Unsupported @layer "${node.prelude}"`, node.location)
912
+ return
913
+ }
914
+ if (!node.nodes) {
915
+ state.warn('unsupported-at-rule', 'Expected "{ ... }" block for @layer theme', node.location)
916
+ return
917
+ }
918
+ for (const child of node.nodes) {
919
+ if (child.kind === 'rule' && child.selector.trim() === ':root') {
920
+ compileRootRule(state, child)
921
+ continue
922
+ }
923
+ if (child.kind === 'at-rule' && child.name === 'variant') {
924
+ compileVariantBlock(state, child)
925
+ continue
926
+ }
927
+ state.warn(
928
+ child.kind === 'at-rule'
929
+ ? 'unsupported-at-rule'
930
+ : child.kind === 'rule'
931
+ ? 'unsupported-rule'
932
+ : 'unsupported-declaration',
933
+ `Unexpected ${child.kind === 'at-rule' ? `@${child.name}` : child.kind === 'rule' ? child.selector : child.property} inside @layer theme`,
934
+ child.location,
935
+ )
936
+ }
937
+ }
938
+
939
+ function validateVariableParity(state: CompilerState): void {
940
+ if (state.themeVarLocations.size === 0) return
941
+ const themeNames = ['light', 'dark', ...Object.keys(state.themes).filter((t) => t !== 'light' && t !== 'dark')]
942
+ for (const varName of [...state.themeVarLocations.keys()].sort()) {
943
+ if (Object.prototype.hasOwnProperty.call(state.variables, varName)) continue
944
+ const missing = themeNames.filter(
945
+ (themeName) => !Object.prototype.hasOwnProperty.call(state.themes[themeName]?.variables ?? {}, varName),
946
+ )
947
+ if (missing.length > 0) {
948
+ const location = state.themeVarLocations.get(varName)!
949
+ state.warn(
950
+ 'variable-parity',
951
+ `CSS variable "${varName}" is declared in some @variant themes with no :root/@theme fallback and is missing in: ${missing.join(', ')}`,
952
+ location,
953
+ )
954
+ }
955
+ }
956
+ }
957
+
958
+ function compileNodes(
959
+ state: CompilerState,
960
+ nodes: readonly CSSNode[],
961
+ currentFile: string | undefined,
962
+ options: ParseCSSOptions,
963
+ ): void {
964
+ for (const node of nodes) {
965
+ if (node.kind === 'at-rule') {
966
+ if (node.name === 'import') {
967
+ compileImport(state, node, currentFile, options)
968
+ continue
969
+ }
970
+ if (node.name === 'theme') {
971
+ compileThemeBlock(state, node)
972
+ continue
973
+ }
974
+ if (node.name === 'layer') {
975
+ compileLayerBlock(state, node)
976
+ continue
977
+ }
978
+ if (node.name === 'variant') {
979
+ compileVariantBlock(state, node)
980
+ continue
981
+ }
982
+ if (node.name === 'utility') {
983
+ compileUtilityBlock(state, node)
984
+ continue
985
+ }
986
+ state.warn('unsupported-at-rule', `Unsupported at-rule "@${node.name}"`, node.location)
987
+ continue
988
+ }
989
+ if (node.kind === 'rule') {
990
+ if (node.selector.trim() === ':root') {
991
+ compileRootRule(state, node)
992
+ continue
993
+ }
994
+ compileCustomClassRule(state, node, 'component')
995
+ continue
996
+ }
997
+ state.warn('unsupported-declaration', `Unexpected top-level declaration "${node.property}"`, node.location)
998
+ }
999
+ }
1000
+
1001
+ function finalizeInlineLineHeights(state: CompilerState): void {
1002
+ for (const [sizeKey, pending] of state.inlineLineHeights) {
1003
+ let existing = state.fontSize[sizeKey]
1004
+ if (
1005
+ existing === undefined &&
1006
+ !state.resetNamespaces.has('fontSize') &&
1007
+ !state.resetKeys.get('fontSize')?.has(sizeKey)
1008
+ ) {
1009
+ existing = tailwindTokens.fontSize[sizeKey]
1010
+ }
1011
+ if (existing === undefined) continue
1012
+ if (hasVarCall(pending.raw)) {
1013
+ const fontSize = typeof existing === 'string' ? existing : existing.fontSize
1014
+ state.fontSize[sizeKey] = { fontSize, lineHeight: pending.raw }
1015
+ continue
1016
+ }
1017
+ const parsed = parseCSSLineHeight(pending.raw)
1018
+ if (parsed === null) {
1019
+ state.warn(
1020
+ 'invalid-token-value',
1021
+ `Invalid line height "${pending.raw}" for "--text-${sizeKey}--line-height"`,
1022
+ pending.location,
1023
+ )
1024
+ continue
1025
+ }
1026
+ if (typeof existing === 'string') {
1027
+ state.fontSize[sizeKey] = { fontSize: existing, lineHeight: parsed.value }
1028
+ } else if (parsed.kind === 'multiplier' && typeof existing.fontSize === 'number') {
1029
+ const lineHeight = Math.round(existing.fontSize * parsed.value * 1000) / 1000
1030
+ state.fontSize[sizeKey] = { fontSize: existing.fontSize, lineHeight }
1031
+ } else {
1032
+ state.fontSize[sizeKey] = { fontSize: existing.fontSize, lineHeight: parsed.value }
1033
+ }
1034
+ }
1035
+ }
1036
+
1037
+ function buildTokensConfig(state: CompilerState): TokensConfig {
1038
+ const extend: TokensInput = {}
1039
+ if (state.spacing !== undefined) extend.spacing = state.spacing
1040
+ if (Object.keys(state.spacingScale).length > 0) extend.spacingScale = state.spacingScale
1041
+ if (Object.keys(state.colors).length > 0) extend.colors = state.colors
1042
+ if (Object.keys(state.fontSize).length > 0) extend.fontSize = state.fontSize
1043
+ if (Object.keys(state.fontWeight).length > 0) extend.fontWeight = state.fontWeight
1044
+ if (Object.keys(state.leading).length > 0) extend.leading = state.leading
1045
+ if (Object.keys(state.radius).length > 0) extend.radius = state.radius
1046
+ if (Object.keys(state.shadow).length > 0) extend.shadow = state.shadow
1047
+ if (Object.keys(state.insetShadow).length > 0) extend.insetShadow = state.insetShadow
1048
+ if (Object.keys(state.dropShadow).length > 0) extend.dropShadow = state.dropShadow
1049
+ if (Object.keys(state.container).length > 0) extend.container = state.container
1050
+ if (Object.keys(state.aspect).length > 0) extend.aspect = state.aspect
1051
+ if (Object.keys(state.breakpoints).length > 0) extend.breakpoints = state.breakpoints
1052
+ return Object.keys(extend).length > 0 ? { extend } : {}
1053
+ }
1054
+
1055
+ function buildTokenResets(state: CompilerState): CSSTokenResets | undefined {
1056
+ const namespaces = [...state.resetNamespaces]
1057
+ const keys: Partial<Record<CSSTokenNamespace, string[]>> = {}
1058
+ for (const [ns, set] of state.resetKeys) {
1059
+ if (set.size > 0) keys[ns] = [...set]
1060
+ }
1061
+ const prefixes: Partial<Record<CSSTokenNamespace, string[]>> = {}
1062
+ for (const [ns, set] of state.resetPrefixes) {
1063
+ if (set.size > 0) prefixes[ns] = [...set]
1064
+ }
1065
+ const hasNs = namespaces.length > 0
1066
+ const hasKeys = Object.keys(keys).length > 0
1067
+ const hasPrefixes = Object.keys(prefixes).length > 0
1068
+ if (!hasNs && !hasKeys && !hasPrefixes) return undefined
1069
+ return {
1070
+ ...(hasNs ? { namespaces } : {}),
1071
+ ...(hasKeys ? { keys } : {}),
1072
+ ...(hasPrefixes ? { prefixes } : {}),
1073
+ }
1074
+ }
1075
+
1076
+ /**
1077
+ * Parses a NitroWind / Tailwind v4 CSS stylesheet into a plain, JSON-serializable
1078
+ * `NitroWindCSSConfig` containing tokens, token resets, shared variables, themes, and warnings.
1079
+ */
1080
+ export function parseCSS(css: string, options: ParseCSSOptions = {}): NitroWindCSSConfig {
1081
+ const warnings: CSSWarning[] = []
1082
+ const state: CompilerState = {
1083
+ imports: [],
1084
+ warnings,
1085
+ variables: {},
1086
+ themes: {},
1087
+ customClasses: {},
1088
+ themeVarLocations: new Map(),
1089
+ resetNamespaces: new Set(),
1090
+ resetKeys: new Map(),
1091
+ resetPrefixes: new Map(),
1092
+ spacingScale: {},
1093
+ colors: {},
1094
+ fontSize: {},
1095
+ inlineLineHeights: new Map(),
1096
+ varLineHeights: new Set(),
1097
+ fontWeight: {},
1098
+ leading: {},
1099
+ radius: {},
1100
+ shadow: {},
1101
+ insetShadow: {},
1102
+ dropShadow: {},
1103
+ container: {},
1104
+ aspect: {},
1105
+ breakpoints: {},
1106
+ importStack: [options.filename ?? '<entry>'],
1107
+ warn(code, message, location) {
1108
+ const warning: CSSWarning =
1109
+ location.file !== undefined
1110
+ ? { code, message, line: location.line, column: location.column, file: location.file }
1111
+ : { code, message, line: location.line, column: location.column }
1112
+ warnings.push(warning)
1113
+ options.onWarning?.(warning)
1114
+ if (options.strict) {
1115
+ throw new CSSParseError(message, location)
1116
+ }
1117
+ },
1118
+ }
1119
+
1120
+ const ast = parseStylesheet(css, { filename: options.filename })
1121
+ compileNodes(state, ast.nodes, options.filename, options)
1122
+ finalizeInlineLineHeights(state)
1123
+ validateVariableParity(state)
1124
+
1125
+ const themes: Record<string, CSSThemeEntry> = {}
1126
+ for (const [name, entry] of Object.entries(state.themes)) {
1127
+ themes[name] = {
1128
+ ...(entry.colorScheme !== undefined ? { colorScheme: entry.colorScheme } : {}),
1129
+ variables: entry.variables,
1130
+ ...(entry.location !== undefined ? { location: entry.location } : {}),
1131
+ }
1132
+ }
1133
+
1134
+ const customClasses: Record<string, CSSCustomClassDefinition> = {}
1135
+ const applyLocations: Record<string, ReadonlyMap<string, CSSLocation>> = {}
1136
+ for (const [name, entry] of Object.entries(state.customClasses)) {
1137
+ customClasses[name] = { rank: entry.rank, entries: entry.entries }
1138
+ applyLocations[name] = entry.applyLocations
1139
+ }
1140
+ const hasCustomClasses = Object.keys(customClasses).length > 0
1141
+ if (hasCustomClasses) {
1142
+ detectCustomClassCycles(customClasses, applyLocations)
1143
+ }
1144
+
1145
+ const tokenResets = buildTokenResets(state)
1146
+ return {
1147
+ imports: state.imports,
1148
+ tokens: buildTokensConfig(state),
1149
+ ...(tokenResets !== undefined ? { tokenResets } : {}),
1150
+ variables: state.variables,
1151
+ themes,
1152
+ ...(hasCustomClasses ? { customClasses } : {}),
1153
+ warnings: state.warnings,
1154
+ }
1155
+ }
1156
+
1157
+ /**
1158
+ * Applies `initial` token resets from CSS (`--<ns>-*: initial;`, `--<ns>-<prefix>-*: initial;`,
1159
+ * `--<ns>-<key>: initial;`) onto a base `Tokens` object without mutating `base`.
1160
+ */
1161
+ export function applyCSSTokenResets(base: Tokens, resets?: CSSTokenResets): Tokens {
1162
+ if (!resets) return base
1163
+ const next: Tokens = { ...base }
1164
+ const cloneGroup = (ns: CSSTokenNamespace): Record<string, unknown> => {
1165
+ const current = (next as unknown as Record<string, Record<string, unknown> | undefined>)[ns]
1166
+ const copy = current ? { ...current } : {}
1167
+ ;(next as unknown as Record<string, Record<string, unknown>>)[ns] = copy
1168
+ return copy
1169
+ }
1170
+
1171
+ if (resets.namespaces) {
1172
+ for (const ns of resets.namespaces) {
1173
+ ;(next as unknown as Record<string, Record<string, unknown>>)[ns] = {}
1174
+ }
1175
+ }
1176
+ if (resets.prefixes) {
1177
+ for (const [ns, prefixes] of Object.entries(resets.prefixes) as [CSSTokenNamespace, readonly string[]][]) {
1178
+ if (!prefixes || prefixes.length === 0) continue
1179
+ const group = cloneGroup(ns)
1180
+ for (const key of Object.keys(group)) {
1181
+ if (prefixes.some((prefix) => key.startsWith(prefix))) {
1182
+ delete group[key]
1183
+ }
1184
+ }
1185
+ }
1186
+ }
1187
+ if (resets.keys) {
1188
+ for (const [ns, keys] of Object.entries(resets.keys) as [CSSTokenNamespace, readonly string[]][]) {
1189
+ if (!keys || keys.length === 0) continue
1190
+ const group = cloneGroup(ns)
1191
+ for (const key of keys) {
1192
+ delete group[key]
1193
+ }
1194
+ }
1195
+ }
1196
+
1197
+ return next
1198
+ }