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
@@ -0,0 +1,3525 @@
1
+ import { createRequire } from "node:module";
2
+ import process from "node:process";
3
+ import fs from "fs-extra";
4
+ import { getPackageInfoSync } from "local-pkg";
5
+ import path from "pathe";
6
+ import { coerce } from "semver";
7
+ import { createHash } from "node:crypto";
8
+ import { createConsola } from "consola";
9
+ import path$1 from "node:path";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
11
+ import { promises } from "node:fs";
12
+ import postcss from "postcss";
13
+ import * as t from "@babel/types";
14
+ import generate from "@babel/generator";
15
+ import _babelTraverse from "@babel/traverse";
16
+ import { parse, parse as parse$1 } from "@babel/parser";
17
+ import { loadConfig } from "tailwindcss-config";
18
+ //#region package.json
19
+ var version = "9.1.0";
20
+ //#endregion
21
+ //#region src/constants.ts
22
+ const pkgName = "tailwindcss-patch";
23
+ const pkgVersion = version;
24
+ //#endregion
25
+ //#region src/cache/context.ts
26
+ const DEFAULT_TAILWIND_CONFIG_FILES = [
27
+ "tailwind.config.js",
28
+ "tailwind.config.cjs",
29
+ "tailwind.config.mjs",
30
+ "tailwind.config.ts",
31
+ "tailwind.config.cts",
32
+ "tailwind.config.mts"
33
+ ];
34
+ function normalizePathname(value) {
35
+ return path.normalize(value).replaceAll("\\", "/");
36
+ }
37
+ function resolveRealpathSyncSafe(value) {
38
+ const resolved = path.resolve(value);
39
+ try {
40
+ return normalizePathname(fs.realpathSync(resolved));
41
+ } catch {
42
+ return normalizePathname(resolved);
43
+ }
44
+ }
45
+ function resolveFileMtimeMsSync(value) {
46
+ if (!value) return;
47
+ try {
48
+ const stat = fs.statSync(value);
49
+ if (!stat.isFile()) return;
50
+ return stat.mtimeMs;
51
+ } catch {
52
+ return;
53
+ }
54
+ }
55
+ function resolveTailwindConfigPath(options, majorVersion) {
56
+ const tailwind = options.tailwind;
57
+ const baseDir = tailwind.cwd ?? options.projectRoot;
58
+ const configured = (() => {
59
+ if (majorVersion === 2 && tailwind.v2?.config) return tailwind.v2.config;
60
+ if (majorVersion === 3 && tailwind.v3?.config) return tailwind.v3.config;
61
+ return tailwind.config;
62
+ })();
63
+ if (configured) {
64
+ const absolute = path.isAbsolute(configured) ? configured : path.resolve(baseDir, configured);
65
+ if (fs.pathExistsSync(absolute)) return resolveRealpathSyncSafe(absolute);
66
+ }
67
+ for (const candidate of DEFAULT_TAILWIND_CONFIG_FILES) {
68
+ const absolute = path.resolve(baseDir, candidate);
69
+ if (fs.pathExistsSync(absolute)) return resolveRealpathSyncSafe(absolute);
70
+ }
71
+ }
72
+ function stableSerialize(input) {
73
+ if (input === null) return "null";
74
+ if (typeof input === "string") return JSON.stringify(input);
75
+ if (typeof input === "number" || typeof input === "boolean") return JSON.stringify(input);
76
+ if (Array.isArray(input)) return `[${input.map((item) => stableSerialize(item)).join(",")}]`;
77
+ if (typeof input === "object") return `{${Object.entries(input).filter(([, value]) => value !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${JSON.stringify(key)}:${stableSerialize(value)}`).join(",")}}`;
78
+ return JSON.stringify(String(input));
79
+ }
80
+ function hash(input) {
81
+ return createHash("sha256").update(input).digest("hex");
82
+ }
83
+ function toFingerprintOptions(normalized) {
84
+ return {
85
+ overwrite: normalized.overwrite,
86
+ output: {
87
+ removeUniversalSelector: normalized.output.removeUniversalSelector,
88
+ format: normalized.output.format
89
+ },
90
+ features: normalized.features,
91
+ tailwind: {
92
+ packageName: normalized.tailwind.packageName,
93
+ cwd: normalized.tailwind.cwd,
94
+ config: normalized.tailwind.config,
95
+ postcssPlugin: normalized.tailwind.postcssPlugin,
96
+ versionHint: normalized.tailwind.versionHint,
97
+ v2: normalized.tailwind.v2,
98
+ v3: normalized.tailwind.v3,
99
+ v4: normalized.tailwind.v4
100
+ }
101
+ };
102
+ }
103
+ function createCacheContextDescriptor(options, packageInfo, majorVersion) {
104
+ const projectRootRealpath = resolveRealpathSyncSafe(options.projectRoot);
105
+ const processCwdRealpath = resolveRealpathSyncSafe(process.cwd());
106
+ const cacheCwdRealpath = resolveRealpathSyncSafe(options.cache.cwd);
107
+ const tailwindPackageRootRealpath = resolveRealpathSyncSafe(packageInfo.rootPath);
108
+ const tailwindConfigPath = resolveTailwindConfigPath(options, majorVersion);
109
+ const tailwindConfigMtimeMs = resolveFileMtimeMsSync(tailwindConfigPath);
110
+ const optionsHash = hash(stableSerialize(toFingerprintOptions(options)));
111
+ const metadata = {
112
+ fingerprintVersion: 1,
113
+ projectRootRealpath,
114
+ processCwdRealpath,
115
+ cacheCwdRealpath,
116
+ ...tailwindConfigPath === void 0 ? {} : { tailwindConfigPath },
117
+ ...tailwindConfigMtimeMs === void 0 ? {} : { tailwindConfigMtimeMs },
118
+ tailwindPackageRootRealpath,
119
+ tailwindPackageVersion: packageInfo.version ?? "unknown",
120
+ patcherVersion: pkgVersion,
121
+ majorVersion,
122
+ optionsHash
123
+ };
124
+ return {
125
+ fingerprint: hash(stableSerialize(metadata)),
126
+ metadata
127
+ };
128
+ }
129
+ function explainContextMismatch(current, cached) {
130
+ const reasons = [];
131
+ if (current.projectRootRealpath !== cached.projectRootRealpath) reasons.push(`project-root changed: ${cached.projectRootRealpath} -> ${current.projectRootRealpath}`);
132
+ if (current.processCwdRealpath !== cached.processCwdRealpath) reasons.push(`process-cwd changed: ${cached.processCwdRealpath} -> ${current.processCwdRealpath}`);
133
+ if (current.cacheCwdRealpath !== cached.cacheCwdRealpath) reasons.push(`cache-cwd changed: ${cached.cacheCwdRealpath} -> ${current.cacheCwdRealpath}`);
134
+ if ((current.tailwindConfigPath ?? "") !== (cached.tailwindConfigPath ?? "")) reasons.push(`tailwind-config path changed: ${cached.tailwindConfigPath ?? "<none>"} -> ${current.tailwindConfigPath ?? "<none>"}`);
135
+ if ((current.tailwindConfigMtimeMs ?? -1) !== (cached.tailwindConfigMtimeMs ?? -1)) reasons.push("tailwind-config mtime changed");
136
+ if (current.tailwindPackageRootRealpath !== cached.tailwindPackageRootRealpath) reasons.push(`tailwind-package root changed: ${cached.tailwindPackageRootRealpath} -> ${current.tailwindPackageRootRealpath}`);
137
+ if (current.tailwindPackageVersion !== cached.tailwindPackageVersion) reasons.push(`tailwind-package version changed: ${cached.tailwindPackageVersion} -> ${current.tailwindPackageVersion}`);
138
+ if (current.patcherVersion !== cached.patcherVersion) reasons.push(`patcher version changed: ${cached.patcherVersion} -> ${current.patcherVersion}`);
139
+ if (current.majorVersion !== cached.majorVersion) reasons.push(`major version changed: ${cached.majorVersion} -> ${current.majorVersion}`);
140
+ if (current.optionsHash !== cached.optionsHash) reasons.push(`patch options hash changed: ${cached.optionsHash.slice(0, 12)} -> ${current.optionsHash.slice(0, 12)}`);
141
+ return reasons;
142
+ }
143
+ //#endregion
144
+ //#region src/logger.ts
145
+ const logger = createConsola();
146
+ //#endregion
147
+ //#region src/cache/store.ts
148
+ function isErrnoException(error) {
149
+ return error instanceof Error && typeof error.code === "string";
150
+ }
151
+ function isAccessDenied(error) {
152
+ return isErrnoException(error) && Boolean(error.code && [
153
+ "EPERM",
154
+ "EBUSY",
155
+ "EACCES"
156
+ ].includes(error.code));
157
+ }
158
+ function toStringArray(value) {
159
+ if (!Array.isArray(value)) return [];
160
+ return value.filter((item) => typeof item === "string");
161
+ }
162
+ function asObject(value) {
163
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
164
+ return value;
165
+ }
166
+ function toReadMeta(meta) {
167
+ return {
168
+ ...meta,
169
+ details: [...meta.details]
170
+ };
171
+ }
172
+ function cloneEntry(entry) {
173
+ return {
174
+ context: { ...entry.context },
175
+ values: [...entry.values],
176
+ updatedAt: entry.updatedAt
177
+ };
178
+ }
179
+ var CacheStore = class {
180
+ driver;
181
+ lockPath;
182
+ memoryCache = null;
183
+ memoryIndex = null;
184
+ lastReadMeta = {
185
+ hit: false,
186
+ reason: "context-not-found",
187
+ details: []
188
+ };
189
+ constructor(options, context) {
190
+ this.options = options;
191
+ this.context = context;
192
+ this.driver = options.driver ?? "file";
193
+ this.lockPath = `${this.options.path}.lock`;
194
+ }
195
+ isContextAware() {
196
+ return this.context !== void 0;
197
+ }
198
+ createEmptyIndex() {
199
+ return {
200
+ schemaVersion: 2,
201
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
202
+ contexts: {}
203
+ };
204
+ }
205
+ async ensureDir() {
206
+ await fs.ensureDir(this.options.dir);
207
+ }
208
+ ensureDirSync() {
209
+ fs.ensureDirSync(this.options.dir);
210
+ }
211
+ createTempPath() {
212
+ const uniqueSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
213
+ return `${this.options.path}.${uniqueSuffix}.tmp`;
214
+ }
215
+ async replaceCacheFile(tempPath) {
216
+ try {
217
+ await fs.rename(tempPath, this.options.path);
218
+ return true;
219
+ } catch (error) {
220
+ if (isErrnoException(error) && (error.code === "EEXIST" || error.code === "EPERM")) {
221
+ try {
222
+ await fs.remove(this.options.path);
223
+ } catch (removeError) {
224
+ if (isAccessDenied(removeError)) {
225
+ logger.debug("Tailwind class cache locked or read-only, skipping update.", removeError);
226
+ return false;
227
+ }
228
+ if (!isErrnoException(removeError) || removeError.code !== "ENOENT") throw removeError;
229
+ }
230
+ await fs.rename(tempPath, this.options.path);
231
+ return true;
232
+ }
233
+ throw error;
234
+ }
235
+ }
236
+ replaceCacheFileSync(tempPath) {
237
+ try {
238
+ fs.renameSync(tempPath, this.options.path);
239
+ return true;
240
+ } catch (error) {
241
+ if (isErrnoException(error) && (error.code === "EEXIST" || error.code === "EPERM")) {
242
+ try {
243
+ fs.removeSync(this.options.path);
244
+ } catch (removeError) {
245
+ if (isAccessDenied(removeError)) {
246
+ logger.debug("Tailwind class cache locked or read-only, skipping update.", removeError);
247
+ return false;
248
+ }
249
+ if (!isErrnoException(removeError) || removeError.code !== "ENOENT") throw removeError;
250
+ }
251
+ fs.renameSync(tempPath, this.options.path);
252
+ return true;
253
+ }
254
+ throw error;
255
+ }
256
+ }
257
+ async cleanupTempFile(tempPath) {
258
+ try {
259
+ await fs.remove(tempPath);
260
+ } catch {}
261
+ }
262
+ cleanupTempFileSync(tempPath) {
263
+ try {
264
+ fs.removeSync(tempPath);
265
+ } catch {}
266
+ }
267
+ async delay(ms) {
268
+ await new Promise((resolve) => setTimeout(resolve, ms));
269
+ }
270
+ async acquireLock() {
271
+ await fs.ensureDir(this.options.dir);
272
+ const maxAttempts = 40;
273
+ for (let attempt = 0; attempt < maxAttempts; attempt++) try {
274
+ await fs.writeFile(this.lockPath, `${process.pid}\n${Date.now()}`, { flag: "wx" });
275
+ return true;
276
+ } catch (error) {
277
+ if (!isErrnoException(error) || error.code !== "EEXIST") {
278
+ logger.debug("Unable to acquire cache lock.", error);
279
+ return false;
280
+ }
281
+ try {
282
+ const stat = await fs.stat(this.lockPath);
283
+ if (Date.now() - stat.mtimeMs > 3e4) {
284
+ await fs.remove(this.lockPath);
285
+ continue;
286
+ }
287
+ } catch {}
288
+ await this.delay(25);
289
+ }
290
+ logger.debug("Timed out while waiting for cache lock; skipping cache mutation.");
291
+ return false;
292
+ }
293
+ releaseLockSyncOrAsync(sync) {
294
+ if (sync) {
295
+ try {
296
+ fs.removeSync(this.lockPath);
297
+ } catch {}
298
+ return;
299
+ }
300
+ return fs.remove(this.lockPath).catch(() => void 0);
301
+ }
302
+ acquireLockSync() {
303
+ fs.ensureDirSync(this.options.dir);
304
+ const maxAttempts = 40;
305
+ for (let attempt = 0; attempt < maxAttempts; attempt++) try {
306
+ fs.writeFileSync(this.lockPath, `${process.pid}\n${Date.now()}`, { flag: "wx" });
307
+ return true;
308
+ } catch (error) {
309
+ if (!isErrnoException(error) || error.code !== "EEXIST") {
310
+ logger.debug("Unable to acquire cache lock.", error);
311
+ return false;
312
+ }
313
+ try {
314
+ const stat = fs.statSync(this.lockPath);
315
+ if (Date.now() - stat.mtimeMs > 3e4) {
316
+ fs.removeSync(this.lockPath);
317
+ continue;
318
+ }
319
+ } catch {}
320
+ const start = Date.now();
321
+ while (Date.now() - start < 25);
322
+ }
323
+ logger.debug("Timed out while waiting for cache lock; skipping cache mutation.");
324
+ return false;
325
+ }
326
+ async withFileLock(fn) {
327
+ if (!await this.acquireLock()) return;
328
+ try {
329
+ return await fn();
330
+ } finally {
331
+ await this.releaseLockSyncOrAsync(false);
332
+ }
333
+ }
334
+ withFileLockSync(fn) {
335
+ if (!this.acquireLockSync()) return;
336
+ try {
337
+ return fn();
338
+ } finally {
339
+ this.releaseLockSyncOrAsync(true);
340
+ }
341
+ }
342
+ normalizeContextEntry(value) {
343
+ const record = asObject(value);
344
+ if (!record) return;
345
+ const values = toStringArray(record["values"]);
346
+ if (values.length === 0) return;
347
+ const contextRecord = asObject(record["context"]);
348
+ if (!contextRecord) return;
349
+ const { fingerprintVersion, projectRootRealpath, processCwdRealpath, cacheCwdRealpath, tailwindConfigPath, tailwindConfigMtimeMs, tailwindPackageRootRealpath, tailwindPackageVersion, patcherVersion, majorVersion, optionsHash } = contextRecord;
350
+ if (fingerprintVersion !== 1 || typeof projectRootRealpath !== "string" || typeof processCwdRealpath !== "string" || typeof cacheCwdRealpath !== "string" || typeof tailwindPackageRootRealpath !== "string" || typeof tailwindPackageVersion !== "string" || typeof patcherVersion !== "string" || majorVersion !== 2 && majorVersion !== 3 && majorVersion !== 4 || typeof optionsHash !== "string") return;
351
+ return {
352
+ context: {
353
+ fingerprintVersion,
354
+ projectRootRealpath,
355
+ processCwdRealpath,
356
+ cacheCwdRealpath,
357
+ ...typeof tailwindConfigPath === "string" ? { tailwindConfigPath } : {},
358
+ ...typeof tailwindConfigMtimeMs === "number" ? { tailwindConfigMtimeMs } : {},
359
+ tailwindPackageRootRealpath,
360
+ tailwindPackageVersion,
361
+ patcherVersion,
362
+ majorVersion,
363
+ optionsHash
364
+ },
365
+ values,
366
+ updatedAt: typeof record["updatedAt"] === "string" ? record["updatedAt"] : (/* @__PURE__ */ new Date(0)).toISOString()
367
+ };
368
+ }
369
+ normalizeIndexFile(payload) {
370
+ if (Array.isArray(payload)) return {
371
+ kind: "legacy",
372
+ data: toStringArray(payload)
373
+ };
374
+ const record = asObject(payload);
375
+ if (!record) return { kind: "invalid" };
376
+ if (record["schemaVersion"] !== 2) return { kind: "invalid" };
377
+ const contextsRecord = asObject(record["contexts"]);
378
+ if (!contextsRecord) return { kind: "invalid" };
379
+ const contexts = {};
380
+ for (const [fingerprint, value] of Object.entries(contextsRecord)) {
381
+ if (typeof fingerprint !== "string" || !fingerprint) continue;
382
+ const entry = this.normalizeContextEntry(value);
383
+ if (!entry) continue;
384
+ contexts[fingerprint] = entry;
385
+ }
386
+ return {
387
+ kind: "v2",
388
+ data: {
389
+ schemaVersion: 2,
390
+ updatedAt: typeof record["updatedAt"] === "string" ? record["updatedAt"] : (/* @__PURE__ */ new Date(0)).toISOString(),
391
+ contexts
392
+ }
393
+ };
394
+ }
395
+ async readParsedCacheFile(cleanupInvalid) {
396
+ try {
397
+ if (!await fs.pathExists(this.options.path)) return { kind: "empty" };
398
+ const payload = await fs.readJSON(this.options.path);
399
+ const normalized = this.normalizeIndexFile(payload);
400
+ if (normalized.kind !== "invalid") return normalized;
401
+ if (cleanupInvalid) {
402
+ logger.warn("Unable to read Tailwind class cache index, removing invalid file.");
403
+ await fs.remove(this.options.path);
404
+ }
405
+ return { kind: "invalid" };
406
+ } catch (error) {
407
+ if (isErrnoException(error) && error.code === "ENOENT") return { kind: "empty" };
408
+ logger.warn("Unable to read Tailwind class cache index, removing invalid file.", error);
409
+ if (cleanupInvalid) try {
410
+ await fs.remove(this.options.path);
411
+ } catch (cleanupError) {
412
+ logger.error("Failed to clean up invalid cache file", cleanupError);
413
+ }
414
+ return { kind: "invalid" };
415
+ }
416
+ }
417
+ readParsedCacheFileSync(cleanupInvalid) {
418
+ try {
419
+ if (!fs.pathExistsSync(this.options.path)) return { kind: "empty" };
420
+ const payload = fs.readJSONSync(this.options.path);
421
+ const normalized = this.normalizeIndexFile(payload);
422
+ if (normalized.kind !== "invalid") return normalized;
423
+ if (cleanupInvalid) {
424
+ logger.warn("Unable to read Tailwind class cache index, removing invalid file.");
425
+ fs.removeSync(this.options.path);
426
+ }
427
+ return { kind: "invalid" };
428
+ } catch (error) {
429
+ if (isErrnoException(error) && error.code === "ENOENT") return { kind: "empty" };
430
+ logger.warn("Unable to read Tailwind class cache index, removing invalid file.", error);
431
+ if (cleanupInvalid) try {
432
+ fs.removeSync(this.options.path);
433
+ } catch (cleanupError) {
434
+ logger.error("Failed to clean up invalid cache file", cleanupError);
435
+ }
436
+ return { kind: "invalid" };
437
+ }
438
+ }
439
+ findProjectMatch(index) {
440
+ if (!this.context) return;
441
+ const current = this.context.metadata.projectRootRealpath;
442
+ return Object.entries(index.contexts).find(([, entry]) => entry.context.projectRootRealpath === current);
443
+ }
444
+ async writeIndexFile(index) {
445
+ const tempPath = this.createTempPath();
446
+ try {
447
+ await this.ensureDir();
448
+ await fs.writeJSON(tempPath, index);
449
+ if (await this.replaceCacheFile(tempPath)) return this.options.path;
450
+ await this.cleanupTempFile(tempPath);
451
+ return;
452
+ } catch (error) {
453
+ await this.cleanupTempFile(tempPath);
454
+ logger.error("Unable to persist Tailwind class cache", error);
455
+ return;
456
+ }
457
+ }
458
+ writeIndexFileSync(index) {
459
+ const tempPath = this.createTempPath();
460
+ try {
461
+ this.ensureDirSync();
462
+ fs.writeJSONSync(tempPath, index);
463
+ if (this.replaceCacheFileSync(tempPath)) return this.options.path;
464
+ this.cleanupTempFileSync(tempPath);
465
+ return;
466
+ } catch (error) {
467
+ this.cleanupTempFileSync(tempPath);
468
+ logger.error("Unable to persist Tailwind class cache", error);
469
+ return;
470
+ }
471
+ }
472
+ async write(data) {
473
+ if (!this.options.enabled) return;
474
+ if (this.driver === "noop") return;
475
+ if (this.driver === "memory") {
476
+ if (!this.isContextAware()) {
477
+ this.memoryCache = new Set(data);
478
+ return "memory";
479
+ }
480
+ const index = this.memoryIndex ?? this.createEmptyIndex();
481
+ if (!this.context) return "memory";
482
+ index.contexts[this.context.fingerprint] = {
483
+ context: { ...this.context.metadata },
484
+ values: Array.from(data),
485
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
486
+ };
487
+ index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
488
+ this.memoryIndex = index;
489
+ return "memory";
490
+ }
491
+ if (!this.isContextAware()) {
492
+ const tempPath = this.createTempPath();
493
+ try {
494
+ await this.ensureDir();
495
+ await fs.writeJSON(tempPath, Array.from(data));
496
+ if (await this.replaceCacheFile(tempPath)) return this.options.path;
497
+ await this.cleanupTempFile(tempPath);
498
+ return;
499
+ } catch (error) {
500
+ await this.cleanupTempFile(tempPath);
501
+ logger.error("Unable to persist Tailwind class cache", error);
502
+ return;
503
+ }
504
+ }
505
+ return await this.withFileLock(async () => {
506
+ const parsed = await this.readParsedCacheFile(false);
507
+ const index = parsed.kind === "v2" ? parsed.data : this.createEmptyIndex();
508
+ if (this.context) index.contexts[this.context.fingerprint] = {
509
+ context: { ...this.context.metadata },
510
+ values: Array.from(data),
511
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
512
+ };
513
+ index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
514
+ return this.writeIndexFile(index);
515
+ });
516
+ }
517
+ writeSync(data) {
518
+ if (!this.options.enabled) return;
519
+ if (this.driver === "noop") return;
520
+ if (this.driver === "memory") {
521
+ if (!this.isContextAware()) {
522
+ this.memoryCache = new Set(data);
523
+ return "memory";
524
+ }
525
+ const index = this.memoryIndex ?? this.createEmptyIndex();
526
+ if (!this.context) return "memory";
527
+ index.contexts[this.context.fingerprint] = {
528
+ context: { ...this.context.metadata },
529
+ values: Array.from(data),
530
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
531
+ };
532
+ index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
533
+ this.memoryIndex = index;
534
+ return "memory";
535
+ }
536
+ if (!this.isContextAware()) {
537
+ const tempPath = this.createTempPath();
538
+ try {
539
+ this.ensureDirSync();
540
+ fs.writeJSONSync(tempPath, Array.from(data));
541
+ if (this.replaceCacheFileSync(tempPath)) return this.options.path;
542
+ this.cleanupTempFileSync(tempPath);
543
+ return;
544
+ } catch (error) {
545
+ this.cleanupTempFileSync(tempPath);
546
+ logger.error("Unable to persist Tailwind class cache", error);
547
+ return;
548
+ }
549
+ }
550
+ return this.withFileLockSync(() => {
551
+ const parsed = this.readParsedCacheFileSync(false);
552
+ const index = parsed.kind === "v2" ? parsed.data : this.createEmptyIndex();
553
+ if (this.context) index.contexts[this.context.fingerprint] = {
554
+ context: { ...this.context.metadata },
555
+ values: Array.from(data),
556
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
557
+ };
558
+ index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
559
+ return this.writeIndexFileSync(index);
560
+ });
561
+ }
562
+ async readWithMeta() {
563
+ if (!this.options.enabled) return {
564
+ data: /* @__PURE__ */ new Set(),
565
+ meta: {
566
+ hit: false,
567
+ reason: "cache-disabled",
568
+ details: ["cache disabled"]
569
+ }
570
+ };
571
+ if (this.driver === "noop") return {
572
+ data: /* @__PURE__ */ new Set(),
573
+ meta: {
574
+ hit: false,
575
+ reason: "noop-driver",
576
+ details: ["cache driver is noop"]
577
+ }
578
+ };
579
+ if (this.driver === "memory") {
580
+ if (!this.isContextAware()) {
581
+ const cache = new Set(this.memoryCache ?? []);
582
+ return {
583
+ data: cache,
584
+ meta: {
585
+ hit: cache.size > 0,
586
+ reason: cache.size > 0 ? "hit" : "context-not-found",
587
+ details: cache.size > 0 ? ["memory cache hit"] : ["memory cache miss"]
588
+ }
589
+ };
590
+ }
591
+ const index = this.memoryIndex;
592
+ if (!index || !this.context) return {
593
+ data: /* @__PURE__ */ new Set(),
594
+ meta: {
595
+ hit: false,
596
+ reason: "context-not-found",
597
+ ...this.context?.fingerprint === void 0 ? {} : { fingerprint: this.context.fingerprint },
598
+ schemaVersion: 2,
599
+ details: ["no in-memory cache index for current context"]
600
+ }
601
+ };
602
+ const entry = index.contexts[this.context.fingerprint];
603
+ if (entry) return {
604
+ data: new Set(entry.values),
605
+ meta: {
606
+ hit: true,
607
+ reason: "hit",
608
+ fingerprint: this.context.fingerprint,
609
+ schemaVersion: 2,
610
+ details: ["memory cache hit"]
611
+ }
612
+ };
613
+ const projectMatch = this.findProjectMatch(index);
614
+ if (projectMatch && this.context) {
615
+ const [, matchedEntry] = projectMatch;
616
+ return {
617
+ data: /* @__PURE__ */ new Set(),
618
+ meta: {
619
+ hit: false,
620
+ reason: "context-mismatch",
621
+ fingerprint: this.context.fingerprint,
622
+ schemaVersion: 2,
623
+ details: explainContextMismatch(this.context.metadata, matchedEntry.context)
624
+ }
625
+ };
626
+ }
627
+ return {
628
+ data: /* @__PURE__ */ new Set(),
629
+ meta: {
630
+ hit: false,
631
+ reason: "context-not-found",
632
+ fingerprint: this.context.fingerprint,
633
+ schemaVersion: 2,
634
+ details: ["context fingerprint not found in memory cache index"]
635
+ }
636
+ };
637
+ }
638
+ const parsed = await this.readParsedCacheFile(true);
639
+ if (parsed.kind === "empty") return {
640
+ data: /* @__PURE__ */ new Set(),
641
+ meta: {
642
+ hit: false,
643
+ reason: "file-missing",
644
+ details: ["cache file not found"]
645
+ }
646
+ };
647
+ if (parsed.kind === "invalid") return {
648
+ data: /* @__PURE__ */ new Set(),
649
+ meta: {
650
+ hit: false,
651
+ reason: "invalid-schema",
652
+ details: ["cache schema invalid and has been reset"]
653
+ }
654
+ };
655
+ if (!this.isContextAware()) {
656
+ if (parsed.kind === "legacy") return {
657
+ data: new Set(parsed.data),
658
+ meta: {
659
+ hit: parsed.data.length > 0,
660
+ reason: parsed.data.length > 0 ? "hit" : "context-not-found",
661
+ details: ["legacy cache format"]
662
+ }
663
+ };
664
+ const union = Object.values(parsed.data.contexts).flatMap((entry) => entry.values);
665
+ return {
666
+ data: new Set(union),
667
+ meta: {
668
+ hit: union.length > 0,
669
+ reason: union.length > 0 ? "hit" : "context-not-found",
670
+ schemaVersion: parsed.data.schemaVersion,
671
+ details: ["context-less read merged all cache entries"]
672
+ }
673
+ };
674
+ }
675
+ if (parsed.kind === "legacy") return {
676
+ data: /* @__PURE__ */ new Set(),
677
+ meta: {
678
+ hit: false,
679
+ reason: "legacy-schema",
680
+ ...this.context?.fingerprint === void 0 ? {} : { fingerprint: this.context.fingerprint },
681
+ details: ["legacy cache schema detected; rebuilding cache with context fingerprint"]
682
+ }
683
+ };
684
+ if (!this.context) return {
685
+ data: /* @__PURE__ */ new Set(),
686
+ meta: {
687
+ hit: false,
688
+ reason: "context-not-found",
689
+ details: ["cache context missing"]
690
+ }
691
+ };
692
+ const entry = parsed.data.contexts[this.context.fingerprint];
693
+ if (entry) {
694
+ const mismatchReasons = explainContextMismatch(this.context.metadata, entry.context);
695
+ if (mismatchReasons.length === 0) return {
696
+ data: new Set(entry.values),
697
+ meta: {
698
+ hit: true,
699
+ reason: "hit",
700
+ fingerprint: this.context.fingerprint,
701
+ schemaVersion: parsed.data.schemaVersion,
702
+ details: [`context fingerprint ${this.context.fingerprint.slice(0, 12)} matched`]
703
+ }
704
+ };
705
+ return {
706
+ data: /* @__PURE__ */ new Set(),
707
+ meta: {
708
+ hit: false,
709
+ reason: "context-mismatch",
710
+ fingerprint: this.context.fingerprint,
711
+ schemaVersion: parsed.data.schemaVersion,
712
+ details: mismatchReasons
713
+ }
714
+ };
715
+ }
716
+ const projectMatch = this.findProjectMatch(parsed.data);
717
+ if (projectMatch) {
718
+ const [matchedFingerprint, matchedEntry] = projectMatch;
719
+ return {
720
+ data: /* @__PURE__ */ new Set(),
721
+ meta: {
722
+ hit: false,
723
+ reason: "context-mismatch",
724
+ fingerprint: this.context.fingerprint,
725
+ schemaVersion: parsed.data.schemaVersion,
726
+ details: [`nearest context fingerprint: ${matchedFingerprint.slice(0, 12)}`, ...explainContextMismatch(this.context.metadata, matchedEntry.context)]
727
+ }
728
+ };
729
+ }
730
+ return {
731
+ data: /* @__PURE__ */ new Set(),
732
+ meta: {
733
+ hit: false,
734
+ reason: "context-not-found",
735
+ fingerprint: this.context.fingerprint,
736
+ schemaVersion: parsed.data.schemaVersion,
737
+ details: ["context fingerprint not found in cache index"]
738
+ }
739
+ };
740
+ }
741
+ readWithMetaSync() {
742
+ if (!this.options.enabled) return {
743
+ data: /* @__PURE__ */ new Set(),
744
+ meta: {
745
+ hit: false,
746
+ reason: "cache-disabled",
747
+ details: ["cache disabled"]
748
+ }
749
+ };
750
+ if (this.driver === "noop") return {
751
+ data: /* @__PURE__ */ new Set(),
752
+ meta: {
753
+ hit: false,
754
+ reason: "noop-driver",
755
+ details: ["cache driver is noop"]
756
+ }
757
+ };
758
+ if (this.driver === "memory") {
759
+ if (!this.isContextAware()) {
760
+ const cache = new Set(this.memoryCache ?? []);
761
+ return {
762
+ data: cache,
763
+ meta: {
764
+ hit: cache.size > 0,
765
+ reason: cache.size > 0 ? "hit" : "context-not-found",
766
+ details: cache.size > 0 ? ["memory cache hit"] : ["memory cache miss"]
767
+ }
768
+ };
769
+ }
770
+ const index = this.memoryIndex;
771
+ if (!index || !this.context) return {
772
+ data: /* @__PURE__ */ new Set(),
773
+ meta: {
774
+ hit: false,
775
+ reason: "context-not-found",
776
+ ...this.context?.fingerprint === void 0 ? {} : { fingerprint: this.context.fingerprint },
777
+ schemaVersion: 2,
778
+ details: ["no in-memory cache index for current context"]
779
+ }
780
+ };
781
+ const entry = index.contexts[this.context.fingerprint];
782
+ if (entry) return {
783
+ data: new Set(entry.values),
784
+ meta: {
785
+ hit: true,
786
+ reason: "hit",
787
+ fingerprint: this.context.fingerprint,
788
+ schemaVersion: 2,
789
+ details: ["memory cache hit"]
790
+ }
791
+ };
792
+ const projectMatch = this.findProjectMatch(index);
793
+ if (projectMatch && this.context) {
794
+ const [, matchedEntry] = projectMatch;
795
+ return {
796
+ data: /* @__PURE__ */ new Set(),
797
+ meta: {
798
+ hit: false,
799
+ reason: "context-mismatch",
800
+ fingerprint: this.context.fingerprint,
801
+ schemaVersion: 2,
802
+ details: explainContextMismatch(this.context.metadata, matchedEntry.context)
803
+ }
804
+ };
805
+ }
806
+ return {
807
+ data: /* @__PURE__ */ new Set(),
808
+ meta: {
809
+ hit: false,
810
+ reason: "context-not-found",
811
+ fingerprint: this.context.fingerprint,
812
+ schemaVersion: 2,
813
+ details: ["context fingerprint not found in memory cache index"]
814
+ }
815
+ };
816
+ }
817
+ const parsed = this.readParsedCacheFileSync(true);
818
+ if (parsed.kind === "empty") return {
819
+ data: /* @__PURE__ */ new Set(),
820
+ meta: {
821
+ hit: false,
822
+ reason: "file-missing",
823
+ details: ["cache file not found"]
824
+ }
825
+ };
826
+ if (parsed.kind === "invalid") return {
827
+ data: /* @__PURE__ */ new Set(),
828
+ meta: {
829
+ hit: false,
830
+ reason: "invalid-schema",
831
+ details: ["cache schema invalid and has been reset"]
832
+ }
833
+ };
834
+ if (!this.isContextAware()) {
835
+ if (parsed.kind === "legacy") return {
836
+ data: new Set(parsed.data),
837
+ meta: {
838
+ hit: parsed.data.length > 0,
839
+ reason: parsed.data.length > 0 ? "hit" : "context-not-found",
840
+ details: ["legacy cache format"]
841
+ }
842
+ };
843
+ const union = Object.values(parsed.data.contexts).flatMap((entry) => entry.values);
844
+ return {
845
+ data: new Set(union),
846
+ meta: {
847
+ hit: union.length > 0,
848
+ reason: union.length > 0 ? "hit" : "context-not-found",
849
+ schemaVersion: parsed.data.schemaVersion,
850
+ details: ["context-less read merged all cache entries"]
851
+ }
852
+ };
853
+ }
854
+ if (parsed.kind === "legacy") return {
855
+ data: /* @__PURE__ */ new Set(),
856
+ meta: {
857
+ hit: false,
858
+ reason: "legacy-schema",
859
+ ...this.context?.fingerprint === void 0 ? {} : { fingerprint: this.context.fingerprint },
860
+ details: ["legacy cache schema detected; rebuilding cache with context fingerprint"]
861
+ }
862
+ };
863
+ if (!this.context) return {
864
+ data: /* @__PURE__ */ new Set(),
865
+ meta: {
866
+ hit: false,
867
+ reason: "context-not-found",
868
+ details: ["cache context missing"]
869
+ }
870
+ };
871
+ const entry = parsed.data.contexts[this.context.fingerprint];
872
+ if (entry) {
873
+ const mismatchReasons = explainContextMismatch(this.context.metadata, entry.context);
874
+ if (mismatchReasons.length === 0) return {
875
+ data: new Set(entry.values),
876
+ meta: {
877
+ hit: true,
878
+ reason: "hit",
879
+ fingerprint: this.context.fingerprint,
880
+ schemaVersion: parsed.data.schemaVersion,
881
+ details: [`context fingerprint ${this.context.fingerprint.slice(0, 12)} matched`]
882
+ }
883
+ };
884
+ return {
885
+ data: /* @__PURE__ */ new Set(),
886
+ meta: {
887
+ hit: false,
888
+ reason: "context-mismatch",
889
+ fingerprint: this.context.fingerprint,
890
+ schemaVersion: parsed.data.schemaVersion,
891
+ details: mismatchReasons
892
+ }
893
+ };
894
+ }
895
+ const projectMatch = this.findProjectMatch(parsed.data);
896
+ if (projectMatch) {
897
+ const [matchedFingerprint, matchedEntry] = projectMatch;
898
+ return {
899
+ data: /* @__PURE__ */ new Set(),
900
+ meta: {
901
+ hit: false,
902
+ reason: "context-mismatch",
903
+ fingerprint: this.context.fingerprint,
904
+ schemaVersion: parsed.data.schemaVersion,
905
+ details: [`nearest context fingerprint: ${matchedFingerprint.slice(0, 12)}`, ...explainContextMismatch(this.context.metadata, matchedEntry.context)]
906
+ }
907
+ };
908
+ }
909
+ return {
910
+ data: /* @__PURE__ */ new Set(),
911
+ meta: {
912
+ hit: false,
913
+ reason: "context-not-found",
914
+ fingerprint: this.context.fingerprint,
915
+ schemaVersion: parsed.data.schemaVersion,
916
+ details: ["context fingerprint not found in cache index"]
917
+ }
918
+ };
919
+ }
920
+ async read() {
921
+ const result = await this.readWithMeta();
922
+ this.lastReadMeta = toReadMeta(result.meta);
923
+ return new Set(result.data);
924
+ }
925
+ readSync() {
926
+ const result = this.readWithMetaSync();
927
+ this.lastReadMeta = toReadMeta(result.meta);
928
+ return new Set(result.data);
929
+ }
930
+ getLastReadMeta() {
931
+ return toReadMeta(this.lastReadMeta);
932
+ }
933
+ countEntriesFromParsed(parsed) {
934
+ if (parsed.kind === "legacy") return {
935
+ contexts: parsed.data.length ? 1 : 0,
936
+ entries: parsed.data.length
937
+ };
938
+ if (parsed.kind === "v2") {
939
+ const values = Object.values(parsed.data.contexts);
940
+ return {
941
+ contexts: values.length,
942
+ entries: values.reduce((acc, item) => acc + item.values.length, 0)
943
+ };
944
+ }
945
+ return {
946
+ contexts: 0,
947
+ entries: 0
948
+ };
949
+ }
950
+ async clear(options) {
951
+ const scope = options?.scope ?? "current";
952
+ if (!this.options.enabled || this.driver === "noop") return {
953
+ scope,
954
+ filesRemoved: 0,
955
+ entriesRemoved: 0,
956
+ contextsRemoved: 0
957
+ };
958
+ if (this.driver === "memory") {
959
+ if (!this.isContextAware() || scope === "all") {
960
+ const entriesRemoved = this.memoryCache?.size ?? (this.memoryIndex ? this.countEntriesFromParsed({
961
+ kind: "v2",
962
+ data: this.memoryIndex
963
+ }).entries : 0);
964
+ const contextsRemoved = this.memoryIndex ? Object.keys(this.memoryIndex.contexts).length : this.memoryCache?.size ? 1 : 0;
965
+ this.memoryCache = null;
966
+ this.memoryIndex = null;
967
+ return {
968
+ scope,
969
+ filesRemoved: 0,
970
+ entriesRemoved,
971
+ contextsRemoved
972
+ };
973
+ }
974
+ if (!this.context || !this.memoryIndex) return {
975
+ scope,
976
+ filesRemoved: 0,
977
+ entriesRemoved: 0,
978
+ contextsRemoved: 0
979
+ };
980
+ const entry = this.memoryIndex.contexts[this.context.fingerprint];
981
+ if (!entry) return {
982
+ scope,
983
+ filesRemoved: 0,
984
+ entriesRemoved: 0,
985
+ contextsRemoved: 0
986
+ };
987
+ const entriesRemoved = entry.values.length;
988
+ delete this.memoryIndex.contexts[this.context.fingerprint];
989
+ return {
990
+ scope,
991
+ filesRemoved: 0,
992
+ entriesRemoved,
993
+ contextsRemoved: 1
994
+ };
995
+ }
996
+ return await this.withFileLock(async () => {
997
+ const parsed = await this.readParsedCacheFile(false);
998
+ if (parsed.kind === "empty") return {
999
+ scope,
1000
+ filesRemoved: 0,
1001
+ entriesRemoved: 0,
1002
+ contextsRemoved: 0
1003
+ };
1004
+ if (!this.isContextAware() || scope === "all") {
1005
+ const counts = this.countEntriesFromParsed(parsed);
1006
+ await fs.remove(this.options.path);
1007
+ return {
1008
+ scope,
1009
+ filesRemoved: 1,
1010
+ entriesRemoved: counts.entries,
1011
+ contextsRemoved: counts.contexts
1012
+ };
1013
+ }
1014
+ if (parsed.kind !== "v2" || !this.context) {
1015
+ const counts = this.countEntriesFromParsed(parsed);
1016
+ await fs.remove(this.options.path);
1017
+ return {
1018
+ scope,
1019
+ filesRemoved: 1,
1020
+ entriesRemoved: counts.entries,
1021
+ contextsRemoved: counts.contexts
1022
+ };
1023
+ }
1024
+ const entry = parsed.data.contexts[this.context.fingerprint];
1025
+ if (!entry) return {
1026
+ scope,
1027
+ filesRemoved: 0,
1028
+ entriesRemoved: 0,
1029
+ contextsRemoved: 0
1030
+ };
1031
+ const entriesRemoved = entry.values.length;
1032
+ delete parsed.data.contexts[this.context.fingerprint];
1033
+ if (Object.keys(parsed.data.contexts).length === 0) {
1034
+ await fs.remove(this.options.path);
1035
+ return {
1036
+ scope,
1037
+ filesRemoved: 1,
1038
+ entriesRemoved,
1039
+ contextsRemoved: 1
1040
+ };
1041
+ }
1042
+ parsed.data.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1043
+ await this.writeIndexFile(parsed.data);
1044
+ return {
1045
+ scope,
1046
+ filesRemoved: 0,
1047
+ entriesRemoved,
1048
+ contextsRemoved: 1
1049
+ };
1050
+ }) ?? {
1051
+ scope,
1052
+ filesRemoved: 0,
1053
+ entriesRemoved: 0,
1054
+ contextsRemoved: 0
1055
+ };
1056
+ }
1057
+ clearSync(options) {
1058
+ const scope = options?.scope ?? "current";
1059
+ if (!this.options.enabled || this.driver === "noop") return {
1060
+ scope,
1061
+ filesRemoved: 0,
1062
+ entriesRemoved: 0,
1063
+ contextsRemoved: 0
1064
+ };
1065
+ if (this.driver === "memory") {
1066
+ if (!this.isContextAware() || scope === "all") {
1067
+ const entriesRemoved = this.memoryCache?.size ?? (this.memoryIndex ? this.countEntriesFromParsed({
1068
+ kind: "v2",
1069
+ data: this.memoryIndex
1070
+ }).entries : 0);
1071
+ const contextsRemoved = this.memoryIndex ? Object.keys(this.memoryIndex.contexts).length : this.memoryCache?.size ? 1 : 0;
1072
+ this.memoryCache = null;
1073
+ this.memoryIndex = null;
1074
+ return {
1075
+ scope,
1076
+ filesRemoved: 0,
1077
+ entriesRemoved,
1078
+ contextsRemoved
1079
+ };
1080
+ }
1081
+ if (!this.context || !this.memoryIndex) return {
1082
+ scope,
1083
+ filesRemoved: 0,
1084
+ entriesRemoved: 0,
1085
+ contextsRemoved: 0
1086
+ };
1087
+ const entry = this.memoryIndex.contexts[this.context.fingerprint];
1088
+ if (!entry) return {
1089
+ scope,
1090
+ filesRemoved: 0,
1091
+ entriesRemoved: 0,
1092
+ contextsRemoved: 0
1093
+ };
1094
+ const entriesRemoved = entry.values.length;
1095
+ delete this.memoryIndex.contexts[this.context.fingerprint];
1096
+ return {
1097
+ scope,
1098
+ filesRemoved: 0,
1099
+ entriesRemoved,
1100
+ contextsRemoved: 1
1101
+ };
1102
+ }
1103
+ return this.withFileLockSync(() => {
1104
+ const parsed = this.readParsedCacheFileSync(false);
1105
+ if (parsed.kind === "empty") return {
1106
+ scope,
1107
+ filesRemoved: 0,
1108
+ entriesRemoved: 0,
1109
+ contextsRemoved: 0
1110
+ };
1111
+ if (!this.isContextAware() || scope === "all") {
1112
+ const counts = this.countEntriesFromParsed(parsed);
1113
+ fs.removeSync(this.options.path);
1114
+ return {
1115
+ scope,
1116
+ filesRemoved: 1,
1117
+ entriesRemoved: counts.entries,
1118
+ contextsRemoved: counts.contexts
1119
+ };
1120
+ }
1121
+ if (parsed.kind !== "v2" || !this.context) {
1122
+ const counts = this.countEntriesFromParsed(parsed);
1123
+ fs.removeSync(this.options.path);
1124
+ return {
1125
+ scope,
1126
+ filesRemoved: 1,
1127
+ entriesRemoved: counts.entries,
1128
+ contextsRemoved: counts.contexts
1129
+ };
1130
+ }
1131
+ const entry = parsed.data.contexts[this.context.fingerprint];
1132
+ if (!entry) return {
1133
+ scope,
1134
+ filesRemoved: 0,
1135
+ entriesRemoved: 0,
1136
+ contextsRemoved: 0
1137
+ };
1138
+ const entriesRemoved = entry.values.length;
1139
+ delete parsed.data.contexts[this.context.fingerprint];
1140
+ if (Object.keys(parsed.data.contexts).length === 0) {
1141
+ fs.removeSync(this.options.path);
1142
+ return {
1143
+ scope,
1144
+ filesRemoved: 1,
1145
+ entriesRemoved,
1146
+ contextsRemoved: 1
1147
+ };
1148
+ }
1149
+ parsed.data.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1150
+ this.writeIndexFileSync(parsed.data);
1151
+ return {
1152
+ scope,
1153
+ filesRemoved: 0,
1154
+ entriesRemoved,
1155
+ contextsRemoved: 1
1156
+ };
1157
+ }) ?? {
1158
+ scope,
1159
+ filesRemoved: 0,
1160
+ entriesRemoved: 0,
1161
+ contextsRemoved: 0
1162
+ };
1163
+ }
1164
+ readIndexSnapshot() {
1165
+ if (this.driver === "memory") return this.memoryIndex ? {
1166
+ ...this.memoryIndex,
1167
+ contexts: Object.fromEntries(Object.entries(this.memoryIndex.contexts).map(([key, value]) => [key, cloneEntry(value)]))
1168
+ } : void 0;
1169
+ const parsed = this.readParsedCacheFileSync(false);
1170
+ if (parsed.kind !== "v2") return;
1171
+ return {
1172
+ ...parsed.data,
1173
+ contexts: Object.fromEntries(Object.entries(parsed.data.contexts).map(([key, value]) => [key, cloneEntry(value)]))
1174
+ };
1175
+ }
1176
+ };
1177
+ //#endregion
1178
+ //#region src/options/legacy.ts
1179
+ const deprecatedRegistryMapping = {
1180
+ output: "extract",
1181
+ tailwind: "tailwindcss"
1182
+ };
1183
+ const deprecatedTailwindMapping = {
1184
+ package: "packageName",
1185
+ legacy: "v2",
1186
+ classic: "v3",
1187
+ next: "v4"
1188
+ };
1189
+ function assertNoDeprecatedRegistryOptions(registry) {
1190
+ const usedRegistryKeys = Object.keys(deprecatedRegistryMapping).filter((key) => Object.hasOwn(registry, key));
1191
+ if (usedRegistryKeys.length > 0) {
1192
+ const mapping = usedRegistryKeys.map((key) => `${key} -> ${deprecatedRegistryMapping[key]}`).join(", ");
1193
+ throw new Error(`Legacy registry fields are no longer supported: ${usedRegistryKeys.join(", ")}. Use the modern fields instead: ${mapping}.`);
1194
+ }
1195
+ const tailwind = registry.tailwindcss;
1196
+ if (!tailwind) return;
1197
+ const usedTailwindKeys = Object.keys(deprecatedTailwindMapping).filter((key) => Object.hasOwn(tailwind, key));
1198
+ if (usedTailwindKeys.length > 0) {
1199
+ const mapping = usedTailwindKeys.map((key) => `${key} -> tailwindcss.${deprecatedTailwindMapping[key]}`).join(", ");
1200
+ throw new Error(`Legacy "registry.tailwindcss" fields are no longer supported: ${usedTailwindKeys.join(", ")}. Use the modern fields instead: ${mapping}.`);
1201
+ }
1202
+ }
1203
+ function fromUnifiedConfig(registry) {
1204
+ if (!registry) return {};
1205
+ assertNoDeprecatedRegistryOptions(registry);
1206
+ const extract = registry.extract ? {
1207
+ ...registry.extract.write === void 0 ? {} : { write: registry.extract.write },
1208
+ ...registry.extract.file === void 0 ? {} : { file: registry.extract.file },
1209
+ ...registry.extract.format === void 0 ? {} : { format: registry.extract.format },
1210
+ ...registry.extract.pretty === void 0 ? {} : { pretty: registry.extract.pretty },
1211
+ ...registry.extract.removeUniversalSelector === void 0 ? {} : { removeUniversalSelector: registry.extract.removeUniversalSelector }
1212
+ } : void 0;
1213
+ const tailwindcss = registry.tailwindcss ? {
1214
+ ...registry.tailwindcss.version === void 0 ? {} : { version: registry.tailwindcss.version },
1215
+ ...registry.tailwindcss.packageName === void 0 ? {} : { packageName: registry.tailwindcss.packageName },
1216
+ ...registry.tailwindcss.resolve === void 0 ? {} : { resolve: registry.tailwindcss.resolve },
1217
+ ...registry.tailwindcss.config === void 0 ? {} : { config: registry.tailwindcss.config },
1218
+ ...registry.tailwindcss.cwd === void 0 ? {} : { cwd: registry.tailwindcss.cwd },
1219
+ ...registry.tailwindcss.v2 === void 0 ? {} : { v2: registry.tailwindcss.v2 },
1220
+ ...registry.tailwindcss.v3 === void 0 ? {} : { v3: registry.tailwindcss.v3 },
1221
+ ...registry.tailwindcss.v4 === void 0 ? {} : { v4: registry.tailwindcss.v4 }
1222
+ } : void 0;
1223
+ const apply = registry.apply ? {
1224
+ ...registry.apply.overwrite === void 0 ? {} : { overwrite: registry.apply.overwrite },
1225
+ ...registry.apply.exposeContext === void 0 ? {} : { exposeContext: registry.apply.exposeContext },
1226
+ ...registry.apply.extendLengthUnits === void 0 ? {} : { extendLengthUnits: registry.apply.extendLengthUnits }
1227
+ } : void 0;
1228
+ return {
1229
+ ...registry.projectRoot === void 0 ? {} : { projectRoot: registry.projectRoot },
1230
+ ...apply === void 0 ? {} : { apply },
1231
+ ...registry.cache === void 0 ? {} : { cache: registry.cache },
1232
+ ...registry.filter === void 0 ? {} : { filter: registry.filter },
1233
+ ...extract === void 0 ? {} : { extract },
1234
+ ...tailwindcss === void 0 ? {} : { tailwindcss }
1235
+ };
1236
+ }
1237
+ //#endregion
1238
+ //#region src/options/normalize.ts
1239
+ function resolveRealpathSafe(value) {
1240
+ const resolved = path.resolve(value);
1241
+ try {
1242
+ return path.normalize(fs.realpathSync(resolved));
1243
+ } catch {
1244
+ return path.normalize(resolved);
1245
+ }
1246
+ }
1247
+ function toPrettyValue(value) {
1248
+ if (typeof value === "number") return value > 0 ? value : false;
1249
+ if (value === true) return 2;
1250
+ return false;
1251
+ }
1252
+ function normalizeCacheDriver(driver) {
1253
+ if (driver === "memory" || driver === "noop") return driver;
1254
+ return "file";
1255
+ }
1256
+ function normalizeCacheOptions(cache, projectRoot) {
1257
+ let enabled = false;
1258
+ let cwd = resolveRealpathSafe(projectRoot);
1259
+ let dir = path.resolve(cwd, "node_modules/.cache", pkgName);
1260
+ let file = "class-cache.json";
1261
+ let strategy = "merge";
1262
+ let driver = "file";
1263
+ if (typeof cache === "boolean") enabled = cache;
1264
+ else if (typeof cache === "object" && cache) {
1265
+ enabled = cache.enabled ?? true;
1266
+ cwd = cache.cwd ? resolveRealpathSafe(cache.cwd) : cwd;
1267
+ dir = cache.dir ? path.resolve(cache.dir) : path.resolve(cwd, "node_modules/.cache", pkgName);
1268
+ file = cache.file ?? file;
1269
+ strategy = cache.strategy ?? strategy;
1270
+ driver = normalizeCacheDriver(cache.driver);
1271
+ }
1272
+ const filename = path.resolve(dir, file);
1273
+ return {
1274
+ enabled,
1275
+ cwd,
1276
+ dir,
1277
+ file,
1278
+ path: filename,
1279
+ strategy,
1280
+ driver
1281
+ };
1282
+ }
1283
+ function normalizeOutputOptions(output) {
1284
+ return {
1285
+ enabled: output?.write ?? true,
1286
+ file: output?.file ?? ".tw-patch/tw-class-list.json",
1287
+ format: output?.format ?? "json",
1288
+ pretty: toPrettyValue(output?.pretty ?? true),
1289
+ removeUniversalSelector: output?.removeUniversalSelector ?? true
1290
+ };
1291
+ }
1292
+ function normalizeExposeContextOptions(exposeContext) {
1293
+ if (exposeContext === false) return {
1294
+ enabled: false,
1295
+ refProperty: "contextRef"
1296
+ };
1297
+ if (typeof exposeContext === "object" && exposeContext) return {
1298
+ enabled: true,
1299
+ refProperty: exposeContext.refProperty ?? "contextRef"
1300
+ };
1301
+ return {
1302
+ enabled: true,
1303
+ refProperty: "contextRef"
1304
+ };
1305
+ }
1306
+ function normalizeExtendLengthUnitsOptions(extend) {
1307
+ if (extend === false || extend === void 0) return null;
1308
+ if (extend.enabled === false) return null;
1309
+ const base = {
1310
+ units: ["rpx"],
1311
+ overwrite: true
1312
+ };
1313
+ return {
1314
+ ...base,
1315
+ ...extend,
1316
+ enabled: extend.enabled ?? true,
1317
+ units: extend.units ?? base.units,
1318
+ overwrite: extend.overwrite ?? base.overwrite
1319
+ };
1320
+ }
1321
+ function normalizeTailwindV4Options(v4, fallbackBase) {
1322
+ const configuredBase = v4?.base ? path.resolve(v4.base) : void 0;
1323
+ const base = configuredBase ?? fallbackBase;
1324
+ const cssEntries = Array.isArray(v4?.cssEntries) ? v4.cssEntries.filter((entry) => Boolean(entry)).map((entry) => path.resolve(entry)) : [];
1325
+ const userSources = v4?.sources;
1326
+ const hasUserDefinedSources = Boolean(userSources?.length);
1327
+ const sources = hasUserDefinedSources ? userSources : [{
1328
+ base: fallbackBase,
1329
+ pattern: "**/*",
1330
+ negated: false
1331
+ }];
1332
+ return {
1333
+ base,
1334
+ ...configuredBase === void 0 ? {} : { configuredBase },
1335
+ ...v4?.css === void 0 ? {} : { css: v4.css },
1336
+ cssEntries,
1337
+ sources,
1338
+ hasUserDefinedSources
1339
+ };
1340
+ }
1341
+ function normalizeTailwindOptions(tailwind, projectRoot, shouldDefaultResolveFromCwd) {
1342
+ const packageName = tailwind?.packageName ?? "tailwindcss";
1343
+ const versionHint = tailwind?.version;
1344
+ const cwd = tailwind?.cwd ?? projectRoot;
1345
+ const resolve = tailwind?.resolve ?? (shouldDefaultResolveFromCwd ? { paths: [cwd] } : void 0);
1346
+ const config = tailwind?.config;
1347
+ const postcssPlugin = tailwind?.postcssPlugin;
1348
+ const v4 = normalizeTailwindV4Options(tailwind?.v4, cwd);
1349
+ return {
1350
+ packageName,
1351
+ cwd,
1352
+ ...versionHint === void 0 ? {} : { versionHint },
1353
+ ...resolve === void 0 ? {} : { resolve },
1354
+ ...config === void 0 ? {} : { config },
1355
+ ...postcssPlugin === void 0 ? {} : { postcssPlugin },
1356
+ ...tailwind?.v2 === void 0 ? {} : { v2: tailwind.v2 },
1357
+ ...tailwind?.v3 === void 0 ? {} : { v3: tailwind.v3 },
1358
+ v4
1359
+ };
1360
+ }
1361
+ const deprecatedOptionMapping = {
1362
+ cwd: "projectRoot",
1363
+ overwrite: "apply.overwrite",
1364
+ tailwind: "tailwindcss",
1365
+ features: "apply",
1366
+ output: "extract"
1367
+ };
1368
+ function assertNoDeprecatedOptions(options) {
1369
+ const used = Object.keys(deprecatedOptionMapping).filter((key) => Object.hasOwn(options, key));
1370
+ if (used.length === 0) return;
1371
+ const mapping = used.map((key) => `${key} -> ${deprecatedOptionMapping[key]}`).join(", ");
1372
+ throw new Error(`Legacy TailwindcssPatcher options are no longer supported: ${used.join(", ")}. Use the modern fields instead: ${mapping}.`);
1373
+ }
1374
+ function normalizeOptions(options = {}) {
1375
+ assertNoDeprecatedOptions(options);
1376
+ const projectRoot = resolveRealpathSafe(options.projectRoot ? path.resolve(options.projectRoot) : process.cwd());
1377
+ const overwrite = options.apply?.overwrite ?? true;
1378
+ const output = normalizeOutputOptions(options.extract);
1379
+ const cache = normalizeCacheOptions(options.cache, projectRoot);
1380
+ const tailwind = normalizeTailwindOptions(options.tailwindcss, projectRoot, options.projectRoot !== void 0 || options.tailwindcss?.cwd !== void 0);
1381
+ const exposeContext = normalizeExposeContextOptions(options.apply?.exposeContext);
1382
+ const extendLengthUnits = normalizeExtendLengthUnitsOptions(options.apply?.extendLengthUnits);
1383
+ const filter = (className) => {
1384
+ if (output.removeUniversalSelector && className === "*") return false;
1385
+ if (typeof options.filter === "function") return options.filter(className) !== false;
1386
+ return true;
1387
+ };
1388
+ return {
1389
+ projectRoot,
1390
+ overwrite,
1391
+ tailwind,
1392
+ features: {
1393
+ exposeContext,
1394
+ extendLengthUnits
1395
+ },
1396
+ output,
1397
+ cache,
1398
+ filter
1399
+ };
1400
+ }
1401
+ //#endregion
1402
+ //#region ../../node_modules/.pnpm/tsdown@0.21.10_synckit@0.11.12_typescript@6.0.3/node_modules/tsdown/esm-shims.js
1403
+ const getFilename = () => fileURLToPath(import.meta.url);
1404
+ const getDirname = () => path$1.dirname(getFilename());
1405
+ const __dirname = /* @__PURE__ */ getDirname();
1406
+ //#endregion
1407
+ //#region src/config/workspace.ts
1408
+ let configModulePromise;
1409
+ let defuPromise;
1410
+ function isNodeError$1(error) {
1411
+ return !!error && typeof error === "object" && ("code" in error || "message" in error);
1412
+ }
1413
+ function isMissingModuleError(error, pkgName) {
1414
+ if (!isNodeError$1(error)) return false;
1415
+ const code = error.code;
1416
+ if (code !== "MODULE_NOT_FOUND" && code !== "ERR_MODULE_NOT_FOUND") return false;
1417
+ const message = error.message ?? "";
1418
+ return message.includes(pkgName) || message.includes(`${pkgName}/dist/`);
1419
+ }
1420
+ function isMissingConfigModuleError(error) {
1421
+ return isMissingModuleError(error, "@tailwindcss-mangle/config");
1422
+ }
1423
+ function isMissingSharedModuleError(error) {
1424
+ return isMissingModuleError(error, "@tailwindcss-mangle/shared");
1425
+ }
1426
+ async function loadWorkspaceConfigModule() {
1427
+ if (!configModulePromise) configModulePromise = import("@tailwindcss-mangle/config").catch(async (error) => {
1428
+ if (!isMissingConfigModuleError(error)) throw error;
1429
+ return import(pathToFileURL(path.resolve(__dirname, "../../../config/src/index.ts")).href);
1430
+ });
1431
+ return configModulePromise;
1432
+ }
1433
+ async function loadWorkspaceDefu() {
1434
+ if (!defuPromise) defuPromise = import("./dist-BjUV1yEM.mjs").then((mod) => mod.defu).catch(async (error) => {
1435
+ if (!isMissingSharedModuleError(error)) throw error;
1436
+ return (await import(pathToFileURL(path.resolve(__dirname, "../../../shared/src/utils.ts")).href)).defu;
1437
+ });
1438
+ return defuPromise;
1439
+ }
1440
+ async function loadPatchOptionsForWorkspace(cwd, overrides) {
1441
+ const merge = await loadWorkspaceDefu();
1442
+ const { config } = await (await loadWorkspaceConfigModule()).getConfig(cwd);
1443
+ if (config && typeof config === "object" && "patch" in config && config.patch !== void 0) throw new Error("Legacy workspace config field \"patch\" is no longer supported. Move patcher options under \"registry\".");
1444
+ const base = config?.registry ? fromUnifiedConfig(config.registry) : {};
1445
+ return merge(overrides ?? {}, base, { projectRoot: cwd });
1446
+ }
1447
+ //#endregion
1448
+ //#region src/v4/candidates.ts
1449
+ function resolveValidTailwindV4Candidates(designSystem, candidates) {
1450
+ const validCandidates = /* @__PURE__ */ new Set();
1451
+ const parsedCandidates = [];
1452
+ for (const candidate of candidates) {
1453
+ if (!candidate || parsedCandidates.includes(candidate)) continue;
1454
+ if (designSystem.parseCandidate(candidate).length > 0) parsedCandidates.push(candidate);
1455
+ }
1456
+ if (parsedCandidates.length === 0) return validCandidates;
1457
+ const cssByCandidate = designSystem.candidatesToCss(parsedCandidates);
1458
+ for (let index = 0; index < parsedCandidates.length; index++) {
1459
+ const candidate = parsedCandidates[index];
1460
+ const candidateCss = cssByCandidate[index];
1461
+ if (candidate && typeof candidateCss === "string" && candidateCss.trim().length > 0) validCandidates.add(candidate);
1462
+ }
1463
+ return validCandidates;
1464
+ }
1465
+ function splitTopLevel(value, separator) {
1466
+ const result = [];
1467
+ let start = 0;
1468
+ let depth = 0;
1469
+ let quote;
1470
+ for (let index = 0; index < value.length; index++) {
1471
+ const character = value[index];
1472
+ if (character === "\\") {
1473
+ index++;
1474
+ continue;
1475
+ }
1476
+ if (quote) {
1477
+ if (character === quote) quote = void 0;
1478
+ continue;
1479
+ }
1480
+ if (character === "\"" || character === "'") {
1481
+ quote = character;
1482
+ continue;
1483
+ }
1484
+ if (character === "(" || character === "[" || character === "{") {
1485
+ depth++;
1486
+ continue;
1487
+ }
1488
+ if (character === ")" || character === "]" || character === "}") {
1489
+ depth = Math.max(0, depth - 1);
1490
+ continue;
1491
+ }
1492
+ if (depth === 0 && character === separator) {
1493
+ const item = value.slice(start, index).trim();
1494
+ if (item) result.push(item);
1495
+ start = index + 1;
1496
+ }
1497
+ }
1498
+ const item = value.slice(start).trim();
1499
+ if (item) result.push(item);
1500
+ return result;
1501
+ }
1502
+ const sequencePattern = /^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/;
1503
+ function expandSequence(value) {
1504
+ const match = value.match(sequencePattern);
1505
+ if (!match) return [value];
1506
+ const [, startValue, endValue, stepValue] = match;
1507
+ if (startValue === void 0 || endValue === void 0) return [value];
1508
+ const start = Number.parseInt(startValue, 10);
1509
+ const end = Number.parseInt(endValue, 10);
1510
+ let step = stepValue === void 0 ? start <= end ? 1 : -1 : Number.parseInt(stepValue, 10);
1511
+ if (step === 0) throw new Error("Step cannot be zero in Tailwind CSS v4 inline source sequence.");
1512
+ const ascending = start < end;
1513
+ if (ascending && step < 0) step = -step;
1514
+ if (!ascending && step > 0) step = -step;
1515
+ const result = [];
1516
+ for (let current = start; ascending ? current <= end : current >= end; current += step) result.push(current.toString());
1517
+ return result;
1518
+ }
1519
+ function expandInlinePattern(pattern) {
1520
+ const openIndex = pattern.indexOf("{");
1521
+ if (openIndex === -1) return [pattern];
1522
+ const prefix = pattern.slice(0, openIndex);
1523
+ const rest = pattern.slice(openIndex);
1524
+ let depth = 0;
1525
+ let closeIndex = -1;
1526
+ for (let index = 0; index < rest.length; index++) {
1527
+ const character = rest[index];
1528
+ if (character === "{") depth++;
1529
+ else if (character === "}") {
1530
+ depth--;
1531
+ if (depth === 0) {
1532
+ closeIndex = index;
1533
+ break;
1534
+ }
1535
+ }
1536
+ }
1537
+ if (closeIndex === -1) throw new Error(`The Tailwind CSS v4 inline source pattern "${pattern}" is not balanced.`);
1538
+ const body = rest.slice(1, closeIndex);
1539
+ const suffix = rest.slice(closeIndex + 1);
1540
+ const parts = sequencePattern.test(body) ? expandSequence(body) : splitTopLevel(body, ",").flatMap((part) => expandInlinePattern(part));
1541
+ const suffixes = expandInlinePattern(suffix);
1542
+ const result = [];
1543
+ for (const part of parts) for (const expandedSuffix of suffixes) result.push(`${prefix}${part}${expandedSuffix}`);
1544
+ return result;
1545
+ }
1546
+ function unquoteCssString(value) {
1547
+ const quote = value[0];
1548
+ if (quote !== "\"" && quote !== "'" || value[value.length - 1] !== quote) return;
1549
+ let result = "";
1550
+ for (let index = 1; index < value.length - 1; index++) {
1551
+ const character = value[index];
1552
+ if (character === "\\") {
1553
+ index++;
1554
+ result += value[index] ?? "";
1555
+ continue;
1556
+ }
1557
+ result += character;
1558
+ }
1559
+ return result;
1560
+ }
1561
+ function extractTailwindV4InlineSourceCandidates(css) {
1562
+ const included = /* @__PURE__ */ new Set();
1563
+ const excluded = /* @__PURE__ */ new Set();
1564
+ postcss.parse(css).walkAtRules("source", (rule) => {
1565
+ let params = rule.params.trim();
1566
+ if (!params) return;
1567
+ let negated = false;
1568
+ if (params.startsWith("not ")) {
1569
+ negated = true;
1570
+ params = params.slice(4).trim();
1571
+ }
1572
+ if (!params.startsWith("inline(") || !params.endsWith(")")) return;
1573
+ const inlineValue = unquoteCssString(params.slice(7, -1).trim());
1574
+ if (inlineValue === void 0) return;
1575
+ const target = negated ? excluded : included;
1576
+ for (const part of splitTopLevel(inlineValue, " ")) for (const candidate of expandInlinePattern(part)) target.add(candidate);
1577
+ });
1578
+ return {
1579
+ included,
1580
+ excluded
1581
+ };
1582
+ }
1583
+ //#endregion
1584
+ //#region src/v4/node-adapter.ts
1585
+ const nodeModulePromiseCache = /* @__PURE__ */ new Map();
1586
+ const designSystemPromiseCache = /* @__PURE__ */ new Map();
1587
+ function unique(values) {
1588
+ return Array.from(new Set(Array.from(values).filter(Boolean).map((value) => path.resolve(value))));
1589
+ }
1590
+ function createRequireBase(base) {
1591
+ return path.join(base, "package.json");
1592
+ }
1593
+ async function importResolvedModule(resolved) {
1594
+ return import(pathToFileURL(resolved).href);
1595
+ }
1596
+ async function importTailwindNodeFromBase(base) {
1597
+ try {
1598
+ return await importResolvedModule(createRequire(createRequireBase(base)).resolve("@tailwindcss/node"));
1599
+ } catch {
1600
+ return;
1601
+ }
1602
+ }
1603
+ async function importFallbackTailwindNode() {
1604
+ return import("@tailwindcss/node");
1605
+ }
1606
+ async function loadTailwindV4NodeModule(baseCandidates) {
1607
+ const bases = unique(baseCandidates);
1608
+ const cacheKey = JSON.stringify(bases);
1609
+ const cached = nodeModulePromiseCache.get(cacheKey);
1610
+ if (cached) return cached;
1611
+ const promise = (async () => {
1612
+ for (const base of bases) {
1613
+ const loaded = await importTailwindNodeFromBase(base);
1614
+ if (loaded) return loaded;
1615
+ }
1616
+ return importFallbackTailwindNode();
1617
+ })();
1618
+ nodeModulePromiseCache.set(cacheKey, promise);
1619
+ promise.catch(() => {
1620
+ if (nodeModulePromiseCache.get(cacheKey) === promise) nodeModulePromiseCache.delete(cacheKey);
1621
+ });
1622
+ return promise;
1623
+ }
1624
+ function createDesignSystemCacheKey(css, bases) {
1625
+ return JSON.stringify({
1626
+ css,
1627
+ bases: unique(bases)
1628
+ });
1629
+ }
1630
+ function getTailwindV4DesignSystemCacheKey(source) {
1631
+ return createDesignSystemCacheKey(source.css, [source.base, ...source.baseFallbacks]);
1632
+ }
1633
+ async function loadTailwindV4DesignSystem(source) {
1634
+ const bases = unique([source.base, ...source.baseFallbacks]);
1635
+ if (bases.length === 0) throw new Error("No base directories provided for Tailwind CSS v4 design system.");
1636
+ const cacheKey = createDesignSystemCacheKey(source.css, bases);
1637
+ const cached = designSystemPromiseCache.get(cacheKey);
1638
+ if (cached) return cached;
1639
+ const promise = (async () => {
1640
+ const node = await loadTailwindV4NodeModule([source.projectRoot, ...bases]);
1641
+ let lastError;
1642
+ for (const base of bases) try {
1643
+ return await node.__unstable__loadDesignSystem(source.css, { base });
1644
+ } catch (error) {
1645
+ lastError = error;
1646
+ }
1647
+ if (lastError instanceof Error) throw lastError;
1648
+ throw new Error("Failed to load Tailwind CSS v4 design system.");
1649
+ })();
1650
+ designSystemPromiseCache.set(cacheKey, promise);
1651
+ promise.catch(() => {
1652
+ if (designSystemPromiseCache.get(cacheKey) === promise) designSystemPromiseCache.delete(cacheKey);
1653
+ });
1654
+ return promise;
1655
+ }
1656
+ async function compileTailwindV4Source(source) {
1657
+ const node = await loadTailwindV4NodeModule([
1658
+ source.projectRoot,
1659
+ source.base,
1660
+ ...source.baseFallbacks
1661
+ ]);
1662
+ const dependencies = new Set(source.dependencies);
1663
+ return {
1664
+ compiled: await node.compile(source.css, {
1665
+ base: source.base,
1666
+ onDependency(dependency) {
1667
+ dependencies.add(path.resolve(dependency));
1668
+ }
1669
+ }),
1670
+ dependencies
1671
+ };
1672
+ }
1673
+ //#endregion
1674
+ //#region src/extraction/candidate-extractor.ts
1675
+ let oxideImportPromise;
1676
+ const designSystemCandidateCache = /* @__PURE__ */ new Map();
1677
+ async function importOxide() {
1678
+ return import("@tailwindcss/oxide");
1679
+ }
1680
+ function getOxideModule() {
1681
+ oxideImportPromise ??= importOxide();
1682
+ return oxideImportPromise;
1683
+ }
1684
+ async function extractRawCandidatesWithPositions(content, extension = "html") {
1685
+ const { Scanner } = await getOxideModule();
1686
+ return new Scanner({}).getCandidatesWithPositions({
1687
+ content,
1688
+ extension
1689
+ }).map(({ candidate, position }) => ({
1690
+ rawCandidate: candidate,
1691
+ start: position,
1692
+ end: position + candidate.length
1693
+ }));
1694
+ }
1695
+ async function extractRawCandidates(sources) {
1696
+ const { Scanner } = await getOxideModule();
1697
+ return new Scanner(sources === void 0 ? {} : { sources }).scan();
1698
+ }
1699
+ async function extractValidCandidates(options) {
1700
+ const providedOptions = options ?? {};
1701
+ const defaultCwd = providedOptions.cwd ?? process.cwd();
1702
+ const base = providedOptions.base ?? defaultCwd;
1703
+ const baseFallbacks = providedOptions.baseFallbacks ?? [];
1704
+ const css = providedOptions.css ?? "@import \"tailwindcss\";";
1705
+ const sources = (providedOptions.sources ?? [{
1706
+ base: defaultCwd,
1707
+ pattern: "**/*",
1708
+ negated: false
1709
+ }]).map((source) => ({
1710
+ base: source.base ?? defaultCwd,
1711
+ pattern: source.pattern,
1712
+ negated: source.negated
1713
+ }));
1714
+ const source = {
1715
+ projectRoot: defaultCwd,
1716
+ base,
1717
+ baseFallbacks,
1718
+ css,
1719
+ dependencies: []
1720
+ };
1721
+ const designSystemKey = getTailwindV4DesignSystemCacheKey(source);
1722
+ const designSystem = await loadTailwindV4DesignSystem(source);
1723
+ const candidateCache = designSystemCandidateCache.get(designSystemKey) ?? /* @__PURE__ */ new Map();
1724
+ designSystemCandidateCache.set(designSystemKey, candidateCache);
1725
+ const candidates = await extractRawCandidates(sources);
1726
+ const validCandidates = [];
1727
+ const uncachedCandidates = [];
1728
+ for (const rawCandidate of candidates) {
1729
+ const cached = candidateCache.get(rawCandidate);
1730
+ if (cached === true) {
1731
+ validCandidates.push(rawCandidate);
1732
+ continue;
1733
+ }
1734
+ if (cached === false) continue;
1735
+ if (designSystem.parseCandidate(rawCandidate).length > 0) {
1736
+ uncachedCandidates.push(rawCandidate);
1737
+ continue;
1738
+ }
1739
+ candidateCache.set(rawCandidate, false);
1740
+ }
1741
+ if (uncachedCandidates.length === 0) return validCandidates;
1742
+ const validUncachedCandidates = resolveValidTailwindV4Candidates(designSystem, uncachedCandidates);
1743
+ for (const candidate of uncachedCandidates) {
1744
+ const isValid = validUncachedCandidates.has(candidate);
1745
+ candidateCache.set(candidate, isValid);
1746
+ if (!isValid) continue;
1747
+ validCandidates.push(candidate);
1748
+ }
1749
+ return validCandidates;
1750
+ }
1751
+ function normalizeSources(sources, cwd) {
1752
+ return (sources?.length ? sources : [{
1753
+ base: cwd,
1754
+ pattern: "**/*",
1755
+ negated: false
1756
+ }]).map((source) => ({
1757
+ base: source.base ?? cwd,
1758
+ pattern: source.pattern,
1759
+ negated: source.negated
1760
+ }));
1761
+ }
1762
+ function buildLineOffsets(content) {
1763
+ const offsets = [0];
1764
+ for (let i = 0; i < content.length; i++) if (content[i] === "\n") offsets.push(i + 1);
1765
+ if (offsets[offsets.length - 1] !== content.length) offsets.push(content.length);
1766
+ return offsets;
1767
+ }
1768
+ function resolveLineMeta(content, offsets, index) {
1769
+ let low = 0;
1770
+ let high = offsets.length - 1;
1771
+ while (low <= high) {
1772
+ const mid = Math.floor((low + high) / 2);
1773
+ const start = offsets[mid];
1774
+ if (start === void 0) break;
1775
+ const nextStart = offsets[mid + 1] ?? content.length;
1776
+ if (index < start) {
1777
+ high = mid - 1;
1778
+ continue;
1779
+ }
1780
+ if (index >= nextStart) {
1781
+ low = mid + 1;
1782
+ continue;
1783
+ }
1784
+ const line = mid + 1;
1785
+ const column = index - start + 1;
1786
+ const lineEnd = content.indexOf("\n", start);
1787
+ return {
1788
+ line,
1789
+ column,
1790
+ lineText: content.slice(start, lineEnd === -1 ? content.length : lineEnd)
1791
+ };
1792
+ }
1793
+ const lastStart = offsets[offsets.length - 2] ?? 0;
1794
+ return {
1795
+ line: offsets.length - 1,
1796
+ column: index - lastStart + 1,
1797
+ lineText: content.slice(lastStart)
1798
+ };
1799
+ }
1800
+ function toExtension(filename) {
1801
+ return path.extname(filename).replace(/^\./, "") || "txt";
1802
+ }
1803
+ function toRelativeFile(cwd, filename) {
1804
+ const relative = path.relative(cwd, filename);
1805
+ return relative === "" ? path.basename(filename) : relative;
1806
+ }
1807
+ async function extractProjectCandidatesWithPositions(options) {
1808
+ const cwd = options?.cwd ? path.resolve(options.cwd) : process.cwd();
1809
+ const normalizedSources = normalizeSources(options?.sources, cwd);
1810
+ const { Scanner } = await getOxideModule();
1811
+ const scanner = new Scanner({ sources: normalizedSources });
1812
+ const files = scanner.files ?? [];
1813
+ const entries = [];
1814
+ const skipped = [];
1815
+ for (const file of files) {
1816
+ let content;
1817
+ try {
1818
+ content = await promises.readFile(file, "utf8");
1819
+ } catch (error) {
1820
+ skipped.push({
1821
+ file,
1822
+ reason: error instanceof Error ? error.message : "Unknown error"
1823
+ });
1824
+ continue;
1825
+ }
1826
+ const extension = toExtension(file);
1827
+ const matches = scanner.getCandidatesWithPositions({
1828
+ file,
1829
+ content,
1830
+ extension
1831
+ });
1832
+ if (!matches.length) continue;
1833
+ const offsets = buildLineOffsets(content);
1834
+ const relativeFile = toRelativeFile(cwd, file);
1835
+ for (const match of matches) {
1836
+ const info = resolveLineMeta(content, offsets, match.position);
1837
+ entries.push({
1838
+ rawCandidate: match.candidate,
1839
+ file,
1840
+ relativeFile,
1841
+ extension,
1842
+ start: match.position,
1843
+ end: match.position + match.candidate.length,
1844
+ length: match.candidate.length,
1845
+ line: info.line,
1846
+ column: info.column,
1847
+ lineText: info.lineText
1848
+ });
1849
+ }
1850
+ }
1851
+ return {
1852
+ entries,
1853
+ filesScanned: files.length,
1854
+ skippedFiles: skipped,
1855
+ sources: normalizedSources
1856
+ };
1857
+ }
1858
+ function groupTokensByFile(report, options) {
1859
+ const key = options?.key ?? "relative";
1860
+ const stripAbsolute = options?.stripAbsolutePaths ?? key !== "absolute";
1861
+ return report.entries.reduce((acc, entry) => {
1862
+ const bucketKey = key === "absolute" ? entry.file : entry.relativeFile;
1863
+ const bucket = acc[bucketKey] ?? (acc[bucketKey] = []);
1864
+ const value = stripAbsolute ? {
1865
+ ...entry,
1866
+ file: entry.relativeFile
1867
+ } : entry;
1868
+ bucket.push(value);
1869
+ return acc;
1870
+ }, {});
1871
+ }
1872
+ //#endregion
1873
+ //#region src/utils.ts
1874
+ function isObject(val) {
1875
+ return val !== null && typeof val === "object" && Array.isArray(val) === false;
1876
+ }
1877
+ /**
1878
+ * Apply the changes to the string such that a change in the length
1879
+ * of the string does not break the indexes of the subsequent changes.
1880
+ */
1881
+ function spliceChangesIntoString(str, changes) {
1882
+ const firstChange = changes[0];
1883
+ if (!firstChange) return str;
1884
+ changes.sort((a, b) => {
1885
+ return a.end - b.end || a.start - b.start;
1886
+ });
1887
+ let result = "";
1888
+ let previous = firstChange;
1889
+ result += str.slice(0, previous.start);
1890
+ result += previous.replacement;
1891
+ for (let i = 1; i < changes.length; ++i) {
1892
+ const change = changes[i];
1893
+ if (!change) continue;
1894
+ result += str.slice(previous.end, change.start);
1895
+ result += change.replacement;
1896
+ previous = change;
1897
+ }
1898
+ result += str.slice(previous.end);
1899
+ return result;
1900
+ }
1901
+ //#endregion
1902
+ //#region src/runtime/class-collector.ts
1903
+ function collectRuntimeCandidateKeys(context) {
1904
+ const candidateRuleCache = context.candidateRuleCache;
1905
+ if (candidateRuleCache instanceof Map && candidateRuleCache.size > 0) return candidateRuleCache.keys();
1906
+ return context.classCache.keys();
1907
+ }
1908
+ function collectClassesFromContexts(contexts, filter) {
1909
+ const set = /* @__PURE__ */ new Set();
1910
+ for (const context of contexts) {
1911
+ if (!isObject(context) || !context.classCache) continue;
1912
+ for (const key of collectRuntimeCandidateKeys(context)) {
1913
+ const className = key.toString();
1914
+ if (filter(className)) set.add(className);
1915
+ }
1916
+ }
1917
+ return set;
1918
+ }
1919
+ async function collectClassesFromTailwindV4(options) {
1920
+ const set = /* @__PURE__ */ new Set();
1921
+ const v4Options = options.tailwind.v4;
1922
+ if (!v4Options) return set;
1923
+ const toAbsolute = (value) => {
1924
+ if (!value) return;
1925
+ return path.isAbsolute(value) ? value : path.resolve(options.projectRoot, value);
1926
+ };
1927
+ const resolvedConfiguredBase = toAbsolute(v4Options.configuredBase);
1928
+ const resolvedDefaultBase = toAbsolute(v4Options.base) ?? process.cwd();
1929
+ const resolveSources = (base) => {
1930
+ if (!v4Options.sources?.length) return;
1931
+ return v4Options.sources.map((source) => ({
1932
+ base: source.base ?? base,
1933
+ pattern: source.pattern,
1934
+ negated: source.negated
1935
+ }));
1936
+ };
1937
+ if (v4Options.cssEntries.length > 0) for (const entry of v4Options.cssEntries) {
1938
+ const filePath = path.isAbsolute(entry) ? entry : path.resolve(options.projectRoot, entry);
1939
+ if (!await fs.pathExists(filePath)) continue;
1940
+ const css = await fs.readFile(filePath, "utf8");
1941
+ const entryDir = path.dirname(filePath);
1942
+ const designSystemBases = resolvedConfiguredBase && resolvedConfiguredBase !== entryDir ? [entryDir, resolvedConfiguredBase] : [entryDir];
1943
+ const sources = resolveSources(resolvedConfiguredBase ?? entryDir);
1944
+ const firstBase = designSystemBases[0] ?? entryDir;
1945
+ const candidates = await extractValidCandidates({
1946
+ cwd: options.projectRoot,
1947
+ base: firstBase,
1948
+ baseFallbacks: designSystemBases.slice(1),
1949
+ css,
1950
+ ...sources === void 0 ? {} : { sources }
1951
+ });
1952
+ for (const candidate of candidates) if (options.filter(candidate)) set.add(candidate);
1953
+ }
1954
+ else {
1955
+ const baseForCss = resolvedConfiguredBase ?? resolvedDefaultBase;
1956
+ const sources = resolveSources(baseForCss);
1957
+ const candidates = await extractValidCandidates({
1958
+ cwd: options.projectRoot,
1959
+ base: baseForCss,
1960
+ ...v4Options.css === void 0 ? {} : { css: v4Options.css },
1961
+ ...sources === void 0 ? {} : { sources }
1962
+ });
1963
+ for (const candidate of candidates) if (options.filter(candidate)) set.add(candidate);
1964
+ }
1965
+ return set;
1966
+ }
1967
+ //#endregion
1968
+ //#region src/runtime/context-registry.ts
1969
+ const require = createRequire(import.meta.url);
1970
+ function resolveRuntimeEntry(packageInfo, majorVersion) {
1971
+ const root = packageInfo.rootPath;
1972
+ if (majorVersion === 2) {
1973
+ const jitIndex = path.join(root, "lib/jit/index.js");
1974
+ if (fs.existsSync(jitIndex)) return jitIndex;
1975
+ } else if (majorVersion === 3) {
1976
+ const plugin = path.join(root, "lib/plugin.js");
1977
+ const index = path.join(root, "lib/index.js");
1978
+ if (fs.existsSync(plugin)) return plugin;
1979
+ if (fs.existsSync(index)) return index;
1980
+ }
1981
+ }
1982
+ function loadRuntimeContexts(packageInfo, majorVersion, refProperty) {
1983
+ if (majorVersion === 4) return [];
1984
+ const entry = resolveRuntimeEntry(packageInfo, majorVersion);
1985
+ if (!entry) return [];
1986
+ const moduleExports = require(entry);
1987
+ if (!moduleExports) return [];
1988
+ const ref = moduleExports[refProperty];
1989
+ if (!ref) return [];
1990
+ if (Array.isArray(ref)) return ref;
1991
+ if (typeof ref === "object" && Array.isArray(ref.value)) return ref.value;
1992
+ return [];
1993
+ }
1994
+ //#endregion
1995
+ //#region src/babel/index.ts
1996
+ function _interopDefaultCompat(e) {
1997
+ return e && typeof e === "object" && "default" in e ? e.default : e;
1998
+ }
1999
+ const generate$1 = _interopDefaultCompat(generate);
2000
+ const traverse = _interopDefaultCompat(_babelTraverse);
2001
+ //#endregion
2002
+ //#region src/patching/operations/export-context/postcss-v2.ts
2003
+ const IDENTIFIER_RE$1 = /^[A-Z_$][\w$]*$/i;
2004
+ function toIdentifierName$1(property) {
2005
+ if (!property) return "contextRef";
2006
+ const sanitized = property.replace(/[^\w$]/gu, "_");
2007
+ if (/^\d/.test(sanitized)) return `_${sanitized}`;
2008
+ return sanitized || "contextRef";
2009
+ }
2010
+ function createExportsMember(property) {
2011
+ if (IDENTIFIER_RE$1.test(property)) return t.memberExpression(t.identifier("exports"), t.identifier(property));
2012
+ return t.memberExpression(t.identifier("exports"), t.stringLiteral(property), true);
2013
+ }
2014
+ function transformProcessTailwindFeaturesReturnContextV2(content) {
2015
+ const ast = parse$1(content, { sourceType: "unambiguous" });
2016
+ let hasPatched = false;
2017
+ traverse(ast, { FunctionDeclaration(path) {
2018
+ const node = path.node;
2019
+ if (node.id?.name !== "processTailwindFeatures" || node.body.body.length !== 1 || !t.isReturnStatement(node.body.body[0])) return;
2020
+ const returnStatement = node.body.body[0];
2021
+ if (!t.isFunctionExpression(returnStatement.argument)) return;
2022
+ const body = returnStatement.argument.body.body;
2023
+ const lastStatement = body[body.length - 1];
2024
+ const alreadyReturnsContext = Boolean(t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context");
2025
+ hasPatched = alreadyReturnsContext;
2026
+ if (!alreadyReturnsContext) body.push(t.returnStatement(t.identifier("context")));
2027
+ } });
2028
+ return {
2029
+ code: hasPatched ? content : generate$1(ast).code,
2030
+ hasPatched
2031
+ };
2032
+ }
2033
+ function transformPostcssPluginV2(content, options) {
2034
+ const refIdentifier = t.identifier(toIdentifierName$1(options.refProperty));
2035
+ const exportMember = createExportsMember(options.refProperty);
2036
+ const valueMember = t.memberExpression(refIdentifier, t.identifier("value"));
2037
+ const ast = parse$1(content);
2038
+ let hasPatched = false;
2039
+ traverse(ast, {
2040
+ Program(path) {
2041
+ const program = path.node;
2042
+ const index = program.body.findIndex((statement) => {
2043
+ return t.isFunctionDeclaration(statement) && statement.id?.name === "_default";
2044
+ });
2045
+ if (index === -1) return;
2046
+ const previous = program.body[index - 1];
2047
+ const beforePrevious = program.body[index - 2];
2048
+ const alreadyHasVariable = Boolean(previous && t.isVariableDeclaration(previous) && previous.declarations.length === 1 && (() => {
2049
+ const declaration = previous.declarations[0];
2050
+ return Boolean(declaration && t.isIdentifier(declaration.id) && declaration.id.name === refIdentifier.name);
2051
+ })());
2052
+ const alreadyAssignsExports = Boolean(beforePrevious && t.isExpressionStatement(beforePrevious) && t.isAssignmentExpression(beforePrevious.expression) && t.isMemberExpression(beforePrevious.expression.left) && t.isIdentifier(beforePrevious.expression.right) && beforePrevious.expression.right.name === refIdentifier.name && generate$1(beforePrevious.expression.left).code === generate$1(exportMember).code);
2053
+ hasPatched = alreadyHasVariable && alreadyAssignsExports;
2054
+ if (!alreadyHasVariable) program.body.splice(index, 0, t.variableDeclaration("var", [t.variableDeclarator(refIdentifier, t.objectExpression([t.objectProperty(t.identifier("value"), t.arrayExpression())]))]), t.expressionStatement(t.assignmentExpression("=", exportMember, refIdentifier)));
2055
+ },
2056
+ FunctionDeclaration(path) {
2057
+ if (hasPatched) return;
2058
+ const fn = path.node;
2059
+ if (fn.id?.name !== "_default") return;
2060
+ if (fn.body.body.length !== 1 || !t.isReturnStatement(fn.body.body[0])) return;
2061
+ const returnStatement = fn.body.body[0];
2062
+ if (!t.isCallExpression(returnStatement.argument) || !t.isMemberExpression(returnStatement.argument.callee) || !t.isArrayExpression(returnStatement.argument.callee.object)) return;
2063
+ const fnExpression = returnStatement.argument.callee.object.elements[1];
2064
+ if (!fnExpression || !t.isFunctionExpression(fnExpression)) return;
2065
+ const statements = fnExpression.body.body;
2066
+ if (t.isExpressionStatement(statements[0]) && t.isAssignmentExpression(statements[0].expression) && t.isNumericLiteral(statements[0].expression.right)) {
2067
+ hasPatched = true;
2068
+ return;
2069
+ }
2070
+ const lastStatement = statements[statements.length - 1];
2071
+ if (lastStatement && t.isExpressionStatement(lastStatement)) statements[statements.length - 1] = t.expressionStatement(t.callExpression(t.memberExpression(valueMember, t.identifier("push")), [lastStatement.expression]));
2072
+ const index = statements.findIndex((statement) => t.isIfStatement(statement));
2073
+ if (index > -1) {
2074
+ const ifStatement = statements[index];
2075
+ if (t.isBlockStatement(ifStatement.consequent) && ifStatement.consequent.body[1] && t.isForOfStatement(ifStatement.consequent.body[1])) {
2076
+ const forOf = ifStatement.consequent.body[1];
2077
+ if (t.isBlockStatement(forOf.body) && forOf.body.body.length === 1) {
2078
+ const nestedIf = forOf.body.body[0];
2079
+ if (nestedIf && t.isIfStatement(nestedIf) && t.isBlockStatement(nestedIf.consequent) && nestedIf.consequent.body.length === 1 && t.isExpressionStatement(nestedIf.consequent.body[0])) nestedIf.consequent.body[0] = t.expressionStatement(t.callExpression(t.memberExpression(valueMember, t.identifier("push")), [nestedIf.consequent.body[0].expression]));
2080
+ }
2081
+ }
2082
+ }
2083
+ statements.unshift(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(valueMember, t.identifier("length")), t.numericLiteral(0))));
2084
+ }
2085
+ });
2086
+ return {
2087
+ code: hasPatched ? content : generate$1(ast).code,
2088
+ hasPatched
2089
+ };
2090
+ }
2091
+ //#endregion
2092
+ //#region src/patching/operations/export-context/postcss-v3.ts
2093
+ const IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
2094
+ function toIdentifierName(property) {
2095
+ if (!property) return "contextRef";
2096
+ const sanitized = property.replace(/[^\w$]/gu, "_");
2097
+ if (/^\d/.test(sanitized)) return `_${sanitized}`;
2098
+ return sanitized || "contextRef";
2099
+ }
2100
+ function createModuleExportsMember(property) {
2101
+ const object = t.memberExpression(t.identifier("module"), t.identifier("exports"));
2102
+ if (IDENTIFIER_RE.test(property)) return t.memberExpression(object, t.identifier(property));
2103
+ return t.memberExpression(object, t.stringLiteral(property), true);
2104
+ }
2105
+ function transformProcessTailwindFeaturesReturnContext(content) {
2106
+ const ast = parse$1(content);
2107
+ let hasPatched = false;
2108
+ traverse(ast, { FunctionDeclaration(path) {
2109
+ const node = path.node;
2110
+ if (node.id?.name !== "processTailwindFeatures" || node.body.body.length !== 1) return;
2111
+ const [returnStatement] = node.body.body;
2112
+ if (!t.isReturnStatement(returnStatement) || !t.isFunctionExpression(returnStatement.argument)) return;
2113
+ const body = returnStatement.argument.body.body;
2114
+ const lastStatement = body[body.length - 1];
2115
+ const alreadyReturnsContext = Boolean(t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context");
2116
+ hasPatched = alreadyReturnsContext;
2117
+ if (!alreadyReturnsContext) body.push(t.returnStatement(t.identifier("context")));
2118
+ } });
2119
+ return {
2120
+ code: hasPatched ? content : generate$1(ast).code,
2121
+ hasPatched
2122
+ };
2123
+ }
2124
+ function transformPostcssPlugin(content, { refProperty }) {
2125
+ const ast = parse$1(content);
2126
+ const refIdentifier = t.identifier(toIdentifierName(refProperty));
2127
+ const moduleExportsMember = createModuleExportsMember(refProperty);
2128
+ const valueMember = t.memberExpression(refIdentifier, t.identifier("value"));
2129
+ let hasPatched = false;
2130
+ traverse(ast, {
2131
+ Program(path) {
2132
+ const program = path.node;
2133
+ const index = program.body.findIndex((statement) => {
2134
+ return t.isExpressionStatement(statement) && t.isAssignmentExpression(statement.expression) && t.isMemberExpression(statement.expression.left) && t.isFunctionExpression(statement.expression.right) && statement.expression.right.id?.name === "tailwindcss";
2135
+ });
2136
+ if (index === -1) return;
2137
+ const previousStatement = program.body[index - 1];
2138
+ const lastStatement = program.body[program.body.length - 1];
2139
+ const alreadyHasVariable = Boolean(previousStatement && t.isVariableDeclaration(previousStatement) && previousStatement.declarations.length === 1 && (() => {
2140
+ const declaration = previousStatement.declarations[0];
2141
+ return Boolean(declaration && t.isIdentifier(declaration.id) && declaration.id.name === refIdentifier.name);
2142
+ })());
2143
+ const alreadyAssignsModuleExports = Boolean(t.isExpressionStatement(lastStatement) && t.isAssignmentExpression(lastStatement.expression) && t.isMemberExpression(lastStatement.expression.left) && t.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === refIdentifier.name && generate$1(lastStatement.expression.left).code === generate$1(moduleExportsMember).code);
2144
+ hasPatched = alreadyHasVariable && alreadyAssignsModuleExports;
2145
+ if (!alreadyHasVariable) program.body.splice(index, 0, t.variableDeclaration("const", [t.variableDeclarator(refIdentifier, t.objectExpression([t.objectProperty(t.identifier("value"), t.arrayExpression())]))]));
2146
+ if (!alreadyAssignsModuleExports) program.body.push(t.expressionStatement(t.assignmentExpression("=", moduleExportsMember, refIdentifier)));
2147
+ },
2148
+ FunctionExpression(path) {
2149
+ if (hasPatched) return;
2150
+ const fn = path.node;
2151
+ if (fn.id?.name !== "tailwindcss" || fn.body.body.length !== 1) return;
2152
+ const [returnStatement] = fn.body.body;
2153
+ if (!returnStatement || !t.isReturnStatement(returnStatement) || !t.isObjectExpression(returnStatement.argument)) return;
2154
+ const properties = returnStatement.argument.properties;
2155
+ if (properties.length !== 2) return;
2156
+ const pluginsProperty = properties.find((prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "plugins");
2157
+ if (!pluginsProperty || !t.isObjectProperty(pluginsProperty) || !t.isCallExpression(pluginsProperty.value) || !t.isMemberExpression(pluginsProperty.value.callee) || !t.isArrayExpression(pluginsProperty.value.callee.object)) return;
2158
+ const targetPlugin = pluginsProperty.value.callee.object.elements[1];
2159
+ if (!targetPlugin || !t.isFunctionExpression(targetPlugin)) return;
2160
+ const statements = targetPlugin.body.body;
2161
+ const last = statements[statements.length - 1];
2162
+ if (last && t.isExpressionStatement(last)) statements[statements.length - 1] = t.expressionStatement(t.callExpression(t.memberExpression(valueMember, t.identifier("push")), [last.expression]));
2163
+ const index = statements.findIndex((s) => t.isIfStatement(s));
2164
+ if (index > -1) {
2165
+ const ifStatement = statements[index];
2166
+ if (t.isBlockStatement(ifStatement.consequent)) {
2167
+ const [, second] = ifStatement.consequent.body;
2168
+ if (second && t.isForOfStatement(second) && t.isBlockStatement(second.body)) {
2169
+ const bodyStatement = second.body.body[0];
2170
+ if (bodyStatement && t.isIfStatement(bodyStatement) && t.isBlockStatement(bodyStatement.consequent) && bodyStatement.consequent.body.length === 1 && t.isExpressionStatement(bodyStatement.consequent.body[0])) bodyStatement.consequent.body[0] = t.expressionStatement(t.callExpression(t.memberExpression(valueMember, t.identifier("push")), [bodyStatement.consequent.body[0].expression]));
2171
+ }
2172
+ }
2173
+ }
2174
+ statements.unshift(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(valueMember, t.identifier("length")), t.numericLiteral(0))));
2175
+ }
2176
+ });
2177
+ return {
2178
+ code: hasPatched ? content : generate$1(ast).code,
2179
+ hasPatched
2180
+ };
2181
+ }
2182
+ //#endregion
2183
+ //#region src/patching/operations/export-context/index.ts
2184
+ function writeFileIfRequired(filePath, code, overwrite, successMessage) {
2185
+ if (!overwrite) return;
2186
+ fs.writeFileSync(filePath, code, { encoding: "utf8" });
2187
+ logger.success(successMessage);
2188
+ }
2189
+ function applyExposeContextPatch(params) {
2190
+ const { rootDir, refProperty, overwrite, majorVersion } = params;
2191
+ const result = {
2192
+ applied: false,
2193
+ files: {}
2194
+ };
2195
+ if (majorVersion === 3) {
2196
+ const processFileRelative = "lib/processTailwindFeatures.js";
2197
+ const processFilePath = path.resolve(rootDir, processFileRelative);
2198
+ if (fs.existsSync(processFilePath)) {
2199
+ const { code, hasPatched } = transformProcessTailwindFeaturesReturnContext(fs.readFileSync(processFilePath, "utf8"));
2200
+ result.files[processFileRelative] = code;
2201
+ if (!hasPatched) {
2202
+ writeFileIfRequired(processFilePath, code, overwrite, "Patched Tailwind CSS processTailwindFeatures to expose runtime context.");
2203
+ result.applied = true;
2204
+ }
2205
+ }
2206
+ const pluginRelative = ["lib/plugin.js", "lib/index.js"].find((candidate) => fs.existsSync(path.resolve(rootDir, candidate)));
2207
+ if (pluginRelative) {
2208
+ const pluginPath = path.resolve(rootDir, pluginRelative);
2209
+ const { code, hasPatched } = transformPostcssPlugin(fs.readFileSync(pluginPath, "utf8"), { refProperty });
2210
+ result.files[pluginRelative] = code;
2211
+ if (!hasPatched) {
2212
+ writeFileIfRequired(pluginPath, code, overwrite, "Patched Tailwind CSS plugin entry to collect runtime contexts.");
2213
+ result.applied = true;
2214
+ }
2215
+ }
2216
+ } else if (majorVersion === 2) {
2217
+ const processFileRelative = "lib/jit/processTailwindFeatures.js";
2218
+ const processFilePath = path.resolve(rootDir, processFileRelative);
2219
+ if (fs.existsSync(processFilePath)) {
2220
+ const { code, hasPatched } = transformProcessTailwindFeaturesReturnContextV2(fs.readFileSync(processFilePath, "utf8"));
2221
+ result.files[processFileRelative] = code;
2222
+ if (!hasPatched) {
2223
+ writeFileIfRequired(processFilePath, code, overwrite, "Patched Tailwind CSS JIT processTailwindFeatures to expose runtime context.");
2224
+ result.applied = true;
2225
+ }
2226
+ }
2227
+ const pluginRelative = "lib/jit/index.js";
2228
+ const pluginPath = path.resolve(rootDir, pluginRelative);
2229
+ if (fs.existsSync(pluginPath)) {
2230
+ const { code, hasPatched } = transformPostcssPluginV2(fs.readFileSync(pluginPath, "utf8"), { refProperty });
2231
+ result.files[pluginRelative] = code;
2232
+ if (!hasPatched) {
2233
+ writeFileIfRequired(pluginPath, code, overwrite, "Patched Tailwind CSS JIT entry to collect runtime contexts.");
2234
+ result.applied = true;
2235
+ }
2236
+ }
2237
+ }
2238
+ return result;
2239
+ }
2240
+ //#endregion
2241
+ //#region src/patching/operations/extend-length-units.ts
2242
+ function updateLengthUnitsArray(content, options) {
2243
+ const { variableName = "lengthUnits", units } = options;
2244
+ const ast = parse$1(content);
2245
+ let arrayRef;
2246
+ let changed = false;
2247
+ traverse(ast, { Identifier(path) {
2248
+ if (path.node.name === variableName && t.isVariableDeclarator(path.parent) && t.isArrayExpression(path.parent.init)) {
2249
+ arrayRef = path.parent.init;
2250
+ const existing = new Set(path.parent.init.elements.map((element) => t.isStringLiteral(element) ? element.value : void 0).filter(Boolean));
2251
+ for (const unit of units) if (!existing.has(unit)) {
2252
+ path.parent.init.elements = path.parent.init.elements.map((element) => {
2253
+ if (t.isStringLiteral(element)) return t.stringLiteral(element.value);
2254
+ return element;
2255
+ });
2256
+ path.parent.init.elements.push(t.stringLiteral(unit));
2257
+ changed = true;
2258
+ }
2259
+ }
2260
+ } });
2261
+ return {
2262
+ ...arrayRef === void 0 ? {} : { arrayRef },
2263
+ changed
2264
+ };
2265
+ }
2266
+ function applyExtendLengthUnitsPatchV3(rootDir, options) {
2267
+ if (!options.enabled) return {
2268
+ changed: false,
2269
+ code: void 0
2270
+ };
2271
+ const opts = {
2272
+ ...options,
2273
+ lengthUnitsFilePath: options.lengthUnitsFilePath ?? "lib/util/dataTypes.js",
2274
+ variableName: options.variableName ?? "lengthUnits"
2275
+ };
2276
+ const dataTypesFilePath = path.resolve(rootDir, opts.lengthUnitsFilePath);
2277
+ if (!fs.existsSync(dataTypesFilePath)) return {
2278
+ changed: false,
2279
+ code: void 0
2280
+ };
2281
+ const content = fs.readFileSync(dataTypesFilePath, "utf8");
2282
+ const { arrayRef, changed } = updateLengthUnitsArray(content, opts);
2283
+ if (!arrayRef || !changed) return {
2284
+ changed: false,
2285
+ code: void 0
2286
+ };
2287
+ const { code } = generate$1(arrayRef, { jsescOption: { quotes: "single" } });
2288
+ if (arrayRef.start != null && arrayRef.end != null) {
2289
+ const nextCode = `${content.slice(0, arrayRef.start)}${code}${content.slice(arrayRef.end)}`;
2290
+ if (opts.overwrite) {
2291
+ const target = opts.destPath ? path.resolve(opts.destPath) : dataTypesFilePath;
2292
+ fs.writeFileSync(target, nextCode, "utf8");
2293
+ logger.success("Patched Tailwind CSS length unit list (v3).");
2294
+ }
2295
+ return {
2296
+ changed: true,
2297
+ code: nextCode
2298
+ };
2299
+ }
2300
+ return {
2301
+ changed: false,
2302
+ code: void 0
2303
+ };
2304
+ }
2305
+ function applyExtendLengthUnitsPatchV4(rootDir, options) {
2306
+ if (!options.enabled) return {
2307
+ files: [],
2308
+ changed: false
2309
+ };
2310
+ const opts = { ...options };
2311
+ const distDir = path.resolve(rootDir, "dist");
2312
+ if (!fs.existsSync(distDir)) return {
2313
+ files: [],
2314
+ changed: false
2315
+ };
2316
+ const chunkNames = fs.readdirSync(distDir).filter((entry) => entry.endsWith(".js") || entry.endsWith(".mjs"));
2317
+ const pattern = /\[\s*["']cm["'],\s*["']mm["'],[\w,"']+\]/;
2318
+ const candidates = chunkNames.map((chunkName) => {
2319
+ const file = path.join(distDir, chunkName);
2320
+ const code = fs.readFileSync(file, "utf8");
2321
+ const match = pattern.exec(code);
2322
+ if (!match) return null;
2323
+ return {
2324
+ file,
2325
+ code,
2326
+ match,
2327
+ hasPatched: false
2328
+ };
2329
+ }).filter((candidate) => candidate !== null);
2330
+ for (const item of candidates) {
2331
+ const { code, file, match } = item;
2332
+ const ast = parse$1(match[0], { sourceType: "unambiguous" });
2333
+ traverse(ast, { ArrayExpression(path) {
2334
+ for (const unit of opts.units) {
2335
+ if (path.node.elements.some((element) => t.isStringLiteral(element) && element.value === unit)) {
2336
+ item.hasPatched = true;
2337
+ return;
2338
+ }
2339
+ path.node.elements.push(t.stringLiteral(unit));
2340
+ }
2341
+ } });
2342
+ if (item.hasPatched) continue;
2343
+ const { code: replacement } = generate$1(ast, { minified: true });
2344
+ const start = match.index ?? 0;
2345
+ item.code = spliceChangesIntoString(code, [{
2346
+ start,
2347
+ end: start + match[0].length,
2348
+ replacement: replacement.endsWith(";") ? replacement.slice(0, -1) : replacement
2349
+ }]);
2350
+ if (opts.overwrite) fs.writeFileSync(file, item.code, "utf8");
2351
+ }
2352
+ if (candidates.some((file) => !file.hasPatched)) logger.success("Patched Tailwind CSS length unit list (v4).");
2353
+ return {
2354
+ changed: candidates.some((file) => !file.hasPatched),
2355
+ files: candidates
2356
+ };
2357
+ }
2358
+ //#endregion
2359
+ //#region src/patching/patch-runner.ts
2360
+ function applyTailwindPatches(context) {
2361
+ const { packageInfo, options, majorVersion } = context;
2362
+ const results = {};
2363
+ if (options.features.exposeContext.enabled && (majorVersion === 2 || majorVersion === 3)) results.exposeContext = applyExposeContextPatch({
2364
+ rootDir: packageInfo.rootPath,
2365
+ refProperty: options.features.exposeContext.refProperty,
2366
+ overwrite: options.overwrite,
2367
+ majorVersion
2368
+ });
2369
+ if (options.features.extendLengthUnits?.enabled) {
2370
+ if (majorVersion === 3) results.extendLengthUnits = applyExtendLengthUnitsPatchV3(packageInfo.rootPath, options.features.extendLengthUnits);
2371
+ else if (majorVersion === 4) results.extendLengthUnits = applyExtendLengthUnitsPatchV4(packageInfo.rootPath, options.features.extendLengthUnits);
2372
+ }
2373
+ return results;
2374
+ }
2375
+ //#endregion
2376
+ //#region src/runtime/process-tailwindcss.ts
2377
+ function createCwdRequire(cwd) {
2378
+ return createRequire(path.join(cwd, "package.json"));
2379
+ }
2380
+ function resolveModuleEntry(id, moduleRequire) {
2381
+ return path.isAbsolute(id) ? id : moduleRequire.resolve(id);
2382
+ }
2383
+ function resolvePackageRootFromEntry(entry) {
2384
+ let current = path.dirname(entry);
2385
+ while (current && current !== path.dirname(current)) {
2386
+ const packageJsonPath = path.join(current, "package.json");
2387
+ if (fs.pathExistsSync(packageJsonPath)) return current;
2388
+ current = path.dirname(current);
2389
+ }
2390
+ }
2391
+ function resolveCacheKey(moduleRequire, entry) {
2392
+ try {
2393
+ return moduleRequire.resolve(entry);
2394
+ } catch {
2395
+ return entry;
2396
+ }
2397
+ }
2398
+ function clearTailwindV3RuntimeState(pluginName, moduleRequire) {
2399
+ try {
2400
+ const root = resolvePackageRootFromEntry(resolveModuleEntry(pluginName, moduleRequire));
2401
+ if (!root) return;
2402
+ const sharedStatePath = path.join(root, "lib/lib/sharedState.js");
2403
+ if (!fs.pathExistsSync(sharedStatePath)) return;
2404
+ const sharedStateKey = resolveCacheKey(moduleRequire, sharedStatePath);
2405
+ const sharedState = moduleRequire.cache[sharedStateKey]?.exports;
2406
+ sharedState?.contextMap?.clear();
2407
+ sharedState?.configContextMap?.clear();
2408
+ sharedState?.contextSourcesMap?.clear();
2409
+ sharedState?.sourceHashMap?.clear();
2410
+ for (const candidate of ["lib/plugin.js", "lib/index.js"]) {
2411
+ const runtimeEntry = path.join(root, candidate);
2412
+ if (!fs.pathExistsSync(runtimeEntry)) continue;
2413
+ const runtimeKey = resolveCacheKey(moduleRequire, runtimeEntry);
2414
+ const runtimeModule = moduleRequire.cache[runtimeKey]?.exports;
2415
+ runtimeModule?.contextRef?.value?.splice(0, runtimeModule.contextRef.value.length);
2416
+ break;
2417
+ }
2418
+ } catch {}
2419
+ }
2420
+ async function resolveConfigPath(options) {
2421
+ if (options.config && path.isAbsolute(options.config)) return options.config;
2422
+ const result = await loadConfig({ cwd: options.cwd });
2423
+ if (!result) throw new Error(`Unable to locate Tailwind CSS config from ${options.cwd}`);
2424
+ return result.filepath;
2425
+ }
2426
+ async function runTailwindBuild(options) {
2427
+ const configPath = await resolveConfigPath(options);
2428
+ const pluginName = options.postcssPlugin ?? (options.majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss");
2429
+ const moduleRequire = createCwdRequire(options.cwd);
2430
+ if (options.majorVersion === 3) clearTailwindV3RuntimeState(pluginName, moduleRequire);
2431
+ if (options.majorVersion === 4) return postcss([moduleRequire(pluginName)({ config: configPath })]).process("@import 'tailwindcss';", { from: void 0 });
2432
+ return postcss([moduleRequire(pluginName)({ config: configPath })]).process("@tailwind base;@tailwind components;@tailwind utilities;", { from: void 0 });
2433
+ }
2434
+ //#endregion
2435
+ //#region src/patching/status.ts
2436
+ function inspectLengthUnitsArray(content, variableName, units) {
2437
+ const ast = parse$1(content);
2438
+ let found = false;
2439
+ let missingUnits = [];
2440
+ traverse(ast, { Identifier(path) {
2441
+ if (path.node.name === variableName && t.isVariableDeclarator(path.parent) && t.isArrayExpression(path.parent.init)) {
2442
+ found = true;
2443
+ const existing = new Set(path.parent.init.elements.map((element) => t.isStringLiteral(element) ? element.value : void 0).filter(Boolean));
2444
+ missingUnits = units.filter((unit) => !existing.has(unit));
2445
+ path.stop();
2446
+ }
2447
+ } });
2448
+ return {
2449
+ found,
2450
+ missingUnits
2451
+ };
2452
+ }
2453
+ function checkExposeContextPatch(context) {
2454
+ const { packageInfo, options, majorVersion } = context;
2455
+ const refProperty = options.features.exposeContext.refProperty;
2456
+ if (!options.features.exposeContext.enabled) return {
2457
+ name: "exposeContext",
2458
+ status: "skipped",
2459
+ reason: "exposeContext feature disabled",
2460
+ files: []
2461
+ };
2462
+ if (majorVersion === 4) return {
2463
+ name: "exposeContext",
2464
+ status: "unsupported",
2465
+ reason: "Context export patch is only required for Tailwind v2/v3",
2466
+ files: []
2467
+ };
2468
+ const checks = [];
2469
+ function inspectFile(relative, transform) {
2470
+ const filePath = path.resolve(packageInfo.rootPath, relative);
2471
+ if (!fs.existsSync(filePath)) {
2472
+ checks.push({
2473
+ relative,
2474
+ exists: false,
2475
+ patched: false
2476
+ });
2477
+ return;
2478
+ }
2479
+ const { hasPatched } = transform(fs.readFileSync(filePath, "utf8"));
2480
+ checks.push({
2481
+ relative,
2482
+ exists: true,
2483
+ patched: hasPatched
2484
+ });
2485
+ }
2486
+ if (majorVersion === 3) {
2487
+ inspectFile("lib/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContext);
2488
+ const pluginRelative = ["lib/plugin.js", "lib/index.js"].find((candidate) => fs.existsSync(path.resolve(packageInfo.rootPath, candidate)));
2489
+ if (pluginRelative) inspectFile(pluginRelative, (content) => transformPostcssPlugin(content, { refProperty }));
2490
+ else checks.push({
2491
+ relative: "lib/plugin.js",
2492
+ exists: false,
2493
+ patched: false
2494
+ });
2495
+ } else {
2496
+ inspectFile("lib/jit/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContextV2);
2497
+ inspectFile("lib/jit/index.js", (content) => transformPostcssPluginV2(content, { refProperty }));
2498
+ }
2499
+ const files = checks.filter((check) => check.exists).map((check) => check.relative);
2500
+ const missingFiles = checks.filter((check) => !check.exists);
2501
+ const unpatchedFiles = checks.filter((check) => check.exists && !check.patched);
2502
+ const reasons = [];
2503
+ if (missingFiles.length) reasons.push(`missing files: ${missingFiles.map((item) => item.relative).join(", ")}`);
2504
+ if (unpatchedFiles.length) reasons.push(`unpatched files: ${unpatchedFiles.map((item) => item.relative).join(", ")}`);
2505
+ return {
2506
+ name: "exposeContext",
2507
+ status: reasons.length ? "not-applied" : "applied",
2508
+ ...reasons.length ? { reason: reasons.join("; ") } : {},
2509
+ files
2510
+ };
2511
+ }
2512
+ function checkExtendLengthUnitsV3(rootDir, options) {
2513
+ const lengthUnitsFilePath = options.lengthUnitsFilePath ?? "lib/util/dataTypes.js";
2514
+ const variableName = options.variableName ?? "lengthUnits";
2515
+ const target = path.resolve(rootDir, lengthUnitsFilePath);
2516
+ const files = fs.existsSync(target) ? [path.relative(rootDir, target)] : [];
2517
+ if (!fs.existsSync(target)) return {
2518
+ name: "extendLengthUnits",
2519
+ status: "not-applied",
2520
+ reason: `missing ${lengthUnitsFilePath}`,
2521
+ files
2522
+ };
2523
+ const { found, missingUnits } = inspectLengthUnitsArray(fs.readFileSync(target, "utf8"), variableName, options.units);
2524
+ if (!found) return {
2525
+ name: "extendLengthUnits",
2526
+ status: "not-applied",
2527
+ reason: `could not locate ${variableName} array in ${lengthUnitsFilePath}`,
2528
+ files
2529
+ };
2530
+ if (missingUnits.length) return {
2531
+ name: "extendLengthUnits",
2532
+ status: "not-applied",
2533
+ reason: `missing units: ${missingUnits.join(", ")}`,
2534
+ files
2535
+ };
2536
+ return {
2537
+ name: "extendLengthUnits",
2538
+ status: "applied",
2539
+ files
2540
+ };
2541
+ }
2542
+ function checkExtendLengthUnitsV4(rootDir, options) {
2543
+ const distDir = path.resolve(rootDir, "dist");
2544
+ if (!fs.existsSync(distDir)) return {
2545
+ name: "extendLengthUnits",
2546
+ status: "not-applied",
2547
+ reason: "dist directory not found for Tailwind v4 package",
2548
+ files: []
2549
+ };
2550
+ const result = applyExtendLengthUnitsPatchV4(rootDir, {
2551
+ ...options,
2552
+ enabled: true,
2553
+ overwrite: false
2554
+ });
2555
+ if (result.files.length === 0) return {
2556
+ name: "extendLengthUnits",
2557
+ status: "not-applied",
2558
+ reason: "no bundle chunks matched the length unit pattern",
2559
+ files: []
2560
+ };
2561
+ const files = result.files.map((file) => path.relative(rootDir, file.file));
2562
+ const pending = result.files.filter((file) => !file.hasPatched);
2563
+ if (pending.length) return {
2564
+ name: "extendLengthUnits",
2565
+ status: "not-applied",
2566
+ reason: `missing units in ${pending.length} bundle${pending.length > 1 ? "s" : ""}`,
2567
+ files: pending.map((file) => path.relative(rootDir, file.file))
2568
+ };
2569
+ return {
2570
+ name: "extendLengthUnits",
2571
+ status: "applied",
2572
+ files
2573
+ };
2574
+ }
2575
+ function checkExtendLengthUnitsPatch(context) {
2576
+ const { packageInfo, options, majorVersion } = context;
2577
+ if (!options.features.extendLengthUnits) return {
2578
+ name: "extendLengthUnits",
2579
+ status: "skipped",
2580
+ reason: "extendLengthUnits feature disabled",
2581
+ files: []
2582
+ };
2583
+ if (majorVersion === 2) return {
2584
+ name: "extendLengthUnits",
2585
+ status: "unsupported",
2586
+ reason: "length unit extension is only applied for Tailwind v3/v4",
2587
+ files: []
2588
+ };
2589
+ if (majorVersion === 3) return checkExtendLengthUnitsV3(packageInfo.rootPath, options.features.extendLengthUnits);
2590
+ return checkExtendLengthUnitsV4(packageInfo.rootPath, options.features.extendLengthUnits);
2591
+ }
2592
+ function getPatchStatusReport(context) {
2593
+ return {
2594
+ package: {
2595
+ name: context.packageInfo.name ?? context.packageInfo.packageJson?.name,
2596
+ version: context.packageInfo.version,
2597
+ root: context.packageInfo.rootPath
2598
+ },
2599
+ majorVersion: context.majorVersion,
2600
+ entries: [checkExposeContextPatch(context), checkExtendLengthUnitsPatch(context)]
2601
+ };
2602
+ }
2603
+ //#endregion
2604
+ //#region src/runtime/collector.ts
2605
+ function resolveTailwindExecutionOptions(normalized, majorVersion) {
2606
+ const base = normalized.tailwind;
2607
+ if (majorVersion === 2 && base.v2) return {
2608
+ cwd: base.v2.cwd ?? base.cwd ?? normalized.projectRoot,
2609
+ config: base.v2.config ?? base.config,
2610
+ postcssPlugin: base.v2.postcssPlugin ?? base.postcssPlugin
2611
+ };
2612
+ if (majorVersion === 3 && base.v3) return {
2613
+ cwd: base.v3.cwd ?? base.cwd ?? normalized.projectRoot,
2614
+ config: base.v3.config ?? base.config,
2615
+ postcssPlugin: base.v3.postcssPlugin ?? base.postcssPlugin
2616
+ };
2617
+ return {
2618
+ cwd: base.cwd ?? normalized.projectRoot,
2619
+ config: base.config,
2620
+ postcssPlugin: base.postcssPlugin
2621
+ };
2622
+ }
2623
+ var BaseCollector = class {
2624
+ constructor(packageInfo, options, majorVersion) {
2625
+ this.packageInfo = packageInfo;
2626
+ this.options = options;
2627
+ this.majorVersion = majorVersion;
2628
+ }
2629
+ async patch() {
2630
+ return applyTailwindPatches({
2631
+ packageInfo: this.packageInfo,
2632
+ options: this.options,
2633
+ majorVersion: this.majorVersion
2634
+ });
2635
+ }
2636
+ async getPatchStatus() {
2637
+ return getPatchStatusReport({
2638
+ packageInfo: this.packageInfo,
2639
+ options: this.options,
2640
+ majorVersion: this.majorVersion
2641
+ });
2642
+ }
2643
+ getContexts() {
2644
+ return loadRuntimeContexts(this.packageInfo, this.majorVersion, this.options.features.exposeContext.refProperty);
2645
+ }
2646
+ };
2647
+ var RuntimeCollector = class extends BaseCollector {
2648
+ inFlightBuild;
2649
+ constructor(packageInfo, options, majorVersion, snapshotFactory) {
2650
+ super(packageInfo, options, majorVersion);
2651
+ this.snapshotFactory = snapshotFactory;
2652
+ }
2653
+ async collectClassSet() {
2654
+ return collectClassesFromContexts(this.getContexts(), this.options.filter);
2655
+ }
2656
+ getPatchSnapshot() {
2657
+ return this.snapshotFactory();
2658
+ }
2659
+ async runTailwindBuildIfNeeded() {
2660
+ if (this.inFlightBuild) return this.inFlightBuild;
2661
+ const executionOptions = resolveTailwindExecutionOptions(this.options, this.majorVersion);
2662
+ const buildOptions = {
2663
+ cwd: executionOptions.cwd,
2664
+ majorVersion: this.majorVersion,
2665
+ ...executionOptions.config === void 0 ? {} : { config: executionOptions.config },
2666
+ ...executionOptions.postcssPlugin === void 0 ? {} : { postcssPlugin: executionOptions.postcssPlugin }
2667
+ };
2668
+ this.inFlightBuild = runTailwindBuild(buildOptions).then(() => void 0);
2669
+ try {
2670
+ await this.inFlightBuild;
2671
+ } finally {
2672
+ this.inFlightBuild = void 0;
2673
+ }
2674
+ }
2675
+ };
2676
+ var TailwindV4Collector = class extends BaseCollector {
2677
+ constructor(packageInfo, options, snapshotFactory) {
2678
+ super(packageInfo, options, 4);
2679
+ this.snapshotFactory = snapshotFactory;
2680
+ }
2681
+ snapshotFactory;
2682
+ async collectClassSet() {
2683
+ return collectClassesFromTailwindV4(this.options);
2684
+ }
2685
+ getPatchSnapshot() {
2686
+ return this.snapshotFactory();
2687
+ }
2688
+ };
2689
+ //#endregion
2690
+ //#region src/api/tailwindcss-patcher.ts
2691
+ function resolveInstalledMajorVersion(version) {
2692
+ if (!version) return;
2693
+ const coerced = coerce(version);
2694
+ if (!coerced) return;
2695
+ const major = coerced.major;
2696
+ if (major === 2 || major === 3 || major === 4) return major;
2697
+ if (major >= 4) return 4;
2698
+ }
2699
+ function validateInstalledVersion(packageVersion, expectedMajor, packageName) {
2700
+ const installedMajor = resolveInstalledMajorVersion(packageVersion);
2701
+ if (installedMajor === void 0) return;
2702
+ if (installedMajor !== expectedMajor) throw new Error(`Configured tailwindcss.version=${expectedMajor}, but resolved package "${packageName}" is version ${packageVersion}. Update the configuration or resolve the correct package.`);
2703
+ }
2704
+ function resolveMajorVersionOrThrow(configuredMajor, packageVersion, packageName) {
2705
+ if (configuredMajor !== void 0) {
2706
+ validateInstalledVersion(packageVersion, configuredMajor, packageName);
2707
+ return configuredMajor;
2708
+ }
2709
+ const installedMajor = resolveInstalledMajorVersion(packageVersion);
2710
+ if (installedMajor !== void 0) return installedMajor;
2711
+ throw new Error(`Unable to infer Tailwind CSS major version from resolved package "${packageName}" (${packageVersion ?? "unknown"}). Set "tailwindcss.version" to 2, 3, or 4 explicitly.`);
2712
+ }
2713
+ function createCollector(packageInfo, options, majorVersion, snapshotFactory) {
2714
+ if (majorVersion === 4) return new TailwindV4Collector(packageInfo, options, snapshotFactory);
2715
+ return new RuntimeCollector(packageInfo, options, majorVersion, snapshotFactory);
2716
+ }
2717
+ function getPackageInfoFromCwd(packageName, cwd) {
2718
+ try {
2719
+ const packageJsonPath = createRequire(path.join(cwd, "package.json")).resolve(`${packageName}/package.json`);
2720
+ const packageJson = fs.readJSONSync(packageJsonPath);
2721
+ return {
2722
+ name: packageName,
2723
+ version: typeof packageJson.version === "string" ? packageJson.version : void 0,
2724
+ rootPath: path.dirname(packageJsonPath),
2725
+ packageJsonPath,
2726
+ packageJson
2727
+ };
2728
+ } catch {
2729
+ return;
2730
+ }
2731
+ }
2732
+ function getTailwindPackageInfo(options) {
2733
+ const cwd = options.tailwind.cwd ?? options.projectRoot;
2734
+ return (options.tailwind.resolve?.paths?.length ? getPackageInfoFromCwd(options.tailwind.packageName, cwd) : void 0) ?? getPackageInfoSync(options.tailwind.packageName, options.tailwind.resolve);
2735
+ }
2736
+ var TailwindcssPatcher = class {
2737
+ options;
2738
+ packageInfo;
2739
+ majorVersion;
2740
+ cacheContext;
2741
+ cacheStore;
2742
+ collector;
2743
+ patchMemo;
2744
+ constructor(options = {}) {
2745
+ this.options = normalizeOptions(options);
2746
+ const packageInfo = getTailwindPackageInfo(this.options);
2747
+ if (!packageInfo) throw new Error(`Unable to locate Tailwind CSS package "${this.options.tailwind.packageName}".`);
2748
+ this.packageInfo = packageInfo;
2749
+ this.majorVersion = resolveMajorVersionOrThrow(this.options.tailwind.versionHint, this.packageInfo.version, this.options.tailwind.packageName);
2750
+ this.cacheContext = createCacheContextDescriptor(this.options, this.packageInfo, this.majorVersion);
2751
+ this.cacheStore = new CacheStore(this.options.cache, this.cacheContext);
2752
+ this.collector = createCollector(this.packageInfo, this.options, this.majorVersion, () => this.createPatchSnapshot());
2753
+ }
2754
+ async patch() {
2755
+ const snapshot = this.collector.getPatchSnapshot();
2756
+ if (this.patchMemo && this.patchMemo.snapshot === snapshot) return this.patchMemo.result;
2757
+ const result = await this.collector.patch();
2758
+ this.patchMemo = {
2759
+ result,
2760
+ snapshot: this.collector.getPatchSnapshot()
2761
+ };
2762
+ return result;
2763
+ }
2764
+ async getPatchStatus() {
2765
+ return this.collector.getPatchStatus();
2766
+ }
2767
+ getContexts() {
2768
+ return this.collector.getContexts();
2769
+ }
2770
+ createPatchSnapshot() {
2771
+ const entries = [];
2772
+ const pushSnapshot = (filePath) => {
2773
+ if (!fs.pathExistsSync(filePath)) {
2774
+ entries.push(`${filePath}:missing`);
2775
+ return;
2776
+ }
2777
+ const stat = fs.statSync(filePath);
2778
+ entries.push(`${filePath}:${stat.size}:${Math.trunc(stat.mtimeMs)}`);
2779
+ };
2780
+ if (this.options.features.exposeContext.enabled && (this.majorVersion === 2 || this.majorVersion === 3)) if (this.majorVersion === 2) {
2781
+ pushSnapshot(path.resolve(this.packageInfo.rootPath, "lib/jit/processTailwindFeatures.js"));
2782
+ pushSnapshot(path.resolve(this.packageInfo.rootPath, "lib/jit/index.js"));
2783
+ } else {
2784
+ pushSnapshot(path.resolve(this.packageInfo.rootPath, "lib/processTailwindFeatures.js"));
2785
+ const pluginPath = ["lib/plugin.js", "lib/index.js"].map((file) => path.resolve(this.packageInfo.rootPath, file)).find((file) => fs.pathExistsSync(file));
2786
+ if (pluginPath) pushSnapshot(pluginPath);
2787
+ }
2788
+ if (this.options.features.extendLengthUnits?.enabled) {
2789
+ if (this.majorVersion === 3) {
2790
+ const target = this.options.features.extendLengthUnits.lengthUnitsFilePath ?? "lib/util/dataTypes.js";
2791
+ pushSnapshot(path.resolve(this.packageInfo.rootPath, target));
2792
+ } else if (this.majorVersion === 4) {
2793
+ const distDir = path.resolve(this.packageInfo.rootPath, "dist");
2794
+ if (fs.pathExistsSync(distDir)) {
2795
+ const chunkNames = fs.readdirSync(distDir).filter((entry) => entry.endsWith(".js") || entry.endsWith(".mjs")).sort();
2796
+ for (const chunkName of chunkNames) pushSnapshot(path.join(distDir, chunkName));
2797
+ } else entries.push(`${distDir}:missing`);
2798
+ }
2799
+ }
2800
+ return entries.join("|");
2801
+ }
2802
+ async collectClassSet() {
2803
+ if (this.majorVersion === 4) return this.collector.collectClassSet();
2804
+ return collectClassesFromContexts(this.getContexts(), this.options.filter);
2805
+ }
2806
+ async runTailwindBuildIfNeeded() {
2807
+ await this.collector.runTailwindBuildIfNeeded?.();
2808
+ }
2809
+ debugCacheRead(meta) {
2810
+ if (meta.hit) {
2811
+ logger.debug(`[cache] hit fingerprint=${meta.fingerprint?.slice(0, 12) ?? "n/a"} schema=${meta.schemaVersion ?? "legacy"} ${meta.details.join("; ")}`);
2812
+ return;
2813
+ }
2814
+ logger.debug(`[cache] miss reason=${meta.reason} fingerprint=${meta.fingerprint?.slice(0, 12) ?? "n/a"} schema=${meta.schemaVersion ?? "legacy"} ${meta.details.join("; ")}`);
2815
+ }
2816
+ async mergeWithCache(set) {
2817
+ if (!this.options.cache.enabled) return set;
2818
+ const { data: existing, meta } = await this.cacheStore.readWithMeta();
2819
+ this.debugCacheRead(meta);
2820
+ if (this.options.cache.strategy === "merge") {
2821
+ for (const value of existing) set.add(value);
2822
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : await this.cacheStore.write(set);
2823
+ if (writeTarget) logger.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
2824
+ } else if (set.size > 0) {
2825
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : await this.cacheStore.write(set);
2826
+ if (writeTarget) logger.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
2827
+ } else return existing;
2828
+ return set;
2829
+ }
2830
+ mergeWithCacheSync(set) {
2831
+ if (!this.options.cache.enabled) return set;
2832
+ const { data: existing, meta } = this.cacheStore.readWithMetaSync();
2833
+ this.debugCacheRead(meta);
2834
+ if (this.options.cache.strategy === "merge") {
2835
+ for (const value of existing) set.add(value);
2836
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : this.cacheStore.writeSync(set);
2837
+ if (writeTarget) logger.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
2838
+ } else if (set.size > 0) {
2839
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : this.cacheStore.writeSync(set);
2840
+ if (writeTarget) logger.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
2841
+ } else return existing;
2842
+ return set;
2843
+ }
2844
+ areSetsEqual(a, b) {
2845
+ if (a.size !== b.size) return false;
2846
+ for (const value of a) if (!b.has(value)) return false;
2847
+ return true;
2848
+ }
2849
+ async getClassSet() {
2850
+ await this.runTailwindBuildIfNeeded();
2851
+ const set = await this.collectClassSet();
2852
+ return this.mergeWithCache(set);
2853
+ }
2854
+ getClassSetSync() {
2855
+ if (this.majorVersion === 4) throw new Error("getClassSetSync is not supported for Tailwind CSS v4 projects. Use getClassSet instead.");
2856
+ const contexts = this.getContexts();
2857
+ const set = collectClassesFromContexts(contexts, this.options.filter);
2858
+ const merged = this.mergeWithCacheSync(set);
2859
+ if (contexts.length === 0 && merged.size === 0) return;
2860
+ return merged;
2861
+ }
2862
+ async extract(options) {
2863
+ const shouldWrite = options?.write ?? this.options.output.enabled;
2864
+ const classSet = await this.getClassSet();
2865
+ const classList = Array.from(classSet);
2866
+ const result = {
2867
+ classList,
2868
+ classSet
2869
+ };
2870
+ if (!shouldWrite || !this.options.output.file) return result;
2871
+ const target = path.resolve(this.options.output.file);
2872
+ await fs.ensureDir(path.dirname(target));
2873
+ if (this.options.output.format === "json") {
2874
+ const spaces = typeof this.options.output.pretty === "number" ? this.options.output.pretty : void 0;
2875
+ await fs.writeJSON(target, classList, { spaces });
2876
+ } else await fs.writeFile(target, `${classList.join("\n")}\n`, "utf8");
2877
+ logger.success(`Tailwind CSS class list saved to ${target.replace(process.cwd(), ".")}`);
2878
+ return {
2879
+ ...result,
2880
+ filename: target
2881
+ };
2882
+ }
2883
+ async clearCache(options) {
2884
+ const result = await this.cacheStore.clear(options);
2885
+ logger.debug(`[cache] clear scope=${result.scope} contexts=${result.contextsRemoved} entries=${result.entriesRemoved} files=${result.filesRemoved}`);
2886
+ return result;
2887
+ }
2888
+ extractValidCandidates = extractValidCandidates;
2889
+ async collectContentTokens(options) {
2890
+ return extractProjectCandidatesWithPositions({
2891
+ cwd: options?.cwd ?? this.options.projectRoot,
2892
+ sources: options?.sources ?? this.options.tailwind.v4?.sources ?? []
2893
+ });
2894
+ }
2895
+ async collectContentTokensByFile(options) {
2896
+ const collectContentOptions = {
2897
+ ...options?.cwd === void 0 ? {} : { cwd: options.cwd },
2898
+ ...options?.sources === void 0 ? {} : { sources: options.sources }
2899
+ };
2900
+ return groupTokensByFile(await this.collectContentTokens(collectContentOptions), {
2901
+ ...options?.key === void 0 ? {} : { key: options.key },
2902
+ ...options?.stripAbsolutePaths === void 0 ? {} : { stripAbsolutePaths: options.stripAbsolutePaths }
2903
+ });
2904
+ }
2905
+ };
2906
+ //#endregion
2907
+ //#region src/commands/migration-report.ts
2908
+ const MIGRATION_REPORT_KIND = "tw-patch-migrate-report";
2909
+ const MIGRATION_REPORT_SCHEMA_VERSION = 1;
2910
+ function assertMigrationReportCompatibility(report, reportFile) {
2911
+ if (report.reportKind !== void 0 && report.reportKind !== "tw-patch-migrate-report") throw new Error(`Unsupported report kind "${report.reportKind}" in ${reportFile}.`);
2912
+ if (report.schemaVersion !== void 0 && (!Number.isInteger(report.schemaVersion) || report.schemaVersion > 1)) throw new Error(`Unsupported report schema version "${String(report.schemaVersion)}" in ${reportFile}. Current supported version is 1.`);
2913
+ }
2914
+ //#endregion
2915
+ //#region src/commands/migration-aggregation.ts
2916
+ function createMigrationAggregationState() {
2917
+ return {
2918
+ scannedFiles: 0,
2919
+ changedFiles: 0,
2920
+ writtenFiles: 0,
2921
+ backupsWritten: 0,
2922
+ unchangedFiles: 0,
2923
+ missingFiles: 0,
2924
+ entries: []
2925
+ };
2926
+ }
2927
+ function collectMigrationExecutionResult(state, result) {
2928
+ if (result.missing) {
2929
+ state.missingFiles += 1;
2930
+ return;
2931
+ }
2932
+ state.scannedFiles += 1;
2933
+ state.entries.push(result.entry);
2934
+ if (result.changed) {
2935
+ state.changedFiles += 1;
2936
+ if (result.wrote) state.writtenFiles += 1;
2937
+ if (result.backupWritten) state.backupsWritten += 1;
2938
+ } else state.unchangedFiles += 1;
2939
+ }
2940
+ function buildMigrationReport(state, context) {
2941
+ const { cwd, dryRun, rollbackOnError, backupDirectory, toolName, toolVersion, generatedAt = (/* @__PURE__ */ new Date()).toISOString() } = context;
2942
+ return {
2943
+ reportKind: MIGRATION_REPORT_KIND,
2944
+ schemaVersion: 1,
2945
+ generatedAt,
2946
+ tool: {
2947
+ name: toolName,
2948
+ version: toolVersion
2949
+ },
2950
+ cwd,
2951
+ dryRun,
2952
+ rollbackOnError,
2953
+ ...backupDirectory ? { backupDirectory } : {},
2954
+ scannedFiles: state.scannedFiles,
2955
+ changedFiles: state.changedFiles,
2956
+ writtenFiles: state.writtenFiles,
2957
+ backupsWritten: state.backupsWritten,
2958
+ unchangedFiles: state.unchangedFiles,
2959
+ missingFiles: state.missingFiles,
2960
+ entries: state.entries
2961
+ };
2962
+ }
2963
+ //#endregion
2964
+ //#region src/commands/migration-source.ts
2965
+ const ROOT_LEGACY_KEYS = [
2966
+ "cwd",
2967
+ "overwrite",
2968
+ "tailwind",
2969
+ "features",
2970
+ "output",
2971
+ "applyPatches"
2972
+ ];
2973
+ function getPropertyKeyName(property) {
2974
+ if (!property.computed && t.isIdentifier(property.key)) return property.key.name;
2975
+ if (t.isStringLiteral(property.key)) return property.key.value;
2976
+ }
2977
+ function findObjectProperty(objectExpression, name) {
2978
+ for (const property of objectExpression.properties) {
2979
+ if (!t.isObjectProperty(property)) continue;
2980
+ if (getPropertyKeyName(property) === name) return property;
2981
+ }
2982
+ }
2983
+ function findObjectExpressionProperty(objectExpression, name) {
2984
+ const property = findObjectProperty(objectExpression, name);
2985
+ if (!property) return;
2986
+ if (t.isObjectExpression(property.value)) return property.value;
2987
+ }
2988
+ function removeObjectProperty(objectExpression, property) {
2989
+ const index = objectExpression.properties.indexOf(property);
2990
+ if (index >= 0) objectExpression.properties.splice(index, 1);
2991
+ }
2992
+ function hasObjectProperty(objectExpression, name) {
2993
+ return findObjectProperty(objectExpression, name) !== void 0;
2994
+ }
2995
+ function keyAsIdentifier(name) {
2996
+ return t.identifier(name);
2997
+ }
2998
+ function mergeObjectProperties(target, source) {
2999
+ let changed = false;
3000
+ for (const sourceProperty of source.properties) {
3001
+ if (t.isSpreadElement(sourceProperty)) {
3002
+ target.properties.push(sourceProperty);
3003
+ changed = true;
3004
+ continue;
3005
+ }
3006
+ const sourceKey = getPropertyKeyName(sourceProperty);
3007
+ if (!sourceKey) {
3008
+ target.properties.push(sourceProperty);
3009
+ changed = true;
3010
+ continue;
3011
+ }
3012
+ if (hasObjectProperty(target, sourceKey)) continue;
3013
+ target.properties.push(sourceProperty);
3014
+ changed = true;
3015
+ }
3016
+ return changed;
3017
+ }
3018
+ function moveProperty(objectExpression, from, to, changes, scope) {
3019
+ const source = findObjectProperty(objectExpression, from);
3020
+ if (!source) return false;
3021
+ const target = findObjectProperty(objectExpression, to);
3022
+ if (!target) {
3023
+ source.key = keyAsIdentifier(to);
3024
+ source.computed = false;
3025
+ source.shorthand = false;
3026
+ changes.add(`${scope}.${from} -> ${scope}.${to}`);
3027
+ return true;
3028
+ }
3029
+ if (t.isObjectExpression(source.value) && t.isObjectExpression(target.value)) {
3030
+ if (mergeObjectProperties(target.value, source.value)) changes.add(`${scope}.${from} merged into ${scope}.${to}`);
3031
+ }
3032
+ removeObjectProperty(objectExpression, source);
3033
+ changes.add(`${scope}.${from} removed (preferred ${scope}.${to})`);
3034
+ return true;
3035
+ }
3036
+ function migrateExtractOptions(extract, changes, scope) {
3037
+ let changed = false;
3038
+ changed = moveProperty(extract, "enabled", "write", changes, scope) || changed;
3039
+ changed = moveProperty(extract, "stripUniversalSelector", "removeUniversalSelector", changes, scope) || changed;
3040
+ return changed;
3041
+ }
3042
+ function migrateTailwindOptions(tailwindcss, changes, scope) {
3043
+ let changed = false;
3044
+ changed = moveProperty(tailwindcss, "package", "packageName", changes, scope) || changed;
3045
+ changed = moveProperty(tailwindcss, "legacy", "v2", changes, scope) || changed;
3046
+ changed = moveProperty(tailwindcss, "classic", "v3", changes, scope) || changed;
3047
+ changed = moveProperty(tailwindcss, "next", "v4", changes, scope) || changed;
3048
+ return changed;
3049
+ }
3050
+ function migrateApplyOptions(apply, changes, scope) {
3051
+ return moveProperty(apply, "exportContext", "exposeContext", changes, scope);
3052
+ }
3053
+ function ensureObjectExpressionProperty(objectExpression, name, changes, scope) {
3054
+ const existing = findObjectProperty(objectExpression, name);
3055
+ if (existing) return t.isObjectExpression(existing.value) ? existing.value : void 0;
3056
+ const value = t.objectExpression([]);
3057
+ objectExpression.properties.push(t.objectProperty(keyAsIdentifier(name), value));
3058
+ changes.add(`${scope}.${name} created`);
3059
+ return value;
3060
+ }
3061
+ function moveOverwriteToApply(objectExpression, changes, scope) {
3062
+ const overwrite = findObjectProperty(objectExpression, "overwrite");
3063
+ if (!overwrite) return false;
3064
+ const apply = ensureObjectExpressionProperty(objectExpression, "apply", changes, scope);
3065
+ if (!apply) return false;
3066
+ if (!hasObjectProperty(apply, "overwrite")) {
3067
+ apply.properties.push(t.objectProperty(keyAsIdentifier("overwrite"), overwrite.value));
3068
+ changes.add(`${scope}.overwrite -> ${scope}.apply.overwrite`);
3069
+ }
3070
+ removeObjectProperty(objectExpression, overwrite);
3071
+ return true;
3072
+ }
3073
+ function hasAnyRootLegacyKeys(objectExpression) {
3074
+ return ROOT_LEGACY_KEYS.some((key) => hasObjectProperty(objectExpression, key));
3075
+ }
3076
+ function migrateOptionObject(objectExpression, scope, changes) {
3077
+ let changed = false;
3078
+ changed = moveProperty(objectExpression, "cwd", "projectRoot", changes, scope) || changed;
3079
+ changed = moveProperty(objectExpression, "tailwind", "tailwindcss", changes, scope) || changed;
3080
+ changed = moveProperty(objectExpression, "features", "apply", changes, scope) || changed;
3081
+ changed = moveProperty(objectExpression, "applyPatches", "apply", changes, scope) || changed;
3082
+ changed = moveProperty(objectExpression, "output", "extract", changes, scope) || changed;
3083
+ changed = moveOverwriteToApply(objectExpression, changes, scope) || changed;
3084
+ const extract = findObjectExpressionProperty(objectExpression, "extract");
3085
+ if (extract) changed = migrateExtractOptions(extract, changes, scope) || changed;
3086
+ const tailwindcss = findObjectExpressionProperty(objectExpression, "tailwindcss");
3087
+ if (tailwindcss) changed = migrateTailwindOptions(tailwindcss, changes, scope) || changed;
3088
+ const apply = findObjectExpressionProperty(objectExpression, "apply");
3089
+ if (apply) changed = migrateApplyOptions(apply, changes, scope) || changed;
3090
+ return changed;
3091
+ }
3092
+ function unwrapExpression(node) {
3093
+ let current = node;
3094
+ while (t.isTSAsExpression(current) || t.isTSSatisfiesExpression(current) || t.isTSTypeAssertion(current) || t.isParenthesizedExpression(current)) current = current.expression;
3095
+ return current;
3096
+ }
3097
+ function resolveObjectExpressionFromExpression(expression) {
3098
+ const unwrapped = unwrapExpression(expression);
3099
+ if (t.isObjectExpression(unwrapped)) return unwrapped;
3100
+ if (t.isCallExpression(unwrapped)) {
3101
+ const [firstArg] = unwrapped.arguments;
3102
+ if (!firstArg || !t.isExpression(firstArg)) return;
3103
+ const firstArgUnwrapped = unwrapExpression(firstArg);
3104
+ if (t.isObjectExpression(firstArgUnwrapped)) return firstArgUnwrapped;
3105
+ }
3106
+ }
3107
+ function resolveObjectExpressionFromProgram(program, name) {
3108
+ for (const statement of program.body) {
3109
+ if (!t.isVariableDeclaration(statement)) continue;
3110
+ for (const declaration of statement.declarations) {
3111
+ if (!t.isIdentifier(declaration.id) || declaration.id.name !== name || !declaration.init) continue;
3112
+ const objectExpression = resolveObjectExpressionFromExpression(declaration.init);
3113
+ if (objectExpression) return objectExpression;
3114
+ }
3115
+ }
3116
+ }
3117
+ function resolveRootConfigObjectExpression(program) {
3118
+ for (const statement of program.body) {
3119
+ if (!t.isExportDefaultDeclaration(statement)) continue;
3120
+ const declaration = statement.declaration;
3121
+ if (t.isIdentifier(declaration)) return resolveObjectExpressionFromProgram(program, declaration.name);
3122
+ const objectExpression = resolveObjectExpressionFromExpression(declaration);
3123
+ if (objectExpression) return objectExpression;
3124
+ }
3125
+ }
3126
+ function migrateConfigSource(source) {
3127
+ const ast = parse(source, {
3128
+ sourceType: "module",
3129
+ plugins: ["typescript", "jsx"]
3130
+ });
3131
+ const root = resolveRootConfigObjectExpression(ast.program);
3132
+ if (!root) return {
3133
+ changed: false,
3134
+ code: source,
3135
+ changes: []
3136
+ };
3137
+ const changes = /* @__PURE__ */ new Set();
3138
+ let changed = false;
3139
+ const registry = findObjectExpressionProperty(root, "registry");
3140
+ if (registry) changed = migrateOptionObject(registry, "registry", changes) || changed;
3141
+ const patch = findObjectExpressionProperty(root, "patch");
3142
+ if (patch) changed = migrateOptionObject(patch, "patch", changes) || changed;
3143
+ if (hasAnyRootLegacyKeys(root)) changed = migrateOptionObject(root, "root", changes) || changed;
3144
+ if (!changed) return {
3145
+ changed: false,
3146
+ code: source,
3147
+ changes: []
3148
+ };
3149
+ const generated = generate(ast, { comments: true }).code;
3150
+ return {
3151
+ changed: true,
3152
+ code: source.endsWith("\n") ? `${generated}\n` : generated,
3153
+ changes: [...changes]
3154
+ };
3155
+ }
3156
+ //#endregion
3157
+ //#region src/commands/migration-target-files.ts
3158
+ const DEFAULT_CONFIG_FILENAMES = [
3159
+ "tailwindcss-patch.config.ts",
3160
+ "tailwindcss-patch.config.js",
3161
+ "tailwindcss-patch.config.mjs",
3162
+ "tailwindcss-patch.config.cjs",
3163
+ "tailwindcss-mangle.config.ts",
3164
+ "tailwindcss-mangle.config.js",
3165
+ "tailwindcss-mangle.config.mjs",
3166
+ "tailwindcss-mangle.config.cjs"
3167
+ ];
3168
+ const DEFAULT_CONFIG_FILENAME_SET = new Set(DEFAULT_CONFIG_FILENAMES);
3169
+ const DEFAULT_WORKSPACE_IGNORED_DIRS = new Set([
3170
+ ".git",
3171
+ ".idea",
3172
+ ".turbo",
3173
+ ".vscode",
3174
+ ".yarn",
3175
+ "coverage",
3176
+ "dist",
3177
+ "node_modules",
3178
+ "tmp"
3179
+ ]);
3180
+ function resolveTargetFiles(cwd, files) {
3181
+ const candidates = files && files.length > 0 ? files : [...DEFAULT_CONFIG_FILENAMES];
3182
+ const resolved = /* @__PURE__ */ new Set();
3183
+ for (const file of candidates) resolved.add(path.resolve(cwd, file));
3184
+ return [...resolved];
3185
+ }
3186
+ async function collectWorkspaceConfigFiles(cwd, maxDepth) {
3187
+ const files = /* @__PURE__ */ new Set();
3188
+ const queue = [{
3189
+ dir: cwd,
3190
+ depth: 0
3191
+ }];
3192
+ while (queue.length > 0) {
3193
+ const current = queue.shift();
3194
+ if (!current) continue;
3195
+ const { dir, depth } = current;
3196
+ let entries;
3197
+ try {
3198
+ entries = await fs.readdir(dir, { withFileTypes: true });
3199
+ } catch {
3200
+ continue;
3201
+ }
3202
+ for (const entry of entries) {
3203
+ const absolutePath = path.resolve(dir, entry.name);
3204
+ if (entry.isFile() && DEFAULT_CONFIG_FILENAME_SET.has(entry.name)) {
3205
+ files.add(absolutePath);
3206
+ continue;
3207
+ }
3208
+ if (!entry.isDirectory()) continue;
3209
+ if (DEFAULT_WORKSPACE_IGNORED_DIRS.has(entry.name)) continue;
3210
+ if (depth >= maxDepth) continue;
3211
+ queue.push({
3212
+ dir: absolutePath,
3213
+ depth: depth + 1
3214
+ });
3215
+ }
3216
+ }
3217
+ return [...files].sort((a, b) => a.localeCompare(b));
3218
+ }
3219
+ function resolveBackupRelativePath(cwd, file) {
3220
+ const relative = path.relative(cwd, file);
3221
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
3222
+ const sanitized = file.replace(/[:/\\]+/g, "_");
3223
+ return path.join("__external__", `${sanitized}.bak`);
3224
+ }
3225
+ return `${relative}.bak`;
3226
+ }
3227
+ function normalizePattern(pattern) {
3228
+ return pattern.replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "");
3229
+ }
3230
+ function globToRegExp(globPattern) {
3231
+ const normalized = normalizePattern(globPattern);
3232
+ let pattern = "";
3233
+ for (let i = 0; i < normalized.length; i += 1) {
3234
+ const char = normalized[i];
3235
+ if (char === "*") {
3236
+ if (normalized[i + 1] === "*") {
3237
+ pattern += ".*";
3238
+ i += 1;
3239
+ } else pattern += "[^/]*";
3240
+ continue;
3241
+ }
3242
+ if (char === "?") {
3243
+ pattern += "[^/]";
3244
+ continue;
3245
+ }
3246
+ if ("\\^$+?.()|{}[]".includes(char)) {
3247
+ pattern += `\\${char}`;
3248
+ continue;
3249
+ }
3250
+ pattern += char;
3251
+ }
3252
+ return new RegExp(`^${pattern}$`);
3253
+ }
3254
+ function toPatternList(patterns) {
3255
+ if (!patterns || patterns.length === 0) return [];
3256
+ return patterns.map((pattern) => pattern.trim()).filter(Boolean).map(globToRegExp);
3257
+ }
3258
+ function normalizeFileForPattern(file, cwd) {
3259
+ const relative = path.relative(cwd, file);
3260
+ if (!relative.startsWith("..") && !path.isAbsolute(relative)) return relative.replace(/\\/g, "/");
3261
+ return file.replace(/\\/g, "/");
3262
+ }
3263
+ function filterTargetFiles(targetFiles, cwd, include, exclude) {
3264
+ const includePatterns = toPatternList(include);
3265
+ const excludePatterns = toPatternList(exclude);
3266
+ if (includePatterns.length === 0 && excludePatterns.length === 0) return targetFiles;
3267
+ return targetFiles.filter((file) => {
3268
+ const normalized = normalizeFileForPattern(file, cwd);
3269
+ if (!(includePatterns.length === 0 || includePatterns.some((pattern) => pattern.test(normalized)))) return false;
3270
+ return !excludePatterns.some((pattern) => pattern.test(normalized));
3271
+ });
3272
+ }
3273
+ //#endregion
3274
+ //#region src/commands/migration-file-executor.ts
3275
+ async function rollbackWrittenEntries(wroteEntries) {
3276
+ let rollbackCount = 0;
3277
+ for (const written of [...wroteEntries].reverse()) try {
3278
+ await fs.writeFile(written.file, written.source, "utf8");
3279
+ written.entry.written = false;
3280
+ written.entry.rolledBack = true;
3281
+ rollbackCount += 1;
3282
+ } catch {}
3283
+ return rollbackCount;
3284
+ }
3285
+ async function executeMigrationFile(options) {
3286
+ const { cwd, file, dryRun, rollbackOnError, backupDirectory, wroteEntries } = options;
3287
+ if (!await fs.pathExists(file)) return {
3288
+ missing: true,
3289
+ changed: false,
3290
+ wrote: false,
3291
+ backupWritten: false
3292
+ };
3293
+ const source = await fs.readFile(file, "utf8");
3294
+ const migrated = migrateConfigSource(source);
3295
+ const entry = {
3296
+ file,
3297
+ changed: migrated.changed,
3298
+ written: false,
3299
+ rolledBack: false,
3300
+ changes: migrated.changes
3301
+ };
3302
+ if (!migrated.changed || dryRun) return {
3303
+ missing: false,
3304
+ changed: migrated.changed,
3305
+ wrote: false,
3306
+ backupWritten: false,
3307
+ entry
3308
+ };
3309
+ let backupWritten = false;
3310
+ try {
3311
+ if (backupDirectory) {
3312
+ const backupRelativePath = resolveBackupRelativePath(cwd, file);
3313
+ const backupFile = path.resolve(backupDirectory, backupRelativePath);
3314
+ await fs.ensureDir(path.dirname(backupFile));
3315
+ await fs.writeFile(backupFile, source, "utf8");
3316
+ entry.backupFile = backupFile;
3317
+ backupWritten = true;
3318
+ }
3319
+ await fs.writeFile(file, migrated.code, "utf8");
3320
+ entry.written = true;
3321
+ wroteEntries.push({
3322
+ file,
3323
+ source,
3324
+ entry
3325
+ });
3326
+ return {
3327
+ missing: false,
3328
+ changed: true,
3329
+ wrote: true,
3330
+ backupWritten,
3331
+ entry
3332
+ };
3333
+ } catch (error) {
3334
+ const rollbackCount = rollbackOnError && wroteEntries.length > 0 ? await rollbackWrittenEntries(wroteEntries) : 0;
3335
+ const reason = error instanceof Error ? error.message : String(error);
3336
+ const rollbackHint = rollbackOnError && rollbackCount > 0 ? ` Rolled back ${rollbackCount} previously written file(s).` : "";
3337
+ throw new Error(`Failed to write migrated config "${file}": ${reason}.${rollbackHint}`);
3338
+ }
3339
+ }
3340
+ async function restoreConfigEntries(entries, dryRun) {
3341
+ let scannedEntries = 0;
3342
+ let restorableEntries = 0;
3343
+ let restoredFiles = 0;
3344
+ let missingBackups = 0;
3345
+ let skippedEntries = 0;
3346
+ const restored = [];
3347
+ for (const entry of entries) {
3348
+ scannedEntries += 1;
3349
+ const targetFile = entry.file ? path.resolve(entry.file) : void 0;
3350
+ const backupFile = entry.backupFile ? path.resolve(entry.backupFile) : void 0;
3351
+ if (!targetFile || !backupFile) {
3352
+ skippedEntries += 1;
3353
+ continue;
3354
+ }
3355
+ restorableEntries += 1;
3356
+ if (!await fs.pathExists(backupFile)) {
3357
+ missingBackups += 1;
3358
+ continue;
3359
+ }
3360
+ if (!dryRun) {
3361
+ const backupContent = await fs.readFile(backupFile, "utf8");
3362
+ await fs.ensureDir(path.dirname(targetFile));
3363
+ await fs.writeFile(targetFile, backupContent, "utf8");
3364
+ }
3365
+ restoredFiles += 1;
3366
+ restored.push(targetFile);
3367
+ }
3368
+ return {
3369
+ scannedEntries,
3370
+ restorableEntries,
3371
+ restoredFiles,
3372
+ missingBackups,
3373
+ skippedEntries,
3374
+ restored
3375
+ };
3376
+ }
3377
+ //#endregion
3378
+ //#region src/commands/migration-report-loader.ts
3379
+ async function loadMigrationReportForRestore(reportFile) {
3380
+ const report = await fs.readJSON(reportFile);
3381
+ assertMigrationReportCompatibility(report, reportFile);
3382
+ return {
3383
+ ...report.reportKind === void 0 ? {} : { reportKind: report.reportKind },
3384
+ ...report.schemaVersion === void 0 ? {} : { schemaVersion: report.schemaVersion },
3385
+ entries: Array.isArray(report.entries) ? report.entries : []
3386
+ };
3387
+ }
3388
+ //#endregion
3389
+ //#region src/commands/migration-target-resolver.ts
3390
+ async function resolveMigrationTargetFiles(options) {
3391
+ const { cwd, files, workspace, maxDepth, include, exclude } = options;
3392
+ const resolvedMaxDepth = maxDepth ?? 6;
3393
+ return filterTargetFiles(files && files.length > 0 ? resolveTargetFiles(cwd, files) : workspace ? await collectWorkspaceConfigFiles(cwd, resolvedMaxDepth) : resolveTargetFiles(cwd), cwd, include, exclude);
3394
+ }
3395
+ //#endregion
3396
+ //#region src/commands/migrate-config.ts
3397
+ async function migrateConfigFiles(options) {
3398
+ const cwd = path.resolve(options.cwd);
3399
+ const dryRun = options.dryRun ?? false;
3400
+ const rollbackOnError = options.rollbackOnError ?? true;
3401
+ const backupDirectory = options.backupDir ? path.resolve(cwd, options.backupDir) : void 0;
3402
+ const targetFiles = await resolveMigrationTargetFiles({
3403
+ cwd,
3404
+ files: options.files,
3405
+ workspace: options.workspace,
3406
+ maxDepth: options.maxDepth,
3407
+ include: options.include,
3408
+ exclude: options.exclude
3409
+ });
3410
+ const aggregation = createMigrationAggregationState();
3411
+ const wroteEntries = [];
3412
+ for (const file of targetFiles) collectMigrationExecutionResult(aggregation, await executeMigrationFile({
3413
+ cwd,
3414
+ file,
3415
+ dryRun,
3416
+ rollbackOnError,
3417
+ wroteEntries,
3418
+ ...backupDirectory ? { backupDirectory } : {}
3419
+ }));
3420
+ return buildMigrationReport(aggregation, {
3421
+ cwd,
3422
+ dryRun,
3423
+ rollbackOnError,
3424
+ ...backupDirectory ? { backupDirectory } : {},
3425
+ toolName: pkgName,
3426
+ toolVersion: pkgVersion
3427
+ });
3428
+ }
3429
+ async function restoreConfigFiles(options) {
3430
+ const cwd = path.resolve(options.cwd);
3431
+ const dryRun = options.dryRun ?? false;
3432
+ const strict = options.strict ?? false;
3433
+ const reportFile = path.resolve(cwd, options.reportFile);
3434
+ const report = await loadMigrationReportForRestore(reportFile);
3435
+ const { scannedEntries, restorableEntries, restoredFiles, missingBackups, skippedEntries, restored } = await restoreConfigEntries(report.entries, dryRun);
3436
+ if (strict && missingBackups > 0) throw new Error(`Restore failed: ${missingBackups} backup file(s) missing in report ${reportFile}.`);
3437
+ return {
3438
+ cwd,
3439
+ reportFile,
3440
+ ...report.reportKind === void 0 ? {} : { reportKind: report.reportKind },
3441
+ ...report.schemaVersion === void 0 ? {} : { reportSchemaVersion: report.schemaVersion },
3442
+ dryRun,
3443
+ strict,
3444
+ scannedEntries,
3445
+ restorableEntries,
3446
+ restoredFiles,
3447
+ missingBackups,
3448
+ skippedEntries,
3449
+ restored
3450
+ };
3451
+ }
3452
+ //#endregion
3453
+ //#region src/commands/types.ts
3454
+ const tailwindcssPatchCommands = [
3455
+ "install",
3456
+ "extract",
3457
+ "tokens",
3458
+ "init",
3459
+ "migrate",
3460
+ "restore",
3461
+ "validate",
3462
+ "status"
3463
+ ];
3464
+ //#endregion
3465
+ //#region src/commands/validate.ts
3466
+ const VALIDATE_EXIT_CODES = {
3467
+ OK: 0,
3468
+ REPORT_INCOMPATIBLE: 21,
3469
+ MISSING_BACKUPS: 22,
3470
+ IO_ERROR: 23,
3471
+ UNKNOWN_ERROR: 24
3472
+ };
3473
+ const VALIDATE_FAILURE_REASONS = [
3474
+ "report-incompatible",
3475
+ "missing-backups",
3476
+ "io-error",
3477
+ "unknown-error"
3478
+ ];
3479
+ const IO_ERROR_CODES = new Set([
3480
+ "ENOENT",
3481
+ "EACCES",
3482
+ "EPERM",
3483
+ "EISDIR",
3484
+ "ENOTDIR",
3485
+ "EMFILE",
3486
+ "ENFILE"
3487
+ ]);
3488
+ function isNodeError(error) {
3489
+ return !!error && typeof error === "object" && ("code" in error || "message" in error);
3490
+ }
3491
+ function classifyValidateError(error) {
3492
+ const message = error instanceof Error ? error.message : String(error);
3493
+ if (message.startsWith("Unsupported report kind") || message.startsWith("Unsupported report schema version")) return {
3494
+ reason: "report-incompatible",
3495
+ exitCode: VALIDATE_EXIT_CODES.REPORT_INCOMPATIBLE,
3496
+ message
3497
+ };
3498
+ if (message.startsWith("Restore failed:")) return {
3499
+ reason: "missing-backups",
3500
+ exitCode: VALIDATE_EXIT_CODES.MISSING_BACKUPS,
3501
+ message
3502
+ };
3503
+ if (isNodeError(error) && typeof error.code === "string" && IO_ERROR_CODES.has(error.code)) return {
3504
+ reason: "io-error",
3505
+ exitCode: VALIDATE_EXIT_CODES.IO_ERROR,
3506
+ message
3507
+ };
3508
+ return {
3509
+ reason: "unknown-error",
3510
+ exitCode: VALIDATE_EXIT_CODES.UNKNOWN_ERROR,
3511
+ message
3512
+ };
3513
+ }
3514
+ var ValidateCommandError = class extends Error {
3515
+ reason;
3516
+ exitCode;
3517
+ constructor(summary, options) {
3518
+ super(summary.message, options);
3519
+ this.name = "ValidateCommandError";
3520
+ this.reason = summary.reason;
3521
+ this.exitCode = summary.exitCode;
3522
+ }
3523
+ };
3524
+ //#endregion
3525
+ export { extractTailwindV4InlineSourceCandidates as C, normalizeOptions as D, loadWorkspaceConfigModule as E, CacheStore as O, loadTailwindV4DesignSystem as S, loadPatchOptionsForWorkspace as T, extractRawCandidates as _, tailwindcssPatchCommands as a, groupTokensByFile as b, MIGRATION_REPORT_KIND as c, getPatchStatusReport as d, runTailwindBuild as f, extractProjectCandidatesWithPositions as g, collectClassesFromTailwindV4 as h, classifyValidateError as i, logger as k, MIGRATION_REPORT_SCHEMA_VERSION as l, collectClassesFromContexts as m, VALIDATE_FAILURE_REASONS as n, migrateConfigFiles as o, loadRuntimeContexts as p, ValidateCommandError as r, restoreConfigFiles as s, VALIDATE_EXIT_CODES as t, TailwindcssPatcher as u, extractRawCandidatesWithPositions as v, resolveValidTailwindV4Candidates as w, compileTailwindV4Source as x, extractValidCandidates as y };