tailwindcss-patch 9.0.0-alpha.5 → 9.0.1

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 (40) 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-BGBMTX9A.js +35 -0
  13. package/dist/index.bundle-ByrTqrr3.mjs +18 -0
  14. package/dist/index.d.mts +68 -67
  15. package/dist/index.d.ts +68 -67
  16. package/dist/index.js +28 -57
  17. package/dist/index.mjs +3 -57
  18. package/dist/validate-B8H-8rWO.js +3487 -0
  19. package/dist/validate-BI8356RT.mjs +3336 -0
  20. package/dist/validate-Bu_rkfQF.d.ts +686 -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/options/legacy.ts +2 -2
  28. package/src/options/normalize.ts +10 -5
  29. package/src/runtime/collector.ts +7 -7
  30. package/src/runtime/process-tailwindcss.ts +33 -17
  31. package/dist/chunk-4BA7N3QJ.mjs +0 -4378
  32. package/dist/chunk-A7IKQTXK.js +0 -4378
  33. package/dist/chunk-OSH52QWA.mjs +0 -10
  34. package/dist/chunk-QQXAOMUH.js +0 -25
  35. package/dist/chunk-YYBY7EM5.mjs +0 -21
  36. package/dist/chunk-ZPLR2UEW.js +0 -7
  37. package/dist/dist-22YCNIJW.js +0 -269
  38. package/dist/dist-7W73GIRD.mjs +0 -269
  39. package/dist/validate-nbmOI2w8.d.mts +0 -677
  40. package/dist/validate-nbmOI2w8.d.ts +0 -677
