tailwindcss-patch 9.0.1 → 9.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.
@@ -0,0 +1,224 @@
1
+ import type { TailwindV4DesignSystem } from './types'
2
+ import postcss from 'postcss'
3
+
4
+ export function resolveValidTailwindV4Candidates(
5
+ designSystem: TailwindV4DesignSystem,
6
+ candidates: Iterable<string>,
7
+ ): Set<string> {
8
+ const validCandidates = new Set<string>()
9
+ const parsedCandidates: string[] = []
10
+
11
+ for (const candidate of candidates) {
12
+ if (!candidate || parsedCandidates.includes(candidate)) {
13
+ continue
14
+ }
15
+
16
+ if (designSystem.parseCandidate(candidate).length > 0) {
17
+ parsedCandidates.push(candidate)
18
+ }
19
+ }
20
+
21
+ if (parsedCandidates.length === 0) {
22
+ return validCandidates
23
+ }
24
+
25
+ const cssByCandidate = designSystem.candidatesToCss(parsedCandidates)
26
+ for (let index = 0; index < parsedCandidates.length; index++) {
27
+ const candidate = parsedCandidates[index]
28
+ const candidateCss = cssByCandidate[index]
29
+ if (candidate && typeof candidateCss === 'string' && candidateCss.trim().length > 0) {
30
+ validCandidates.add(candidate)
31
+ }
32
+ }
33
+
34
+ return validCandidates
35
+ }
36
+
37
+ function splitTopLevel(value: string, separator: string) {
38
+ const result: string[] = []
39
+ let start = 0
40
+ let depth = 0
41
+ let quote: string | undefined
42
+
43
+ for (let index = 0; index < value.length; index++) {
44
+ const character = value[index]
45
+ if (character === '\\') {
46
+ index++
47
+ continue
48
+ }
49
+
50
+ if (quote) {
51
+ if (character === quote) {
52
+ quote = undefined
53
+ }
54
+ continue
55
+ }
56
+
57
+ if (character === '"' || character === '\'') {
58
+ quote = character
59
+ continue
60
+ }
61
+
62
+ if (character === '(' || character === '[' || character === '{') {
63
+ depth++
64
+ continue
65
+ }
66
+
67
+ if (character === ')' || character === ']' || character === '}') {
68
+ depth = Math.max(0, depth - 1)
69
+ continue
70
+ }
71
+
72
+ if (depth === 0 && character === separator) {
73
+ const item = value.slice(start, index).trim()
74
+ if (item) {
75
+ result.push(item)
76
+ }
77
+ start = index + 1
78
+ }
79
+ }
80
+
81
+ const item = value.slice(start).trim()
82
+ if (item) {
83
+ result.push(item)
84
+ }
85
+ return result
86
+ }
87
+
88
+ const sequencePattern = /^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/
89
+
90
+ function expandSequence(value: string) {
91
+ const match = value.match(sequencePattern)
92
+ if (!match) {
93
+ return [value]
94
+ }
95
+
96
+ const [, startValue, endValue, stepValue] = match
97
+ if (startValue === undefined || endValue === undefined) {
98
+ return [value]
99
+ }
100
+
101
+ const start = Number.parseInt(startValue, 10)
102
+ const end = Number.parseInt(endValue, 10)
103
+ let step = stepValue === undefined ? (start <= end ? 1 : -1) : Number.parseInt(stepValue, 10)
104
+ if (step === 0) {
105
+ throw new Error('Step cannot be zero in Tailwind CSS v4 inline source sequence.')
106
+ }
107
+
108
+ const ascending = start < end
109
+ if (ascending && step < 0) {
110
+ step = -step
111
+ }
112
+ if (!ascending && step > 0) {
113
+ step = -step
114
+ }
115
+
116
+ const result: string[] = []
117
+ for (let current = start; ascending ? current <= end : current >= end; current += step) {
118
+ result.push(current.toString())
119
+ }
120
+ return result
121
+ }
122
+
123
+ function expandInlinePattern(pattern: string): string[] {
124
+ const openIndex = pattern.indexOf('{')
125
+ if (openIndex === -1) {
126
+ return [pattern]
127
+ }
128
+
129
+ const prefix = pattern.slice(0, openIndex)
130
+ const rest = pattern.slice(openIndex)
131
+ let depth = 0
132
+ let closeIndex = -1
133
+ for (let index = 0; index < rest.length; index++) {
134
+ const character = rest[index]
135
+ if (character === '{') {
136
+ depth++
137
+ }
138
+ else if (character === '}') {
139
+ depth--
140
+ if (depth === 0) {
141
+ closeIndex = index
142
+ break
143
+ }
144
+ }
145
+ }
146
+
147
+ if (closeIndex === -1) {
148
+ throw new Error(`The Tailwind CSS v4 inline source pattern "${pattern}" is not balanced.`)
149
+ }
150
+
151
+ const body = rest.slice(1, closeIndex)
152
+ const suffix = rest.slice(closeIndex + 1)
153
+ const parts = sequencePattern.test(body)
154
+ ? expandSequence(body)
155
+ : splitTopLevel(body, ',').flatMap(part => expandInlinePattern(part))
156
+ const suffixes = expandInlinePattern(suffix)
157
+
158
+ const result: string[] = []
159
+ for (const part of parts) {
160
+ for (const expandedSuffix of suffixes) {
161
+ result.push(`${prefix}${part}${expandedSuffix}`)
162
+ }
163
+ }
164
+ return result
165
+ }
166
+
167
+ function unquoteCssString(value: string) {
168
+ const quote = value[0]
169
+ if ((quote !== '"' && quote !== '\'') || value[value.length - 1] !== quote) {
170
+ return undefined
171
+ }
172
+
173
+ let result = ''
174
+ for (let index = 1; index < value.length - 1; index++) {
175
+ const character = value[index]
176
+ if (character === '\\') {
177
+ index++
178
+ result += value[index] ?? ''
179
+ continue
180
+ }
181
+ result += character
182
+ }
183
+ return result
184
+ }
185
+
186
+ export function extractTailwindV4InlineSourceCandidates(css: string) {
187
+ const included = new Set<string>()
188
+ const excluded = new Set<string>()
189
+
190
+ const root = postcss.parse(css)
191
+ root.walkAtRules('source', (rule) => {
192
+ let params = rule.params.trim()
193
+ if (!params) {
194
+ return
195
+ }
196
+
197
+ let negated = false
198
+ if (params.startsWith('not ')) {
199
+ negated = true
200
+ params = params.slice(4).trim()
201
+ }
202
+
203
+ if (!params.startsWith('inline(') || !params.endsWith(')')) {
204
+ return
205
+ }
206
+
207
+ const inlineValue = unquoteCssString(params.slice(7, -1).trim())
208
+ if (inlineValue === undefined) {
209
+ return
210
+ }
211
+
212
+ const target = negated ? excluded : included
213
+ for (const part of splitTopLevel(inlineValue, ' ')) {
214
+ for (const candidate of expandInlinePattern(part)) {
215
+ target.add(candidate)
216
+ }
217
+ }
218
+ })
219
+
220
+ return {
221
+ included,
222
+ excluded,
223
+ }
224
+ }
@@ -0,0 +1,93 @@
1
+ import type {
2
+ TailwindV4Engine,
3
+ TailwindV4GenerateOptions,
4
+ TailwindV4GenerateResult,
5
+ TailwindV4ResolvedSource,
6
+ TailwindV4SourcePattern,
7
+ } from './types'
8
+ import { extractRawCandidates, extractRawCandidatesWithPositions } from '../extraction/candidate-extractor'
9
+ import { extractTailwindV4InlineSourceCandidates, resolveValidTailwindV4Candidates } from './candidates'
10
+ import { compileTailwindV4Source, loadTailwindV4DesignSystem } from './node-adapter'
11
+
12
+ function resolveScanSources(
13
+ options: TailwindV4GenerateOptions | undefined,
14
+ compiledSources: TailwindV4SourcePattern[],
15
+ ) {
16
+ if (Array.isArray(options?.scanSources)) {
17
+ return options.scanSources
18
+ }
19
+ if (options?.scanSources === true) {
20
+ return compiledSources
21
+ }
22
+ return []
23
+ }
24
+
25
+ async function collectRawCandidates(
26
+ source: TailwindV4ResolvedSource,
27
+ options: TailwindV4GenerateOptions | undefined,
28
+ compiledSources: TailwindV4SourcePattern[] = [],
29
+ ) {
30
+ const rawCandidates = new Set<string>()
31
+
32
+ for (const candidate of options?.candidates ?? []) {
33
+ rawCandidates.add(candidate)
34
+ }
35
+
36
+ for (const candidateSource of options?.sources ?? []) {
37
+ const candidates = await extractRawCandidatesWithPositions(candidateSource.content, candidateSource.extension)
38
+ for (const candidate of candidates) {
39
+ rawCandidates.add(candidate.rawCandidate)
40
+ }
41
+ }
42
+
43
+ const filesystemSources = resolveScanSources(options, compiledSources)
44
+ if (filesystemSources.length > 0) {
45
+ for (const candidate of await extractRawCandidates(filesystemSources)) {
46
+ rawCandidates.add(candidate)
47
+ }
48
+ }
49
+
50
+ const inlineSources = extractTailwindV4InlineSourceCandidates(source.css)
51
+ for (const candidate of inlineSources.included) {
52
+ rawCandidates.add(candidate)
53
+ }
54
+ for (const candidate of inlineSources.excluded) {
55
+ rawCandidates.delete(candidate)
56
+ }
57
+
58
+ return rawCandidates
59
+ }
60
+
61
+ export function createTailwindV4Engine(source: TailwindV4ResolvedSource): TailwindV4Engine {
62
+ return {
63
+ source,
64
+ loadDesignSystem() {
65
+ return loadTailwindV4DesignSystem(source)
66
+ },
67
+ async validateCandidates(candidates) {
68
+ const designSystem = await loadTailwindV4DesignSystem(source)
69
+ return resolveValidTailwindV4Candidates(designSystem, candidates)
70
+ },
71
+ async generate(options): Promise<TailwindV4GenerateResult> {
72
+ const { compiled, dependencies } = await compileTailwindV4Source(source)
73
+ const rawCandidates = await collectRawCandidates(source, options, compiled.sources)
74
+ const designSystem = await loadTailwindV4DesignSystem(source)
75
+ const classSet = resolveValidTailwindV4Candidates(designSystem, rawCandidates)
76
+ const inlineSources = extractTailwindV4InlineSourceCandidates(source.css)
77
+ for (const candidate of inlineSources.excluded) {
78
+ classSet.delete(candidate)
79
+ }
80
+
81
+ const css = compiled.build(Array.from(classSet))
82
+
83
+ return {
84
+ css,
85
+ classSet,
86
+ rawCandidates,
87
+ dependencies: Array.from(dependencies),
88
+ sources: compiled.sources,
89
+ root: compiled.root,
90
+ }
91
+ },
92
+ }
93
+ }
@@ -0,0 +1,25 @@
1
+ export {
2
+ extractTailwindV4InlineSourceCandidates,
3
+ resolveValidTailwindV4Candidates,
4
+ } from './candidates'
5
+ export { createTailwindV4Engine } from './engine'
6
+ export {
7
+ compileTailwindV4Source,
8
+ loadTailwindV4DesignSystem,
9
+ loadTailwindV4NodeModule,
10
+ } from './node-adapter'
11
+ export {
12
+ resolveTailwindV4Source,
13
+ resolveTailwindV4SourceFromPatchOptions,
14
+ tailwindV4SourceOptionsFromPatchOptions,
15
+ } from './source'
16
+ export type {
17
+ TailwindV4CandidateSource,
18
+ TailwindV4DesignSystem,
19
+ TailwindV4Engine,
20
+ TailwindV4GenerateOptions,
21
+ TailwindV4GenerateResult,
22
+ TailwindV4ResolvedSource,
23
+ TailwindV4SourceOptions,
24
+ TailwindV4SourcePattern,
25
+ } from './types'
@@ -0,0 +1,209 @@
1
+ import type {
2
+ TailwindV4DesignSystem,
3
+ TailwindV4ResolvedSource,
4
+ TailwindV4SourcePattern,
5
+ } from './types'
6
+ import { createRequire } from 'node:module'
7
+ import { pathToFileURL } from 'node:url'
8
+ import path from 'pathe'
9
+
10
+ interface TailwindV4CompiledSource {
11
+ sources: TailwindV4SourcePattern[]
12
+ root: null | 'none' | {
13
+ base: string
14
+ pattern: string
15
+ }
16
+ build: (candidates: string[]) => string
17
+ }
18
+
19
+ interface TailwindV4NodeModule {
20
+ compile: (css: string, options: {
21
+ base: string
22
+ onDependency: (dependency: string) => void
23
+ customCssResolver?: (id: string, base: string) => Promise<string | false | undefined>
24
+ }) => Promise<TailwindV4CompiledSource>
25
+ __unstable__loadDesignSystem: (css: string, options: { base: string }) => Promise<TailwindV4DesignSystem>
26
+ }
27
+
28
+ const nodeModulePromiseCache = new Map<string, Promise<TailwindV4NodeModule>>()
29
+ const designSystemPromiseCache = new Map<string, Promise<TailwindV4DesignSystem>>()
30
+
31
+ function unique(values: Iterable<string>) {
32
+ return Array.from(new Set(Array.from(values).filter(Boolean).map(value => path.resolve(value))))
33
+ }
34
+
35
+ function createRequireBase(base: string) {
36
+ return path.join(base, 'package.json')
37
+ }
38
+
39
+ function isRelativeSpecifier(id: string) {
40
+ return id.startsWith('./') || id.startsWith('../') || id === '.' || id === '..'
41
+ }
42
+
43
+ function isAbsoluteSpecifier(id: string) {
44
+ return path.isAbsolute(id)
45
+ }
46
+
47
+ function isCssSpecifier(id: string) {
48
+ return path.extname(id) === '.css'
49
+ }
50
+
51
+ function createCssResolutionCandidates(id: string) {
52
+ if (isCssSpecifier(id)) {
53
+ return [id]
54
+ }
55
+ return [`${id}/index.css`, id]
56
+ }
57
+
58
+ function createFallbackCssResolver(baseCandidates: string[]) {
59
+ const bases = unique(baseCandidates)
60
+ return async (id: string) => {
61
+ if (isRelativeSpecifier(id) || isAbsoluteSpecifier(id)) {
62
+ return undefined
63
+ }
64
+
65
+ for (const base of bases) {
66
+ const requireFromBase = createRequire(createRequireBase(base))
67
+ for (const candidate of createCssResolutionCandidates(id)) {
68
+ try {
69
+ return requireFromBase.resolve(candidate)
70
+ }
71
+ catch {}
72
+ }
73
+ }
74
+ return undefined
75
+ }
76
+ }
77
+
78
+ async function importResolvedModule(resolved: string): Promise<TailwindV4NodeModule> {
79
+ return import(pathToFileURL(resolved).href) as unknown as Promise<TailwindV4NodeModule>
80
+ }
81
+
82
+ async function importTailwindNodeFromBase(base: string): Promise<TailwindV4NodeModule | undefined> {
83
+ try {
84
+ const resolved = createRequire(createRequireBase(base)).resolve('@tailwindcss/node')
85
+ return await importResolvedModule(resolved)
86
+ }
87
+ catch {
88
+ return undefined
89
+ }
90
+ }
91
+
92
+ async function importFallbackTailwindNode(): Promise<TailwindV4NodeModule> {
93
+ return import('@tailwindcss/node') as unknown as Promise<TailwindV4NodeModule>
94
+ }
95
+
96
+ export async function loadTailwindV4NodeModule(baseCandidates: string[]): Promise<TailwindV4NodeModule> {
97
+ const bases = unique(baseCandidates)
98
+ const cacheKey = JSON.stringify(bases)
99
+ const cached = nodeModulePromiseCache.get(cacheKey)
100
+ if (cached) {
101
+ return cached
102
+ }
103
+
104
+ const promise = (async () => {
105
+ for (const base of bases) {
106
+ const loaded = await importTailwindNodeFromBase(base)
107
+ if (loaded) {
108
+ return loaded
109
+ }
110
+ }
111
+
112
+ return importFallbackTailwindNode()
113
+ })()
114
+
115
+ nodeModulePromiseCache.set(cacheKey, promise)
116
+ promise.catch(() => {
117
+ if (nodeModulePromiseCache.get(cacheKey) === promise) {
118
+ nodeModulePromiseCache.delete(cacheKey)
119
+ }
120
+ })
121
+ return promise
122
+ }
123
+
124
+ function createDesignSystemCacheKey(css: string, bases: string[]) {
125
+ return JSON.stringify({
126
+ css,
127
+ bases: unique(bases),
128
+ })
129
+ }
130
+
131
+ export function getTailwindV4DesignSystemCacheKey(source: Pick<TailwindV4ResolvedSource, 'css' | 'base' | 'baseFallbacks'>) {
132
+ return createDesignSystemCacheKey(source.css, [source.base, ...source.baseFallbacks])
133
+ }
134
+
135
+ export async function loadTailwindV4DesignSystem(source: TailwindV4ResolvedSource): Promise<TailwindV4DesignSystem> {
136
+ const bases = unique([source.base, ...source.baseFallbacks])
137
+ if (bases.length === 0) {
138
+ throw new Error('No base directories provided for Tailwind CSS v4 design system.')
139
+ }
140
+
141
+ const cacheKey = createDesignSystemCacheKey(source.css, bases)
142
+ const cached = designSystemPromiseCache.get(cacheKey)
143
+ if (cached) {
144
+ return cached
145
+ }
146
+
147
+ const promise = (async () => {
148
+ const node = await loadTailwindV4NodeModule([source.projectRoot, ...bases])
149
+ let lastError: unknown
150
+
151
+ for (const base of bases) {
152
+ try {
153
+ return await node.__unstable__loadDesignSystem(source.css, { base })
154
+ }
155
+ catch (error) {
156
+ lastError = error
157
+ }
158
+ }
159
+
160
+ if (lastError instanceof Error) {
161
+ throw lastError
162
+ }
163
+ throw new Error('Failed to load Tailwind CSS v4 design system.')
164
+ })()
165
+
166
+ designSystemPromiseCache.set(cacheKey, promise)
167
+ promise.catch(() => {
168
+ if (designSystemPromiseCache.get(cacheKey) === promise) {
169
+ designSystemPromiseCache.delete(cacheKey)
170
+ }
171
+ })
172
+ return promise
173
+ }
174
+
175
+ export async function compileTailwindV4Source(source: TailwindV4ResolvedSource) {
176
+ const bases = unique([source.base, ...source.baseFallbacks])
177
+ if (bases.length === 0) {
178
+ throw new Error('No base directories provided for Tailwind CSS v4 compiler.')
179
+ }
180
+
181
+ const node = await loadTailwindV4NodeModule([source.projectRoot, ...bases])
182
+ let lastError: unknown
183
+
184
+ for (const base of bases) {
185
+ const dependencies = new Set(source.dependencies)
186
+ try {
187
+ const compiled = await node.compile(source.css, {
188
+ base,
189
+ customCssResolver: createFallbackCssResolver([source.projectRoot, ...bases]),
190
+ onDependency(dependency) {
191
+ dependencies.add(path.resolve(dependency))
192
+ },
193
+ })
194
+
195
+ return {
196
+ compiled,
197
+ dependencies,
198
+ }
199
+ }
200
+ catch (error) {
201
+ lastError = error
202
+ }
203
+ }
204
+
205
+ if (lastError instanceof Error) {
206
+ throw lastError
207
+ }
208
+ throw new Error('Failed to compile Tailwind CSS v4 source.')
209
+ }