tailwindcss-patch 9.0.0 → 9.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 (49) hide show
  1. package/dist/chunk-8l464Juk.js +28 -0
  2. package/dist/cli.d.mts +1 -2
  3. package/dist/cli.d.ts +1 -2
  4. package/dist/cli.js +18 -22
  5. package/dist/cli.mjs +17 -22
  6. package/dist/commands/cli-runtime.d.mts +5 -10
  7. package/dist/commands/cli-runtime.d.ts +5 -10
  8. package/dist/commands/cli-runtime.js +582 -1217
  9. package/dist/commands/cli-runtime.mjs +570 -1216
  10. package/dist/dist-B1VBpHtd.js +21 -0
  11. package/dist/dist-BjUV1yEM.mjs +19 -0
  12. package/dist/index.bundle-0Fe7Jx8V.mjs +194 -0
  13. package/dist/index.bundle-C4Y53Ygf.js +232 -0
  14. package/dist/index.d.mts +133 -67
  15. package/dist/index.d.ts +133 -67
  16. package/dist/index.js +33 -57
  17. package/dist/index.mjs +3 -57
  18. package/dist/validate-4FCU-Ql3.mjs +3525 -0
  19. package/dist/validate-Bu_rkfQF.d.ts +686 -0
  20. package/dist/validate-BuhhSYBe.js +3700 -0
  21. package/dist/validate-CIMnzW8O.d.mts +685 -0
  22. package/package.json +11 -11
  23. package/src/api/tailwindcss-patcher.ts +33 -6
  24. package/src/commands/basic-handlers.ts +0 -1
  25. package/src/config/index.ts +1 -1
  26. package/src/config/workspace.ts +1 -1
  27. package/src/extraction/candidate-extractor.ts +14 -69
  28. package/src/index.bundle.ts +21 -0
  29. package/src/index.ts +16 -0
  30. package/src/options/legacy.ts +2 -2
  31. package/src/options/normalize.ts +10 -5
  32. package/src/runtime/collector.ts +7 -7
  33. package/src/runtime/process-tailwindcss.ts +33 -17
  34. package/src/v4/candidates.ts +224 -0
  35. package/src/v4/engine.ts +70 -0
  36. package/src/v4/index.ts +25 -0
  37. package/src/v4/node-adapter.ts +149 -0
  38. package/src/v4/source.ts +193 -0
  39. package/src/v4/types.ts +57 -0
  40. package/dist/chunk-4RRHMRLJ.js +0 -4378
  41. package/dist/chunk-AOSPLINO.mjs +0 -4378
  42. package/dist/chunk-OSH52QWA.mjs +0 -10
  43. package/dist/chunk-QQXAOMUH.js +0 -25
  44. package/dist/chunk-YYBY7EM5.mjs +0 -21
  45. package/dist/chunk-ZPLR2UEW.js +0 -7
  46. package/dist/dist-22YCNIJW.js +0 -269
  47. package/dist/dist-7W73GIRD.mjs +0 -269
  48. package/dist/validate-nbmOI2w8.d.mts +0 -677
  49. package/dist/validate-nbmOI2w8.d.ts +0 -677
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tailwindcss-patch",
3
- "version": "9.0.0",
3
+ "version": "9.1.0",
4
4
  "description": "patch tailwindcss for exposing context and extract classes",
5
5
  "author": "ice breaker <1324318532@qq.com>",
6
6
  "license": "MIT",
@@ -62,31 +62,31 @@
62
62
  },
63
63
  "dependencies": {
64
64
  "@babel/generator": "^7.29.1",
65
- "@babel/parser": "^7.29.2",
65
+ "@babel/parser": "^7.29.3",
66
66
  "@babel/traverse": "^7.29.0",
67
67
  "@babel/types": "^7.29.0",
68
- "@tailwindcss/node": "^4.2.2",
68
+ "@tailwindcss/node": "^4.2.4",
69
69
  "cac": "6.7.14",
70
70
  "consola": "^3.4.2",
71
71
  "fs-extra": "^11.3.4",
72
72
  "local-pkg": "^1.1.2",
73
73
  "pathe": "^2.0.3",
74
- "postcss": "^8.5.8",
74
+ "postcss": "^8.5.14",
75
75
  "semver": "^7.7.4",
76
- "tailwindcss-config": "^1.1.4",
77
- "@tailwindcss-mangle/config": "7.0.0"
76
+ "tailwindcss-config": "^1.1.5",
77
+ "@tailwindcss-mangle/config": "7.0.1"
78
78
  },