@@ -0,0 +1,3336 @@
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 * as t from "@babel/types";
13
+ import generate from "@babel/generator";
14
+ import _babelTraverse from "@babel/traverse";
15
+ import { parse, parse as parse$1 } from "@babel/parser";
16
+ import postcss from "postcss";
17
+ import { loadConfig } from "tailwindcss-config";
18
+ //#region package.json
19
+ var version = "9.0.1";
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/extraction/candidate-extractor.ts
1449
+ let nodeImportPromise;
1450
+ let oxideImportPromise;
1451
+ const designSystemPromiseCache = /* @__PURE__ */ new Map();
1452
+ const designSystemCandidateCache = /* @__PURE__ */ new Map();
1453
+ async function importNode() {
1454
+ return import("@tailwindcss/node");
1455
+ }
1456
+ async function importOxide() {
1457
+ return import("@tailwindcss/oxide");
1458
+ }
1459
+ function getNodeModule() {
1460
+ nodeImportPromise ??= importNode();
1461
+ return nodeImportPromise;
1462
+ }
1463
+ function getOxideModule() {
1464
+ oxideImportPromise ??= importOxide();
1465
+ return oxideImportPromise;
1466
+ }
1467
+ function createDesignSystemCacheKey(css, bases) {
1468
+ return JSON.stringify({
1469
+ css,
1470
+ bases: Array.from(new Set(bases.filter(Boolean)))
1471
+ });
1472
+ }
1473
+ async function loadDesignSystem(css, bases) {
1474
+ const uniqueBases = Array.from(new Set(bases.filter(Boolean)));
1475
+ if (uniqueBases.length === 0) throw new Error("No base directories provided for Tailwind CSS design system.");
1476
+ const cacheKey = createDesignSystemCacheKey(css, uniqueBases);
1477
+ const cached = designSystemPromiseCache.get(cacheKey);
1478
+ if (cached) return cached;
1479
+ const promise = (async () => {
1480
+ const { __unstable__loadDesignSystem } = await getNodeModule();
1481
+ let lastError;
1482
+ for (const base of uniqueBases) try {
1483
+ return await __unstable__loadDesignSystem(css, { base });
1484
+ } catch (error) {
1485
+ lastError = error;
1486
+ }
1487
+ if (lastError instanceof Error) throw lastError;
1488
+ throw new Error("Failed to load Tailwind CSS design system.");
1489
+ })();
1490
+ designSystemPromiseCache.set(cacheKey, promise);
1491
+ promise.catch(() => {
1492
+ if (designSystemPromiseCache.get(cacheKey) === promise) {
1493
+ designSystemPromiseCache.delete(cacheKey);
1494
+ designSystemCandidateCache.delete(cacheKey);
1495
+ }
1496
+ });
1497
+ return promise;
1498
+ }
1499
+ async function extractRawCandidatesWithPositions(content, extension = "html") {
1500
+ const { Scanner } = await getOxideModule();
1501
+ return new Scanner({}).getCandidatesWithPositions({
1502
+ content,
1503
+ extension
1504
+ }).map(({ candidate, position }) => ({
1505
+ rawCandidate: candidate,
1506
+ start: position,
1507
+ end: position + candidate.length
1508
+ }));
1509
+ }
1510
+ async function extractRawCandidates(sources) {
1511
+ const { Scanner } = await getOxideModule();
1512
+ return new Scanner(sources === void 0 ? {} : { sources }).scan();
1513
+ }
1514
+ async function extractValidCandidates(options) {
1515
+ const providedOptions = options ?? {};
1516
+ const defaultCwd = providedOptions.cwd ?? process.cwd();
1517
+ const base = providedOptions.base ?? defaultCwd;
1518
+ const baseFallbacks = providedOptions.baseFallbacks ?? [];
1519
+ const css = providedOptions.css ?? "@import \"tailwindcss\";";
1520
+ const sources = (providedOptions.sources ?? [{
1521
+ base: defaultCwd,
1522
+ pattern: "**/*",
1523
+ negated: false
1524
+ }]).map((source) => ({
1525
+ base: source.base ?? defaultCwd,
1526
+ pattern: source.pattern,
1527
+ negated: source.negated
1528
+ }));
1529
+ const designSystemKey = createDesignSystemCacheKey(css, [base, ...baseFallbacks]);
1530
+ const designSystem = await loadDesignSystem(css, [base, ...baseFallbacks]);
1531
+ const candidateCache = designSystemCandidateCache.get(designSystemKey) ?? /* @__PURE__ */ new Map();
1532
+ designSystemCandidateCache.set(designSystemKey, candidateCache);
1533
+ const candidates = await extractRawCandidates(sources);
1534
+ const validCandidates = [];
1535
+ const uncachedCandidates = [];
1536
+ for (const rawCandidate of candidates) {
1537
+ const cached = candidateCache.get(rawCandidate);
1538
+ if (cached === true) {
1539
+ validCandidates.push(rawCandidate);
1540
+ continue;
1541
+ }
1542
+ if (cached === false) continue;
1543
+ if (designSystem.parseCandidate(rawCandidate).length > 0) {
1544
+ uncachedCandidates.push(rawCandidate);
1545
+ continue;
1546
+ }
1547
+ candidateCache.set(rawCandidate, false);
1548
+ }
1549
+ if (uncachedCandidates.length === 0) return validCandidates;
1550
+ const cssByCandidate = designSystem.candidatesToCss(uncachedCandidates);
1551
+ for (let index = 0; index < uncachedCandidates.length; index++) {
1552
+ const candidate = uncachedCandidates[index];
1553
+ if (candidate === void 0) continue;
1554
+ const candidateCss = cssByCandidate[index];
1555
+ const isValid = typeof candidateCss === "string" && candidateCss.trim().length > 0;
1556
+ candidateCache.set(candidate, isValid);
1557
+ if (!isValid) continue;
1558
+ validCandidates.push(candidate);
1559
+ }
1560
+ return validCandidates;
1561
+ }
1562
+ function normalizeSources(sources, cwd) {
1563
+ return (sources?.length ? sources : [{
1564
+ base: cwd,
1565
+ pattern: "**/*",
1566
+ negated: false
1567
+ }]).map((source) => ({
1568
+ base: source.base ?? cwd,
1569
+ pattern: source.pattern,
1570
+ negated: source.negated
1571
+ }));
1572
+ }
1573
+ function buildLineOffsets(content) {
1574
+ const offsets = [0];
1575
+ for (let i = 0; i < content.length; i++) if (content[i] === "\n") offsets.push(i + 1);
1576
+ if (offsets[offsets.length - 1] !== content.length) offsets.push(content.length);
1577
+ return offsets;
1578
+ }
1579
+ function resolveLineMeta(content, offsets, index) {
1580
+ let low = 0;
1581
+ let high = offsets.length - 1;
1582
+ while (low <= high) {
1583
+ const mid = Math.floor((low + high) / 2);
1584
+ const start = offsets[mid];
1585
+ if (start === void 0) break;
1586
+ const nextStart = offsets[mid + 1] ?? content.length;
1587
+ if (index < start) {
1588
+ high = mid - 1;
1589
+ continue;
1590
+ }
1591
+ if (index >= nextStart) {
1592
+ low = mid + 1;
1593
+ continue;
1594
+ }
1595
+ const line = mid + 1;
1596
+ const column = index - start + 1;
1597
+ const lineEnd = content.indexOf("\n", start);
1598
+ return {
1599
+ line,
1600
+ column,
1601
+ lineText: content.slice(start, lineEnd === -1 ? content.length : lineEnd)
1602
+ };
1603
+ }
1604
+ const lastStart = offsets[offsets.length - 2] ?? 0;
1605
+ return {
1606
+ line: offsets.length - 1,
1607
+ column: index - lastStart + 1,
1608
+ lineText: content.slice(lastStart)
1609
+ };
1610
+ }
1611
+ function toExtension(filename) {
1612
+ return path.extname(filename).replace(/^\./, "") || "txt";
1613
+ }
1614
+ function toRelativeFile(cwd, filename) {
1615
+ const relative = path.relative(cwd, filename);
1616
+ return relative === "" ? path.basename(filename) : relative;
1617
+ }
1618
+ async function extractProjectCandidatesWithPositions(options) {
1619
+ const cwd = options?.cwd ? path.resolve(options.cwd) : process.cwd();
1620
+ const normalizedSources = normalizeSources(options?.sources, cwd);
1621
+ const { Scanner } = await getOxideModule();
1622
+ const scanner = new Scanner({ sources: normalizedSources });
1623
+ const files = scanner.files ?? [];
1624
+ const entries = [];
1625
+ const skipped = [];
1626
+ for (const file of files) {
1627
+ let content;
1628
+ try {
1629
+ content = await promises.readFile(file, "utf8");
1630
+ } catch (error) {
1631
+ skipped.push({
1632
+ file,
1633
+ reason: error instanceof Error ? error.message : "Unknown error"
1634
+ });
1635
+ continue;
1636
+ }
1637
+ const extension = toExtension(file);
1638
+ const matches = scanner.getCandidatesWithPositions({
1639
+ file,
1640
+ content,
1641
+ extension
1642
+ });
1643
+ if (!matches.length) continue;
1644
+ const offsets = buildLineOffsets(content);
1645
+ const relativeFile = toRelativeFile(cwd, file);
1646
+ for (const match of matches) {
1647
+ const info = resolveLineMeta(content, offsets, match.position);
1648
+ entries.push({
1649
+ rawCandidate: match.candidate,
1650
+ file,
1651
+ relativeFile,
1652
+ extension,
1653
+ start: match.position,
1654
+ end: match.position + match.candidate.length,
1655
+ length: match.candidate.length,
1656
+ line: info.line,
1657
+ column: info.column,
1658
+ lineText: info.lineText
1659
+ });
1660
+ }
1661
+ }
1662
+ return {
1663
+ entries,
1664
+ filesScanned: files.length,
1665
+ skippedFiles: skipped,
1666
+ sources: normalizedSources
1667
+ };
1668
+ }
1669
+ function groupTokensByFile(report, options) {
1670
+ const key = options?.key ?? "relative";
1671
+ const stripAbsolute = options?.stripAbsolutePaths ?? key !== "absolute";
1672
+ return report.entries.reduce((acc, entry) => {
1673
+ const bucketKey = key === "absolute" ? entry.file : entry.relativeFile;
1674
+ const bucket = acc[bucketKey] ?? (acc[bucketKey] = []);
1675
+ const value = stripAbsolute ? {
1676
+ ...entry,
1677
+ file: entry.relativeFile
1678
+ } : entry;
1679
+ bucket.push(value);
1680
+ return acc;
1681
+ }, {});
1682
+ }
1683
+ //#endregion
1684
+ //#region src/utils.ts
1685
+ function isObject(val) {
1686
+ return val !== null && typeof val === "object" && Array.isArray(val) === false;
1687
+ }
1688
+ /**
1689
+ * Apply the changes to the string such that a change in the length
1690
+ * of the string does not break the indexes of the subsequent changes.
1691
+ */
1692
+ function spliceChangesIntoString(str, changes) {
1693
+ const firstChange = changes[0];
1694
+ if (!firstChange) return str;
1695
+ changes.sort((a, b) => {
1696
+ return a.end - b.end || a.start - b.start;
1697
+ });
1698
+ let result = "";
1699
+ let previous = firstChange;
1700
+ result += str.slice(0, previous.start);
1701
+ result += previous.replacement;
1702
+ for (let i = 1; i < changes.length; ++i) {
1703
+ const change = changes[i];
1704
+ if (!change) continue;
1705
+ result += str.slice(previous.end, change.start);
1706
+ result += change.replacement;
1707
+ previous = change;
1708
+ }
1709
+ result += str.slice(previous.end);
1710
+ return result;
1711
+ }
1712
+ //#endregion
1713
+ //#region src/runtime/class-collector.ts
1714
+ function collectRuntimeCandidateKeys(context) {
1715
+ const candidateRuleCache = context.candidateRuleCache;
1716
+ if (candidateRuleCache instanceof Map && candidateRuleCache.size > 0) return candidateRuleCache.keys();
1717
+ return context.classCache.keys();
1718
+ }
1719
+ function collectClassesFromContexts(contexts, filter) {
1720
+ const set = /* @__PURE__ */ new Set();
1721
+ for (const context of contexts) {
1722
+ if (!isObject(context) || !context.classCache) continue;
1723
+ for (const key of collectRuntimeCandidateKeys(context)) {
1724
+ const className = key.toString();
1725
+ if (filter(className)) set.add(className);
1726
+ }
1727
+ }
1728
+ return set;
1729
+ }
1730
+ async function collectClassesFromTailwindV4(options) {
1731
+ const set = /* @__PURE__ */ new Set();
1732
+ const v4Options = options.tailwind.v4;
1733
+ if (!v4Options) return set;
1734
+ const toAbsolute = (value) => {
1735
+ if (!value) return;
1736
+ return path.isAbsolute(value) ? value : path.resolve(options.projectRoot, value);
1737
+ };
1738
+ const resolvedConfiguredBase = toAbsolute(v4Options.configuredBase);
1739
+ const resolvedDefaultBase = toAbsolute(v4Options.base) ?? process.cwd();
1740
+ const resolveSources = (base) => {
1741
+ if (!v4Options.sources?.length) return;
1742
+ return v4Options.sources.map((source) => ({
1743
+ base: source.base ?? base,
1744
+ pattern: source.pattern,
1745
+ negated: source.negated
1746
+ }));
1747
+ };
1748
+ if (v4Options.cssEntries.length > 0) for (const entry of v4Options.cssEntries) {
1749
+ const filePath = path.isAbsolute(entry) ? entry : path.resolve(options.projectRoot, entry);
1750
+ if (!await fs.pathExists(filePath)) continue;
1751
+ const css = await fs.readFile(filePath, "utf8");
1752
+ const entryDir = path.dirname(filePath);
1753
+ const designSystemBases = resolvedConfiguredBase && resolvedConfiguredBase !== entryDir ? [entryDir, resolvedConfiguredBase] : [entryDir];
1754
+ const sources = resolveSources(resolvedConfiguredBase ?? entryDir);
1755
+ const firstBase = designSystemBases[0] ?? entryDir;
1756
+ const candidates = await extractValidCandidates({
1757
+ cwd: options.projectRoot,
1758
+ base: firstBase,
1759
+ baseFallbacks: designSystemBases.slice(1),
1760
+ css,
1761
+ ...sources === void 0 ? {} : { sources }
1762
+ });
1763
+ for (const candidate of candidates) if (options.filter(candidate)) set.add(candidate);
1764
+ }
1765
+ else {
1766
+ const baseForCss = resolvedConfiguredBase ?? resolvedDefaultBase;
1767
+ const sources = resolveSources(baseForCss);
1768
+ const candidates = await extractValidCandidates({
1769
+ cwd: options.projectRoot,
1770
+ base: baseForCss,
1771
+ ...v4Options.css === void 0 ? {} : { css: v4Options.css },
1772
+ ...sources === void 0 ? {} : { sources }
1773
+ });
1774
+ for (const candidate of candidates) if (options.filter(candidate)) set.add(candidate);
1775
+ }
1776
+ return set;
1777
+ }
1778
+ //#endregion
1779
+ //#region src/runtime/context-registry.ts
1780
+ const require = createRequire(import.meta.url);
1781
+ function resolveRuntimeEntry(packageInfo, majorVersion) {
1782
+ const root = packageInfo.rootPath;
1783
+ if (majorVersion === 2) {
1784
+ const jitIndex = path.join(root, "lib/jit/index.js");
1785
+ if (fs.existsSync(jitIndex)) return jitIndex;
1786
+ } else if (majorVersion === 3) {
1787
+ const plugin = path.join(root, "lib/plugin.js");
1788
+ const index = path.join(root, "lib/index.js");
1789
+ if (fs.existsSync(plugin)) return plugin;
1790
+ if (fs.existsSync(index)) return index;
1791
+ }
1792
+ }
1793
+ function loadRuntimeContexts(packageInfo, majorVersion, refProperty) {
1794
+ if (majorVersion === 4) return [];
1795
+ const entry = resolveRuntimeEntry(packageInfo, majorVersion);
1796
+ if (!entry) return [];
1797
+ const moduleExports = require(entry);
1798
+ if (!moduleExports) return [];
1799
+ const ref = moduleExports[refProperty];
1800
+ if (!ref) return [];
1801
+ if (Array.isArray(ref)) return ref;
1802
+ if (typeof ref === "object" && Array.isArray(ref.value)) return ref.value;
1803
+ return [];
1804
+ }
1805
+ //#endregion
1806
+ //#region src/babel/index.ts
1807
+ function _interopDefaultCompat(e) {
1808
+ return e && typeof e === "object" && "default" in e ? e.default : e;
1809
+ }
1810
+ const generate$1 = _interopDefaultCompat(generate);
1811
+ const traverse = _interopDefaultCompat(_babelTraverse);
1812
+ //#endregion
1813
+ //#region src/patching/operations/export-context/postcss-v2.ts
1814
+ const IDENTIFIER_RE$1 = /^[A-Z_$][\w$]*$/i;
1815
+ function toIdentifierName$1(property) {
1816
+ if (!property) return "contextRef";
1817
+ const sanitized = property.replace(/[^\w$]/gu, "_");
1818
+ if (/^\d/.test(sanitized)) return `_${sanitized}`;
1819
+ return sanitized || "contextRef";
1820
+ }
1821
+ function createExportsMember(property) {
1822
+ if (IDENTIFIER_RE$1.test(property)) return t.memberExpression(t.identifier("exports"), t.identifier(property));
1823
+ return t.memberExpression(t.identifier("exports"), t.stringLiteral(property), true);
1824
+ }
1825
+ function transformProcessTailwindFeaturesReturnContextV2(content) {
1826
+ const ast = parse$1(content, { sourceType: "unambiguous" });
1827
+ let hasPatched = false;
1828
+ traverse(ast, { FunctionDeclaration(path) {
1829
+ const node = path.node;
1830
+ if (node.id?.name !== "processTailwindFeatures" || node.body.body.length !== 1 || !t.isReturnStatement(node.body.body[0])) return;
1831
+ const returnStatement = node.body.body[0];
1832
+ if (!t.isFunctionExpression(returnStatement.argument)) return;
1833
+ const body = returnStatement.argument.body.body;
1834
+ const lastStatement = body[body.length - 1];
1835
+ const alreadyReturnsContext = Boolean(t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context");
1836
+ hasPatched = alreadyReturnsContext;
1837
+ if (!alreadyReturnsContext) body.push(t.returnStatement(t.identifier("context")));
1838
+ } });
1839
+ return {
1840
+ code: hasPatched ? content : generate$1(ast).code,
1841
+ hasPatched
1842
+ };
1843
+ }
1844
+ function transformPostcssPluginV2(content, options) {
1845
+ const refIdentifier = t.identifier(toIdentifierName$1(options.refProperty));
1846
+ const exportMember = createExportsMember(options.refProperty);
1847
+ const valueMember = t.memberExpression(refIdentifier, t.identifier("value"));
1848
+ const ast = parse$1(content);
1849
+ let hasPatched = false;
1850
+ traverse(ast, {
1851
+ Program(path) {
1852
+ const program = path.node;
1853
+ const index = program.body.findIndex((statement) => {
1854
+ return t.isFunctionDeclaration(statement) && statement.id?.name === "_default";
1855
+ });
1856
+ if (index === -1) return;
1857
+ const previous = program.body[index - 1];
1858
+ const beforePrevious = program.body[index - 2];
1859
+ const alreadyHasVariable = Boolean(previous && t.isVariableDeclaration(previous) && previous.declarations.length === 1 && (() => {
1860
+ const declaration = previous.declarations[0];
1861
+ return Boolean(declaration && t.isIdentifier(declaration.id) && declaration.id.name === refIdentifier.name);
1862
+ })());
1863
+ 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);
1864
+ hasPatched = alreadyHasVariable && alreadyAssignsExports;
1865
+ 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)));
1866
+ },
1867
+ FunctionDeclaration(path) {
1868
+ if (hasPatched) return;
1869
+ const fn = path.node;
1870
+ if (fn.id?.name !== "_default") return;
1871
+ if (fn.body.body.length !== 1 || !t.isReturnStatement(fn.body.body[0])) return;
1872
+ const returnStatement = fn.body.body[0];
1873
+ if (!t.isCallExpression(returnStatement.argument) || !t.isMemberExpression(returnStatement.argument.callee) || !t.isArrayExpression(returnStatement.argument.callee.object)) return;
1874
+ const fnExpression = returnStatement.argument.callee.object.elements[1];
1875
+ if (!fnExpression || !t.isFunctionExpression(fnExpression)) return;
1876
+ const statements = fnExpression.body.body;
1877
+ if (t.isExpressionStatement(statements[0]) && t.isAssignmentExpression(statements[0].expression) && t.isNumericLiteral(statements[0].expression.right)) {
1878
+ hasPatched = true;
1879
+ return;
1880
+ }
1881
+ const lastStatement = statements[statements.length - 1];
1882
+ if (lastStatement && t.isExpressionStatement(lastStatement)) statements[statements.length - 1] = t.expressionStatement(t.callExpression(t.memberExpression(valueMember, t.identifier("push")), [lastStatement.expression]));
1883
+ const index = statements.findIndex((statement) => t.isIfStatement(statement));
1884
+ if (index > -1) {
1885
+ const ifStatement = statements[index];
1886
+ if (t.isBlockStatement(ifStatement.consequent) && ifStatement.consequent.body[1] && t.isForOfStatement(ifStatement.consequent.body[1])) {
1887
+ const forOf = ifStatement.consequent.body[1];
1888
+ if (t.isBlockStatement(forOf.body) && forOf.body.body.length === 1) {
1889
+ const nestedIf = forOf.body.body[0];
1890
+ 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]));
1891
+ }
1892
+ }
1893
+ }
1894
+ statements.unshift(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(valueMember, t.identifier("length")), t.numericLiteral(0))));
1895
+ }
1896
+ });
1897
+ return {
1898
+ code: hasPatched ? content : generate$1(ast).code,
1899
+ hasPatched
1900
+ };
1901
+ }
1902
+ //#endregion
1903
+ //#region src/patching/operations/export-context/postcss-v3.ts
1904
+ const IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
1905
+ function toIdentifierName(property) {
1906
+ if (!property) return "contextRef";
1907
+ const sanitized = property.replace(/[^\w$]/gu, "_");
1908
+ if (/^\d/.test(sanitized)) return `_${sanitized}`;
1909
+ return sanitized || "contextRef";
1910
+ }
1911
+ function createModuleExportsMember(property) {
1912
+ const object = t.memberExpression(t.identifier("module"), t.identifier("exports"));
1913
+ if (IDENTIFIER_RE.test(property)) return t.memberExpression(object, t.identifier(property));
1914
+ return t.memberExpression(object, t.stringLiteral(property), true);
1915
+ }
1916
+ function transformProcessTailwindFeaturesReturnContext(content) {
1917
+ const ast = parse$1(content);
1918
+ let hasPatched = false;
1919
+ traverse(ast, { FunctionDeclaration(path) {
1920
+ const node = path.node;
1921
+ if (node.id?.name !== "processTailwindFeatures" || node.body.body.length !== 1) return;
1922
+ const [returnStatement] = node.body.body;
1923
+ if (!t.isReturnStatement(returnStatement) || !t.isFunctionExpression(returnStatement.argument)) return;
1924
+ const body = returnStatement.argument.body.body;
1925
+ const lastStatement = body[body.length - 1];
1926
+ const alreadyReturnsContext = Boolean(t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context");
1927
+ hasPatched = alreadyReturnsContext;
1928
+ if (!alreadyReturnsContext) body.push(t.returnStatement(t.identifier("context")));
1929
+ } });
1930
+ return {
1931
+ code: hasPatched ? content : generate$1(ast).code,
1932
+ hasPatched
1933
+ };
1934
+ }
1935
+ function transformPostcssPlugin(content, { refProperty }) {
1936
+ const ast = parse$1(content);
1937
+ const refIdentifier = t.identifier(toIdentifierName(refProperty));
1938
+ const moduleExportsMember = createModuleExportsMember(refProperty);
1939
+ const valueMember = t.memberExpression(refIdentifier, t.identifier("value"));
1940
+ let hasPatched = false;
1941
+ traverse(ast, {
1942
+ Program(path) {
1943
+ const program = path.node;
1944
+ const index = program.body.findIndex((statement) => {
1945
+ return t.isExpressionStatement(statement) && t.isAssignmentExpression(statement.expression) && t.isMemberExpression(statement.expression.left) && t.isFunctionExpression(statement.expression.right) && statement.expression.right.id?.name === "tailwindcss";
1946
+ });
1947
+ if (index === -1) return;
1948
+ const previousStatement = program.body[index - 1];
1949
+ const lastStatement = program.body[program.body.length - 1];
1950
+ const alreadyHasVariable = Boolean(previousStatement && t.isVariableDeclaration(previousStatement) && previousStatement.declarations.length === 1 && (() => {
1951
+ const declaration = previousStatement.declarations[0];
1952
+ return Boolean(declaration && t.isIdentifier(declaration.id) && declaration.id.name === refIdentifier.name);
1953
+ })());
1954
+ 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);
1955
+ hasPatched = alreadyHasVariable && alreadyAssignsModuleExports;
1956
+ if (!alreadyHasVariable) program.body.splice(index, 0, t.variableDeclaration("const", [t.variableDeclarator(refIdentifier, t.objectExpression([t.objectProperty(t.identifier("value"), t.arrayExpression())]))]));
1957
+ if (!alreadyAssignsModuleExports) program.body.push(t.expressionStatement(t.assignmentExpression("=", moduleExportsMember, refIdentifier)));
1958
+ },
1959
+ FunctionExpression(path) {
1960
+ if (hasPatched) return;
1961
+ const fn = path.node;
1962
+ if (fn.id?.name !== "tailwindcss" || fn.body.body.length !== 1) return;
1963
+ const [returnStatement] = fn.body.body;
1964
+ if (!returnStatement || !t.isReturnStatement(returnStatement) || !t.isObjectExpression(returnStatement.argument)) return;
1965
+ const properties = returnStatement.argument.properties;
1966
+ if (properties.length !== 2) return;
1967
+ const pluginsProperty = properties.find((prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "plugins");
1968
+ if (!pluginsProperty || !t.isObjectProperty(pluginsProperty) || !t.isCallExpression(pluginsProperty.value) || !t.isMemberExpression(pluginsProperty.value.callee) || !t.isArrayExpression(pluginsProperty.value.callee.object)) return;
1969
+ const targetPlugin = pluginsProperty.value.callee.object.elements[1];
1970
+ if (!targetPlugin || !t.isFunctionExpression(targetPlugin)) return;
1971
+ const statements = targetPlugin.body.body;
1972
+ const last = statements[statements.length - 1];
1973
+ if (last && t.isExpressionStatement(last)) statements[statements.length - 1] = t.expressionStatement(t.callExpression(t.memberExpression(valueMember, t.identifier("push")), [last.expression]));
1974
+ const index = statements.findIndex((s) => t.isIfStatement(s));
1975
+ if (index > -1) {
1976
+ const ifStatement = statements[index];
1977
+ if (t.isBlockStatement(ifStatement.consequent)) {
1978
+ const [, second] = ifStatement.consequent.body;
1979
+ if (second && t.isForOfStatement(second) && t.isBlockStatement(second.body)) {
1980
+ const bodyStatement = second.body.body[0];
1981
+ 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]));
1982
+ }
1983
+ }
1984
+ }
1985
+ statements.unshift(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(valueMember, t.identifier("length")), t.numericLiteral(0))));
1986
+ }
1987
+ });
1988
+ return {
1989
+ code: hasPatched ? content : generate$1(ast).code,
1990
+ hasPatched
1991
+ };
1992
+ }
1993
+ //#endregion
1994
+ //#region src/patching/operations/export-context/index.ts
1995
+ function writeFileIfRequired(filePath, code, overwrite, successMessage) {
1996
+ if (!overwrite) return;
1997
+ fs.writeFileSync(filePath, code, { encoding: "utf8" });
1998
+ logger.success(successMessage);
1999
+ }
2000
+ function applyExposeContextPatch(params) {
2001
+ const { rootDir, refProperty, overwrite, majorVersion } = params;
2002
+ const result = {
2003
+ applied: false,
2004
+ files: {}
2005
+ };
2006
+ if (majorVersion === 3) {
2007
+ const processFileRelative = "lib/processTailwindFeatures.js";
2008
+ const processFilePath = path.resolve(rootDir, processFileRelative);
2009
+ if (fs.existsSync(processFilePath)) {
2010
+ const { code, hasPatched } = transformProcessTailwindFeaturesReturnContext(fs.readFileSync(processFilePath, "utf8"));
2011
+ result.files[processFileRelative] = code;
2012
+ if (!hasPatched) {
2013
+ writeFileIfRequired(processFilePath, code, overwrite, "Patched Tailwind CSS processTailwindFeatures to expose runtime context.");
2014
+ result.applied = true;
2015
+ }
2016
+ }
2017
+ const pluginRelative = ["lib/plugin.js", "lib/index.js"].find((candidate) => fs.existsSync(path.resolve(rootDir, candidate)));
2018
+ if (pluginRelative) {
2019
+ const pluginPath = path.resolve(rootDir, pluginRelative);
2020
+ const { code, hasPatched } = transformPostcssPlugin(fs.readFileSync(pluginPath, "utf8"), { refProperty });
2021
+ result.files[pluginRelative] = code;
2022
+ if (!hasPatched) {
2023
+ writeFileIfRequired(pluginPath, code, overwrite, "Patched Tailwind CSS plugin entry to collect runtime contexts.");
2024
+ result.applied = true;
2025
+ }
2026
+ }
2027
+ } else if (majorVersion === 2) {
2028
+ const processFileRelative = "lib/jit/processTailwindFeatures.js";
2029
+ const processFilePath = path.resolve(rootDir, processFileRelative);
2030
+ if (fs.existsSync(processFilePath)) {
2031
+ const { code, hasPatched } = transformProcessTailwindFeaturesReturnContextV2(fs.readFileSync(processFilePath, "utf8"));
2032
+ result.files[processFileRelative] = code;
2033
+ if (!hasPatched) {
2034
+ writeFileIfRequired(processFilePath, code, overwrite, "Patched Tailwind CSS JIT processTailwindFeatures to expose runtime context.");
2035
+ result.applied = true;
2036
+ }
2037
+ }
2038
+ const pluginRelative = "lib/jit/index.js";
2039
+ const pluginPath = path.resolve(rootDir, pluginRelative);
2040
+ if (fs.existsSync(pluginPath)) {
2041
+ const { code, hasPatched } = transformPostcssPluginV2(fs.readFileSync(pluginPath, "utf8"), { refProperty });
2042
+ result.files[pluginRelative] = code;
2043
+ if (!hasPatched) {
2044
+ writeFileIfRequired(pluginPath, code, overwrite, "Patched Tailwind CSS JIT entry to collect runtime contexts.");
2045
+ result.applied = true;
2046
+ }
2047
+ }
2048
+ }
2049
+ return result;
2050
+ }
2051
+ //#endregion
2052
+ //#region src/patching/operations/extend-length-units.ts
2053
+ function updateLengthUnitsArray(content, options) {
2054
+ const { variableName = "lengthUnits", units } = options;
2055
+ const ast = parse$1(content);
2056
+ let arrayRef;
2057
+ let changed = false;
2058
+ traverse(ast, { Identifier(path) {
2059
+ if (path.node.name === variableName && t.isVariableDeclarator(path.parent) && t.isArrayExpression(path.parent.init)) {
2060
+ arrayRef = path.parent.init;
2061
+ const existing = new Set(path.parent.init.elements.map((element) => t.isStringLiteral(element) ? element.value : void 0).filter(Boolean));
2062
+ for (const unit of units) if (!existing.has(unit)) {
2063
+ path.parent.init.elements = path.parent.init.elements.map((element) => {
2064
+ if (t.isStringLiteral(element)) return t.stringLiteral(element.value);
2065
+ return element;
2066
+ });
2067
+ path.parent.init.elements.push(t.stringLiteral(unit));
2068
+ changed = true;
2069
+ }
2070
+ }
2071
+ } });
2072
+ return {
2073
+ ...arrayRef === void 0 ? {} : { arrayRef },
2074
+ changed
2075
+ };
2076
+ }
2077
+ function applyExtendLengthUnitsPatchV3(rootDir, options) {
2078
+ if (!options.enabled) return {
2079
+ changed: false,
2080
+ code: void 0
2081
+ };
2082
+ const opts = {
2083
+ ...options,
2084
+ lengthUnitsFilePath: options.lengthUnitsFilePath ?? "lib/util/dataTypes.js",
2085
+ variableName: options.variableName ?? "lengthUnits"
2086
+ };
2087
+ const dataTypesFilePath = path.resolve(rootDir, opts.lengthUnitsFilePath);
2088
+ if (!fs.existsSync(dataTypesFilePath)) return {
2089
+ changed: false,
2090
+ code: void 0
2091
+ };
2092
+ const content = fs.readFileSync(dataTypesFilePath, "utf8");
2093
+ const { arrayRef, changed } = updateLengthUnitsArray(content, opts);
2094
+ if (!arrayRef || !changed) return {
2095
+ changed: false,
2096
+ code: void 0
2097
+ };
2098
+ const { code } = generate$1(arrayRef, { jsescOption: { quotes: "single" } });
2099
+ if (arrayRef.start != null && arrayRef.end != null) {
2100
+ const nextCode = `${content.slice(0, arrayRef.start)}${code}${content.slice(arrayRef.end)}`;
2101
+ if (opts.overwrite) {
2102
+ const target = opts.destPath ? path.resolve(opts.destPath) : dataTypesFilePath;
2103
+ fs.writeFileSync(target, nextCode, "utf8");
2104
+ logger.success("Patched Tailwind CSS length unit list (v3).");
2105
+ }
2106
+ return {
2107
+ changed: true,
2108
+ code: nextCode
2109
+ };
2110
+ }
2111
+ return {
2112
+ changed: false,
2113
+ code: void 0
2114
+ };
2115
+ }
2116
+ function applyExtendLengthUnitsPatchV4(rootDir, options) {
2117
+ if (!options.enabled) return {
2118
+ files: [],
2119
+ changed: false
2120
+ };
2121
+ const opts = { ...options };
2122
+ const distDir = path.resolve(rootDir, "dist");
2123
+ if (!fs.existsSync(distDir)) return {
2124
+ files: [],
2125
+ changed: false
2126
+ };
2127
+ const chunkNames = fs.readdirSync(distDir).filter((entry) => entry.endsWith(".js") || entry.endsWith(".mjs"));
2128
+ const pattern = /\[\s*["']cm["'],\s*["']mm["'],[\w,"']+\]/;
2129
+ const candidates = chunkNames.map((chunkName) => {
2130
+ const file = path.join(distDir, chunkName);
2131
+ const code = fs.readFileSync(file, "utf8");
2132
+ const match = pattern.exec(code);
2133
+ if (!match) return null;
2134
+ return {
2135
+ file,
2136
+ code,
2137
+ match,
2138
+ hasPatched: false
2139
+ };
2140
+ }).filter((candidate) => candidate !== null);
2141
+ for (const item of candidates) {
2142
+ const { code, file, match } = item;
2143
+ const ast = parse$1(match[0], { sourceType: "unambiguous" });
2144
+ traverse(ast, { ArrayExpression(path) {
2145
+ for (const unit of opts.units) {
2146
+ if (path.node.elements.some((element) => t.isStringLiteral(element) && element.value === unit)) {
2147
+ item.hasPatched = true;
2148
+ return;
2149
+ }
2150
+ path.node.elements.push(t.stringLiteral(unit));
2151
+ }
2152
+ } });
2153
+ if (item.hasPatched) continue;
2154
+ const { code: replacement } = generate$1(ast, { minified: true });
2155
+ const start = match.index ?? 0;
2156
+ item.code = spliceChangesIntoString(code, [{
2157
+ start,
2158
+ end: start + match[0].length,
2159
+ replacement: replacement.endsWith(";") ? replacement.slice(0, -1) : replacement
2160
+ }]);
2161
+ if (opts.overwrite) fs.writeFileSync(file, item.code, "utf8");
2162
+ }
2163
+ if (candidates.some((file) => !file.hasPatched)) logger.success("Patched Tailwind CSS length unit list (v4).");
2164
+ return {
2165
+ changed: candidates.some((file) => !file.hasPatched),
2166
+ files: candidates
2167
+ };
2168
+ }
2169
+ //#endregion
2170
+ //#region src/patching/patch-runner.ts
2171
+ function applyTailwindPatches(context) {
2172
+ const { packageInfo, options, majorVersion } = context;
2173
+ const results = {};
2174
+ if (options.features.exposeContext.enabled && (majorVersion === 2 || majorVersion === 3)) results.exposeContext = applyExposeContextPatch({
2175
+ rootDir: packageInfo.rootPath,
2176
+ refProperty: options.features.exposeContext.refProperty,
2177
+ overwrite: options.overwrite,
2178
+ majorVersion
2179
+ });
2180
+ if (options.features.extendLengthUnits?.enabled) {
2181
+ if (majorVersion === 3) results.extendLengthUnits = applyExtendLengthUnitsPatchV3(packageInfo.rootPath, options.features.extendLengthUnits);
2182
+ else if (majorVersion === 4) results.extendLengthUnits = applyExtendLengthUnitsPatchV4(packageInfo.rootPath, options.features.extendLengthUnits);
2183
+ }
2184
+ return results;
2185
+ }
2186
+ //#endregion
2187
+ //#region src/runtime/process-tailwindcss.ts
2188
+ function createCwdRequire(cwd) {
2189
+ return createRequire(path.join(cwd, "package.json"));
2190
+ }
2191
+ function resolveModuleEntry(id, moduleRequire) {
2192
+ return path.isAbsolute(id) ? id : moduleRequire.resolve(id);
2193
+ }
2194
+ function resolvePackageRootFromEntry(entry) {
2195
+ let current = path.dirname(entry);
2196
+ while (current && current !== path.dirname(current)) {
2197
+ const packageJsonPath = path.join(current, "package.json");
2198
+ if (fs.pathExistsSync(packageJsonPath)) return current;
2199
+ current = path.dirname(current);
2200
+ }
2201
+ }
2202
+ function resolveCacheKey(moduleRequire, entry) {
2203
+ try {
2204
+ return moduleRequire.resolve(entry);
2205
+ } catch {
2206
+ return entry;
2207
+ }
2208
+ }
2209
+ function clearTailwindV3RuntimeState(pluginName, moduleRequire) {
2210
+ try {
2211
+ const root = resolvePackageRootFromEntry(resolveModuleEntry(pluginName, moduleRequire));
2212
+ if (!root) return;
2213
+ const sharedStatePath = path.join(root, "lib/lib/sharedState.js");
2214
+ if (!fs.pathExistsSync(sharedStatePath)) return;
2215
+ const sharedStateKey = resolveCacheKey(moduleRequire, sharedStatePath);
2216
+ const sharedState = moduleRequire.cache[sharedStateKey]?.exports;
2217
+ sharedState?.contextMap?.clear();
2218
+ sharedState?.configContextMap?.clear();
2219
+ sharedState?.contextSourcesMap?.clear();
2220
+ sharedState?.sourceHashMap?.clear();
2221
+ for (const candidate of ["lib/plugin.js", "lib/index.js"]) {
2222
+ const runtimeEntry = path.join(root, candidate);
2223
+ if (!fs.pathExistsSync(runtimeEntry)) continue;
2224
+ const runtimeKey = resolveCacheKey(moduleRequire, runtimeEntry);
2225
+ const runtimeModule = moduleRequire.cache[runtimeKey]?.exports;
2226
+ runtimeModule?.contextRef?.value?.splice(0, runtimeModule.contextRef.value.length);
2227
+ break;
2228
+ }
2229
+ } catch {}
2230
+ }
2231
+ async function resolveConfigPath(options) {
2232
+ if (options.config && path.isAbsolute(options.config)) return options.config;
2233
+ const result = await loadConfig({ cwd: options.cwd });
2234
+ if (!result) throw new Error(`Unable to locate Tailwind CSS config from ${options.cwd}`);
2235
+ return result.filepath;
2236
+ }
2237
+ async function runTailwindBuild(options) {
2238
+ const configPath = await resolveConfigPath(options);
2239
+ const pluginName = options.postcssPlugin ?? (options.majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss");
2240
+ const moduleRequire = createCwdRequire(options.cwd);
2241
+ if (options.majorVersion === 3) clearTailwindV3RuntimeState(pluginName, moduleRequire);
2242
+ if (options.majorVersion === 4) return postcss([moduleRequire(pluginName)({ config: configPath })]).process("@import 'tailwindcss';", { from: void 0 });
2243
+ return postcss([moduleRequire(pluginName)({ config: configPath })]).process("@tailwind base;@tailwind components;@tailwind utilities;", { from: void 0 });
2244
+ }
2245
+ //#endregion
2246
+ //#region src/patching/status.ts
2247
+ function inspectLengthUnitsArray(content, variableName, units) {
2248
+ const ast = parse$1(content);
2249
+ let found = false;
2250
+ let missingUnits = [];
2251
+ traverse(ast, { Identifier(path) {
2252
+ if (path.node.name === variableName && t.isVariableDeclarator(path.parent) && t.isArrayExpression(path.parent.init)) {
2253
+ found = true;
2254
+ const existing = new Set(path.parent.init.elements.map((element) => t.isStringLiteral(element) ? element.value : void 0).filter(Boolean));
2255
+ missingUnits = units.filter((unit) => !existing.has(unit));
2256
+ path.stop();
2257
+ }
2258
+ } });
2259
+ return {
2260
+ found,
2261
+ missingUnits
2262
+ };
2263
+ }
2264
+ function checkExposeContextPatch(context) {
2265
+ const { packageInfo, options, majorVersion } = context;
2266
+ const refProperty = options.features.exposeContext.refProperty;
2267
+ if (!options.features.exposeContext.enabled) return {
2268
+ name: "exposeContext",
2269
+ status: "skipped",
2270
+ reason: "exposeContext feature disabled",
2271
+ files: []
2272
+ };
2273
+ if (majorVersion === 4) return {
2274
+ name: "exposeContext",
2275
+ status: "unsupported",
2276
+ reason: "Context export patch is only required for Tailwind v2/v3",
2277
+ files: []
2278
+ };
2279
+ const checks = [];
2280
+ function inspectFile(relative, transform) {
2281
+ const filePath = path.resolve(packageInfo.rootPath, relative);
2282
+ if (!fs.existsSync(filePath)) {
2283
+ checks.push({
2284
+ relative,
2285
+ exists: false,
2286
+ patched: false
2287
+ });
2288
+ return;
2289
+ }
2290
+ const { hasPatched } = transform(fs.readFileSync(filePath, "utf8"));
2291
+ checks.push({
2292
+ relative,
2293
+ exists: true,
2294
+ patched: hasPatched
2295
+ });
2296
+ }
2297
+ if (majorVersion === 3) {
2298
+ inspectFile("lib/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContext);
2299
+ const pluginRelative = ["lib/plugin.js", "lib/index.js"].find((candidate) => fs.existsSync(path.resolve(packageInfo.rootPath, candidate)));
2300
+ if (pluginRelative) inspectFile(pluginRelative, (content) => transformPostcssPlugin(content, { refProperty }));
2301
+ else checks.push({
2302
+ relative: "lib/plugin.js",
2303
+ exists: false,
2304
+ patched: false
2305
+ });
2306
+ } else {
2307
+ inspectFile("lib/jit/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContextV2);
2308
+ inspectFile("lib/jit/index.js", (content) => transformPostcssPluginV2(content, { refProperty }));
2309
+ }
2310
+ const files = checks.filter((check) => check.exists).map((check) => check.relative);
2311
+ const missingFiles = checks.filter((check) => !check.exists);
2312
+ const unpatchedFiles = checks.filter((check) => check.exists && !check.patched);
2313
+ const reasons = [];
2314
+ if (missingFiles.length) reasons.push(`missing files: ${missingFiles.map((item) => item.relative).join(", ")}`);
2315
+ if (unpatchedFiles.length) reasons.push(`unpatched files: ${unpatchedFiles.map((item) => item.relative).join(", ")}`);
2316
+ return {
2317
+ name: "exposeContext",
2318
+ status: reasons.length ? "not-applied" : "applied",
2319
+ ...reasons.length ? { reason: reasons.join("; ") } : {},
2320
+ files
2321
+ };
2322
+ }
2323
+ function checkExtendLengthUnitsV3(rootDir, options) {
2324
+ const lengthUnitsFilePath = options.lengthUnitsFilePath ?? "lib/util/dataTypes.js";
2325
+ const variableName = options.variableName ?? "lengthUnits";
2326
+ const target = path.resolve(rootDir, lengthUnitsFilePath);
2327
+ const files = fs.existsSync(target) ? [path.relative(rootDir, target)] : [];
2328
+ if (!fs.existsSync(target)) return {
2329
+ name: "extendLengthUnits",
2330
+ status: "not-applied",
2331
+ reason: `missing ${lengthUnitsFilePath}`,
2332
+ files
2333
+ };
2334
+ const { found, missingUnits } = inspectLengthUnitsArray(fs.readFileSync(target, "utf8"), variableName, options.units);
2335
+ if (!found) return {
2336
+ name: "extendLengthUnits",
2337
+ status: "not-applied",
2338
+ reason: `could not locate ${variableName} array in ${lengthUnitsFilePath}`,
2339
+ files
2340
+ };
2341
+ if (missingUnits.length) return {
2342
+ name: "extendLengthUnits",
2343
+ status: "not-applied",
2344
+ reason: `missing units: ${missingUnits.join(", ")}`,
2345
+ files
2346
+ };
2347
+ return {
2348
+ name: "extendLengthUnits",
2349
+ status: "applied",
2350
+ files
2351
+ };
2352
+ }
2353
+ function checkExtendLengthUnitsV4(rootDir, options) {
2354
+ const distDir = path.resolve(rootDir, "dist");
2355
+ if (!fs.existsSync(distDir)) return {
2356
+ name: "extendLengthUnits",
2357
+ status: "not-applied",
2358
+ reason: "dist directory not found for Tailwind v4 package",
2359
+ files: []
2360
+ };
2361
+ const result = applyExtendLengthUnitsPatchV4(rootDir, {
2362
+ ...options,
2363
+ enabled: true,
2364
+ overwrite: false
2365
+ });
2366
+ if (result.files.length === 0) return {
2367
+ name: "extendLengthUnits",
2368
+ status: "not-applied",
2369
+ reason: "no bundle chunks matched the length unit pattern",
2370
+ files: []
2371
+ };
2372
+ const files = result.files.map((file) => path.relative(rootDir, file.file));
2373
+ const pending = result.files.filter((file) => !file.hasPatched);
2374
+ if (pending.length) return {
2375
+ name: "extendLengthUnits",
2376
+ status: "not-applied",
2377
+ reason: `missing units in ${pending.length} bundle${pending.length > 1 ? "s" : ""}`,
2378
+ files: pending.map((file) => path.relative(rootDir, file.file))
2379
+ };
2380
+ return {
2381
+ name: "extendLengthUnits",
2382
+ status: "applied",
2383
+ files
2384
+ };
2385
+ }
2386
+ function checkExtendLengthUnitsPatch(context) {
2387
+ const { packageInfo, options, majorVersion } = context;
2388
+ if (!options.features.extendLengthUnits) return {
2389
+ name: "extendLengthUnits",
2390
+ status: "skipped",
2391
+ reason: "extendLengthUnits feature disabled",
2392
+ files: []
2393
+ };
2394
+ if (majorVersion === 2) return {
2395
+ name: "extendLengthUnits",
2396
+ status: "unsupported",
2397
+ reason: "length unit extension is only applied for Tailwind v3/v4",
2398
+ files: []
2399
+ };
2400
+ if (majorVersion === 3) return checkExtendLengthUnitsV3(packageInfo.rootPath, options.features.extendLengthUnits);
2401
+ return checkExtendLengthUnitsV4(packageInfo.rootPath, options.features.extendLengthUnits);
2402
+ }
2403
+ function getPatchStatusReport(context) {
2404
+ return {
2405
+ package: {
2406
+ name: context.packageInfo.name ?? context.packageInfo.packageJson?.name,
2407
+ version: context.packageInfo.version,
2408
+ root: context.packageInfo.rootPath
2409
+ },
2410
+ majorVersion: context.majorVersion,
2411
+ entries: [checkExposeContextPatch(context), checkExtendLengthUnitsPatch(context)]
2412
+ };
2413
+ }
2414
+ //#endregion
2415
+ //#region src/runtime/collector.ts
2416
+ function resolveTailwindExecutionOptions(normalized, majorVersion) {
2417
+ const base = normalized.tailwind;
2418
+ if (majorVersion === 2 && base.v2) return {
2419
+ cwd: base.v2.cwd ?? base.cwd ?? normalized.projectRoot,
2420
+ config: base.v2.config ?? base.config,
2421
+ postcssPlugin: base.v2.postcssPlugin ?? base.postcssPlugin
2422
+ };
2423
+ if (majorVersion === 3 && base.v3) return {
2424
+ cwd: base.v3.cwd ?? base.cwd ?? normalized.projectRoot,
2425
+ config: base.v3.config ?? base.config,
2426
+ postcssPlugin: base.v3.postcssPlugin ?? base.postcssPlugin
2427
+ };
2428
+ return {
2429
+ cwd: base.cwd ?? normalized.projectRoot,
2430
+ config: base.config,
2431
+ postcssPlugin: base.postcssPlugin
2432
+ };
2433
+ }
2434
+ var BaseCollector = class {
2435
+ constructor(packageInfo, options, majorVersion) {
2436
+ this.packageInfo = packageInfo;
2437
+ this.options = options;
2438
+ this.majorVersion = majorVersion;
2439
+ }
2440
+ async patch() {
2441
+ return applyTailwindPatches({
2442
+ packageInfo: this.packageInfo,
2443
+ options: this.options,
2444
+ majorVersion: this.majorVersion
2445
+ });
2446
+ }
2447
+ async getPatchStatus() {
2448
+ return getPatchStatusReport({
2449
+ packageInfo: this.packageInfo,
2450
+ options: this.options,
2451
+ majorVersion: this.majorVersion
2452
+ });
2453
+ }
2454
+ getContexts() {
2455
+ return loadRuntimeContexts(this.packageInfo, this.majorVersion, this.options.features.exposeContext.refProperty);
2456
+ }
2457
+ };
2458
+ var RuntimeCollector = class extends BaseCollector {
2459
+ inFlightBuild;
2460
+ constructor(packageInfo, options, majorVersion, snapshotFactory) {
2461
+ super(packageInfo, options, majorVersion);
2462
+ this.snapshotFactory = snapshotFactory;
2463
+ }
2464
+ async collectClassSet() {
2465
+ return collectClassesFromContexts(this.getContexts(), this.options.filter);
2466
+ }
2467
+ getPatchSnapshot() {
2468
+ return this.snapshotFactory();
2469
+ }
2470
+ async runTailwindBuildIfNeeded() {
2471
+ if (this.inFlightBuild) return this.inFlightBuild;
2472
+ const executionOptions = resolveTailwindExecutionOptions(this.options, this.majorVersion);
2473
+ const buildOptions = {
2474
+ cwd: executionOptions.cwd,
2475
+ majorVersion: this.majorVersion,
2476
+ ...executionOptions.config === void 0 ? {} : { config: executionOptions.config },
2477
+ ...executionOptions.postcssPlugin === void 0 ? {} : { postcssPlugin: executionOptions.postcssPlugin }
2478
+ };
2479
+ this.inFlightBuild = runTailwindBuild(buildOptions).then(() => void 0);
2480
+ try {
2481
+ await this.inFlightBuild;
2482
+ } finally {
2483
+ this.inFlightBuild = void 0;
2484
+ }
2485
+ }
2486
+ };
2487
+ var TailwindV4Collector = class extends BaseCollector {
2488
+ constructor(packageInfo, options, snapshotFactory) {
2489
+ super(packageInfo, options, 4);
2490
+ this.snapshotFactory = snapshotFactory;
2491
+ }
2492
+ snapshotFactory;
2493
+ async collectClassSet() {
2494
+ return collectClassesFromTailwindV4(this.options);
2495
+ }
2496
+ getPatchSnapshot() {
2497
+ return this.snapshotFactory();
2498
+ }
2499
+ };
2500
+ //#endregion
2501
+ //#region src/api/tailwindcss-patcher.ts
2502
+ function resolveInstalledMajorVersion(version) {
2503
+ if (!version) return;
2504
+ const coerced = coerce(version);
2505
+ if (!coerced) return;
2506
+ const major = coerced.major;
2507
+ if (major === 2 || major === 3 || major === 4) return major;
2508
+ if (major >= 4) return 4;
2509
+ }
2510
+ function validateInstalledVersion(packageVersion, expectedMajor, packageName) {
2511
+ const installedMajor = resolveInstalledMajorVersion(packageVersion);
2512
+ if (installedMajor === void 0) return;
2513
+ 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.`);
2514
+ }
2515
+ function resolveMajorVersionOrThrow(configuredMajor, packageVersion, packageName) {
2516
+ if (configuredMajor !== void 0) {
2517
+ validateInstalledVersion(packageVersion, configuredMajor, packageName);
2518
+ return configuredMajor;
2519
+ }
2520
+ const installedMajor = resolveInstalledMajorVersion(packageVersion);
2521
+ if (installedMajor !== void 0) return installedMajor;
2522
+ 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.`);
2523
+ }
2524
+ function createCollector(packageInfo, options, majorVersion, snapshotFactory) {
2525
+ if (majorVersion === 4) return new TailwindV4Collector(packageInfo, options, snapshotFactory);
2526
+ return new RuntimeCollector(packageInfo, options, majorVersion, snapshotFactory);
2527
+ }
2528
+ function getPackageInfoFromCwd(packageName, cwd) {
2529
+ try {
2530
+ const packageJsonPath = createRequire(path.join(cwd, "package.json")).resolve(`${packageName}/package.json`);
2531
+ const packageJson = fs.readJSONSync(packageJsonPath);
2532
+ return {
2533
+ name: packageName,
2534
+ version: typeof packageJson.version === "string" ? packageJson.version : void 0,
2535
+ rootPath: path.dirname(packageJsonPath),
2536
+ packageJsonPath,
2537
+ packageJson
2538
+ };
2539
+ } catch {
2540
+ return;
2541
+ }
2542
+ }
2543
+ function getTailwindPackageInfo(options) {
2544
+ const cwd = options.tailwind.cwd ?? options.projectRoot;
2545
+ return (options.tailwind.resolve?.paths?.length ? getPackageInfoFromCwd(options.tailwind.packageName, cwd) : void 0) ?? getPackageInfoSync(options.tailwind.packageName, options.tailwind.resolve);
2546
+ }
2547
+ var TailwindcssPatcher = class {
2548
+ options;
2549
+ packageInfo;
2550
+ majorVersion;
2551
+ cacheContext;
2552
+ cacheStore;
2553
+ collector;
2554
+ patchMemo;
2555
+ constructor(options = {}) {
2556
+ this.options = normalizeOptions(options);
2557
+ const packageInfo = getTailwindPackageInfo(this.options);
2558
+ if (!packageInfo) throw new Error(`Unable to locate Tailwind CSS package "${this.options.tailwind.packageName}".`);
2559
+ this.packageInfo = packageInfo;
2560
+ this.majorVersion = resolveMajorVersionOrThrow(this.options.tailwind.versionHint, this.packageInfo.version, this.options.tailwind.packageName);
2561
+ this.cacheContext = createCacheContextDescriptor(this.options, this.packageInfo, this.majorVersion);
2562
+ this.cacheStore = new CacheStore(this.options.cache, this.cacheContext);
2563
+ this.collector = createCollector(this.packageInfo, this.options, this.majorVersion, () => this.createPatchSnapshot());
2564
+ }
2565
+ async patch() {
2566
+ const snapshot = this.collector.getPatchSnapshot();
2567
+ if (this.patchMemo && this.patchMemo.snapshot === snapshot) return this.patchMemo.result;
2568
+ const result = await this.collector.patch();
2569
+ this.patchMemo = {
2570
+ result,
2571
+ snapshot: this.collector.getPatchSnapshot()
2572
+ };
2573
+ return result;
2574
+ }
2575
+ async getPatchStatus() {
2576
+ return this.collector.getPatchStatus();
2577
+ }
2578
+ getContexts() {
2579
+ return this.collector.getContexts();
2580
+ }
2581
+ createPatchSnapshot() {
2582
+ const entries = [];
2583
+ const pushSnapshot = (filePath) => {
2584
+ if (!fs.pathExistsSync(filePath)) {
2585
+ entries.push(`${filePath}:missing`);
2586
+ return;
2587
+ }
2588
+ const stat = fs.statSync(filePath);
2589
+ entries.push(`${filePath}:${stat.size}:${Math.trunc(stat.mtimeMs)}`);
2590
+ };
2591
+ if (this.options.features.exposeContext.enabled && (this.majorVersion === 2 || this.majorVersion === 3)) if (this.majorVersion === 2) {
2592
+ pushSnapshot(path.resolve(this.packageInfo.rootPath, "lib/jit/processTailwindFeatures.js"));
2593
+ pushSnapshot(path.resolve(this.packageInfo.rootPath, "lib/jit/index.js"));
2594
+ } else {
2595
+ pushSnapshot(path.resolve(this.packageInfo.rootPath, "lib/processTailwindFeatures.js"));
2596
+ const pluginPath = ["lib/plugin.js", "lib/index.js"].map((file) => path.resolve(this.packageInfo.rootPath, file)).find((file) => fs.pathExistsSync(file));
2597
+ if (pluginPath) pushSnapshot(pluginPath);
2598
+ }
2599
+ if (this.options.features.extendLengthUnits?.enabled) {
2600
+ if (this.majorVersion === 3) {
2601
+ const target = this.options.features.extendLengthUnits.lengthUnitsFilePath ?? "lib/util/dataTypes.js";
2602
+ pushSnapshot(path.resolve(this.packageInfo.rootPath, target));
2603
+ } else if (this.majorVersion === 4) {
2604
+ const distDir = path.resolve(this.packageInfo.rootPath, "dist");
2605
+ if (fs.pathExistsSync(distDir)) {
2606
+ const chunkNames = fs.readdirSync(distDir).filter((entry) => entry.endsWith(".js") || entry.endsWith(".mjs")).sort();
2607
+ for (const chunkName of chunkNames) pushSnapshot(path.join(distDir, chunkName));
2608
+ } else entries.push(`${distDir}:missing`);
2609
+ }
2610
+ }
2611
+ return entries.join("|");
2612
+ }
2613
+ async collectClassSet() {
2614
+ if (this.majorVersion === 4) return this.collector.collectClassSet();
2615
+ return collectClassesFromContexts(this.getContexts(), this.options.filter);
2616
+ }
2617
+ async runTailwindBuildIfNeeded() {
2618
+ await this.collector.runTailwindBuildIfNeeded?.();
2619
+ }
2620
+ debugCacheRead(meta) {
2621
+ if (meta.hit) {
2622
+ logger.debug(`[cache] hit fingerprint=${meta.fingerprint?.slice(0, 12) ?? "n/a"} schema=${meta.schemaVersion ?? "legacy"} ${meta.details.join("; ")}`);
2623
+ return;
2624
+ }
2625
+ logger.debug(`[cache] miss reason=${meta.reason} fingerprint=${meta.fingerprint?.slice(0, 12) ?? "n/a"} schema=${meta.schemaVersion ?? "legacy"} ${meta.details.join("; ")}`);
2626
+ }
2627
+ async mergeWithCache(set) {
2628
+ if (!this.options.cache.enabled) return set;
2629
+ const { data: existing, meta } = await this.cacheStore.readWithMeta();
2630
+ this.debugCacheRead(meta);
2631
+ if (this.options.cache.strategy === "merge") {
2632
+ for (const value of existing) set.add(value);
2633
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : await this.cacheStore.write(set);
2634
+ if (writeTarget) logger.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
2635
+ } else if (set.size > 0) {
2636
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : await this.cacheStore.write(set);
2637
+ if (writeTarget) logger.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
2638
+ } else return existing;
2639
+ return set;
2640
+ }
2641
+ mergeWithCacheSync(set) {
2642
+ if (!this.options.cache.enabled) return set;
2643
+ const { data: existing, meta } = this.cacheStore.readWithMetaSync();
2644
+ this.debugCacheRead(meta);
2645
+ if (this.options.cache.strategy === "merge") {
2646
+ for (const value of existing) set.add(value);
2647
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : this.cacheStore.writeSync(set);
2648
+ if (writeTarget) logger.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
2649
+ } else if (set.size > 0) {
2650
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : this.cacheStore.writeSync(set);
2651
+ if (writeTarget) logger.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
2652
+ } else return existing;
2653
+ return set;
2654
+ }
2655
+ areSetsEqual(a, b) {
2656
+ if (a.size !== b.size) return false;
2657
+ for (const value of a) if (!b.has(value)) return false;
2658
+ return true;
2659
+ }
2660
+ async getClassSet() {
2661
+ await this.runTailwindBuildIfNeeded();
2662
+ const set = await this.collectClassSet();
2663
+ return this.mergeWithCache(set);
2664
+ }
2665
+ getClassSetSync() {
2666
+ if (this.majorVersion === 4) throw new Error("getClassSetSync is not supported for Tailwind CSS v4 projects. Use getClassSet instead.");
2667
+ const contexts = this.getContexts();
2668
+ const set = collectClassesFromContexts(contexts, this.options.filter);
2669
+ const merged = this.mergeWithCacheSync(set);
2670
+ if (contexts.length === 0 && merged.size === 0) return;
2671
+ return merged;
2672
+ }
2673
+ async extract(options) {
2674
+ const shouldWrite = options?.write ?? this.options.output.enabled;
2675
+ const classSet = await this.getClassSet();
2676
+ const classList = Array.from(classSet);
2677
+ const result = {
2678
+ classList,
2679
+ classSet
2680
+ };
2681
+ if (!shouldWrite || !this.options.output.file) return result;
2682
+ const target = path.resolve(this.options.output.file);
2683
+ await fs.ensureDir(path.dirname(target));
2684
+ if (this.options.output.format === "json") {
2685
+ const spaces = typeof this.options.output.pretty === "number" ? this.options.output.pretty : void 0;
2686
+ await fs.writeJSON(target, classList, { spaces });
2687
+ } else await fs.writeFile(target, `${classList.join("\n")}\n`, "utf8");
2688
+ logger.success(`Tailwind CSS class list saved to ${target.replace(process.cwd(), ".")}`);
2689
+ return {
2690
+ ...result,
2691
+ filename: target
2692
+ };
2693
+ }
2694
+ async clearCache(options) {
2695
+ const result = await this.cacheStore.clear(options);
2696
+ logger.debug(`[cache] clear scope=${result.scope} contexts=${result.contextsRemoved} entries=${result.entriesRemoved} files=${result.filesRemoved}`);
2697
+ return result;
2698
+ }
2699
+ extractValidCandidates = extractValidCandidates;
2700
+ async collectContentTokens(options) {
2701
+ return extractProjectCandidatesWithPositions({
2702
+ cwd: options?.cwd ?? this.options.projectRoot,
2703
+ sources: options?.sources ?? this.options.tailwind.v4?.sources ?? []
2704
+ });
2705
+ }
2706
+ async collectContentTokensByFile(options) {
2707
+ const collectContentOptions = {
2708
+ ...options?.cwd === void 0 ? {} : { cwd: options.cwd },
2709
+ ...options?.sources === void 0 ? {} : { sources: options.sources }
2710
+ };
2711
+ return groupTokensByFile(await this.collectContentTokens(collectContentOptions), {
2712
+ ...options?.key === void 0 ? {} : { key: options.key },
2713
+ ...options?.stripAbsolutePaths === void 0 ? {} : { stripAbsolutePaths: options.stripAbsolutePaths }
2714
+ });
2715
+ }
2716
+ };
2717
+ //#endregion
2718
+ //#region src/commands/migration-report.ts
2719
+ const MIGRATION_REPORT_KIND = "tw-patch-migrate-report";
2720
+ const MIGRATION_REPORT_SCHEMA_VERSION = 1;
2721
+ function assertMigrationReportCompatibility(report, reportFile) {
2722
+ if (report.reportKind !== void 0 && report.reportKind !== "tw-patch-migrate-report") throw new Error(`Unsupported report kind "${report.reportKind}" in ${reportFile}.`);
2723
+ 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.`);
2724
+ }
2725
+ //#endregion
2726
+ //#region src/commands/migration-aggregation.ts
2727
+ function createMigrationAggregationState() {
2728
+ return {
2729
+ scannedFiles: 0,
2730
+ changedFiles: 0,
2731
+ writtenFiles: 0,
2732
+ backupsWritten: 0,
2733
+ unchangedFiles: 0,
2734
+ missingFiles: 0,
2735
+ entries: []
2736
+ };
2737
+ }
2738
+ function collectMigrationExecutionResult(state, result) {
2739
+ if (result.missing) {
2740
+ state.missingFiles += 1;
2741
+ return;
2742
+ }
2743
+ state.scannedFiles += 1;
2744
+ state.entries.push(result.entry);
2745
+ if (result.changed) {
2746
+ state.changedFiles += 1;
2747
+ if (result.wrote) state.writtenFiles += 1;
2748
+ if (result.backupWritten) state.backupsWritten += 1;
2749
+ } else state.unchangedFiles += 1;
2750
+ }
2751
+ function buildMigrationReport(state, context) {
2752
+ const { cwd, dryRun, rollbackOnError, backupDirectory, toolName, toolVersion, generatedAt = (/* @__PURE__ */ new Date()).toISOString() } = context;
2753
+ return {
2754
+ reportKind: MIGRATION_REPORT_KIND,
2755
+ schemaVersion: 1,
2756
+ generatedAt,
2757
+ tool: {
2758
+ name: toolName,
2759
+ version: toolVersion
2760
+ },
2761
+ cwd,
2762
+ dryRun,
2763
+ rollbackOnError,
2764
+ ...backupDirectory ? { backupDirectory } : {},
2765
+ scannedFiles: state.scannedFiles,
2766
+ changedFiles: state.changedFiles,
2767
+ writtenFiles: state.writtenFiles,
2768
+ backupsWritten: state.backupsWritten,
2769
+ unchangedFiles: state.unchangedFiles,
2770
+ missingFiles: state.missingFiles,
2771
+ entries: state.entries
2772
+ };
2773
+ }
2774
+ //#endregion
2775
+ //#region src/commands/migration-source.ts
2776
+ const ROOT_LEGACY_KEYS = [
2777
+ "cwd",
2778
+ "overwrite",
2779
+ "tailwind",
2780
+ "features",
2781
+ "output",
2782
+ "applyPatches"
2783
+ ];
2784
+ function getPropertyKeyName(property) {
2785
+ if (!property.computed && t.isIdentifier(property.key)) return property.key.name;
2786
+ if (t.isStringLiteral(property.key)) return property.key.value;
2787
+ }
2788
+ function findObjectProperty(objectExpression, name) {
2789
+ for (const property of objectExpression.properties) {
2790
+ if (!t.isObjectProperty(property)) continue;
2791
+ if (getPropertyKeyName(property) === name) return property;
2792
+ }
2793
+ }
2794
+ function findObjectExpressionProperty(objectExpression, name) {
2795
+ const property = findObjectProperty(objectExpression, name);
2796
+ if (!property) return;
2797
+ if (t.isObjectExpression(property.value)) return property.value;
2798
+ }
2799
+ function removeObjectProperty(objectExpression, property) {
2800
+ const index = objectExpression.properties.indexOf(property);
2801
+ if (index >= 0) objectExpression.properties.splice(index, 1);
2802
+ }
2803
+ function hasObjectProperty(objectExpression, name) {
2804
+ return findObjectProperty(objectExpression, name) !== void 0;
2805
+ }
2806
+ function keyAsIdentifier(name) {
2807
+ return t.identifier(name);
2808
+ }
2809
+ function mergeObjectProperties(target, source) {
2810
+ let changed = false;
2811
+ for (const sourceProperty of source.properties) {
2812
+ if (t.isSpreadElement(sourceProperty)) {
2813
+ target.properties.push(sourceProperty);
2814
+ changed = true;
2815
+ continue;
2816
+ }
2817
+ const sourceKey = getPropertyKeyName(sourceProperty);
2818
+ if (!sourceKey) {
2819
+ target.properties.push(sourceProperty);
2820
+ changed = true;
2821
+ continue;
2822
+ }
2823
+ if (hasObjectProperty(target, sourceKey)) continue;
2824
+ target.properties.push(sourceProperty);
2825
+ changed = true;
2826
+ }
2827
+ return changed;
2828
+ }
2829
+ function moveProperty(objectExpression, from, to, changes, scope) {
2830
+ const source = findObjectProperty(objectExpression, from);
2831
+ if (!source) return false;
2832
+ const target = findObjectProperty(objectExpression, to);
2833
+ if (!target) {
2834
+ source.key = keyAsIdentifier(to);
2835
+ source.computed = false;
2836
+ source.shorthand = false;
2837
+ changes.add(`${scope}.${from} -> ${scope}.${to}`);
2838
+ return true;
2839
+ }
2840
+ if (t.isObjectExpression(source.value) && t.isObjectExpression(target.value)) {
2841
+ if (mergeObjectProperties(target.value, source.value)) changes.add(`${scope}.${from} merged into ${scope}.${to}`);
2842
+ }
2843
+ removeObjectProperty(objectExpression, source);
2844
+ changes.add(`${scope}.${from} removed (preferred ${scope}.${to})`);
2845
+ return true;
2846
+ }
2847
+ function migrateExtractOptions(extract, changes, scope) {
2848
+ let changed = false;
2849
+ changed = moveProperty(extract, "enabled", "write", changes, scope) || changed;
2850
+ changed = moveProperty(extract, "stripUniversalSelector", "removeUniversalSelector", changes, scope) || changed;
2851
+ return changed;
2852
+ }
2853
+ function migrateTailwindOptions(tailwindcss, changes, scope) {
2854
+ let changed = false;
2855
+ changed = moveProperty(tailwindcss, "package", "packageName", changes, scope) || changed;
2856
+ changed = moveProperty(tailwindcss, "legacy", "v2", changes, scope) || changed;
2857
+ changed = moveProperty(tailwindcss, "classic", "v3", changes, scope) || changed;
2858
+ changed = moveProperty(tailwindcss, "next", "v4", changes, scope) || changed;
2859
+ return changed;
2860
+ }
2861
+ function migrateApplyOptions(apply, changes, scope) {
2862
+ return moveProperty(apply, "exportContext", "exposeContext", changes, scope);
2863
+ }
2864
+ function ensureObjectExpressionProperty(objectExpression, name, changes, scope) {
2865
+ const existing = findObjectProperty(objectExpression, name);
2866
+ if (existing) return t.isObjectExpression(existing.value) ? existing.value : void 0;
2867
+ const value = t.objectExpression([]);
2868
+ objectExpression.properties.push(t.objectProperty(keyAsIdentifier(name), value));
2869
+ changes.add(`${scope}.${name} created`);
2870
+ return value;
2871
+ }
2872
+ function moveOverwriteToApply(objectExpression, changes, scope) {
2873
+ const overwrite = findObjectProperty(objectExpression, "overwrite");
2874
+ if (!overwrite) return false;
2875
+ const apply = ensureObjectExpressionProperty(objectExpression, "apply", changes, scope);
2876
+ if (!apply) return false;
2877
+ if (!hasObjectProperty(apply, "overwrite")) {
2878
+ apply.properties.push(t.objectProperty(keyAsIdentifier("overwrite"), overwrite.value));
2879
+ changes.add(`${scope}.overwrite -> ${scope}.apply.overwrite`);
2880
+ }
2881
+ removeObjectProperty(objectExpression, overwrite);
2882
+ return true;
2883
+ }
2884
+ function hasAnyRootLegacyKeys(objectExpression) {
2885
+ return ROOT_LEGACY_KEYS.some((key) => hasObjectProperty(objectExpression, key));
2886
+ }
2887
+ function migrateOptionObject(objectExpression, scope, changes) {
2888
+ let changed = false;
2889
+ changed = moveProperty(objectExpression, "cwd", "projectRoot", changes, scope) || changed;
2890
+ changed = moveProperty(objectExpression, "tailwind", "tailwindcss", changes, scope) || changed;
2891
+ changed = moveProperty(objectExpression, "features", "apply", changes, scope) || changed;
2892
+ changed = moveProperty(objectExpression, "applyPatches", "apply", changes, scope) || changed;
2893
+ changed = moveProperty(objectExpression, "output", "extract", changes, scope) || changed;
2894
+ changed = moveOverwriteToApply(objectExpression, changes, scope) || changed;
2895
+ const extract = findObjectExpressionProperty(objectExpression, "extract");
2896
+ if (extract) changed = migrateExtractOptions(extract, changes, scope) || changed;
2897
+ const tailwindcss = findObjectExpressionProperty(objectExpression, "tailwindcss");
2898
+ if (tailwindcss) changed = migrateTailwindOptions(tailwindcss, changes, scope) || changed;
2899
+ const apply = findObjectExpressionProperty(objectExpression, "apply");
2900
+ if (apply) changed = migrateApplyOptions(apply, changes, scope) || changed;
2901
+ return changed;
2902
+ }
2903
+ function unwrapExpression(node) {
2904
+ let current = node;
2905
+ while (t.isTSAsExpression(current) || t.isTSSatisfiesExpression(current) || t.isTSTypeAssertion(current) || t.isParenthesizedExpression(current)) current = current.expression;
2906
+ return current;
2907
+ }
2908
+ function resolveObjectExpressionFromExpression(expression) {
2909
+ const unwrapped = unwrapExpression(expression);
2910
+ if (t.isObjectExpression(unwrapped)) return unwrapped;
2911
+ if (t.isCallExpression(unwrapped)) {
2912
+ const [firstArg] = unwrapped.arguments;
2913
+ if (!firstArg || !t.isExpression(firstArg)) return;
2914
+ const firstArgUnwrapped = unwrapExpression(firstArg);
2915
+ if (t.isObjectExpression(firstArgUnwrapped)) return firstArgUnwrapped;
2916
+ }
2917
+ }
2918
+ function resolveObjectExpressionFromProgram(program, name) {
2919
+ for (const statement of program.body) {
2920
+ if (!t.isVariableDeclaration(statement)) continue;
2921
+ for (const declaration of statement.declarations) {
2922
+ if (!t.isIdentifier(declaration.id) || declaration.id.name !== name || !declaration.init) continue;
2923
+ const objectExpression = resolveObjectExpressionFromExpression(declaration.init);
2924
+ if (objectExpression) return objectExpression;
2925
+ }
2926
+ }
2927
+ }
2928
+ function resolveRootConfigObjectExpression(program) {
2929
+ for (const statement of program.body) {
2930
+ if (!t.isExportDefaultDeclaration(statement)) continue;
2931
+ const declaration = statement.declaration;
2932
+ if (t.isIdentifier(declaration)) return resolveObjectExpressionFromProgram(program, declaration.name);
2933
+ const objectExpression = resolveObjectExpressionFromExpression(declaration);
2934
+ if (objectExpression) return objectExpression;
2935
+ }
2936
+ }
2937
+ function migrateConfigSource(source) {
2938
+ const ast = parse(source, {
2939
+ sourceType: "module",
2940
+ plugins: ["typescript", "jsx"]
2941
+ });
2942
+ const root = resolveRootConfigObjectExpression(ast.program);
2943
+ if (!root) return {
2944
+ changed: false,
2945
+ code: source,
2946
+ changes: []
2947
+ };
2948
+ const changes = /* @__PURE__ */ new Set();
2949
+ let changed = false;
2950
+ const registry = findObjectExpressionProperty(root, "registry");
2951
+ if (registry) changed = migrateOptionObject(registry, "registry", changes) || changed;
2952
+ const patch = findObjectExpressionProperty(root, "patch");
2953
+ if (patch) changed = migrateOptionObject(patch, "patch", changes) || changed;
2954
+ if (hasAnyRootLegacyKeys(root)) changed = migrateOptionObject(root, "root", changes) || changed;
2955
+ if (!changed) return {
2956
+ changed: false,
2957
+ code: source,
2958
+ changes: []
2959
+ };
2960
+ const generated = generate(ast, { comments: true }).code;
2961
+ return {
2962
+ changed: true,
2963
+ code: source.endsWith("\n") ? `${generated}\n` : generated,
2964
+ changes: [...changes]
2965
+ };
2966
+ }
2967
+ //#endregion
2968
+ //#region src/commands/migration-target-files.ts
2969
+ const DEFAULT_CONFIG_FILENAMES = [
2970
+ "tailwindcss-patch.config.ts",
2971
+ "tailwindcss-patch.config.js",
2972
+ "tailwindcss-patch.config.mjs",
2973
+ "tailwindcss-patch.config.cjs",
2974
+ "tailwindcss-mangle.config.ts",
2975
+ "tailwindcss-mangle.config.js",
2976
+ "tailwindcss-mangle.config.mjs",
2977
+ "tailwindcss-mangle.config.cjs"
2978
+ ];
2979
+ const DEFAULT_CONFIG_FILENAME_SET = new Set(DEFAULT_CONFIG_FILENAMES);
2980
+ const DEFAULT_WORKSPACE_IGNORED_DIRS = new Set([
2981
+ ".git",
2982
+ ".idea",
2983
+ ".turbo",
2984
+ ".vscode",
2985
+ ".yarn",
2986
+ "coverage",
2987
+ "dist",
2988
+ "node_modules",
2989
+ "tmp"
2990
+ ]);
2991
+ function resolveTargetFiles(cwd, files) {
2992
+ const candidates = files && files.length > 0 ? files : [...DEFAULT_CONFIG_FILENAMES];
2993
+ const resolved = /* @__PURE__ */ new Set();
2994
+ for (const file of candidates) resolved.add(path.resolve(cwd, file));
2995
+ return [...resolved];
2996
+ }
2997
+ async function collectWorkspaceConfigFiles(cwd, maxDepth) {
2998
+ const files = /* @__PURE__ */ new Set();
2999
+ const queue = [{
3000
+ dir: cwd,
3001
+ depth: 0
3002
+ }];
3003
+ while (queue.length > 0) {
3004
+ const current = queue.shift();
3005
+ if (!current) continue;
3006
+ const { dir, depth } = current;
3007
+ let entries;
3008
+ try {
3009
+ entries = await fs.readdir(dir, { withFileTypes: true });
3010
+ } catch {
3011
+ continue;
3012
+ }
3013
+ for (const entry of entries) {
3014
+ const absolutePath = path.resolve(dir, entry.name);
3015
+ if (entry.isFile() && DEFAULT_CONFIG_FILENAME_SET.has(entry.name)) {
3016
+ files.add(absolutePath);
3017
+ continue;
3018
+ }
3019
+ if (!entry.isDirectory()) continue;
3020
+ if (DEFAULT_WORKSPACE_IGNORED_DIRS.has(entry.name)) continue;
3021
+ if (depth >= maxDepth) continue;
3022
+ queue.push({
3023
+ dir: absolutePath,
3024
+ depth: depth + 1
3025
+ });
3026
+ }
3027
+ }
3028
+ return [...files].sort((a, b) => a.localeCompare(b));
3029
+ }
3030
+ function resolveBackupRelativePath(cwd, file) {
3031
+ const relative = path.relative(cwd, file);
3032
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
3033
+ const sanitized = file.replace(/[:/\\]+/g, "_");
3034
+ return path.join("__external__", `${sanitized}.bak`);
3035
+ }
3036
+ return `${relative}.bak`;
3037
+ }
3038
+ function normalizePattern(pattern) {
3039
+ return pattern.replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "");
3040
+ }
3041
+ function globToRegExp(globPattern) {
3042
+ const normalized = normalizePattern(globPattern);
3043
+ let pattern = "";
3044
+ for (let i = 0; i < normalized.length; i += 1) {
3045
+ const char = normalized[i];
3046
+ if (char === "*") {
3047
+ if (normalized[i + 1] === "*") {
3048
+ pattern += ".*";
3049
+ i += 1;
3050
+ } else pattern += "[^/]*";
3051
+ continue;
3052
+ }
3053
+ if (char === "?") {
3054
+ pattern += "[^/]";
3055
+ continue;
3056
+ }
3057
+ if ("\\^$+?.()|{}[]".includes(char)) {
3058
+ pattern += `\\${char}`;
3059
+ continue;
3060
+ }
3061
+ pattern += char;
3062
+ }
3063
+ return new RegExp(`^${pattern}$`);
3064
+ }
3065
+ function toPatternList(patterns) {
3066
+ if (!patterns || patterns.length === 0) return [];
3067
+ return patterns.map((pattern) => pattern.trim()).filter(Boolean).map(globToRegExp);
3068
+ }
3069
+ function normalizeFileForPattern(file, cwd) {
3070
+ const relative = path.relative(cwd, file);
3071
+ if (!relative.startsWith("..") && !path.isAbsolute(relative)) return relative.replace(/\\/g, "/");
3072
+ return file.replace(/\\/g, "/");
3073
+ }
3074
+ function filterTargetFiles(targetFiles, cwd, include, exclude) {
3075
+ const includePatterns = toPatternList(include);
3076
+ const excludePatterns = toPatternList(exclude);
3077
+ if (includePatterns.length === 0 && excludePatterns.length === 0) return targetFiles;
3078
+ return targetFiles.filter((file) => {
3079
+ const normalized = normalizeFileForPattern(file, cwd);
3080
+ if (!(includePatterns.length === 0 || includePatterns.some((pattern) => pattern.test(normalized)))) return false;
3081
+ return !excludePatterns.some((pattern) => pattern.test(normalized));
3082
+ });
3083
+ }
3084
+ //#endregion
3085
+ //#region src/commands/migration-file-executor.ts
3086
+ async function rollbackWrittenEntries(wroteEntries) {
3087
+ let rollbackCount = 0;
3088
+ for (const written of [...wroteEntries].reverse()) try {
3089
+ await fs.writeFile(written.file, written.source, "utf8");
3090
+ written.entry.written = false;
3091
+ written.entry.rolledBack = true;
3092
+ rollbackCount += 1;
3093
+ } catch {}
3094
+ return rollbackCount;
3095
+ }
3096
+ async function executeMigrationFile(options) {
3097
+ const { cwd, file, dryRun, rollbackOnError, backupDirectory, wroteEntries } = options;
3098
+ if (!await fs.pathExists(file)) return {
3099
+ missing: true,
3100
+ changed: false,
3101
+ wrote: false,
3102
+ backupWritten: false
3103
+ };
3104
+ const source = await fs.readFile(file, "utf8");
3105
+ const migrated = migrateConfigSource(source);
3106
+ const entry = {
3107
+ file,
3108
+ changed: migrated.changed,
3109
+ written: false,
3110
+ rolledBack: false,
3111
+ changes: migrated.changes
3112
+ };
3113
+ if (!migrated.changed || dryRun) return {
3114
+ missing: false,
3115
+ changed: migrated.changed,
3116
+ wrote: false,
3117
+ backupWritten: false,
3118
+ entry
3119
+ };
3120
+ let backupWritten = false;
3121
+ try {
3122
+ if (backupDirectory) {
3123
+ const backupRelativePath = resolveBackupRelativePath(cwd, file);
3124
+ const backupFile = path.resolve(backupDirectory, backupRelativePath);
3125
+ await fs.ensureDir(path.dirname(backupFile));
3126
+ await fs.writeFile(backupFile, source, "utf8");
3127
+ entry.backupFile = backupFile;
3128
+ backupWritten = true;
3129
+ }
3130
+ await fs.writeFile(file, migrated.code, "utf8");
3131
+ entry.written = true;
3132
+ wroteEntries.push({
3133
+ file,
3134
+ source,
3135
+ entry
3136
+ });
3137
+ return {
3138
+ missing: false,
3139
+ changed: true,
3140
+ wrote: true,
3141
+ backupWritten,
3142
+ entry
3143
+ };
3144
+ } catch (error) {
3145
+ const rollbackCount = rollbackOnError && wroteEntries.length > 0 ? await rollbackWrittenEntries(wroteEntries) : 0;
3146
+ const reason = error instanceof Error ? error.message : String(error);
3147
+ const rollbackHint = rollbackOnError && rollbackCount > 0 ? ` Rolled back ${rollbackCount} previously written file(s).` : "";
3148
+ throw new Error(`Failed to write migrated config "${file}": ${reason}.${rollbackHint}`);
3149
+ }
3150
+ }
3151
+ async function restoreConfigEntries(entries, dryRun) {
3152
+ let scannedEntries = 0;
3153
+ let restorableEntries = 0;
3154
+ let restoredFiles = 0;
3155
+ let missingBackups = 0;
3156
+ let skippedEntries = 0;
3157
+ const restored = [];
3158
+ for (const entry of entries) {
3159
+ scannedEntries += 1;
3160
+ const targetFile = entry.file ? path.resolve(entry.file) : void 0;
3161
+ const backupFile = entry.backupFile ? path.resolve(entry.backupFile) : void 0;
3162
+ if (!targetFile || !backupFile) {
3163
+ skippedEntries += 1;
3164
+ continue;
3165
+ }
3166
+ restorableEntries += 1;
3167
+ if (!await fs.pathExists(backupFile)) {
3168
+ missingBackups += 1;
3169
+ continue;
3170
+ }
3171
+ if (!dryRun) {
3172
+ const backupContent = await fs.readFile(backupFile, "utf8");
3173
+ await fs.ensureDir(path.dirname(targetFile));
3174
+ await fs.writeFile(targetFile, backupContent, "utf8");
3175
+ }
3176
+ restoredFiles += 1;
3177
+ restored.push(targetFile);
3178
+ }
3179
+ return {
3180
+ scannedEntries,
3181
+ restorableEntries,
3182
+ restoredFiles,
3183
+ missingBackups,
3184
+ skippedEntries,
3185
+ restored
3186
+ };
3187
+ }
3188
+ //#endregion
3189
+ //#region src/commands/migration-report-loader.ts
3190
+ async function loadMigrationReportForRestore(reportFile) {
3191
+ const report = await fs.readJSON(reportFile);
3192
+ assertMigrationReportCompatibility(report, reportFile);
3193
+ return {
3194
+ ...report.reportKind === void 0 ? {} : { reportKind: report.reportKind },
3195
+ ...report.schemaVersion === void 0 ? {} : { schemaVersion: report.schemaVersion },
3196
+ entries: Array.isArray(report.entries) ? report.entries : []
3197
+ };
3198
+ }
3199
+ //#endregion
3200
+ //#region src/commands/migration-target-resolver.ts
3201
+ async function resolveMigrationTargetFiles(options) {
3202
+ const { cwd, files, workspace, maxDepth, include, exclude } = options;
3203
+ const resolvedMaxDepth = maxDepth ?? 6;
3204
+ return filterTargetFiles(files && files.length > 0 ? resolveTargetFiles(cwd, files) : workspace ? await collectWorkspaceConfigFiles(cwd, resolvedMaxDepth) : resolveTargetFiles(cwd), cwd, include, exclude);
3205
+ }
3206
+ //#endregion
3207
+ //#region src/commands/migrate-config.ts
3208
+ async function migrateConfigFiles(options) {
3209
+ const cwd = path.resolve(options.cwd);
3210
+ const dryRun = options.dryRun ?? false;
3211
+ const rollbackOnError = options.rollbackOnError ?? true;
3212
+ const backupDirectory = options.backupDir ? path.resolve(cwd, options.backupDir) : void 0;
3213
+ const targetFiles = await resolveMigrationTargetFiles({
3214
+ cwd,
3215
+ files: options.files,
3216
+ workspace: options.workspace,
3217
+ maxDepth: options.maxDepth,
3218
+ include: options.include,
3219
+ exclude: options.exclude
3220
+ });
3221
+ const aggregation = createMigrationAggregationState();
3222
+ const wroteEntries = [];
3223
+ for (const file of targetFiles) collectMigrationExecutionResult(aggregation, await executeMigrationFile({
3224
+ cwd,
3225
+ file,
3226
+ dryRun,
3227
+ rollbackOnError,
3228
+ wroteEntries,
3229
+ ...backupDirectory ? { backupDirectory } : {}
3230
+ }));
3231
+ return buildMigrationReport(aggregation, {
3232
+ cwd,
3233
+ dryRun,
3234
+ rollbackOnError,
3235
+ ...backupDirectory ? { backupDirectory } : {},
3236
+ toolName: pkgName,
3237
+ toolVersion: pkgVersion
3238
+ });
3239
+ }
3240
+ async function restoreConfigFiles(options) {
3241
+ const cwd = path.resolve(options.cwd);
3242
+ const dryRun = options.dryRun ?? false;
3243
+ const strict = options.strict ?? false;
3244
+ const reportFile = path.resolve(cwd, options.reportFile);
3245
+ const report = await loadMigrationReportForRestore(reportFile);
3246
+ const { scannedEntries, restorableEntries, restoredFiles, missingBackups, skippedEntries, restored } = await restoreConfigEntries(report.entries, dryRun);
3247
+ if (strict && missingBackups > 0) throw new Error(`Restore failed: ${missingBackups} backup file(s) missing in report ${reportFile}.`);
3248
+ return {
3249
+ cwd,
3250
+ reportFile,
3251
+ ...report.reportKind === void 0 ? {} : { reportKind: report.reportKind },
3252
+ ...report.schemaVersion === void 0 ? {} : { reportSchemaVersion: report.schemaVersion },
3253
+ dryRun,
3254
+ strict,
3255
+ scannedEntries,
3256
+ restorableEntries,
3257
+ restoredFiles,
3258
+ missingBackups,
3259
+ skippedEntries,
3260
+ restored
3261
+ };
3262
+ }
3263
+ //#endregion
3264
+ //#region src/commands/types.ts
3265
+ const tailwindcssPatchCommands = [
3266
+ "install",
3267
+ "extract",
3268
+ "tokens",
3269
+ "init",
3270
+ "migrate",
3271
+ "restore",
3272
+ "validate",
3273
+ "status"
3274
+ ];
3275
+ //#endregion
3276
+ //#region src/commands/validate.ts
3277
+ const VALIDATE_EXIT_CODES = {
3278
+ OK: 0,
3279
+ REPORT_INCOMPATIBLE: 21,
3280
+ MISSING_BACKUPS: 22,
3281
+ IO_ERROR: 23,
3282
+ UNKNOWN_ERROR: 24
3283
+ };
3284
+ const VALIDATE_FAILURE_REASONS = [
3285
+ "report-incompatible",
3286
+ "missing-backups",
3287
+ "io-error",
3288
+ "unknown-error"
3289
+ ];
3290
+ const IO_ERROR_CODES = new Set([
3291
+ "ENOENT",
3292
+ "EACCES",
3293
+ "EPERM",
3294
+ "EISDIR",
3295
+ "ENOTDIR",
3296
+ "EMFILE",
3297
+ "ENFILE"
3298
+ ]);
3299
+ function isNodeError(error) {
3300
+ return !!error && typeof error === "object" && ("code" in error || "message" in error);
3301
+ }
3302
+ function classifyValidateError(error) {
3303
+ const message = error instanceof Error ? error.message : String(error);
3304
+ if (message.startsWith("Unsupported report kind") || message.startsWith("Unsupported report schema version")) return {
3305
+ reason: "report-incompatible",
3306
+ exitCode: VALIDATE_EXIT_CODES.REPORT_INCOMPATIBLE,
3307
+ message
3308
+ };
3309
+ if (message.startsWith("Restore failed:")) return {
3310
+ reason: "missing-backups",
3311
+ exitCode: VALIDATE_EXIT_CODES.MISSING_BACKUPS,
3312
+ message
3313
+ };
3314
+ if (isNodeError(error) && typeof error.code === "string" && IO_ERROR_CODES.has(error.code)) return {
3315
+ reason: "io-error",
3316
+ exitCode: VALIDATE_EXIT_CODES.IO_ERROR,
3317
+ message
3318
+ };
3319
+ return {
3320
+ reason: "unknown-error",
3321
+ exitCode: VALIDATE_EXIT_CODES.UNKNOWN_ERROR,
3322
+ message
3323
+ };
3324
+ }
3325
+ var ValidateCommandError = class extends Error {
3326
+ reason;
3327
+ exitCode;
3328
+ constructor(summary, options) {
3329
+ super(summary.message, options);
3330
+ this.name = "ValidateCommandError";
3331
+ this.reason = summary.reason;
3332
+ this.exitCode = summary.exitCode;
3333
+ }
3334
+ };
3335
+ //#endregion
3336
+ export { normalizeOptions as C, loadWorkspaceConfigModule as S, logger 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, 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, CacheStore as w, loadPatchOptionsForWorkspace as x, extractValidCandidates as y };