-
-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathmigrate-js-config.ts
More file actions
256 lines (221 loc) · 7.69 KB
/
Copy pathmigrate-js-config.ts
File metadata and controls
256 lines (221 loc) · 7.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import fs from 'node:fs/promises'
import { dirname } from 'path'
import type { Config } from 'tailwindcss'
import defaultTheme from 'tailwindcss/defaultTheme'
import { fileURLToPath } from 'url'
import { loadModule } from '../../@tailwindcss-node/src/compile'
import { toCss, type AstNode } from '../../tailwindcss/src/ast'
import {
keyPathToCssProperty,
themeableValues,
} from '../../tailwindcss/src/compat/apply-config-to-theme'
import { keyframesToRules } from '../../tailwindcss/src/compat/apply-keyframes-to-theme'
import { resolveConfig, type ConfigFile } from '../../tailwindcss/src/compat/config/resolve-config'
import type { ThemeConfig } from '../../tailwindcss/src/compat/config/types'
import { darkModePlugin } from '../../tailwindcss/src/compat/dark-mode'
import type { DesignSystem } from '../../tailwindcss/src/design-system'
import { findStaticPlugins } from './utils/extract-static-plugins'
import { info } from './utils/renderer'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
export type JSConfigMigration =
// Could not convert the config file, need to inject it as-is in a @config directive
null | {
sources: { base: string; pattern: string }[]
plugins: { base: string; path: string }[]
css: string
}
export async function migrateJsConfig(
designSystem: DesignSystem,
fullConfigPath: string,
base: string,
): Promise<JSConfigMigration> {
let [unresolvedConfig, source] = await Promise.all([
loadModule(fullConfigPath, __dirname, () => {}).then((result) => result.module) as Config,
fs.readFile(fullConfigPath, 'utf-8'),
])
if (!canMigrateConfig(unresolvedConfig, source)) {
info(
'Your configuration file could not be automatically migrated to the new CSS configuration format, so your CSS has been updated to load your existing configuration file.',
)
return null
}
let sources: { base: string; pattern: string }[] = []
let plugins: { base: string; path: string }[] = []
let cssConfigs: string[] = []
if ('darkMode' in unresolvedConfig) {
cssConfigs.push(migrateDarkMode(unresolvedConfig as any))
}
if ('content' in unresolvedConfig) {
sources = migrateContent(unresolvedConfig as any, base)
}
if ('theme' in unresolvedConfig) {
let themeConfig = await migrateTheme(designSystem, unresolvedConfig, base)
if (themeConfig) cssConfigs.push(themeConfig)
}
let simplePlugins = findStaticPlugins(source)
if (simplePlugins !== null) {
for (let plugin of simplePlugins) {
plugins.push({ base, path: plugin })
}
}
return {
sources,
plugins,
css: cssConfigs.join('\n'),
}
}
async function migrateTheme(
designSystem: DesignSystem,
unresolvedConfig: Config,
base: string,
): Promise<string | null> {
// Resolve the config file without applying plugins and presets, as these are
// migrated to CSS separately.
let configToResolve: ConfigFile = {
base,
config: { ...unresolvedConfig, plugins: [], presets: undefined },
}
let { resolvedConfig, replacedThemeKeys } = resolveConfig(designSystem, [configToResolve])
let resetNamespaces = new Map<string, boolean>(
Array.from(replacedThemeKeys.entries()).map(([key]) => [key, false]),
)
let prevSectionKey = ''
let css = `@theme {`
let containsThemeKeys = false
for (let [key, value] of themeableValues(resolvedConfig.theme)) {
if (typeof value !== 'string' && typeof value !== 'number') {
continue
}
if (key[0] === 'keyframes') {
continue
}
containsThemeKeys = true
let sectionKey = createSectionKey(key)
if (sectionKey !== prevSectionKey) {
css += `\n`
prevSectionKey = sectionKey
}
if (resetNamespaces.has(key[0]) && resetNamespaces.get(key[0]) === false) {
resetNamespaces.set(key[0], true)
css += ` --${keyPathToCssProperty([key[0]])}-*: initial;\n`
}
css += ` --${keyPathToCssProperty(key)}: ${value};\n`
}
if ('keyframes' in resolvedConfig.theme) {
containsThemeKeys = true
css += '\n' + keyframesToCss(resolvedConfig.theme.keyframes)
}
if (!containsThemeKeys) {
return null
}
return css + '}\n'
}
function migrateDarkMode(unresolvedConfig: Config & { darkMode: any }): string {
let variant: string = ''
let addVariant = (_name: string, _variant: string) => (variant = _variant)
let config = () => unresolvedConfig.darkMode
darkModePlugin({ config, addVariant })
if (variant === '') {
return ''
}
return `@variant dark (${variant});\n`
}
// Returns a string identifier used to section theme declarations
function createSectionKey(key: string[]): string {
let sectionSegments = []
for (let i = 0; i < key.length - 1; i++) {
let segment = key[i]
// Ignore tuples
if (key[i + 1][0] === '-') {
break
}
sectionSegments.push(segment)
}
return sectionSegments.join('-')
}
function migrateContent(
unresolvedConfig: Config & { content: any },
base: string,
): { base: string; pattern: string }[] {
let sources = []
for (let content of unresolvedConfig.content) {
if (typeof content !== 'string') {
throw new Error('Unsupported content value: ' + content)
}
sources.push({ base, pattern: content })
}
return sources
}
// Applies heuristics to determine if we can attempt to migrate the config
function canMigrateConfig(unresolvedConfig: Config, source: string): boolean {
// The file may not contain non-serializable values
function isSimpleValue(value: unknown): boolean {
if (typeof value === 'function') return false
if (Array.isArray(value)) return value.every(isSimpleValue)
if (typeof value === 'object' && value !== null) {
return Object.values(value).every(isSimpleValue)
}
return ['string', 'number', 'boolean', 'undefined'].includes(typeof value)
}
// - `theme` can contain functions that we attempt to resolve.
// - `plugins` are more complex, we have special heuristics for them.
let { plugins, theme, ...remainder } = unresolvedConfig
if (!isSimpleValue(remainder)) {
return false
}
// The file may only contain known-migrateable top-level properties
let knownProperties = [
'darkMode',
'content',
'theme',
'plugins',
'presets',
'prefix', // Prefix is handled in the dedicated prefix migrator
]
if (Object.keys(unresolvedConfig).some((key) => !knownProperties.includes(key))) {
return false
}
if (findStaticPlugins(source) === null) {
return false
}
if (unresolvedConfig.presets && unresolvedConfig.presets.length > 0) {
return false
}
// Only migrate the config file if all top-level theme keys are allowed to be
// migrated
if (theme && typeof theme === 'object') {
if (theme.extend && !onlyAllowedThemeValues(theme.extend)) return false
let { extend: _extend, ...themeCopy } = theme
if (!onlyAllowedThemeValues(themeCopy)) return false
}
return true
}
const ALLOWED_THEME_KEYS = [
...Object.keys(defaultTheme),
// Used by @tailwindcss/container-queries
'containers',
]
const BLOCKED_THEME_KEYS = ['supports', 'data', 'aria']
function onlyAllowedThemeValues(theme: ThemeConfig): boolean {
for (let key of Object.keys(theme)) {
if (!ALLOWED_THEME_KEYS.includes(key)) {
return false
}
if (BLOCKED_THEME_KEYS.includes(key)) {
return false
}
}
if ('screens' in theme && typeof theme.screens === 'object' && theme.screens !== null) {
for (let screen of Object.values(theme.screens)) {
if (typeof screen === 'object' && screen !== null && ('max' in screen || 'raw' in screen)) {
return false
}
}
}
return true
}
function keyframesToCss(keyframes: Record<string, unknown>): string {
let ast: AstNode[] = keyframesToRules({ theme: { keyframes } })
return toCss(ast).trim() + '\n'
}