79
79
  "devDependencies": {
80
- "@tailwindcss/oxide": "^4.2.2",
81
- "@tailwindcss/postcss": "^4.2.2",
82
- "@tailwindcss/vite": "^4.2.2",
80
+ "@tailwindcss/oxide": "^4.2.4",
81
+ "@tailwindcss/postcss": "^4.2.4",
82
+ "@tailwindcss/vite": "^4.2.4",
83
83
  "tailwindcss": "^4.1.18",
84
84
  "tailwindcss-3": "npm:tailwindcss@^3.4.19",
85
85
  "tailwindcss-4": "npm:tailwindcss@^4.1.18"
86
86
  },
87
87
  "scripts": {
88
- "dev": "tsup --watch --sourcemap",
89
- "build": "tsup",
88
+ "dev": "tsdown --watch --sourcemap",
89
+ "build": "tsdown",
90
90
  "test": "vitest run",
91
91
  "test:types": "pnpm build && tsd --typings dist/index.d.mts --files test-d/**/*.test-d.ts",
92
92
  "test:dev": "vitest",
@@ -1,6 +1,7 @@
1
1
  import type { SourceEntry } from '@tailwindcss/oxide'
2
2
  import type { PackageInfo } from 'local-pkg'
3
3
  import type { NormalizedTailwindCssPatchOptions } from '../config'
4
+ import type { PatchResult, TailwindCollector, TailwindMajorVersion } from '../runtime/collector'
4
5
  import type {
5
6
  CacheClearOptions,
6
7
  CacheClearResult,
@@ -12,6 +13,7 @@ import type {
12
13
  TailwindTokenFileKey,
13
14
  TailwindTokenReport,
14
15
  } from '../types'
16
+ import { createRequire } from 'node:module'
15
17
  import process from 'node:process'
16
18
  import fs from 'fs-extra'
17
19
  import { getPackageInfoSync } from 'local-pkg'
@@ -27,8 +29,7 @@ import {
27
29
  } from '../extraction/candidate-extractor'
28
30
  import { collectClassesFromContexts } from '../install/class-collector'
29
31
  import logger from '../logger'
30
- import { RuntimeCollector, TailwindV4Collector, type PatchResult, type TailwindCollector, type TailwindMajorVersion } from '../runtime/collector'
31
-
32
+ import { RuntimeCollector, TailwindV4Collector } from '../runtime/collector'
32
33
 
33
34
  interface PatchMemo {
34
35
  result: PatchResult
@@ -103,6 +104,35 @@ function createCollector(
103
104
  return new RuntimeCollector(packageInfo, options, majorVersion, snapshotFactory)
104
105
  }
105
106
 
107
+ function getPackageInfoFromCwd(packageName: string, cwd: string): PackageInfo | undefined {
108
+ try {
109
+ const packageJsonPath = createRequire(path.join(cwd, 'package.json')).resolve(`${packageName}/package.json`)
110
+ const packageJson = fs.readJSONSync(packageJsonPath) as PackageInfo['packageJson']
111
+ return {
112
+ name: packageName,
113
+ version: typeof packageJson.version === 'string' ? packageJson.version : undefined,
114
+ rootPath: path.dirname(packageJsonPath),
115
+ packageJsonPath,
116
+ packageJson,
117
+ } as PackageInfo
118
+ }
119
+ catch {
120
+ return undefined
121
+ }
122
+ }
123
+
124
+ function getTailwindPackageInfo(options: NormalizedTailwindCssPatchOptions) {
125
+ const cwd = options.tailwind.cwd ?? options.projectRoot
126
+ const cwdPackageInfo = options.tailwind.resolve?.paths?.length
127
+ ? getPackageInfoFromCwd(options.tailwind.packageName, cwd)
128
+ : undefined
129
+ return cwdPackageInfo
130
+ ?? getPackageInfoSync(
131
+ options.tailwind.packageName,
132
+ options.tailwind.resolve,
133
+ )
134
+ }
135
+
106
136
  export class TailwindcssPatcher {
107
137
  public readonly options: NormalizedTailwindCssPatchOptions
108
138
  public readonly packageInfo: PackageInfo
@@ -119,10 +149,7 @@ export class TailwindcssPatcher {
119
149
 
120
150
  constructor(options: TailwindCssPatchOptions = {}) {
121
151
  this.options = normalizeOptions(options)
122
- const packageInfo = getPackageInfoSync(
123
- this.options.tailwind.packageName,
124
- this.options.tailwind.resolve,
125
- )
152
+ const packageInfo = getTailwindPackageInfo(this.options)
126
153
 
127
154
  if (!packageInfo) {
128
155
  throw new Error(`Unable to locate Tailwind CSS package "${this.options.tailwind.packageName}".`)
@@ -5,7 +5,6 @@ import type { TailwindcssPatchCommandContext } from './types'
5
5
  import process from 'node:process'
6
6
  import fs from 'fs-extra'
7
7
  import path from 'pathe'
8
- import { TailwindcssPatcher } from '../api/tailwindcss-patcher'
9
8
  import { loadWorkspaceConfigModule } from '../config/workspace'
10
9
  import { groupTokensByFile } from '../extraction/candidate-extractor'
11
10
  import logger from '../logger'
@@ -7,9 +7,9 @@ export type {
7
7
  ExposeContextOptions,
8
8
  ExtendLengthUnitsOptions,
9
9
  ExtractOptions,
10
- NormalizedTailwindCssPatchOptions,
11
10
  NormalizedCacheOptions,
12
11
  NormalizedExtendLengthUnitsOptions,
12
+ NormalizedTailwindCssPatchOptions,
13
13
  TailwindCssOptions,
14
14
  TailwindCssPatchOptions,
15
15
  TailwindV2Options,
@@ -82,6 +82,6 @@ export async function loadPatchOptionsForWorkspace(cwd: string, overrides?: Tail
82
82
  const base = config?.registry
83
83
  ? fromUnifiedConfig(config.registry)
84
84
  : {}
85
- const merged = merge(overrides ?? {}, base) as TailwindCssPatchOptions
85
+ const merged = merge(overrides ?? {}, base, { projectRoot: cwd }) as TailwindCssPatchOptions
86
86
  return merged
87
87
  }
@@ -8,78 +8,21 @@ import type {
8
8
  import { promises as fs } from 'node:fs'
9
9
  import process from 'node:process'
10
10
  import path from 'pathe'
11
+ import { resolveValidTailwindV4Candidates } from '../v4/candidates'
12
+ import { getTailwindV4DesignSystemCacheKey, loadTailwindV4DesignSystem } from '../v4/node-adapter'
11
13
 
12
- let nodeImportPromise: ReturnType<typeof importNode> | undefined
13
14
  let oxideImportPromise: ReturnType<typeof importOxide> | undefined
14
- const designSystemPromiseCache = new Map<string, Promise<any>>()
15
15
  const designSystemCandidateCache = new Map<string, Map<string, boolean>>()
16
16
 
17
- async function importNode() {
18
- return import('@tailwindcss/node')
19
- }
20
-
21
17
  async function importOxide() {
22
18
  return import('@tailwindcss/oxide')
23
19
  }
24
20
 
25
- function getNodeModule() {
26
- nodeImportPromise ??= importNode()
27
- return nodeImportPromise
28
- }
29
-
30
21
  function getOxideModule() {
31
22
  oxideImportPromise ??= importOxide()
32
23
  return oxideImportPromise
33
24
  }
34
25
 
35
- function createDesignSystemCacheKey(css: string, bases: string[]) {
36
- return JSON.stringify({
37
- css,
38
- bases: Array.from(new Set(bases.filter(Boolean))),
39
- })
40
- }
41
-
42
- async function loadDesignSystem(css: string, bases: string[]) {
43
- const uniqueBases = Array.from(new Set(bases.filter(Boolean)))
44
- if (uniqueBases.length === 0) {
45
- throw new Error('No base directories provided for Tailwind CSS design system.')
46
- }
47
-
48
- const cacheKey = createDesignSystemCacheKey(css, uniqueBases)
49
- const cached = designSystemPromiseCache.get(cacheKey)
50
- if (cached) {
51
- return cached
52
- }
53
-
54
- const promise = (async () => {
55
- const { __unstable__loadDesignSystem } = await getNodeModule()
56
- let lastError: unknown
57
-
58
- for (const base of uniqueBases) {
59
- try {
60
- return await __unstable__loadDesignSystem(css, { base })
61
- }
62
- catch (error) {
63
- lastError = error
64
- }
65
- }
66
-
67
- if (lastError instanceof Error) {
68
- throw lastError
69
- }
70
- throw new Error('Failed to load Tailwind CSS design system.')
71
- })()
72
-
73
- designSystemPromiseCache.set(cacheKey, promise)
74
- promise.catch(() => {
75
- if (designSystemPromiseCache.get(cacheKey) === promise) {
76
- designSystemPromiseCache.delete(cacheKey)
77
- designSystemCandidateCache.delete(cacheKey)
78
- }
79
- })
80
- return promise
81
- }
82
-
83
26
  export interface ExtractValidCandidatesOption {
84
27
  sources?: SourceEntry[]
85
28
  base?: string
@@ -131,8 +74,15 @@ export async function extractValidCandidates(options?: ExtractValidCandidatesOpt
131
74
  negated: source.negated,
132
75
  }))
133
76
 
134
- const designSystemKey = createDesignSystemCacheKey(css, [base, ...baseFallbacks])
135
- const designSystem = await loadDesignSystem(css, [base, ...baseFallbacks])
77
+ const source = {
78
+ projectRoot: defaultCwd,
79
+ base,
80
+ baseFallbacks,
81
+ css,
82
+ dependencies: [],
83
+ }
84
+ const designSystemKey = getTailwindV4DesignSystemCacheKey(source)
85
+ const designSystem = await loadTailwindV4DesignSystem(source)
136
86
  const candidateCache = designSystemCandidateCache.get(designSystemKey) ?? new Map<string, boolean>()
137
87
  designSystemCandidateCache.set(designSystemKey, candidateCache)
138
88
 
@@ -163,15 +113,10 @@ export async function extractValidCandidates(options?: ExtractValidCandidatesOpt
163
113
  return validCandidates
164
114
  }
165
115
 
166
- const cssByCandidate = designSystem.candidatesToCss(uncachedCandidates)
116
+ const validUncachedCandidates = resolveValidTailwindV4Candidates(designSystem, uncachedCandidates)
167
117
 
168
- for (let index = 0; index < uncachedCandidates.length; index++) {
169
- const candidate = uncachedCandidates[index]
170
- if (candidate === undefined) {
171
- continue
172
- }
173
- const candidateCss = cssByCandidate[index]
174
- const isValid = typeof candidateCss === 'string' && candidateCss.trim().length > 0
118
+ for (const candidate of uncachedCandidates) {
119
+ const isValid = validUncachedCandidates.has(candidate)
175
120
  candidateCache.set(candidate, isValid)
176
121
  if (!isValid) {
177
122
  continue
@@ -33,6 +33,13 @@ import {
33
33
  runTailwindBuild,
34
34
  } from './install'
35
35
  import logger from './logger'
36
+ import {
37
+ createTailwindV4Engine,
38
+ loadTailwindV4DesignSystem,
39
+ resolveTailwindV4Source,
40
+ resolveTailwindV4SourceFromPatchOptions,
41
+ resolveValidTailwindV4Candidates,
42
+ } from './v4'
36
43
 
37
44
  const require = createRequire(import.meta.url)
38
45
 
@@ -46,6 +53,7 @@ export {
46
53
  CacheStore,
47
54
  collectClassesFromContexts,
48
55
  collectClassesFromTailwindV4,
56
+ createTailwindV4Engine,
49
57
  extractProjectCandidatesWithPositions,
50
58
  extractRawCandidates,
51
59
  extractRawCandidatesWithPositions,
@@ -53,11 +61,15 @@ export {
53
61
  getPatchStatusReport,
54
62
  groupTokensByFile,
55
63
  loadRuntimeContexts,
64
+ loadTailwindV4DesignSystem,
56
65
  logger,
57
66
  migrateConfigFiles,
58
67
  MIGRATION_REPORT_KIND,
59
68
  MIGRATION_REPORT_SCHEMA_VERSION,
60
69
  normalizeOptions,
70
+ resolveTailwindV4Source,
71
+ resolveTailwindV4SourceFromPatchOptions,
72
+ resolveValidTailwindV4Candidates,
61
73
  restoreConfigFiles,
62
74
  runTailwindBuild,
63
75
  tailwindcssPatchCommands,
@@ -91,6 +103,15 @@ export type {
91
103
  } from './commands/validate'
92
104
  export type { TailwindCssPatchOptions } from './config'
93
105
  export * from './types'
106
+ export type {
107
+ TailwindV4CandidateSource,
108
+ TailwindV4DesignSystem,
109
+ TailwindV4Engine,
110
+ TailwindV4GenerateOptions,
111
+ TailwindV4GenerateResult,
112
+ TailwindV4ResolvedSource,
113
+ TailwindV4SourceOptions,
114
+ } from './v4'
94
115
 
95
116
  export function mountTailwindcssPatchCommands(cli: CAC, options: TailwindcssPatchCliMountOptions = {}) {
96
117
  return loadCliModule().mountTailwindcssPatchCommands(cli, options)
package/src/index.ts CHANGED
@@ -51,6 +51,22 @@ export {
51
51
  } from './install'
52
52
  export { default as logger } from './logger'
53
53
  export * from './types'
54
+ export {
55
+ createTailwindV4Engine,
56
+ loadTailwindV4DesignSystem,
57
+ resolveTailwindV4Source,
58
+ resolveTailwindV4SourceFromPatchOptions,
59
+ resolveValidTailwindV4Candidates,
60
+ } from './v4'
61
+ export type {
62
+ TailwindV4CandidateSource,
63
+ TailwindV4DesignSystem,
64
+ TailwindV4Engine,
65
+ TailwindV4GenerateOptions,
66
+ TailwindV4GenerateResult,
67
+ TailwindV4ResolvedSource,
68
+ TailwindV4SourceOptions,
69
+ } from './v4'
54
70
 
55
71
  export function defineConfig<T extends TailwindcssMangleConfig>(config: T): T {
56
72
  return config
@@ -19,7 +19,7 @@ type DeprecatedTailwindKey = keyof typeof deprecatedTailwindMapping
19
19
 
20
20
  function assertNoDeprecatedRegistryOptions(registry: RegistryOptions) {
21
21
  const usedRegistryKeys = (Object.keys(deprecatedRegistryMapping) as DeprecatedRegistryKey[])
22
- .filter(key => Object.prototype.hasOwnProperty.call(registry, key))
22
+ .filter(key => Object.hasOwn(registry, key))
23
23
 
24
24
  if (usedRegistryKeys.length > 0) {
25
25
  const mapping = usedRegistryKeys.map(key => `${key} -> ${deprecatedRegistryMapping[key]}`).join(', ')
@@ -34,7 +34,7 @@ function assertNoDeprecatedRegistryOptions(registry: RegistryOptions) {
34
34
  }
35
35
 
36
36
  const usedTailwindKeys = (Object.keys(deprecatedTailwindMapping) as DeprecatedTailwindKey[])
37
- .filter(key => Object.prototype.hasOwnProperty.call(tailwind, key))
37
+ .filter(key => Object.hasOwn(tailwind, key))
38
38
 
39
39
  if (usedTailwindKeys.length > 0) {
40
40
  const mapping = usedTailwindKeys.map(key => `${key} -> tailwindcss.${deprecatedTailwindMapping[key]}`).join(', ')
@@ -1,14 +1,14 @@
1
1
  import type { ILengthUnitsPatchOptions } from '../types'
2
2
  import type {
3
+ ApplyOptions,
3
4
  CacheDriver,
4
5
  CacheStrategy,
5
- ApplyOptions,
6
6
  ExtractOptions,
7
7
  NormalizedCacheOptions,
8
- NormalizedTailwindCssPatchOptions,
9
8
  NormalizedFeatureOptions,
10
9
  NormalizedOutputOptions,
11
10
  NormalizedTailwindConfigOptions,
11
+ NormalizedTailwindCssPatchOptions,
12
12
  NormalizedTailwindV4Options,
13
13
  TailwindCssOptions,
14
14
  TailwindCssPatchOptions,
@@ -176,12 +176,13 @@ function normalizeTailwindV4Options(
176
176
  function normalizeTailwindOptions(
177
177
  tailwind: TailwindCssOptions | undefined,
178
178
  projectRoot: string,
179
+ shouldDefaultResolveFromCwd: boolean,
179
180
  ): NormalizedTailwindConfigOptions {
180
181
  const packageName = tailwind?.packageName ?? 'tailwindcss'
181
182
  const versionHint = tailwind?.version
182
- const resolve = tailwind?.resolve
183
183
 
184
184
  const cwd = tailwind?.cwd ?? projectRoot
185
+ const resolve = tailwind?.resolve ?? (shouldDefaultResolveFromCwd ? { paths: [cwd] } : undefined)
185
186
  const config = tailwind?.config
186
187
  const postcssPlugin = tailwind?.postcssPlugin
187
188
 
@@ -212,7 +213,7 @@ type DeprecatedTopLevelOptionKey = keyof typeof deprecatedOptionMapping
212
213
 
213
214
  function assertNoDeprecatedOptions(options: TailwindCssPatchOptions) {
214
215
  const used = (Object.keys(deprecatedOptionMapping) as DeprecatedTopLevelOptionKey[])
215
- .filter(key => Object.prototype.hasOwnProperty.call(options, key))
216
+ .filter(key => Object.hasOwn(options, key))
216
217
 
217
218
  if (used.length === 0) {
218
219
  return
@@ -232,7 +233,11 @@ export function normalizeOptions(options: TailwindCssPatchOptions = {}): Normali
232
233
 
233
234
  const output = normalizeOutputOptions(options.extract)
234
235
  const cache = normalizeCacheOptions(options.cache, projectRoot)
235
- const tailwind = normalizeTailwindOptions(options.tailwindcss, projectRoot)
236
+ const tailwind = normalizeTailwindOptions(
237
+ options.tailwindcss,
238
+ projectRoot,
239
+ options.projectRoot !== undefined || options.tailwindcss?.cwd !== undefined,
240
+ )
236
241
  const exposeContext = normalizeExposeContextOptions(options.apply?.exposeContext)
237
242
  const extendLengthUnits = normalizeExtendLengthUnitsOptions(options.apply?.extendLengthUnits)
238
243
 
@@ -1,7 +1,7 @@
1
1
  import type { PackageInfo } from 'local-pkg'
2
2
  import type { NormalizedTailwindCssPatchOptions } from '../config'
3
- import type { PatchStatusReport, TailwindcssRuntimeContext } from '../types'
4
3
  import type { applyTailwindPatches } from '../install/patch-runner'
4
+ import type { PatchStatusReport, TailwindcssRuntimeContext } from '../types'
5
5
  import { collectClassesFromContexts, collectClassesFromTailwindV4 } from '../install/class-collector'
6
6
  import { loadRuntimeContexts } from '../install/context-registry'
7
7
  import { applyTailwindPatches as runPatch } from '../install/patch-runner'
@@ -12,12 +12,12 @@ export type TailwindMajorVersion = 2 | 3 | 4
12
12
  export type PatchResult = ReturnType<typeof applyTailwindPatches>
13
13
 
14
14
  export interface TailwindCollector {
15
- patch(): Promise<PatchResult>
16
- getPatchStatus(): Promise<PatchStatusReport>
17
- collectClassSet(): Promise<Set<string>>
18
- getContexts(): TailwindcssRuntimeContext[]
19
- getPatchSnapshot(): string
20
- runTailwindBuildIfNeeded?(): Promise<void>
15
+ patch: () => Promise<PatchResult>
16
+ getPatchStatus: () => Promise<PatchStatusReport>
17
+ collectClassSet: () => Promise<Set<string>>
18
+ getContexts: () => TailwindcssRuntimeContext[]
19
+ getPatchSnapshot: () => string
20
+ runTailwindBuildIfNeeded?: () => Promise<void>
21
21
  }
22
22
 
23
23
  function resolveTailwindExecutionOptions(
@@ -4,7 +4,7 @@ import path from 'pathe'
4
4
  import postcss from 'postcss'
5
5
  import { loadConfig } from 'tailwindcss-config'
6
6
 
7
- const require = createRequire(import.meta.url)
7
+ type NodeRequire = ReturnType<typeof createRequire>
8
8
 
9
9
  export interface TailwindBuildOptions {
10
10
  cwd: string
@@ -13,8 +13,12 @@ export interface TailwindBuildOptions {
13
13
  postcssPlugin?: string
14
14
  }
15
15
 
16
- function resolveModuleEntry(id: string) {
17
- return path.isAbsolute(id) ? id : require.resolve(id)
16
+ function createCwdRequire(cwd: string) {
17
+ return createRequire(path.join(cwd, 'package.json'))
18
+ }
19
+
20
+ function resolveModuleEntry(id: string, moduleRequire: NodeRequire) {
21
+ return path.isAbsolute(id) ? id : moduleRequire.resolve(id)
18
22
  }
19
23
 
20
24
  function resolvePackageRootFromEntry(entry: string) {
@@ -29,9 +33,18 @@ function resolvePackageRootFromEntry(entry: string) {
29
33
  return undefined
30
34
  }
31
35
 
32
- function clearTailwindV3RuntimeState(pluginName: string) {
36
+ function resolveCacheKey(moduleRequire: NodeRequire, entry: string) {
33
37
  try {
34
- const entry = resolveModuleEntry(pluginName)
38
+ return moduleRequire.resolve(entry)
39
+ }
40
+ catch {
41
+ return entry
42
+ }
43
+ }
44
+
45
+ function clearTailwindV3RuntimeState(pluginName: string, moduleRequire: NodeRequire) {
46
+ try {
47
+ const entry = resolveModuleEntry(pluginName, moduleRequire)
35
48
  const root = resolvePackageRootFromEntry(entry)
36
49
  if (!root) {
37
50
  return
@@ -42,13 +55,14 @@ function clearTailwindV3RuntimeState(pluginName: string) {
42
55
  return
43
56
  }
44
57
 
45
- const sharedState = require.cache[sharedStatePath]?.exports as
58
+ const sharedStateKey = resolveCacheKey(moduleRequire, sharedStatePath)
59
+ const sharedState = moduleRequire.cache[sharedStateKey]?.exports as
46
60
  | {
47
- contextMap?: Map<unknown, unknown>
48
- configContextMap?: Map<unknown, unknown>
49
- contextSourcesMap?: Map<unknown, unknown>
50
- sourceHashMap?: Map<unknown, unknown>
51
- }
61
+ contextMap?: Map<unknown, unknown>
62
+ configContextMap?: Map<unknown, unknown>
63
+ contextSourcesMap?: Map<unknown, unknown>
64
+ sourceHashMap?: Map<unknown, unknown>
65
+ }
52
66
  | undefined
53
67
  sharedState?.contextMap?.clear()
54
68
  sharedState?.configContextMap?.clear()
@@ -61,10 +75,11 @@ function clearTailwindV3RuntimeState(pluginName: string) {
61
75
  continue
62
76
  }
63
77
 
64
- const runtimeModule = require.cache[runtimeEntry]?.exports as
78
+ const runtimeKey = resolveCacheKey(moduleRequire, runtimeEntry)
79
+ const runtimeModule = moduleRequire.cache[runtimeKey]?.exports as
65
80
  | {
66
- contextRef?: { value?: unknown[] }
67
- }
81
+ contextRef?: { value?: unknown[] }
82
+ }
68
83
  | undefined
69
84
  runtimeModule?.contextRef?.value?.splice(0, runtimeModule.contextRef.value.length)
70
85
  break
@@ -90,14 +105,15 @@ async function resolveConfigPath(options: TailwindBuildOptions) {
90
105
  export async function runTailwindBuild(options: TailwindBuildOptions) {
91
106
  const configPath = await resolveConfigPath(options)
92
107
  const pluginName = options.postcssPlugin ?? (options.majorVersion === 4 ? '@tailwindcss/postcss' : 'tailwindcss')
108
+ const moduleRequire = createCwdRequire(options.cwd)
93
109
 
94
110
  if (options.majorVersion === 3) {
95
- clearTailwindV3RuntimeState(pluginName)
111
+ clearTailwindV3RuntimeState(pluginName, moduleRequire)
96
112
  }
97
113
 
98
114
  if (options.majorVersion === 4) {
99
115
  return postcss([
100
- require(pluginName)({
116
+ moduleRequire(pluginName)({
101
117
  config: configPath,
102
118
  }),
103
119
  ]).process('@import \'tailwindcss\';', {
@@ -106,7 +122,7 @@ export async function runTailwindBuild(options: TailwindBuildOptions) {
106
122
  }
107
123
 
108
124
  return postcss([
109
- require(pluginName)({
125
+ moduleRequire(pluginName)({
110
126
  config: configPath,
111
127
  }),
112
128
  ]).process('@tailwind base;@tailwind components;@tailwind utilities;', {