-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathconfig.ts
354 lines (294 loc) · 9.67 KB
/
config.ts
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// @ts-check
import * as fs from 'fs/promises'
import * as path from 'path'
import { pathToFileURL } from 'url'
import clearModule from 'clear-module'
import escalade from 'escalade/sync'
import postcss from 'postcss'
// @ts-ignore
import postcssImport from 'postcss-import'
import prettier from 'prettier'
import type { ParserOptions } from 'prettier'
// @ts-ignore
import { generateRules as generateRulesFallback } from 'tailwindcss/lib/lib/generateRules'
// @ts-ignore
import { createContext as createContextFallback } from 'tailwindcss/lib/lib/setupContextUtils'
import loadConfigFallback from 'tailwindcss/loadConfig'
import resolveConfigFallback from 'tailwindcss/resolveConfig'
import type { RequiredConfig } from 'tailwindcss/types/config.js'
import { expiringMap } from './expiring-map.js'
import { resolveCssFrom, resolveJsFrom } from './resolve'
import type { ContextContainer } from './types'
let sourceToPathMap = new Map<string, string | null>()
let sourceToEntryMap = new Map<string, string | null>()
let pathToContextMap = expiringMap<string | null, ContextContainer>(10_000)
let prettierConfigCache = expiringMap<string, string | null>(10_000)
export async function getTailwindConfig(
options: ParserOptions,
): Promise<ContextContainer> {
let key = [
options.filepath,
options.tailwindStylesheet ?? '',
options.tailwindEntryPoint ?? '',
options.tailwindConfig ?? '',
].join(':')
let baseDir = await getBaseDir(options)
// Map the source file to it's associated Tailwind config file
let configPath = sourceToPathMap.get(key)
if (configPath === undefined) {
configPath = getConfigPath(options, baseDir)
sourceToPathMap.set(key, configPath)
}
let entryPoint = sourceToEntryMap.get(key)
if (entryPoint === undefined) {
entryPoint = getEntryPoint(options, baseDir)
sourceToEntryMap.set(key, entryPoint)
}
// Now see if we've loaded the Tailwind config file before (and it's still valid)
let contextKey = `${configPath}:${entryPoint}`
let existing = pathToContextMap.get(contextKey)
if (existing) {
return existing
}
// By this point we know we need to load the Tailwind config file
let result = await loadTailwindConfig(baseDir, configPath, entryPoint)
pathToContextMap.set(contextKey, result)
return result
}
async function getPrettierConfigPath(
options: ParserOptions,
): Promise<string | null> {
// Locating the config file can be mildly expensive so we cache it temporarily
let existingPath = prettierConfigCache.get(options.filepath)
if (existingPath !== undefined) {
return existingPath
}
let path = await prettier.resolveConfigFile(options.filepath)
prettierConfigCache.set(options.filepath, path)
return path
}
async function getBaseDir(options: ParserOptions): Promise<string> {
let prettierConfigPath = await getPrettierConfigPath(options)
if (options.tailwindConfig) {
return prettierConfigPath ? path.dirname(prettierConfigPath) : process.cwd()
}
if (options.tailwindEntryPoint) {
return prettierConfigPath ? path.dirname(prettierConfigPath) : process.cwd()
}
return prettierConfigPath
? path.dirname(prettierConfigPath)
: options.filepath
? path.dirname(options.filepath)
: process.cwd()
}
async function loadTailwindConfig(
baseDir: string,
tailwindConfigPath: string | null,
entryPoint: string | null,
): Promise<ContextContainer> {
let createContext = createContextFallback
let generateRules = generateRulesFallback
let resolveConfig = resolveConfigFallback
let loadConfig = loadConfigFallback
let tailwindConfig: RequiredConfig = { content: [] }
try {
let pkgFile = resolveJsFrom(baseDir, 'tailwindcss/package.json')
let pkgDir = path.dirname(pkgFile)
try {
let v4 = await loadV4(baseDir, pkgDir, entryPoint)
if (v4) {
return v4
}
} catch {}
resolveConfig = require(path.join(pkgDir, 'resolveConfig'))
createContext = require(
path.join(pkgDir, 'lib/lib/setupContextUtils'),
).createContext
generateRules = require(
path.join(pkgDir, 'lib/lib/generateRules'),
).generateRules
// Prior to `[email protected]` this won't exist so we load it last
loadConfig = require(path.join(pkgDir, 'loadConfig'))
} catch {}
if (tailwindConfigPath) {
clearModule(tailwindConfigPath)
const loadedConfig = loadConfig(tailwindConfigPath)
tailwindConfig = loadedConfig.default ?? loadedConfig
}
// suppress "empty content" warning
tailwindConfig.content = ['no-op']
// Create the context
let context = createContext(resolveConfig(tailwindConfig))
return {
context,
generateRules,
}
}
/**
* Create a loader function that can load plugins and config files relative to
* the CSS file that uses them. However, we don't want missing files to prevent
* everything from working so we'll let the error handler decide how to proceed.
*/
function createLoader<T>({
legacy,
filepath,
onError,
}: {
legacy: boolean
filepath: string
onError: (id: string, error: unknown, resourceType: string) => T
}) {
let cacheKey = `${+Date.now()}`
async function loadFile(id: string, base: string, resourceType: string) {
try {
let resolved = resolveJsFrom(base, id)
let url = pathToFileURL(resolved)
url.searchParams.append('t', cacheKey)
return await import(url.href).then((m) => m.default ?? m)
} catch (err) {
return onError(id, err, resourceType)
}
}
if (legacy) {
let baseDir = path.dirname(filepath)
return (id: string) => loadFile(id, baseDir, 'module')
}
return async (id: string, base: string, resourceType: string) => {
return {
base,
module: await loadFile(id, base, resourceType),
}
}
}
async function loadV4(
baseDir: string,
pkgDir: string,
entryPoint: string | null,
) {
// Import Tailwind — if this is v4 it'll have APIs we can use directly
let pkgPath = resolveJsFrom(baseDir, 'tailwindcss')
let tw = await import(pathToFileURL(pkgPath).toString())
// This is not Tailwind v4
if (!tw.__unstable__loadDesignSystem) {
return null
}
// If the user doesn't define an entrypoint then we use the default theme
entryPoint = entryPoint ?? `${pkgDir}/theme.css`
let importBasePath = path.dirname(entryPoint)
// Resolve imports in the entrypoint to a flat CSS tree
let css = await fs.readFile(entryPoint, 'utf-8')
// Determine if the v4 API supports resolving `@import`
let supportsImports = false
try {
await tw.__unstable__loadDesignSystem('@import "./empty";', {
loadStylesheet: () => {
supportsImports = true
return {
base: importBasePath,
content: '',
}
},
})
} catch {}
if (!supportsImports) {
let resolveImports = postcss([postcssImport()])
let result = await resolveImports.process(css, { from: entryPoint })
css = result.css
}
// Load the design system and set up a compatible context object that is
// usable by the rest of the plugin
let design = await tw.__unstable__loadDesignSystem(css, {
base: importBasePath,
// v4.0.0-alpha.25+
loadModule: createLoader({
legacy: false,
filepath: entryPoint,
onError: (id, err, resourceType) => {
console.error(`Unable to load ${resourceType}: ${id}`, err)
if (resourceType === 'config') {
return {}
} else if (resourceType === 'plugin') {
return () => {}
}
},
}),
loadStylesheet: async (id: string, base: string) => {
let resolved = resolveCssFrom(base, id)
return {
base: path.dirname(resolved),
content: await fs.readFile(resolved, 'utf-8'),
}
},
// v4.0.0-alpha.24 and below
loadPlugin: createLoader({
legacy: true,
filepath: entryPoint,
onError(id, err) {
console.error(`Unable to load plugin: ${id}`, err)
return () => {}
},
}),
loadConfig: createLoader({
legacy: true,
filepath: entryPoint,
onError(id, err) {
console.error(`Unable to load config: ${id}`, err)
return {}
},
}),
})
return {
context: {
getClassOrder: (classList: string[]) => design.getClassOrder(classList),
},
// Stubs that are not needed for v4
generateRules: () => [],
}
}
function getConfigPath(options: ParserOptions, baseDir: string): string | null {
if (options.tailwindConfig) {
if (options.tailwindConfig.endsWith('.css')) {
return null
}
return path.resolve(baseDir, options.tailwindConfig)
}
let configPath: string | void = undefined
try {
configPath = escalade(baseDir, (_dir, names) => {
if (names.includes('tailwind.config.js')) {
return 'tailwind.config.js'
}
if (names.includes('tailwind.config.cjs')) {
return 'tailwind.config.cjs'
}
if (names.includes('tailwind.config.mjs')) {
return 'tailwind.config.mjs'
}
if (names.includes('tailwind.config.ts')) {
return 'tailwind.config.ts'
}
})
} catch {}
if (configPath) {
return configPath
}
return null
}
function getEntryPoint(options: ParserOptions, baseDir: string): string | null {
if (options.tailwindStylesheet) {
return path.resolve(baseDir, options.tailwindStylesheet)
}
if (options.tailwindEntryPoint) {
console.warn(
'Use the `tailwindStylesheet` option for v4 projects instead of `tailwindEntryPoint`.',
)
return path.resolve(baseDir, options.tailwindEntryPoint)
}
if (options.tailwindConfig && options.tailwindConfig.endsWith('.css')) {
console.warn(
'Use the `tailwindStylesheet` option for v4 projects instead of `tailwindConfig`.',
)
return path.resolve(baseDir, options.tailwindConfig)
}
return null
}