tailwindcss-patch 8.6.0 → 8.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2441 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;// ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3_yaml@2.8.2/node_modules/tsup/assets/cjs_shims.js
2
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
3
- var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
4
-
5
- // src/logger.ts
6
- var _consola = require('consola');
7
- var logger = _consola.createConsola.call(void 0, );
8
- var logger_default = logger;
9
-
10
- // src/cache/store.ts
11
- var _process = require('process'); var _process2 = _interopRequireDefault(_process);
12
- var _fsextra = require('fs-extra'); var _fsextra2 = _interopRequireDefault(_fsextra);
13
- function isErrnoException(error) {
14
- return error instanceof Error && typeof error.code === "string";
15
- }
16
- function isAccessDenied(error) {
17
- return isErrnoException(error) && Boolean(error.code && ["EPERM", "EBUSY", "EACCES"].includes(error.code));
18
- }
19
- var CacheStore = (_class = class {
20
- constructor(options) {;_class.prototype.__init.call(this);
21
- this.options = options;
22
- this.driver = _nullishCoalesce(options.driver, () => ( "file"));
23
- }
24
-
25
- __init() {this.memoryCache = null}
26
- async ensureDir() {
27
- await _fsextra2.default.ensureDir(this.options.dir);
28
- }
29
- ensureDirSync() {
30
- _fsextra2.default.ensureDirSync(this.options.dir);
31
- }
32
- createTempPath() {
33
- const uniqueSuffix = `${_process2.default.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
34
- return `${this.options.path}.${uniqueSuffix}.tmp`;
35
- }
36
- async replaceCacheFile(tempPath) {
37
- try {
38
- await _fsextra2.default.rename(tempPath, this.options.path);
39
- return true;
40
- } catch (error) {
41
- if (isErrnoException(error) && (error.code === "EEXIST" || error.code === "EPERM")) {
42
- try {
43
- await _fsextra2.default.remove(this.options.path);
44
- } catch (removeError) {
45
- if (isAccessDenied(removeError)) {
46
- logger_default.debug("Tailwind class cache locked or read-only, skipping update.", removeError);
47
- return false;
48
- }
49
- if (!isErrnoException(removeError) || removeError.code !== "ENOENT") {
50
- throw removeError;
51
- }
52
- }
53
- await _fsextra2.default.rename(tempPath, this.options.path);
54
- return true;
55
- }
56
- throw error;
57
- }
58
- }
59
- replaceCacheFileSync(tempPath) {
60
- try {
61
- _fsextra2.default.renameSync(tempPath, this.options.path);
62
- return true;
63
- } catch (error) {
64
- if (isErrnoException(error) && (error.code === "EEXIST" || error.code === "EPERM")) {
65
- try {
66
- _fsextra2.default.removeSync(this.options.path);
67
- } catch (removeError) {
68
- if (isAccessDenied(removeError)) {
69
- logger_default.debug("Tailwind class cache locked or read-only, skipping update.", removeError);
70
- return false;
71
- }
72
- if (!isErrnoException(removeError) || removeError.code !== "ENOENT") {
73
- throw removeError;
74
- }
75
- }
76
- _fsextra2.default.renameSync(tempPath, this.options.path);
77
- return true;
78
- }
79
- throw error;
80
- }
81
- }
82
- async cleanupTempFile(tempPath) {
83
- try {
84
- await _fsextra2.default.remove(tempPath);
85
- } catch (e2) {
86
- }
87
- }
88
- cleanupTempFileSync(tempPath) {
89
- try {
90
- _fsextra2.default.removeSync(tempPath);
91
- } catch (e3) {
92
- }
93
- }
94
- async write(data) {
95
- if (!this.options.enabled) {
96
- return void 0;
97
- }
98
- if (this.driver === "noop") {
99
- return void 0;
100
- }
101
- if (this.driver === "memory") {
102
- this.memoryCache = new Set(data);
103
- return "memory";
104
- }
105
- const tempPath = this.createTempPath();
106
- try {
107
- await this.ensureDir();
108
- await _fsextra2.default.writeJSON(tempPath, Array.from(data));
109
- const replaced = await this.replaceCacheFile(tempPath);
110
- if (replaced) {
111
- return this.options.path;
112
- }
113
- await this.cleanupTempFile(tempPath);
114
- return void 0;
115
- } catch (error) {
116
- await this.cleanupTempFile(tempPath);
117
- logger_default.error("Unable to persist Tailwind class cache", error);
118
- return void 0;
119
- }
120
- }
121
- writeSync(data) {
122
- if (!this.options.enabled) {
123
- return void 0;
124
- }
125
- if (this.driver === "noop") {
126
- return void 0;
127
- }
128
- if (this.driver === "memory") {
129
- this.memoryCache = new Set(data);
130
- return "memory";
131
- }
132
- const tempPath = this.createTempPath();
133
- try {
134
- this.ensureDirSync();
135
- _fsextra2.default.writeJSONSync(tempPath, Array.from(data));
136
- const replaced = this.replaceCacheFileSync(tempPath);
137
- if (replaced) {
138
- return this.options.path;
139
- }
140
- this.cleanupTempFileSync(tempPath);
141
- return void 0;
142
- } catch (error) {
143
- this.cleanupTempFileSync(tempPath);
144
- logger_default.error("Unable to persist Tailwind class cache", error);
145
- return void 0;
146
- }
147
- }
148
- async read() {
149
- if (!this.options.enabled) {
150
- return /* @__PURE__ */ new Set();
151
- }
152
- if (this.driver === "noop") {
153
- return /* @__PURE__ */ new Set();
154
- }
155
- if (this.driver === "memory") {
156
- return new Set(_nullishCoalesce(this.memoryCache, () => ( [])));
157
- }
158
- try {
159
- const exists = await _fsextra2.default.pathExists(this.options.path);
160
- if (!exists) {
161
- return /* @__PURE__ */ new Set();
162
- }
163
- const data = await _fsextra2.default.readJSON(this.options.path);
164
- if (Array.isArray(data)) {
165
- return new Set(data.filter((item) => typeof item === "string"));
166
- }
167
- } catch (error) {
168
- if (isErrnoException(error) && error.code === "ENOENT") {
169
- return /* @__PURE__ */ new Set();
170
- }
171
- logger_default.warn("Unable to read Tailwind class cache, removing invalid file.", error);
172
- try {
173
- await _fsextra2.default.remove(this.options.path);
174
- } catch (cleanupError) {
175
- logger_default.error("Failed to clean up invalid cache file", cleanupError);
176
- }
177
- }
178
- return /* @__PURE__ */ new Set();
179
- }
180
- readSync() {
181
- if (!this.options.enabled) {
182
- return /* @__PURE__ */ new Set();
183
- }
184
- if (this.driver === "noop") {
185
- return /* @__PURE__ */ new Set();
186
- }
187
- if (this.driver === "memory") {
188
- return new Set(_nullishCoalesce(this.memoryCache, () => ( [])));
189
- }
190
- try {
191
- const exists = _fsextra2.default.pathExistsSync(this.options.path);
192
- if (!exists) {
193
- return /* @__PURE__ */ new Set();
194
- }
195
- const data = _fsextra2.default.readJSONSync(this.options.path);
196
- if (Array.isArray(data)) {
197
- return new Set(data.filter((item) => typeof item === "string"));
198
- }
199
- } catch (error) {
200
- if (isErrnoException(error) && error.code === "ENOENT") {
201
- return /* @__PURE__ */ new Set();
202
- }
203
- logger_default.warn("Unable to read Tailwind class cache, removing invalid file.", error);
204
- try {
205
- _fsextra2.default.removeSync(this.options.path);
206
- } catch (cleanupError) {
207
- logger_default.error("Failed to clean up invalid cache file", cleanupError);
208
- }
209
- }
210
- return /* @__PURE__ */ new Set();
211
- }
212
- }, _class);
213
-
214
- // src/extraction/candidate-extractor.ts
215
- var _fs = require('fs');
216
-
217
- var _pathe = require('pathe'); var _pathe2 = _interopRequireDefault(_pathe);
218
- async function importNode() {
219
- return Promise.resolve().then(() => _interopRequireWildcard(require("@tailwindcss/node")));
220
- }
221
- async function importOxide() {
222
- return Promise.resolve().then(() => _interopRequireWildcard(require("@tailwindcss/oxide")));
223
- }
224
- async function extractRawCandidatesWithPositions(content, extension = "html") {
225
- const { Scanner } = await importOxide();
226
- const scanner = new Scanner({});
227
- const result = scanner.getCandidatesWithPositions({ content, extension });
228
- return result.map(({ candidate, position }) => ({
229
- rawCandidate: candidate,
230
- start: position,
231
- end: position + candidate.length
232
- }));
233
- }
234
- async function extractRawCandidates(sources) {
235
- const { Scanner } = await importOxide();
236
- const scanner = new Scanner({
237
- sources
238
- });
239
- return scanner.scan();
240
- }
241
- async function extractValidCandidates(options) {
242
- const providedOptions = _nullishCoalesce(options, () => ( {}));
243
- const defaultCwd = _nullishCoalesce(providedOptions.cwd, () => ( _process2.default.cwd()));
244
- const base = _nullishCoalesce(providedOptions.base, () => ( defaultCwd));
245
- const css = _nullishCoalesce(providedOptions.css, () => ( '@import "tailwindcss";'));
246
- const sources = (_nullishCoalesce(providedOptions.sources, () => ( [
247
- {
248
- base: defaultCwd,
249
- pattern: "**/*",
250
- negated: false
251
- }
252
- ]))).map((source) => ({
253
- base: _nullishCoalesce(source.base, () => ( defaultCwd)),
254
- pattern: source.pattern,
255
- negated: source.negated
256
- }));
257
- const { __unstable__loadDesignSystem } = await importNode();
258
- const designSystem = await __unstable__loadDesignSystem(css, { base });
259
- const candidates = await extractRawCandidates(sources);
260
- const parsedCandidates = candidates.filter(
261
- (rawCandidate) => designSystem.parseCandidate(rawCandidate).length > 0
262
- );
263
- if (parsedCandidates.length === 0) {
264
- return parsedCandidates;
265
- }
266
- const cssByCandidate = designSystem.candidatesToCss(parsedCandidates);
267
- const validCandidates = [];
268
- for (let index = 0; index < parsedCandidates.length; index++) {
269
- const css2 = cssByCandidate[index];
270
- if (typeof css2 === "string" && css2.trim().length > 0) {
271
- validCandidates.push(parsedCandidates[index]);
272
- }
273
- }
274
- return validCandidates;
275
- }
276
- function normalizeSources(sources, cwd) {
277
- const baseSources = _optionalChain([sources, 'optionalAccess', _ => _.length]) ? sources : [
278
- {
279
- base: cwd,
280
- pattern: "**/*",
281
- negated: false
282
- }
283
- ];
284
- return baseSources.map((source) => ({
285
- base: _nullishCoalesce(source.base, () => ( cwd)),
286
- pattern: source.pattern,
287
- negated: source.negated
288
- }));
289
- }
290
- function buildLineOffsets(content) {
291
- const offsets = [0];
292
- for (let i = 0; i < content.length; i++) {
293
- if (content[i] === "\n") {
294
- offsets.push(i + 1);
295
- }
296
- }
297
- if (offsets[offsets.length - 1] !== content.length) {
298
- offsets.push(content.length);
299
- }
300
- return offsets;
301
- }
302
- function resolveLineMeta(content, offsets, index) {
303
- let low = 0;
304
- let high = offsets.length - 1;
305
- while (low <= high) {
306
- const mid = Math.floor((low + high) / 2);
307
- const start = offsets[mid];
308
- const nextStart = _nullishCoalesce(offsets[mid + 1], () => ( content.length));
309
- if (index < start) {
310
- high = mid - 1;
311
- continue;
312
- }
313
- if (index >= nextStart) {
314
- low = mid + 1;
315
- continue;
316
- }
317
- const line = mid + 1;
318
- const column = index - start + 1;
319
- const lineEnd = content.indexOf("\n", start);
320
- const lineText = content.slice(start, lineEnd === -1 ? content.length : lineEnd);
321
- return { line, column, lineText };
322
- }
323
- const lastStart = _nullishCoalesce(offsets[offsets.length - 2], () => ( 0));
324
- return {
325
- line: offsets.length - 1,
326
- column: index - lastStart + 1,
327
- lineText: content.slice(lastStart)
328
- };
329
- }
330
- function toExtension(filename) {
331
- const ext = _pathe2.default.extname(filename).replace(/^\./, "");
332
- return ext || "txt";
333
- }
334
- function toRelativeFile(cwd, filename) {
335
- const relative = _pathe2.default.relative(cwd, filename);
336
- return relative === "" ? _pathe2.default.basename(filename) : relative;
337
- }
338
- async function extractProjectCandidatesWithPositions(options) {
339
- const cwd = _optionalChain([options, 'optionalAccess', _2 => _2.cwd]) ? _pathe2.default.resolve(options.cwd) : _process2.default.cwd();
340
- const normalizedSources = normalizeSources(_optionalChain([options, 'optionalAccess', _3 => _3.sources]), cwd);
341
- const { Scanner } = await importOxide();
342
- const scanner = new Scanner({
343
- sources: normalizedSources
344
- });
345
- const files = _nullishCoalesce(scanner.files, () => ( []));
346
- const entries = [];
347
- const skipped = [];
348
- for (const file of files) {
349
- let content;
350
- try {
351
- content = await _fs.promises.readFile(file, "utf8");
352
- } catch (error) {
353
- skipped.push({
354
- file,
355
- reason: error instanceof Error ? error.message : "Unknown error"
356
- });
357
- continue;
358
- }
359
- const extension = toExtension(file);
360
- const matches = scanner.getCandidatesWithPositions({
361
- file,
362
- content,
363
- extension
364
- });
365
- if (!matches.length) {
366
- continue;
367
- }
368
- const offsets = buildLineOffsets(content);
369
- const relativeFile = toRelativeFile(cwd, file);
370
- for (const match of matches) {
371
- const info = resolveLineMeta(content, offsets, match.position);
372
- entries.push({
373
- rawCandidate: match.candidate,
374
- file,
375
- relativeFile,
376
- extension,
377
- start: match.position,
378
- end: match.position + match.candidate.length,
379
- length: match.candidate.length,
380
- line: info.line,
381
- column: info.column,
382
- lineText: info.lineText
383
- });
384
- }
385
- }
386
- return {
387
- entries,
388
- filesScanned: files.length,
389
- skippedFiles: skipped,
390
- sources: normalizedSources
391
- };
392
- }
393
- function groupTokensByFile(report, options) {
394
- const key = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _4 => _4.key]), () => ( "relative"));
395
- const stripAbsolute = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _5 => _5.stripAbsolutePaths]), () => ( key !== "absolute"));
396
- return report.entries.reduce((acc, entry) => {
397
- const bucketKey = key === "absolute" ? entry.file : entry.relativeFile;
398
- if (!acc[bucketKey]) {
399
- acc[bucketKey] = [];
400
- }
401
- const value = stripAbsolute ? {
402
- ...entry,
403
- file: entry.relativeFile
404
- } : entry;
405
- acc[bucketKey].push(value);
406
- return acc;
407
- }, {});
408
- }
409
-
410
- // src/options/normalize.ts
411
-
412
-
413
-
414
- // src/constants.ts
415
- var pkgName = "tailwindcss-patch";
416
-
417
- // src/options/normalize.ts
418
- function toPrettyValue(value) {
419
- if (typeof value === "number") {
420
- return value > 0 ? value : false;
421
- }
422
- if (value === true) {
423
- return 2;
424
- }
425
- return false;
426
- }
427
- function normalizeCacheDriver(driver) {
428
- if (driver === "memory" || driver === "noop") {
429
- return driver;
430
- }
431
- return "file";
432
- }
433
- function normalizeCacheOptions(cache, projectRoot) {
434
- let enabled = false;
435
- let cwd = projectRoot;
436
- let dir = _pathe2.default.resolve(cwd, "node_modules/.cache", pkgName);
437
- let file = "class-cache.json";
438
- let strategy = "merge";
439
- let driver = "file";
440
- if (typeof cache === "boolean") {
441
- enabled = cache;
442
- } else if (typeof cache === "object" && cache) {
443
- enabled = _nullishCoalesce(cache.enabled, () => ( true));
444
- cwd = _nullishCoalesce(cache.cwd, () => ( cwd));
445
- dir = cache.dir ? _pathe2.default.resolve(cache.dir) : _pathe2.default.resolve(cwd, "node_modules/.cache", pkgName);
446
- file = _nullishCoalesce(cache.file, () => ( file));
447
- strategy = _nullishCoalesce(cache.strategy, () => ( strategy));
448
- driver = normalizeCacheDriver(cache.driver);
449
- }
450
- const filename = _pathe2.default.resolve(dir, file);
451
- return {
452
- enabled,
453
- cwd,
454
- dir,
455
- file,
456
- path: filename,
457
- strategy,
458
- driver
459
- };
460
- }
461
- function normalizeOutputOptions(output) {
462
- const enabled = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _6 => _6.enabled]), () => ( true));
463
- const file = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _7 => _7.file]), () => ( ".tw-patch/tw-class-list.json"));
464
- const format = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _8 => _8.format]), () => ( "json"));
465
- const pretty = toPrettyValue(_nullishCoalesce(_optionalChain([output, 'optionalAccess', _9 => _9.pretty]), () => ( true)));
466
- const removeUniversalSelector = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _10 => _10.removeUniversalSelector]), () => ( true));
467
- return {
468
- enabled,
469
- file,
470
- format,
471
- pretty,
472
- removeUniversalSelector
473
- };
474
- }
475
- function normalizeExposeContextOptions(features) {
476
- if (_optionalChain([features, 'optionalAccess', _11 => _11.exposeContext]) === false) {
477
- return {
478
- enabled: false,
479
- refProperty: "contextRef"
480
- };
481
- }
482
- if (typeof _optionalChain([features, 'optionalAccess', _12 => _12.exposeContext]) === "object" && features.exposeContext) {
483
- return {
484
- enabled: true,
485
- refProperty: _nullishCoalesce(features.exposeContext.refProperty, () => ( "contextRef"))
486
- };
487
- }
488
- return {
489
- enabled: true,
490
- refProperty: "contextRef"
491
- };
492
- }
493
- function normalizeExtendLengthUnitsOptions(features) {
494
- const extend = _optionalChain([features, 'optionalAccess', _13 => _13.extendLengthUnits]);
495
- if (extend === false || extend === void 0) {
496
- return null;
497
- }
498
- if (extend.enabled === false) {
499
- return null;
500
- }
501
- const base = {
502
- units: ["rpx"],
503
- overwrite: true
504
- };
505
- return {
506
- ...base,
507
- ...extend,
508
- enabled: _nullishCoalesce(extend.enabled, () => ( true)),
509
- units: _nullishCoalesce(extend.units, () => ( base.units)),
510
- overwrite: _nullishCoalesce(extend.overwrite, () => ( base.overwrite))
511
- };
512
- }
513
- function normalizeTailwindV4Options(v4, fallbackBase) {
514
- const configuredBase = _optionalChain([v4, 'optionalAccess', _14 => _14.base]) ? _pathe2.default.resolve(v4.base) : void 0;
515
- const base = _nullishCoalesce(configuredBase, () => ( fallbackBase));
516
- const cssEntries = Array.isArray(_optionalChain([v4, 'optionalAccess', _15 => _15.cssEntries])) ? v4.cssEntries.filter((entry) => Boolean(entry)).map((entry) => _pathe2.default.resolve(entry)) : [];
517
- const userSources = _optionalChain([v4, 'optionalAccess', _16 => _16.sources]);
518
- const hasUserDefinedSources = Boolean(_optionalChain([userSources, 'optionalAccess', _17 => _17.length]));
519
- const sources = hasUserDefinedSources ? userSources : [
520
- {
521
- base: fallbackBase,
522
- pattern: "**/*",
523
- negated: false
524
- }
525
- ];
526
- return {
527
- base,
528
- configuredBase,
529
- css: _optionalChain([v4, 'optionalAccess', _18 => _18.css]),
530
- cssEntries,
531
- sources,
532
- hasUserDefinedSources
533
- };
534
- }
535
- function normalizeTailwindOptions(tailwind, projectRoot) {
536
- const packageName = _nullishCoalesce(_optionalChain([tailwind, 'optionalAccess', _19 => _19.packageName]), () => ( "tailwindcss"));
537
- const versionHint = _optionalChain([tailwind, 'optionalAccess', _20 => _20.version]);
538
- const resolve = _optionalChain([tailwind, 'optionalAccess', _21 => _21.resolve]);
539
- const cwd = _nullishCoalesce(_optionalChain([tailwind, 'optionalAccess', _22 => _22.cwd]), () => ( projectRoot));
540
- const config = _optionalChain([tailwind, 'optionalAccess', _23 => _23.config]);
541
- const postcssPlugin = _optionalChain([tailwind, 'optionalAccess', _24 => _24.postcssPlugin]);
542
- const v4 = normalizeTailwindV4Options(_optionalChain([tailwind, 'optionalAccess', _25 => _25.v4]), cwd);
543
- return {
544
- packageName,
545
- versionHint,
546
- resolve,
547
- cwd,
548
- config,
549
- postcssPlugin,
550
- v2: _optionalChain([tailwind, 'optionalAccess', _26 => _26.v2]),
551
- v3: _optionalChain([tailwind, 'optionalAccess', _27 => _27.v3]),
552
- v4
553
- };
554
- }
555
- function normalizeOptions(options = {}) {
556
- const projectRoot = options.cwd ? _pathe2.default.resolve(options.cwd) : _process2.default.cwd();
557
- const overwrite = _nullishCoalesce(options.overwrite, () => ( true));
558
- const output = normalizeOutputOptions(options.output);
559
- const cache = normalizeCacheOptions(options.cache, projectRoot);
560
- const tailwind = normalizeTailwindOptions(options.tailwind, projectRoot);
561
- const exposeContext = normalizeExposeContextOptions(options.features);
562
- const extendLengthUnits = normalizeExtendLengthUnitsOptions(options.features);
563
- const filter = (className) => {
564
- if (output.removeUniversalSelector && className === "*") {
565
- return false;
566
- }
567
- if (typeof options.filter === "function") {
568
- return options.filter(className) !== false;
569
- }
570
- return true;
571
- };
572
- return {
573
- projectRoot,
574
- overwrite,
575
- tailwind,
576
- features: {
577
- exposeContext,
578
- extendLengthUnits
579
- },
580
- output,
581
- cache,
582
- filter
583
- };
584
- }
585
-
586
- // src/patching/status.ts
587
- var _types = require('@babel/types'); var t4 = _interopRequireWildcard(_types); var t = _interopRequireWildcard(_types); var t2 = _interopRequireWildcard(_types); var t3 = _interopRequireWildcard(_types);
588
-
589
-
590
-
591
- // src/babel/index.ts
592
- var _generator = require('@babel/generator'); var _generator2 = _interopRequireDefault(_generator);
593
- var _traverse = require('@babel/traverse'); var _traverse2 = _interopRequireDefault(_traverse);
594
- var _parser = require('@babel/parser');
595
- function _interopDefaultCompat(e) {
596
- return e && typeof e === "object" && "default" in e ? e.default : e;
597
- }
598
- var generate = _interopDefaultCompat(_generator2.default);
599
- var traverse = _interopDefaultCompat(_traverse2.default);
600
-
601
- // src/patching/operations/export-context/postcss-v2.ts
602
-
603
- var IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
604
- function toIdentifierName(property) {
605
- if (!property) {
606
- return "contextRef";
607
- }
608
- const sanitized = property.replace(/[^\w$]/gu, "_");
609
- if (/^\d/.test(sanitized)) {
610
- return `_${sanitized}`;
611
- }
612
- return sanitized || "contextRef";
613
- }
614
- function createExportsMember(property) {
615
- if (IDENTIFIER_RE.test(property)) {
616
- return t.memberExpression(t.identifier("exports"), t.identifier(property));
617
- }
618
- return t.memberExpression(t.identifier("exports"), t.stringLiteral(property), true);
619
- }
620
- function transformProcessTailwindFeaturesReturnContextV2(content) {
621
- const ast = _parser.parse.call(void 0, content, {
622
- sourceType: "unambiguous"
623
- });
624
- let hasPatched = false;
625
- traverse(ast, {
626
- FunctionDeclaration(path11) {
627
- const node = path11.node;
628
- if (_optionalChain([node, 'access', _28 => _28.id, 'optionalAccess', _29 => _29.name]) !== "processTailwindFeatures" || node.body.body.length !== 1 || !t.isReturnStatement(node.body.body[0])) {
629
- return;
630
- }
631
- const returnStatement3 = node.body.body[0];
632
- if (!t.isFunctionExpression(returnStatement3.argument)) {
633
- return;
634
- }
635
- const body = returnStatement3.argument.body.body;
636
- const lastStatement = body[body.length - 1];
637
- const alreadyReturnsContext = Boolean(
638
- t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context"
639
- );
640
- hasPatched = alreadyReturnsContext;
641
- if (!alreadyReturnsContext) {
642
- body.push(t.returnStatement(t.identifier("context")));
643
- }
644
- }
645
- });
646
- return {
647
- code: hasPatched ? content : generate(ast).code,
648
- hasPatched
649
- };
650
- }
651
- function transformPostcssPluginV2(content, options) {
652
- const refIdentifier = t.identifier(toIdentifierName(options.refProperty));
653
- const exportMember = createExportsMember(options.refProperty);
654
- const valueMember = t.memberExpression(refIdentifier, t.identifier("value"));
655
- const ast = _parser.parse.call(void 0, content);
656
- let hasPatched = false;
657
- traverse(ast, {
658
- Program(path11) {
659
- const program = path11.node;
660
- const index = program.body.findIndex((statement) => {
661
- return t.isFunctionDeclaration(statement) && _optionalChain([statement, 'access', _30 => _30.id, 'optionalAccess', _31 => _31.name]) === "_default";
662
- });
663
- if (index === -1) {
664
- return;
665
- }
666
- const previous = program.body[index - 1];
667
- const beforePrevious = program.body[index - 2];
668
- const alreadyHasVariable = Boolean(
669
- previous && t.isVariableDeclaration(previous) && previous.declarations.length === 1 && t.isIdentifier(previous.declarations[0].id) && previous.declarations[0].id.name === refIdentifier.name
670
- );
671
- const alreadyAssignsExports = Boolean(
672
- 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(beforePrevious.expression.left).code === generate(exportMember).code
673
- );
674
- hasPatched = alreadyHasVariable && alreadyAssignsExports;
675
- if (!alreadyHasVariable) {
676
- program.body.splice(
677
- index,
678
- 0,
679
- t.variableDeclaration("var", [
680
- t.variableDeclarator(
681
- refIdentifier,
682
- t.objectExpression([
683
- t.objectProperty(t.identifier("value"), t.arrayExpression())
684
- ])
685
- )
686
- ]),
687
- t.expressionStatement(
688
- t.assignmentExpression("=", exportMember, refIdentifier)
689
- )
690
- );
691
- }
692
- },
693
- FunctionDeclaration(path11) {
694
- if (hasPatched) {
695
- return;
696
- }
697
- const fn = path11.node;
698
- if (_optionalChain([fn, 'access', _32 => _32.id, 'optionalAccess', _33 => _33.name]) !== "_default") {
699
- return;
700
- }
701
- if (fn.body.body.length !== 1 || !t.isReturnStatement(fn.body.body[0])) {
702
- return;
703
- }
704
- const returnStatement3 = fn.body.body[0];
705
- if (!t.isCallExpression(returnStatement3.argument) || !t.isMemberExpression(returnStatement3.argument.callee) || !t.isArrayExpression(returnStatement3.argument.callee.object)) {
706
- return;
707
- }
708
- const fnExpression = returnStatement3.argument.callee.object.elements[1];
709
- if (!fnExpression || !t.isFunctionExpression(fnExpression)) {
710
- return;
711
- }
712
- const block = fnExpression.body;
713
- const statements = block.body;
714
- if (t.isExpressionStatement(statements[0]) && t.isAssignmentExpression(statements[0].expression) && t.isNumericLiteral(statements[0].expression.right)) {
715
- hasPatched = true;
716
- return;
717
- }
718
- const lastStatement = statements[statements.length - 1];
719
- if (lastStatement && t.isExpressionStatement(lastStatement)) {
720
- statements[statements.length - 1] = t.expressionStatement(
721
- t.callExpression(
722
- t.memberExpression(valueMember, t.identifier("push")),
723
- [lastStatement.expression]
724
- )
725
- );
726
- }
727
- const index = statements.findIndex((statement) => t.isIfStatement(statement));
728
- if (index > -1) {
729
- const ifStatement = statements[index];
730
- if (t.isBlockStatement(ifStatement.consequent) && ifStatement.consequent.body[1] && t.isForOfStatement(ifStatement.consequent.body[1])) {
731
- const forOf = ifStatement.consequent.body[1];
732
- if (t.isBlockStatement(forOf.body) && forOf.body.body.length === 1) {
733
- const nestedIf = forOf.body.body[0];
734
- if (nestedIf && t.isIfStatement(nestedIf) && t.isBlockStatement(nestedIf.consequent) && nestedIf.consequent.body.length === 1 && t.isExpressionStatement(nestedIf.consequent.body[0])) {
735
- nestedIf.consequent.body[0] = t.expressionStatement(
736
- t.callExpression(
737
- t.memberExpression(valueMember, t.identifier("push")),
738
- [nestedIf.consequent.body[0].expression]
739
- )
740
- );
741
- }
742
- }
743
- }
744
- }
745
- statements.unshift(
746
- t.expressionStatement(
747
- t.assignmentExpression(
748
- "=",
749
- t.memberExpression(valueMember, t.identifier("length")),
750
- t.numericLiteral(0)
751
- )
752
- )
753
- );
754
- }
755
- });
756
- return {
757
- code: hasPatched ? content : generate(ast).code,
758
- hasPatched
759
- };
760
- }
761
-
762
- // src/patching/operations/export-context/postcss-v3.ts
763
-
764
- var IDENTIFIER_RE2 = /^[A-Z_$][\w$]*$/i;
765
- function toIdentifierName2(property) {
766
- if (!property) {
767
- return "contextRef";
768
- }
769
- const sanitized = property.replace(/[^\w$]/gu, "_");
770
- if (/^\d/.test(sanitized)) {
771
- return `_${sanitized}`;
772
- }
773
- return sanitized || "contextRef";
774
- }
775
- function createModuleExportsMember(property) {
776
- const object = t2.memberExpression(t2.identifier("module"), t2.identifier("exports"));
777
- if (IDENTIFIER_RE2.test(property)) {
778
- return t2.memberExpression(object, t2.identifier(property));
779
- }
780
- return t2.memberExpression(object, t2.stringLiteral(property), true);
781
- }
782
- function transformProcessTailwindFeaturesReturnContext(content) {
783
- const ast = _parser.parse.call(void 0, content);
784
- let hasPatched = false;
785
- traverse(ast, {
786
- FunctionDeclaration(path11) {
787
- const node = path11.node;
788
- if (_optionalChain([node, 'access', _34 => _34.id, 'optionalAccess', _35 => _35.name]) !== "processTailwindFeatures" || node.body.body.length !== 1) {
789
- return;
790
- }
791
- const [returnStatement3] = node.body.body;
792
- if (!t2.isReturnStatement(returnStatement3) || !t2.isFunctionExpression(returnStatement3.argument)) {
793
- return;
794
- }
795
- const expression = returnStatement3.argument;
796
- const body = expression.body.body;
797
- const lastStatement = body[body.length - 1];
798
- const alreadyReturnsContext = Boolean(
799
- t2.isReturnStatement(lastStatement) && t2.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context"
800
- );
801
- hasPatched = alreadyReturnsContext;
802
- if (!alreadyReturnsContext) {
803
- body.push(t2.returnStatement(t2.identifier("context")));
804
- }
805
- }
806
- });
807
- return {
808
- code: hasPatched ? content : generate(ast).code,
809
- hasPatched
810
- };
811
- }
812
- function transformPostcssPlugin(content, { refProperty }) {
813
- const ast = _parser.parse.call(void 0, content);
814
- const refIdentifier = t2.identifier(toIdentifierName2(refProperty));
815
- const moduleExportsMember = createModuleExportsMember(refProperty);
816
- const valueMember = t2.memberExpression(refIdentifier, t2.identifier("value"));
817
- let hasPatched = false;
818
- traverse(ast, {
819
- Program(path11) {
820
- const program = path11.node;
821
- const index = program.body.findIndex((statement) => {
822
- return t2.isExpressionStatement(statement) && t2.isAssignmentExpression(statement.expression) && t2.isMemberExpression(statement.expression.left) && t2.isFunctionExpression(statement.expression.right) && _optionalChain([statement, 'access', _36 => _36.expression, 'access', _37 => _37.right, 'access', _38 => _38.id, 'optionalAccess', _39 => _39.name]) === "tailwindcss";
823
- });
824
- if (index === -1) {
825
- return;
826
- }
827
- const previousStatement = program.body[index - 1];
828
- const lastStatement = program.body[program.body.length - 1];
829
- const alreadyHasVariable = Boolean(
830
- previousStatement && t2.isVariableDeclaration(previousStatement) && previousStatement.declarations.length === 1 && t2.isIdentifier(previousStatement.declarations[0].id) && previousStatement.declarations[0].id.name === refIdentifier.name
831
- );
832
- const alreadyAssignsModuleExports = Boolean(
833
- t2.isExpressionStatement(lastStatement) && t2.isAssignmentExpression(lastStatement.expression) && t2.isMemberExpression(lastStatement.expression.left) && t2.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === refIdentifier.name && generate(lastStatement.expression.left).code === generate(moduleExportsMember).code
834
- );
835
- hasPatched = alreadyHasVariable && alreadyAssignsModuleExports;
836
- if (!alreadyHasVariable) {
837
- program.body.splice(
838
- index,
839
- 0,
840
- t2.variableDeclaration("const", [
841
- t2.variableDeclarator(
842
- refIdentifier,
843
- t2.objectExpression([
844
- t2.objectProperty(t2.identifier("value"), t2.arrayExpression())
845
- ])
846
- )
847
- ])
848
- );
849
- }
850
- if (!alreadyAssignsModuleExports) {
851
- program.body.push(
852
- t2.expressionStatement(
853
- t2.assignmentExpression("=", moduleExportsMember, refIdentifier)
854
- )
855
- );
856
- }
857
- },
858
- FunctionExpression(path11) {
859
- if (hasPatched) {
860
- return;
861
- }
862
- const fn = path11.node;
863
- if (_optionalChain([fn, 'access', _40 => _40.id, 'optionalAccess', _41 => _41.name]) !== "tailwindcss" || fn.body.body.length !== 1) {
864
- return;
865
- }
866
- const [returnStatement3] = fn.body.body;
867
- if (!returnStatement3 || !t2.isReturnStatement(returnStatement3) || !t2.isObjectExpression(returnStatement3.argument)) {
868
- return;
869
- }
870
- const properties = returnStatement3.argument.properties;
871
- if (properties.length !== 2) {
872
- return;
873
- }
874
- const pluginsProperty = properties.find(
875
- (prop) => t2.isObjectProperty(prop) && t2.isIdentifier(prop.key) && prop.key.name === "plugins"
876
- );
877
- if (!pluginsProperty || !t2.isObjectProperty(pluginsProperty) || !t2.isCallExpression(pluginsProperty.value) || !t2.isMemberExpression(pluginsProperty.value.callee) || !t2.isArrayExpression(pluginsProperty.value.callee.object)) {
878
- return;
879
- }
880
- const pluginsArray = pluginsProperty.value.callee.object.elements;
881
- const targetPlugin = pluginsArray[1];
882
- if (!targetPlugin || !t2.isFunctionExpression(targetPlugin)) {
883
- return;
884
- }
885
- const block = targetPlugin.body;
886
- const statements = block.body;
887
- const last = statements[statements.length - 1];
888
- if (last && t2.isExpressionStatement(last)) {
889
- statements[statements.length - 1] = t2.expressionStatement(
890
- t2.callExpression(
891
- t2.memberExpression(valueMember, t2.identifier("push")),
892
- [last.expression]
893
- )
894
- );
895
- }
896
- const index = statements.findIndex((s) => t2.isIfStatement(s));
897
- if (index > -1) {
898
- const ifStatement = statements[index];
899
- if (t2.isBlockStatement(ifStatement.consequent)) {
900
- const [, second] = ifStatement.consequent.body;
901
- if (second && t2.isForOfStatement(second) && t2.isBlockStatement(second.body)) {
902
- const bodyStatement = second.body.body[0];
903
- if (bodyStatement && t2.isIfStatement(bodyStatement) && t2.isBlockStatement(bodyStatement.consequent) && bodyStatement.consequent.body.length === 1 && t2.isExpressionStatement(bodyStatement.consequent.body[0])) {
904
- bodyStatement.consequent.body[0] = t2.expressionStatement(
905
- t2.callExpression(
906
- t2.memberExpression(valueMember, t2.identifier("push")),
907
- [bodyStatement.consequent.body[0].expression]
908
- )
909
- );
910
- }
911
- }
912
- }
913
- }
914
- statements.unshift(
915
- t2.expressionStatement(
916
- t2.assignmentExpression(
917
- "=",
918
- t2.memberExpression(valueMember, t2.identifier("length")),
919
- t2.numericLiteral(0)
920
- )
921
- )
922
- );
923
- }
924
- });
925
- return {
926
- code: hasPatched ? content : generate(ast).code,
927
- hasPatched
928
- };
929
- }
930
-
931
- // src/patching/operations/extend-length-units.ts
932
-
933
-
934
-
935
-
936
- // src/utils.ts
937
- function isObject(val) {
938
- return val !== null && typeof val === "object" && Array.isArray(val) === false;
939
- }
940
- function spliceChangesIntoString(str, changes) {
941
- if (!changes[0]) {
942
- return str;
943
- }
944
- changes.sort((a, b) => {
945
- return a.end - b.end || a.start - b.start;
946
- });
947
- let result = "";
948
- let previous = changes[0];
949
- result += str.slice(0, previous.start);
950
- result += previous.replacement;
951
- for (let i = 1; i < changes.length; ++i) {
952
- const change = changes[i];
953
- result += str.slice(previous.end, change.start);
954
- result += change.replacement;
955
- previous = change;
956
- }
957
- result += str.slice(previous.end);
958
- return result;
959
- }
960
-
961
- // src/patching/operations/extend-length-units.ts
962
- function updateLengthUnitsArray(content, options) {
963
- const { variableName = "lengthUnits", units } = options;
964
- const ast = _parser.parse.call(void 0, content);
965
- let arrayRef;
966
- let changed = false;
967
- traverse(ast, {
968
- Identifier(path11) {
969
- if (path11.node.name === variableName && t3.isVariableDeclarator(path11.parent) && t3.isArrayExpression(path11.parent.init)) {
970
- arrayRef = path11.parent.init;
971
- const existing = new Set(
972
- path11.parent.init.elements.map((element) => t3.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
973
- );
974
- for (const unit of units) {
975
- if (!existing.has(unit)) {
976
- path11.parent.init.elements = path11.parent.init.elements.map((element) => {
977
- if (t3.isStringLiteral(element)) {
978
- return t3.stringLiteral(element.value);
979
- }
980
- return element;
981
- });
982
- path11.parent.init.elements.push(t3.stringLiteral(unit));
983
- changed = true;
984
- }
985
- }
986
- }
987
- }
988
- });
989
- return {
990
- arrayRef,
991
- changed
992
- };
993
- }
994
- function applyExtendLengthUnitsPatchV3(rootDir, options) {
995
- if (!options.enabled) {
996
- return { changed: false, code: void 0 };
997
- }
998
- const opts = {
999
- ...options,
1000
- lengthUnitsFilePath: _nullishCoalesce(options.lengthUnitsFilePath, () => ( "lib/util/dataTypes.js")),
1001
- variableName: _nullishCoalesce(options.variableName, () => ( "lengthUnits"))
1002
- };
1003
- const dataTypesFilePath = _pathe2.default.resolve(rootDir, opts.lengthUnitsFilePath);
1004
- const exists = _fsextra2.default.existsSync(dataTypesFilePath);
1005
- if (!exists) {
1006
- return { changed: false, code: void 0 };
1007
- }
1008
- const content = _fsextra2.default.readFileSync(dataTypesFilePath, "utf8");
1009
- const { arrayRef, changed } = updateLengthUnitsArray(content, opts);
1010
- if (!arrayRef || !changed) {
1011
- return { changed: false, code: void 0 };
1012
- }
1013
- const { code } = generate(arrayRef, {
1014
- jsescOption: { quotes: "single" }
1015
- });
1016
- if (arrayRef.start != null && arrayRef.end != null) {
1017
- const nextCode = `${content.slice(0, arrayRef.start)}${code}${content.slice(arrayRef.end)}`;
1018
- if (opts.overwrite) {
1019
- const target = opts.destPath ? _pathe2.default.resolve(opts.destPath) : dataTypesFilePath;
1020
- _fsextra2.default.writeFileSync(target, nextCode, "utf8");
1021
- logger_default.success("Patched Tailwind CSS length unit list (v3).");
1022
- }
1023
- return {
1024
- changed: true,
1025
- code: nextCode
1026
- };
1027
- }
1028
- return {
1029
- changed: false,
1030
- code: void 0
1031
- };
1032
- }
1033
- function applyExtendLengthUnitsPatchV4(rootDir, options) {
1034
- if (!options.enabled) {
1035
- return { files: [], changed: false };
1036
- }
1037
- const opts = { ...options };
1038
- const distDir = _pathe2.default.resolve(rootDir, "dist");
1039
- if (!_fsextra2.default.existsSync(distDir)) {
1040
- return { files: [], changed: false };
1041
- }
1042
- const entries = _fsextra2.default.readdirSync(distDir);
1043
- const chunkNames = entries.filter((entry) => entry.endsWith(".js") || entry.endsWith(".mjs"));
1044
- const pattern = /\[\s*["']cm["'],\s*["']mm["'],[\w,"']+\]/;
1045
- const candidates = chunkNames.map((chunkName) => {
1046
- const file = _pathe2.default.join(distDir, chunkName);
1047
- const code = _fsextra2.default.readFileSync(file, "utf8");
1048
- const match = pattern.exec(code);
1049
- if (!match) {
1050
- return null;
1051
- }
1052
- return {
1053
- file,
1054
- code,
1055
- match,
1056
- hasPatched: false
1057
- };
1058
- }).filter((candidate) => candidate !== null);
1059
- for (const item of candidates) {
1060
- const { code, file, match } = item;
1061
- const ast = _parser.parse.call(void 0, match[0], { sourceType: "unambiguous" });
1062
- traverse(ast, {
1063
- ArrayExpression(path11) {
1064
- for (const unit of opts.units) {
1065
- if (path11.node.elements.some((element) => t3.isStringLiteral(element) && element.value === unit)) {
1066
- item.hasPatched = true;
1067
- return;
1068
- }
1069
- path11.node.elements.push(t3.stringLiteral(unit));
1070
- }
1071
- }
1072
- });
1073
- if (item.hasPatched) {
1074
- continue;
1075
- }
1076
- const { code: replacement } = generate(ast, { minified: true });
1077
- const start = _nullishCoalesce(match.index, () => ( 0));
1078
- const end = start + match[0].length;
1079
- item.code = spliceChangesIntoString(code, [
1080
- {
1081
- start,
1082
- end,
1083
- replacement: replacement.endsWith(";") ? replacement.slice(0, -1) : replacement
1084
- }
1085
- ]);
1086
- if (opts.overwrite) {
1087
- _fsextra2.default.writeFileSync(file, item.code, "utf8");
1088
- }
1089
- }
1090
- if (candidates.some((file) => !file.hasPatched)) {
1091
- logger_default.success("Patched Tailwind CSS length unit list (v4).");
1092
- }
1093
- return {
1094
- changed: candidates.some((file) => !file.hasPatched),
1095
- files: candidates
1096
- };
1097
- }
1098
-
1099
- // src/patching/status.ts
1100
- function inspectLengthUnitsArray(content, variableName, units) {
1101
- const ast = _parser.parse.call(void 0, content);
1102
- let found = false;
1103
- let missingUnits = [];
1104
- traverse(ast, {
1105
- Identifier(path11) {
1106
- if (path11.node.name === variableName && t4.isVariableDeclarator(path11.parent) && t4.isArrayExpression(path11.parent.init)) {
1107
- found = true;
1108
- const existing = new Set(
1109
- path11.parent.init.elements.map((element) => t4.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
1110
- );
1111
- missingUnits = units.filter((unit) => !existing.has(unit));
1112
- path11.stop();
1113
- }
1114
- }
1115
- });
1116
- return {
1117
- found,
1118
- missingUnits
1119
- };
1120
- }
1121
- function checkExposeContextPatch(context) {
1122
- const { packageInfo, options, majorVersion } = context;
1123
- const refProperty = options.features.exposeContext.refProperty;
1124
- if (!options.features.exposeContext.enabled) {
1125
- return {
1126
- name: "exposeContext",
1127
- status: "skipped",
1128
- reason: "exposeContext feature disabled",
1129
- files: []
1130
- };
1131
- }
1132
- if (majorVersion === 4) {
1133
- return {
1134
- name: "exposeContext",
1135
- status: "unsupported",
1136
- reason: "Context export patch is only required for Tailwind v2/v3",
1137
- files: []
1138
- };
1139
- }
1140
- const checks = [];
1141
- function inspectFile(relative, transform) {
1142
- const filePath = _pathe2.default.resolve(packageInfo.rootPath, relative);
1143
- if (!_fsextra2.default.existsSync(filePath)) {
1144
- checks.push({ relative, exists: false, patched: false });
1145
- return;
1146
- }
1147
- const content = _fsextra2.default.readFileSync(filePath, "utf8");
1148
- const { hasPatched } = transform(content);
1149
- checks.push({
1150
- relative,
1151
- exists: true,
1152
- patched: hasPatched
1153
- });
1154
- }
1155
- if (majorVersion === 3) {
1156
- inspectFile("lib/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContext);
1157
- const pluginCandidates = ["lib/plugin.js", "lib/index.js"];
1158
- const pluginRelative = pluginCandidates.find((candidate) => _fsextra2.default.existsSync(_pathe2.default.resolve(packageInfo.rootPath, candidate)));
1159
- if (pluginRelative) {
1160
- inspectFile(pluginRelative, (content) => transformPostcssPlugin(content, { refProperty }));
1161
- } else {
1162
- checks.push({ relative: "lib/plugin.js", exists: false, patched: false });
1163
- }
1164
- } else {
1165
- inspectFile("lib/jit/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContextV2);
1166
- inspectFile("lib/jit/index.js", (content) => transformPostcssPluginV2(content, { refProperty }));
1167
- }
1168
- const files = checks.filter((check) => check.exists).map((check) => check.relative);
1169
- const missingFiles = checks.filter((check) => !check.exists);
1170
- const unpatchedFiles = checks.filter((check) => check.exists && !check.patched);
1171
- const reasons = [];
1172
- if (missingFiles.length) {
1173
- reasons.push(`missing files: ${missingFiles.map((item) => item.relative).join(", ")}`);
1174
- }
1175
- if (unpatchedFiles.length) {
1176
- reasons.push(`unpatched files: ${unpatchedFiles.map((item) => item.relative).join(", ")}`);
1177
- }
1178
- return {
1179
- name: "exposeContext",
1180
- status: reasons.length ? "not-applied" : "applied",
1181
- reason: reasons.length ? reasons.join("; ") : void 0,
1182
- files
1183
- };
1184
- }
1185
- function checkExtendLengthUnitsV3(rootDir, options) {
1186
- const lengthUnitsFilePath = _nullishCoalesce(options.lengthUnitsFilePath, () => ( "lib/util/dataTypes.js"));
1187
- const variableName = _nullishCoalesce(options.variableName, () => ( "lengthUnits"));
1188
- const target = _pathe2.default.resolve(rootDir, lengthUnitsFilePath);
1189
- const files = _fsextra2.default.existsSync(target) ? [_pathe2.default.relative(rootDir, target)] : [];
1190
- if (!_fsextra2.default.existsSync(target)) {
1191
- return {
1192
- name: "extendLengthUnits",
1193
- status: "not-applied",
1194
- reason: `missing ${lengthUnitsFilePath}`,
1195
- files
1196
- };
1197
- }
1198
- const content = _fsextra2.default.readFileSync(target, "utf8");
1199
- const { found, missingUnits } = inspectLengthUnitsArray(content, variableName, options.units);
1200
- if (!found) {
1201
- return {
1202
- name: "extendLengthUnits",
1203
- status: "not-applied",
1204
- reason: `could not locate ${variableName} array in ${lengthUnitsFilePath}`,
1205
- files
1206
- };
1207
- }
1208
- if (missingUnits.length) {
1209
- return {
1210
- name: "extendLengthUnits",
1211
- status: "not-applied",
1212
- reason: `missing units: ${missingUnits.join(", ")}`,
1213
- files
1214
- };
1215
- }
1216
- return {
1217
- name: "extendLengthUnits",
1218
- status: "applied",
1219
- files
1220
- };
1221
- }
1222
- function checkExtendLengthUnitsV4(rootDir, options) {
1223
- const distDir = _pathe2.default.resolve(rootDir, "dist");
1224
- if (!_fsextra2.default.existsSync(distDir)) {
1225
- return {
1226
- name: "extendLengthUnits",
1227
- status: "not-applied",
1228
- reason: "dist directory not found for Tailwind v4 package",
1229
- files: []
1230
- };
1231
- }
1232
- const result = applyExtendLengthUnitsPatchV4(rootDir, {
1233
- ...options,
1234
- enabled: true,
1235
- overwrite: false
1236
- });
1237
- if (result.files.length === 0) {
1238
- return {
1239
- name: "extendLengthUnits",
1240
- status: "not-applied",
1241
- reason: "no bundle chunks matched the length unit pattern",
1242
- files: []
1243
- };
1244
- }
1245
- const files = result.files.map((file) => _pathe2.default.relative(rootDir, file.file));
1246
- const pending = result.files.filter((file) => !file.hasPatched);
1247
- if (pending.length) {
1248
- return {
1249
- name: "extendLengthUnits",
1250
- status: "not-applied",
1251
- reason: `missing units in ${pending.length} bundle${pending.length > 1 ? "s" : ""}`,
1252
- files: pending.map((file) => _pathe2.default.relative(rootDir, file.file))
1253
- };
1254
- }
1255
- return {
1256
- name: "extendLengthUnits",
1257
- status: "applied",
1258
- files
1259
- };
1260
- }
1261
- function checkExtendLengthUnitsPatch(context) {
1262
- const { packageInfo, options, majorVersion } = context;
1263
- if (!options.features.extendLengthUnits) {
1264
- return {
1265
- name: "extendLengthUnits",
1266
- status: "skipped",
1267
- reason: "extendLengthUnits feature disabled",
1268
- files: []
1269
- };
1270
- }
1271
- if (majorVersion === 2) {
1272
- return {
1273
- name: "extendLengthUnits",
1274
- status: "unsupported",
1275
- reason: "length unit extension is only applied for Tailwind v3/v4",
1276
- files: []
1277
- };
1278
- }
1279
- if (majorVersion === 3) {
1280
- return checkExtendLengthUnitsV3(packageInfo.rootPath, options.features.extendLengthUnits);
1281
- }
1282
- return checkExtendLengthUnitsV4(packageInfo.rootPath, options.features.extendLengthUnits);
1283
- }
1284
- function getPatchStatusReport(context) {
1285
- return {
1286
- package: {
1287
- name: _nullishCoalesce(context.packageInfo.name, () => ( _optionalChain([context, 'access', _42 => _42.packageInfo, 'access', _43 => _43.packageJson, 'optionalAccess', _44 => _44.name]))),
1288
- version: context.packageInfo.version,
1289
- root: context.packageInfo.rootPath
1290
- },
1291
- majorVersion: context.majorVersion,
1292
- entries: [
1293
- checkExposeContextPatch(context),
1294
- checkExtendLengthUnitsPatch(context)
1295
- ]
1296
- };
1297
- }
1298
-
1299
- // src/runtime/class-collector.ts
1300
-
1301
-
1302
-
1303
- function collectClassesFromContexts(contexts, filter) {
1304
- const set = /* @__PURE__ */ new Set();
1305
- for (const context of contexts) {
1306
- if (!isObject(context) || !context.classCache) {
1307
- continue;
1308
- }
1309
- for (const key of context.classCache.keys()) {
1310
- const className = key.toString();
1311
- if (filter(className)) {
1312
- set.add(className);
1313
- }
1314
- }
1315
- }
1316
- return set;
1317
- }
1318
- async function collectClassesFromTailwindV4(options) {
1319
- const set = /* @__PURE__ */ new Set();
1320
- const v4Options = options.tailwind.v4;
1321
- if (!v4Options) {
1322
- return set;
1323
- }
1324
- const toAbsolute = (value) => {
1325
- if (!value) {
1326
- return void 0;
1327
- }
1328
- return _pathe2.default.isAbsolute(value) ? value : _pathe2.default.resolve(options.projectRoot, value);
1329
- };
1330
- const resolvedConfiguredBase = toAbsolute(v4Options.configuredBase);
1331
- const resolvedDefaultBase = _nullishCoalesce(toAbsolute(v4Options.base), () => ( _process2.default.cwd()));
1332
- const resolveSources = (base) => {
1333
- if (!_optionalChain([v4Options, 'access', _45 => _45.sources, 'optionalAccess', _46 => _46.length])) {
1334
- return void 0;
1335
- }
1336
- return v4Options.sources.map((source) => ({
1337
- base: _nullishCoalesce(source.base, () => ( base)),
1338
- pattern: source.pattern,
1339
- negated: source.negated
1340
- }));
1341
- };
1342
- if (v4Options.cssEntries.length > 0) {
1343
- for (const entry of v4Options.cssEntries) {
1344
- const filePath = _pathe2.default.isAbsolute(entry) ? entry : _pathe2.default.resolve(options.projectRoot, entry);
1345
- if (!await _fsextra2.default.pathExists(filePath)) {
1346
- continue;
1347
- }
1348
- const css = await _fsextra2.default.readFile(filePath, "utf8");
1349
- const entryDir = _pathe2.default.dirname(filePath);
1350
- const baseForEntry = _nullishCoalesce(resolvedConfiguredBase, () => ( entryDir));
1351
- const sources = resolveSources(baseForEntry);
1352
- const candidates = await extractValidCandidates({
1353
- cwd: options.projectRoot,
1354
- base: baseForEntry,
1355
- css,
1356
- sources
1357
- });
1358
- for (const candidate of candidates) {
1359
- if (options.filter(candidate)) {
1360
- set.add(candidate);
1361
- }
1362
- }
1363
- }
1364
- } else {
1365
- const baseForCss = _nullishCoalesce(resolvedConfiguredBase, () => ( resolvedDefaultBase));
1366
- const sources = resolveSources(baseForCss);
1367
- const candidates = await extractValidCandidates({
1368
- cwd: options.projectRoot,
1369
- base: baseForCss,
1370
- css: v4Options.css,
1371
- sources
1372
- });
1373
- for (const candidate of candidates) {
1374
- if (options.filter(candidate)) {
1375
- set.add(candidate);
1376
- }
1377
- }
1378
- }
1379
- return set;
1380
- }
1381
-
1382
- // src/runtime/context-registry.ts
1383
- var _module = require('module');
1384
-
1385
-
1386
- var require2 = _module.createRequire.call(void 0, importMetaUrl);
1387
- function resolveRuntimeEntry(packageInfo, majorVersion) {
1388
- const root = packageInfo.rootPath;
1389
- if (majorVersion === 2) {
1390
- const jitIndex = _pathe2.default.join(root, "lib/jit/index.js");
1391
- if (_fsextra2.default.existsSync(jitIndex)) {
1392
- return jitIndex;
1393
- }
1394
- } else if (majorVersion === 3) {
1395
- const plugin = _pathe2.default.join(root, "lib/plugin.js");
1396
- const index = _pathe2.default.join(root, "lib/index.js");
1397
- if (_fsextra2.default.existsSync(plugin)) {
1398
- return plugin;
1399
- }
1400
- if (_fsextra2.default.existsSync(index)) {
1401
- return index;
1402
- }
1403
- }
1404
- return void 0;
1405
- }
1406
- function loadRuntimeContexts(packageInfo, majorVersion, refProperty) {
1407
- if (majorVersion === 4) {
1408
- return [];
1409
- }
1410
- const entry = resolveRuntimeEntry(packageInfo, majorVersion);
1411
- if (!entry) {
1412
- return [];
1413
- }
1414
- const moduleExports = require2(entry);
1415
- if (!moduleExports) {
1416
- return [];
1417
- }
1418
- const ref = moduleExports[refProperty];
1419
- if (!ref) {
1420
- return [];
1421
- }
1422
- if (Array.isArray(ref)) {
1423
- return ref;
1424
- }
1425
- if (typeof ref === "object" && Array.isArray(ref.value)) {
1426
- return ref.value;
1427
- }
1428
- return [];
1429
- }
1430
-
1431
- // src/runtime/process-tailwindcss.ts
1432
-
1433
-
1434
- var _postcss = require('postcss'); var _postcss2 = _interopRequireDefault(_postcss);
1435
- var _tailwindcssconfig = require('tailwindcss-config');
1436
- var require3 = _module.createRequire.call(void 0, importMetaUrl);
1437
- async function resolveConfigPath(options) {
1438
- if (options.config && _pathe2.default.isAbsolute(options.config)) {
1439
- return options.config;
1440
- }
1441
- const result = await _tailwindcssconfig.loadConfig.call(void 0, { cwd: options.cwd });
1442
- if (!result) {
1443
- throw new Error(`Unable to locate Tailwind CSS config from ${options.cwd}`);
1444
- }
1445
- return result.filepath;
1446
- }
1447
- async function runTailwindBuild(options) {
1448
- const configPath = await resolveConfigPath(options);
1449
- const pluginName = _nullishCoalesce(options.postcssPlugin, () => ( (options.majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss")));
1450
- if (options.majorVersion === 4) {
1451
- return _postcss2.default.call(void 0, [
1452
- require3(pluginName)({
1453
- config: configPath
1454
- })
1455
- ]).process("@import 'tailwindcss';", {
1456
- from: void 0
1457
- });
1458
- }
1459
- return _postcss2.default.call(void 0, [
1460
- require3(pluginName)({
1461
- config: configPath
1462
- })
1463
- ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
1464
- from: void 0
1465
- });
1466
- }
1467
-
1468
- // src/api/tailwindcss-patcher.ts
1469
-
1470
-
1471
- var _localpkg = require('local-pkg');
1472
-
1473
- var _semver = require('semver');
1474
-
1475
- // src/options/legacy.ts
1476
- function normalizeLegacyFeatures(patch) {
1477
- const apply = _optionalChain([patch, 'optionalAccess', _47 => _47.applyPatches]);
1478
- const extend = _optionalChain([apply, 'optionalAccess', _48 => _48.extendLengthUnits]);
1479
- let extendOption = false;
1480
- if (extend && typeof extend === "object") {
1481
- extendOption = {
1482
- ...extend,
1483
- enabled: true
1484
- };
1485
- } else if (extend === true) {
1486
- extendOption = {
1487
- enabled: true,
1488
- units: ["rpx"],
1489
- overwrite: _optionalChain([patch, 'optionalAccess', _49 => _49.overwrite])
1490
- };
1491
- }
1492
- return {
1493
- exposeContext: _nullishCoalesce(_optionalChain([apply, 'optionalAccess', _50 => _50.exportContext]), () => ( true)),
1494
- extendLengthUnits: extendOption
1495
- };
1496
- }
1497
- function fromLegacyOptions(options) {
1498
- if (!options) {
1499
- return {};
1500
- }
1501
- const patch = options.patch;
1502
- const features = normalizeLegacyFeatures(patch);
1503
- const output = _optionalChain([patch, 'optionalAccess', _51 => _51.output]);
1504
- const tailwindConfig = _optionalChain([patch, 'optionalAccess', _52 => _52.tailwindcss]);
1505
- const tailwindVersion = _optionalChain([tailwindConfig, 'optionalAccess', _53 => _53.version]);
1506
- const tailwindV2 = _optionalChain([tailwindConfig, 'optionalAccess', _54 => _54.v2]);
1507
- const tailwindV3 = _optionalChain([tailwindConfig, 'optionalAccess', _55 => _55.v3]);
1508
- const tailwindV4 = _optionalChain([tailwindConfig, 'optionalAccess', _56 => _56.v4]);
1509
- const tailwindConfigPath = _nullishCoalesce(_optionalChain([tailwindV3, 'optionalAccess', _57 => _57.config]), () => ( _optionalChain([tailwindV2, 'optionalAccess', _58 => _58.config])));
1510
- const tailwindCwd = _nullishCoalesce(_nullishCoalesce(_optionalChain([tailwindV3, 'optionalAccess', _59 => _59.cwd]), () => ( _optionalChain([tailwindV2, 'optionalAccess', _60 => _60.cwd]))), () => ( _optionalChain([patch, 'optionalAccess', _61 => _61.cwd])));
1511
- return {
1512
- cwd: _optionalChain([patch, 'optionalAccess', _62 => _62.cwd]),
1513
- overwrite: _optionalChain([patch, 'optionalAccess', _63 => _63.overwrite]),
1514
- filter: _optionalChain([patch, 'optionalAccess', _64 => _64.filter]),
1515
- cache: typeof options.cache === "boolean" ? options.cache : options.cache ? {
1516
- ...options.cache,
1517
- enabled: _nullishCoalesce(options.cache.enabled, () => ( true))
1518
- } : void 0,
1519
- output: output ? {
1520
- file: output.filename,
1521
- pretty: output.loose ? 2 : false,
1522
- removeUniversalSelector: output.removeUniversalSelector
1523
- } : void 0,
1524
- tailwind: {
1525
- packageName: _optionalChain([patch, 'optionalAccess', _65 => _65.packageName]),
1526
- version: tailwindVersion,
1527
- resolve: _optionalChain([patch, 'optionalAccess', _66 => _66.resolve]),
1528
- config: tailwindConfigPath,
1529
- cwd: tailwindCwd,
1530
- v2: tailwindV2,
1531
- v3: tailwindV3,
1532
- v4: tailwindV4
1533
- },
1534
- features: {
1535
- exposeContext: features.exposeContext,
1536
- extendLengthUnits: features.extendLengthUnits
1537
- }
1538
- };
1539
- }
1540
- function fromUnifiedConfig(registry) {
1541
- if (!registry) {
1542
- return {};
1543
- }
1544
- const tailwind = registry.tailwind;
1545
- const output = registry.output;
1546
- const pretty = (() => {
1547
- if (_optionalChain([output, 'optionalAccess', _67 => _67.pretty]) === void 0) {
1548
- return void 0;
1549
- }
1550
- if (typeof output.pretty === "boolean") {
1551
- return output.pretty ? 2 : false;
1552
- }
1553
- return output.pretty;
1554
- })();
1555
- return {
1556
- output: output ? {
1557
- file: output.file,
1558
- pretty,
1559
- removeUniversalSelector: output.stripUniversalSelector
1560
- } : void 0,
1561
- tailwind: tailwind ? {
1562
- version: tailwind.version,
1563
- packageName: tailwind.package,
1564
- resolve: tailwind.resolve,
1565
- config: tailwind.config,
1566
- cwd: tailwind.cwd,
1567
- v2: tailwind.legacy,
1568
- v3: tailwind.classic,
1569
- v4: tailwind.next
1570
- } : void 0
1571
- };
1572
- }
1573
-
1574
- // src/patching/operations/export-context/index.ts
1575
-
1576
-
1577
- function writeFileIfRequired(filePath, code, overwrite, successMessage) {
1578
- if (!overwrite) {
1579
- return;
1580
- }
1581
- _fsextra2.default.writeFileSync(filePath, code, {
1582
- encoding: "utf8"
1583
- });
1584
- logger_default.success(successMessage);
1585
- }
1586
- function applyExposeContextPatch(params) {
1587
- const { rootDir, refProperty, overwrite, majorVersion } = params;
1588
- const result = {
1589
- applied: false,
1590
- files: {}
1591
- };
1592
- if (majorVersion === 3) {
1593
- const processFileRelative = "lib/processTailwindFeatures.js";
1594
- const processFilePath = _pathe2.default.resolve(rootDir, processFileRelative);
1595
- if (_fsextra2.default.existsSync(processFilePath)) {
1596
- const content = _fsextra2.default.readFileSync(processFilePath, "utf8");
1597
- const { code, hasPatched } = transformProcessTailwindFeaturesReturnContext(content);
1598
- result.files[processFileRelative] = code;
1599
- if (!hasPatched) {
1600
- writeFileIfRequired(
1601
- processFilePath,
1602
- code,
1603
- overwrite,
1604
- "Patched Tailwind CSS processTailwindFeatures to expose runtime context."
1605
- );
1606
- result.applied = true;
1607
- }
1608
- }
1609
- const pluginCandidates = ["lib/plugin.js", "lib/index.js"];
1610
- const pluginRelative = pluginCandidates.find((candidate) => _fsextra2.default.existsSync(_pathe2.default.resolve(rootDir, candidate)));
1611
- if (pluginRelative) {
1612
- const pluginPath = _pathe2.default.resolve(rootDir, pluginRelative);
1613
- const content = _fsextra2.default.readFileSync(pluginPath, "utf8");
1614
- const { code, hasPatched } = transformPostcssPlugin(content, { refProperty });
1615
- result.files[pluginRelative] = code;
1616
- if (!hasPatched) {
1617
- writeFileIfRequired(
1618
- pluginPath,
1619
- code,
1620
- overwrite,
1621
- "Patched Tailwind CSS plugin entry to collect runtime contexts."
1622
- );
1623
- result.applied = true;
1624
- }
1625
- }
1626
- } else if (majorVersion === 2) {
1627
- const processFileRelative = "lib/jit/processTailwindFeatures.js";
1628
- const processFilePath = _pathe2.default.resolve(rootDir, processFileRelative);
1629
- if (_fsextra2.default.existsSync(processFilePath)) {
1630
- const content = _fsextra2.default.readFileSync(processFilePath, "utf8");
1631
- const { code, hasPatched } = transformProcessTailwindFeaturesReturnContextV2(content);
1632
- result.files[processFileRelative] = code;
1633
- if (!hasPatched) {
1634
- writeFileIfRequired(
1635
- processFilePath,
1636
- code,
1637
- overwrite,
1638
- "Patched Tailwind CSS JIT processTailwindFeatures to expose runtime context."
1639
- );
1640
- result.applied = true;
1641
- }
1642
- }
1643
- const pluginRelative = "lib/jit/index.js";
1644
- const pluginPath = _pathe2.default.resolve(rootDir, pluginRelative);
1645
- if (_fsextra2.default.existsSync(pluginPath)) {
1646
- const content = _fsextra2.default.readFileSync(pluginPath, "utf8");
1647
- const { code, hasPatched } = transformPostcssPluginV2(content, { refProperty });
1648
- result.files[pluginRelative] = code;
1649
- if (!hasPatched) {
1650
- writeFileIfRequired(
1651
- pluginPath,
1652
- code,
1653
- overwrite,
1654
- "Patched Tailwind CSS JIT entry to collect runtime contexts."
1655
- );
1656
- result.applied = true;
1657
- }
1658
- }
1659
- }
1660
- return result;
1661
- }
1662
-
1663
- // src/patching/patch-runner.ts
1664
- function applyTailwindPatches(context) {
1665
- const { packageInfo, options, majorVersion } = context;
1666
- const results = {};
1667
- if (options.features.exposeContext.enabled && (majorVersion === 2 || majorVersion === 3)) {
1668
- results.exposeContext = applyExposeContextPatch({
1669
- rootDir: packageInfo.rootPath,
1670
- refProperty: options.features.exposeContext.refProperty,
1671
- overwrite: options.overwrite,
1672
- majorVersion
1673
- });
1674
- }
1675
- if (_optionalChain([options, 'access', _68 => _68.features, 'access', _69 => _69.extendLengthUnits, 'optionalAccess', _70 => _70.enabled])) {
1676
- if (majorVersion === 3) {
1677
- results.extendLengthUnits = applyExtendLengthUnitsPatchV3(
1678
- packageInfo.rootPath,
1679
- options.features.extendLengthUnits
1680
- );
1681
- } else if (majorVersion === 4) {
1682
- results.extendLengthUnits = applyExtendLengthUnitsPatchV4(
1683
- packageInfo.rootPath,
1684
- options.features.extendLengthUnits
1685
- );
1686
- }
1687
- }
1688
- return results;
1689
- }
1690
-
1691
- // src/api/tailwindcss-patcher.ts
1692
- function resolveMajorVersion(version, hint) {
1693
- if (hint && [2, 3, 4].includes(hint)) {
1694
- return hint;
1695
- }
1696
- if (version) {
1697
- const coerced = _semver.coerce.call(void 0, version);
1698
- if (coerced) {
1699
- const major = coerced.major;
1700
- if (major === 2 || major === 3 || major === 4) {
1701
- return major;
1702
- }
1703
- if (major >= 4) {
1704
- return 4;
1705
- }
1706
- }
1707
- }
1708
- return 3;
1709
- }
1710
- function resolveTailwindExecutionOptions(normalized, majorVersion) {
1711
- const base = normalized.tailwind;
1712
- if (majorVersion === 2 && base.v2) {
1713
- return {
1714
- cwd: _nullishCoalesce(_nullishCoalesce(base.v2.cwd, () => ( base.cwd)), () => ( normalized.projectRoot)),
1715
- config: _nullishCoalesce(base.v2.config, () => ( base.config)),
1716
- postcssPlugin: _nullishCoalesce(base.v2.postcssPlugin, () => ( base.postcssPlugin))
1717
- };
1718
- }
1719
- if (majorVersion === 3 && base.v3) {
1720
- return {
1721
- cwd: _nullishCoalesce(_nullishCoalesce(base.v3.cwd, () => ( base.cwd)), () => ( normalized.projectRoot)),
1722
- config: _nullishCoalesce(base.v3.config, () => ( base.config)),
1723
- postcssPlugin: _nullishCoalesce(base.v3.postcssPlugin, () => ( base.postcssPlugin))
1724
- };
1725
- }
1726
- return {
1727
- cwd: _nullishCoalesce(base.cwd, () => ( normalized.projectRoot)),
1728
- config: base.config,
1729
- postcssPlugin: base.postcssPlugin
1730
- };
1731
- }
1732
- var TailwindcssPatcher = (_class2 = class {
1733
-
1734
-
1735
-
1736
-
1737
- constructor(options = {}) {;_class2.prototype.__init2.call(this);
1738
- const resolvedOptions = options && typeof options === "object" && "patch" in options ? fromLegacyOptions(options) : options;
1739
- this.options = normalizeOptions(resolvedOptions);
1740
- const packageInfo = _localpkg.getPackageInfoSync.call(void 0,
1741
- this.options.tailwind.packageName,
1742
- this.options.tailwind.resolve
1743
- );
1744
- if (!packageInfo) {
1745
- throw new Error(`Unable to locate Tailwind CSS package "${this.options.tailwind.packageName}".`);
1746
- }
1747
- this.packageInfo = packageInfo;
1748
- this.majorVersion = resolveMajorVersion(
1749
- this.packageInfo.version,
1750
- this.options.tailwind.versionHint
1751
- );
1752
- this.cacheStore = new CacheStore(this.options.cache);
1753
- }
1754
- async patch() {
1755
- return applyTailwindPatches({
1756
- packageInfo: this.packageInfo,
1757
- options: this.options,
1758
- majorVersion: this.majorVersion
1759
- });
1760
- }
1761
- async getPatchStatus() {
1762
- return getPatchStatusReport({
1763
- packageInfo: this.packageInfo,
1764
- options: this.options,
1765
- majorVersion: this.majorVersion
1766
- });
1767
- }
1768
- getContexts() {
1769
- return loadRuntimeContexts(
1770
- this.packageInfo,
1771
- this.majorVersion,
1772
- this.options.features.exposeContext.refProperty
1773
- );
1774
- }
1775
- async runTailwindBuildIfNeeded() {
1776
- if (this.majorVersion === 2 || this.majorVersion === 3) {
1777
- const executionOptions = resolveTailwindExecutionOptions(this.options, this.majorVersion);
1778
- await runTailwindBuild({
1779
- cwd: executionOptions.cwd,
1780
- config: executionOptions.config,
1781
- majorVersion: this.majorVersion,
1782
- postcssPlugin: executionOptions.postcssPlugin
1783
- });
1784
- }
1785
- }
1786
- async collectClassSet() {
1787
- if (this.majorVersion === 4) {
1788
- return collectClassesFromTailwindV4(this.options);
1789
- }
1790
- const contexts = this.getContexts();
1791
- return collectClassesFromContexts(contexts, this.options.filter);
1792
- }
1793
- async mergeWithCache(set) {
1794
- if (!this.options.cache.enabled) {
1795
- return set;
1796
- }
1797
- const existing = await this.cacheStore.read();
1798
- if (this.options.cache.strategy === "merge") {
1799
- for (const value of existing) {
1800
- set.add(value);
1801
- }
1802
- await this.cacheStore.write(set);
1803
- } else {
1804
- if (set.size > 0) {
1805
- await this.cacheStore.write(set);
1806
- } else {
1807
- return existing;
1808
- }
1809
- }
1810
- return set;
1811
- }
1812
- mergeWithCacheSync(set) {
1813
- if (!this.options.cache.enabled) {
1814
- return set;
1815
- }
1816
- const existing = this.cacheStore.readSync();
1817
- if (this.options.cache.strategy === "merge") {
1818
- for (const value of existing) {
1819
- set.add(value);
1820
- }
1821
- this.cacheStore.writeSync(set);
1822
- } else {
1823
- if (set.size > 0) {
1824
- this.cacheStore.writeSync(set);
1825
- } else {
1826
- return existing;
1827
- }
1828
- }
1829
- return set;
1830
- }
1831
- async getClassSet() {
1832
- await this.runTailwindBuildIfNeeded();
1833
- const set = await this.collectClassSet();
1834
- return this.mergeWithCache(set);
1835
- }
1836
- getClassSetSync() {
1837
- if (this.majorVersion === 4) {
1838
- throw new Error("getClassSetSync is not supported for Tailwind CSS v4 projects. Use getClassSet instead.");
1839
- }
1840
- const contexts = this.getContexts();
1841
- const set = collectClassesFromContexts(contexts, this.options.filter);
1842
- const merged = this.mergeWithCacheSync(set);
1843
- if (contexts.length === 0 && merged.size === 0) {
1844
- return void 0;
1845
- }
1846
- return merged;
1847
- }
1848
- async extract(options) {
1849
- const shouldWrite = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _71 => _71.write]), () => ( this.options.output.enabled));
1850
- const classSet = await this.getClassSet();
1851
- const classList = Array.from(classSet);
1852
- const result = {
1853
- classList,
1854
- classSet
1855
- };
1856
- if (!shouldWrite || !this.options.output.file) {
1857
- return result;
1858
- }
1859
- const target = _pathe2.default.resolve(this.options.output.file);
1860
- await _fsextra2.default.ensureDir(_pathe2.default.dirname(target));
1861
- if (this.options.output.format === "json") {
1862
- const spaces = typeof this.options.output.pretty === "number" ? this.options.output.pretty : void 0;
1863
- await _fsextra2.default.writeJSON(target, classList, { spaces });
1864
- } else {
1865
- await _fsextra2.default.writeFile(target, `${classList.join("\n")}
1866
- `, "utf8");
1867
- }
1868
- logger_default.success(`Tailwind CSS class list saved to ${target.replace(_process2.default.cwd(), ".")}`);
1869
- return {
1870
- ...result,
1871
- filename: target
1872
- };
1873
- }
1874
- // Backwards compatibility helper used by tests and API consumers.
1875
- __init2() {this.extractValidCandidates = exports.extractValidCandidates = extractValidCandidates}
1876
- async collectContentTokens(options) {
1877
- return extractProjectCandidatesWithPositions({
1878
- cwd: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _72 => _72.cwd]), () => ( this.options.projectRoot)),
1879
- sources: _nullishCoalesce(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _73 => _73.sources]), () => ( _optionalChain([this, 'access', _74 => _74.options, 'access', _75 => _75.tailwind, 'access', _76 => _76.v4, 'optionalAccess', _77 => _77.sources]))), () => ( []))
1880
- });
1881
- }
1882
- async collectContentTokensByFile(options) {
1883
- const report = await this.collectContentTokens({
1884
- cwd: _optionalChain([options, 'optionalAccess', _78 => _78.cwd]),
1885
- sources: _optionalChain([options, 'optionalAccess', _79 => _79.sources])
1886
- });
1887
- return groupTokensByFile(report, {
1888
- key: _optionalChain([options, 'optionalAccess', _80 => _80.key]),
1889
- stripAbsolutePaths: _optionalChain([options, 'optionalAccess', _81 => _81.stripAbsolutePaths])
1890
- });
1891
- }
1892
- }, _class2);
1893
-
1894
- // src/cli/commands.ts
1895
-
1896
- var _config = require('@tailwindcss-mangle/config');
1897
-
1898
- // ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
1899
- function isPlainObject(value) {
1900
- if (value === null || typeof value !== "object") {
1901
- return false;
1902
- }
1903
- const prototype = Object.getPrototypeOf(value);
1904
- if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
1905
- return false;
1906
- }
1907
- if (Symbol.iterator in value) {
1908
- return false;
1909
- }
1910
- if (Symbol.toStringTag in value) {
1911
- return Object.prototype.toString.call(value) === "[object Module]";
1912
- }
1913
- return true;
1914
- }
1915
- function _defu(baseObject, defaults, namespace = ".", merger) {
1916
- if (!isPlainObject(defaults)) {
1917
- return _defu(baseObject, {}, namespace, merger);
1918
- }
1919
- const object = Object.assign({}, defaults);
1920
- for (const key in baseObject) {
1921
- if (key === "__proto__" || key === "constructor") {
1922
- continue;
1923
- }
1924
- const value = baseObject[key];
1925
- if (value === null || value === void 0) {
1926
- continue;
1927
- }
1928
- if (merger && merger(object, key, value, namespace)) {
1929
- continue;
1930
- }
1931
- if (Array.isArray(value) && Array.isArray(object[key])) {
1932
- object[key] = [...value, ...object[key]];
1933
- } else if (isPlainObject(value) && isPlainObject(object[key])) {
1934
- object[key] = _defu(
1935
- value,
1936
- object[key],
1937
- (namespace ? `${namespace}.` : "") + key.toString(),
1938
- merger
1939
- );
1940
- } else {
1941
- object[key] = value;
1942
- }
1943
- }
1944
- return object;
1945
- }
1946
- function createDefu(merger) {
1947
- return (...arguments_) => (
1948
- // eslint-disable-next-line unicorn/no-array-reduce
1949
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
1950
- );
1951
- }
1952
- var defu = createDefu();
1953
- var defuFn = createDefu((object, key, currentValue) => {
1954
- if (object[key] !== void 0 && typeof currentValue === "function") {
1955
- object[key] = currentValue(object[key]);
1956
- return true;
1957
- }
1958
- });
1959
- var defuArrayFn = createDefu((object, key, currentValue) => {
1960
- if (Array.isArray(object[key]) && typeof currentValue === "function") {
1961
- object[key] = currentValue(object[key]);
1962
- return true;
1963
- }
1964
- });
1965
-
1966
- // ../shared/src/utils.ts
1967
- var defuOverrideArray = createDefu((obj, key, value) => {
1968
- if (Array.isArray(obj[key]) && Array.isArray(value)) {
1969
- obj[key] = value;
1970
- return true;
1971
- }
1972
- });
1973
- var preserveClassNames = [
1974
- // https://tailwindcss.com/docs/transition-timing-function start
1975
- // https://github.com/sonofmagic/tailwindcss-mangle/issues/21
1976
- "ease-out",
1977
- "ease-linear",
1978
- "ease-in",
1979
- "ease-in-out"
1980
- // https://tailwindcss.com/docs/transition-timing-function end
1981
- ];
1982
- var preserveClassNamesMap = preserveClassNames.reduce((acc, cur) => {
1983
- acc[cur] = true;
1984
- return acc;
1985
- }, {});
1986
- var acceptChars = [..."abcdefghijklmnopqrstuvwxyz"];
1987
-
1988
- // src/cli/commands.ts
1989
- var _cac = require('cac'); var _cac2 = _interopRequireDefault(_cac);
1990
-
1991
-
1992
- var tailwindcssPatchCommands = ["install", "extract", "tokens", "init", "status"];
1993
- var TOKEN_FORMATS = ["json", "lines", "grouped-json"];
1994
- var DEFAULT_TOKEN_REPORT = ".tw-patch/tw-token-report.json";
1995
- function formatTokenLine(entry) {
1996
- return `${entry.relativeFile}:${entry.line}:${entry.column} ${entry.rawCandidate} (${entry.start}-${entry.end})`;
1997
- }
1998
- function formatGroupedPreview(map, limit = 3) {
1999
- const files = Object.keys(map);
2000
- if (!files.length) {
2001
- return { preview: "", moreFiles: 0 };
2002
- }
2003
- const lines = files.slice(0, limit).map((file) => {
2004
- const tokens = map[file];
2005
- const sample = tokens.slice(0, 3).map((token) => token.rawCandidate).join(", ");
2006
- const suffix = tokens.length > 3 ? ", \u2026" : "";
2007
- return `${file}: ${tokens.length} tokens (${sample}${suffix})`;
2008
- });
2009
- return {
2010
- preview: lines.join("\n"),
2011
- moreFiles: Math.max(0, files.length - limit)
2012
- };
2013
- }
2014
- function resolveCwd(rawCwd) {
2015
- if (!rawCwd) {
2016
- return _process2.default.cwd();
2017
- }
2018
- return _pathe2.default.resolve(rawCwd);
2019
- }
2020
- function createDefaultRunner(factory) {
2021
- let promise;
2022
- return () => {
2023
- if (!promise) {
2024
- promise = factory();
2025
- }
2026
- return promise;
2027
- };
2028
- }
2029
- async function loadPatchOptionsForCwd(cwd, overrides) {
2030
- const { config } = await _config.getConfig.call(void 0, cwd);
2031
- const legacyConfig = config;
2032
- const base = _optionalChain([config, 'optionalAccess', _82 => _82.registry]) ? fromUnifiedConfig(config.registry) : _optionalChain([legacyConfig, 'optionalAccess', _83 => _83.patch]) ? fromLegacyOptions({ patch: legacyConfig.patch }) : {};
2033
- const merged = defu(_nullishCoalesce(overrides, () => ( {})), base);
2034
- return merged;
2035
- }
2036
- function createCommandContext(cli, command, commandName, args, cwd) {
2037
- let cachedOptions;
2038
- let cachedPatcher;
2039
- let cachedConfig;
2040
- const loadPatchOptionsForContext = (overrides) => {
2041
- if (overrides) {
2042
- return loadPatchOptionsForCwd(cwd, overrides);
2043
- }
2044
- if (!cachedOptions) {
2045
- cachedOptions = loadPatchOptionsForCwd(cwd);
2046
- }
2047
- return cachedOptions;
2048
- };
2049
- const createPatcherForContext = async (overrides) => {
2050
- if (overrides) {
2051
- const patchOptions = await loadPatchOptionsForCwd(cwd, overrides);
2052
- return new TailwindcssPatcher(patchOptions);
2053
- }
2054
- if (!cachedPatcher) {
2055
- cachedPatcher = loadPatchOptionsForContext().then((options) => new TailwindcssPatcher(options));
2056
- }
2057
- return cachedPatcher;
2058
- };
2059
- return {
2060
- cli,
2061
- command,
2062
- commandName,
2063
- args,
2064
- cwd,
2065
- logger: logger_default,
2066
- loadConfig: () => {
2067
- if (!cachedConfig) {
2068
- cachedConfig = _config.getConfig.call(void 0, cwd);
2069
- }
2070
- return cachedConfig;
2071
- },
2072
- loadPatchOptions: loadPatchOptionsForContext,
2073
- createPatcher: createPatcherForContext
2074
- };
2075
- }
2076
- function createCwdOptionDefinition(description = "Working directory") {
2077
- return {
2078
- flags: "--cwd <dir>",
2079
- description,
2080
- config: { default: _process2.default.cwd() }
2081
- };
2082
- }
2083
- function buildDefaultCommandDefinitions() {
2084
- return {
2085
- install: {
2086
- description: "Apply Tailwind CSS runtime patches",
2087
- optionDefs: [createCwdOptionDefinition()]
2088
- },
2089
- extract: {
2090
- description: "Collect generated class names into a cache file",
2091
- optionDefs: [
2092
- createCwdOptionDefinition(),
2093
- { flags: "--output <file>", description: "Override output file path" },
2094
- { flags: "--format <format>", description: "Output format (json|lines)" },
2095
- { flags: "--css <file>", description: "Tailwind CSS entry CSS when using v4" },
2096
- { flags: "--no-write", description: "Skip writing to disk" }
2097
- ]
2098
- },
2099
- tokens: {
2100
- description: "Extract Tailwind tokens with file/position metadata",
2101
- optionDefs: [
2102
- createCwdOptionDefinition(),
2103
- { flags: "--output <file>", description: "Override output file path", config: { default: DEFAULT_TOKEN_REPORT } },
2104
- {
2105
- flags: "--format <format>",
2106
- description: "Output format (json|lines|grouped-json)",
2107
- config: { default: "json" }
2108
- },
2109
- {
2110
- flags: "--group-key <key>",
2111
- description: "Grouping key for grouped-json output (relative|absolute)",
2112
- config: { default: "relative" }
2113
- },
2114
- { flags: "--no-write", description: "Skip writing to disk" }
2115
- ]
2116
- },
2117
- init: {
2118
- description: "Generate a tailwindcss-patch config file",
2119
- optionDefs: [createCwdOptionDefinition()]
2120
- },
2121
- status: {
2122
- description: "Check which Tailwind patches are applied",
2123
- optionDefs: [
2124
- createCwdOptionDefinition(),
2125
- { flags: "--json", description: "Print a JSON report of patch status" }
2126
- ]
2127
- }
2128
- };
2129
- }
2130
- function addPrefixIfMissing(value, prefix) {
2131
- if (!prefix || value.startsWith(prefix)) {
2132
- return value;
2133
- }
2134
- return `${prefix}${value}`;
2135
- }
2136
- function resolveCommandNames(command, mountOptions, prefix) {
2137
- const override = _optionalChain([mountOptions, 'access', _84 => _84.commandOptions, 'optionalAccess', _85 => _85[command]]);
2138
- const baseName = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _86 => _86.name]), () => ( command));
2139
- const name = addPrefixIfMissing(baseName, prefix);
2140
- const aliases = (_nullishCoalesce(_optionalChain([override, 'optionalAccess', _87 => _87.aliases]), () => ( []))).map((alias) => addPrefixIfMissing(alias, prefix));
2141
- return { name, aliases };
2142
- }
2143
- function resolveOptionDefinitions(defaults, override) {
2144
- if (!override) {
2145
- return defaults;
2146
- }
2147
- const appendDefaults = _nullishCoalesce(override.appendDefaultOptions, () => ( true));
2148
- const customDefs = _nullishCoalesce(override.optionDefs, () => ( []));
2149
- if (!appendDefaults) {
2150
- return customDefs;
2151
- }
2152
- if (customDefs.length === 0) {
2153
- return defaults;
2154
- }
2155
- return [...defaults, ...customDefs];
2156
- }
2157
- function applyCommandOptions(command, optionDefs) {
2158
- for (const option of optionDefs) {
2159
- command.option(option.flags, _nullishCoalesce(option.description, () => ( "")), option.config);
2160
- }
2161
- }
2162
- function runWithCommandHandler(cli, command, commandName, args, handler, defaultHandler) {
2163
- const cwd = resolveCwd(args.cwd);
2164
- const context = createCommandContext(cli, command, commandName, args, cwd);
2165
- const runDefault = createDefaultRunner(() => defaultHandler(context));
2166
- if (!handler) {
2167
- return runDefault();
2168
- }
2169
- return handler(context, runDefault);
2170
- }
2171
- function resolveCommandMetadata(command, mountOptions, prefix, defaults) {
2172
- const names = resolveCommandNames(command, mountOptions, prefix);
2173
- const definition = defaults[command];
2174
- const override = _optionalChain([mountOptions, 'access', _88 => _88.commandOptions, 'optionalAccess', _89 => _89[command]]);
2175
- const description = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _90 => _90.description]), () => ( definition.description));
2176
- const optionDefs = resolveOptionDefinitions(definition.optionDefs, override);
2177
- return { ...names, description, optionDefs };
2178
- }
2179
- async function installCommandDefaultHandler(ctx) {
2180
- const patcher = await ctx.createPatcher();
2181
- await patcher.patch();
2182
- logger_default.success("Tailwind CSS runtime patched successfully.");
2183
- }
2184
- async function extractCommandDefaultHandler(ctx) {
2185
- const { args } = ctx;
2186
- const overrides = {};
2187
- let hasOverrides = false;
2188
- if (args.output || args.format) {
2189
- overrides.output = {
2190
- file: args.output,
2191
- format: args.format
2192
- };
2193
- hasOverrides = true;
2194
- }
2195
- if (args.css) {
2196
- overrides.tailwind = {
2197
- v4: {
2198
- cssEntries: [args.css]
2199
- }
2200
- };
2201
- hasOverrides = true;
2202
- }
2203
- const patcher = await ctx.createPatcher(hasOverrides ? overrides : void 0);
2204
- const result = await patcher.extract({ write: args.write });
2205
- if (result.filename) {
2206
- logger_default.success(`Collected ${result.classList.length} classes \u2192 ${result.filename}`);
2207
- } else {
2208
- logger_default.success(`Collected ${result.classList.length} classes.`);
2209
- }
2210
- return result;
2211
- }
2212
- async function tokensCommandDefaultHandler(ctx) {
2213
- const { args } = ctx;
2214
- const patcher = await ctx.createPatcher();
2215
- const report = await patcher.collectContentTokens();
2216
- const shouldWrite = _nullishCoalesce(args.write, () => ( true));
2217
- let format = _nullishCoalesce(args.format, () => ( "json"));
2218
- if (!TOKEN_FORMATS.includes(format)) {
2219
- format = "json";
2220
- }
2221
- const targetFile = _nullishCoalesce(args.output, () => ( DEFAULT_TOKEN_REPORT));
2222
- const groupKey = args.groupKey === "absolute" ? "absolute" : "relative";
2223
- const buildGrouped = () => groupTokensByFile(report, {
2224
- key: groupKey,
2225
- stripAbsolutePaths: groupKey !== "absolute"
2226
- });
2227
- const grouped = format === "grouped-json" ? buildGrouped() : null;
2228
- const resolveGrouped = () => _nullishCoalesce(grouped, () => ( buildGrouped()));
2229
- if (shouldWrite) {
2230
- const target = _pathe2.default.resolve(targetFile);
2231
- await _fsextra2.default.ensureDir(_pathe2.default.dirname(target));
2232
- if (format === "json") {
2233
- await _fsextra2.default.writeJSON(target, report, { spaces: 2 });
2234
- } else if (format === "grouped-json") {
2235
- await _fsextra2.default.writeJSON(target, resolveGrouped(), { spaces: 2 });
2236
- } else {
2237
- const lines = report.entries.map(formatTokenLine);
2238
- await _fsextra2.default.writeFile(target, `${lines.join("\n")}
2239
- `, "utf8");
2240
- }
2241
- logger_default.success(`Collected ${report.entries.length} tokens (${format}) \u2192 ${target.replace(_process2.default.cwd(), ".")}`);
2242
- } else {
2243
- logger_default.success(`Collected ${report.entries.length} tokens from ${report.filesScanned} files.`);
2244
- if (format === "lines") {
2245
- const preview = report.entries.slice(0, 5).map(formatTokenLine).join("\n");
2246
- if (preview) {
2247
- logger_default.log("");
2248
- logger_default.info(preview);
2249
- if (report.entries.length > 5) {
2250
- logger_default.info(`\u2026and ${report.entries.length - 5} more.`);
2251
- }
2252
- }
2253
- } else if (format === "grouped-json") {
2254
- const map = resolveGrouped();
2255
- const { preview, moreFiles } = formatGroupedPreview(map);
2256
- if (preview) {
2257
- logger_default.log("");
2258
- logger_default.info(preview);
2259
- if (moreFiles > 0) {
2260
- logger_default.info(`\u2026and ${moreFiles} more files.`);
2261
- }
2262
- }
2263
- } else {
2264
- const previewEntries = report.entries.slice(0, 3);
2265
- if (previewEntries.length) {
2266
- logger_default.log("");
2267
- logger_default.info(JSON.stringify(previewEntries, null, 2));
2268
- }
2269
- }
2270
- }
2271
- if (report.skippedFiles.length) {
2272
- logger_default.warn("Skipped files:");
2273
- for (const skipped of report.skippedFiles) {
2274
- logger_default.warn(` \u2022 ${skipped.file} (${skipped.reason})`);
2275
- }
2276
- }
2277
- return report;
2278
- }
2279
- async function initCommandDefaultHandler(ctx) {
2280
- await _config.initConfig.call(void 0, ctx.cwd);
2281
- logger_default.success(`\u2728 ${_config.CONFIG_NAME}.config.ts initialized!`);
2282
- }
2283
- function formatFilesHint(entry) {
2284
- if (!entry.files.length) {
2285
- return "";
2286
- }
2287
- return ` (${entry.files.join(", ")})`;
2288
- }
2289
- async function statusCommandDefaultHandler(ctx) {
2290
- const patcher = await ctx.createPatcher();
2291
- const report = await patcher.getPatchStatus();
2292
- if (ctx.args.json) {
2293
- logger_default.log(JSON.stringify(report, null, 2));
2294
- return report;
2295
- }
2296
- const applied = report.entries.filter((entry) => entry.status === "applied");
2297
- const pending = report.entries.filter((entry) => entry.status === "not-applied");
2298
- const skipped = report.entries.filter((entry) => entry.status === "skipped" || entry.status === "unsupported");
2299
- const packageLabel = `${_nullishCoalesce(report.package.name, () => ( "tailwindcss"))}@${_nullishCoalesce(report.package.version, () => ( "unknown"))}`;
2300
- logger_default.info(`Patch status for ${packageLabel} (v${report.majorVersion})`);
2301
- if (applied.length) {
2302
- logger_default.success("Applied:");
2303
- applied.forEach((entry) => logger_default.success(` \u2022 ${entry.name}${formatFilesHint(entry)}`));
2304
- }
2305
- if (pending.length) {
2306
- logger_default.warn("Needs attention:");
2307
- pending.forEach((entry) => {
2308
- const details = entry.reason ? ` \u2013 ${entry.reason}` : "";
2309
- logger_default.warn(` \u2022 ${entry.name}${formatFilesHint(entry)}${details}`);
2310
- });
2311
- } else {
2312
- logger_default.success("All applicable patches are applied.");
2313
- }
2314
- if (skipped.length) {
2315
- logger_default.info("Skipped:");
2316
- skipped.forEach((entry) => {
2317
- const details = entry.reason ? ` \u2013 ${entry.reason}` : "";
2318
- logger_default.info(` \u2022 ${entry.name}${details}`);
2319
- });
2320
- }
2321
- return report;
2322
- }
2323
- function mountTailwindcssPatchCommands(cli, options = {}) {
2324
- const prefix = _nullishCoalesce(options.commandPrefix, () => ( ""));
2325
- const selectedCommands = _nullishCoalesce(options.commands, () => ( tailwindcssPatchCommands));
2326
- const defaultDefinitions = buildDefaultCommandDefinitions();
2327
- const registrars = {
2328
- install: () => {
2329
- const metadata = resolveCommandMetadata("install", options, prefix, defaultDefinitions);
2330
- const command = cli.command(metadata.name, metadata.description);
2331
- applyCommandOptions(command, metadata.optionDefs);
2332
- command.action(async (args) => {
2333
- return runWithCommandHandler(
2334
- cli,
2335
- command,
2336
- "install",
2337
- args,
2338
- _optionalChain([options, 'access', _91 => _91.commandHandlers, 'optionalAccess', _92 => _92.install]),
2339
- installCommandDefaultHandler
2340
- );
2341
- });
2342
- metadata.aliases.forEach((alias) => command.alias(alias));
2343
- },
2344
- extract: () => {
2345
- const metadata = resolveCommandMetadata("extract", options, prefix, defaultDefinitions);
2346
- const command = cli.command(metadata.name, metadata.description);
2347
- applyCommandOptions(command, metadata.optionDefs);
2348
- command.action(async (args) => {
2349
- return runWithCommandHandler(
2350
- cli,
2351
- command,
2352
- "extract",
2353
- args,
2354
- _optionalChain([options, 'access', _93 => _93.commandHandlers, 'optionalAccess', _94 => _94.extract]),
2355
- extractCommandDefaultHandler
2356
- );
2357
- });
2358
- metadata.aliases.forEach((alias) => command.alias(alias));
2359
- },
2360
- tokens: () => {
2361
- const metadata = resolveCommandMetadata("tokens", options, prefix, defaultDefinitions);
2362
- const command = cli.command(metadata.name, metadata.description);
2363
- applyCommandOptions(command, metadata.optionDefs);
2364
- command.action(async (args) => {
2365
- return runWithCommandHandler(
2366
- cli,
2367
- command,
2368
- "tokens",
2369
- args,
2370
- _optionalChain([options, 'access', _95 => _95.commandHandlers, 'optionalAccess', _96 => _96.tokens]),
2371
- tokensCommandDefaultHandler
2372
- );
2373
- });
2374
- metadata.aliases.forEach((alias) => command.alias(alias));
2375
- },
2376
- init: () => {
2377
- const metadata = resolveCommandMetadata("init", options, prefix, defaultDefinitions);
2378
- const command = cli.command(metadata.name, metadata.description);
2379
- applyCommandOptions(command, metadata.optionDefs);
2380
- command.action(async (args) => {
2381
- return runWithCommandHandler(
2382
- cli,
2383
- command,
2384
- "init",
2385
- args,
2386
- _optionalChain([options, 'access', _97 => _97.commandHandlers, 'optionalAccess', _98 => _98.init]),
2387
- initCommandDefaultHandler
2388
- );
2389
- });
2390
- metadata.aliases.forEach((alias) => command.alias(alias));
2391
- },
2392
- status: () => {
2393
- const metadata = resolveCommandMetadata("status", options, prefix, defaultDefinitions);
2394
- const command = cli.command(metadata.name, metadata.description);
2395
- applyCommandOptions(command, metadata.optionDefs);
2396
- command.action(async (args) => {
2397
- return runWithCommandHandler(
2398
- cli,
2399
- command,
2400
- "status",
2401
- args,
2402
- _optionalChain([options, 'access', _99 => _99.commandHandlers, 'optionalAccess', _100 => _100.status]),
2403
- statusCommandDefaultHandler
2404
- );
2405
- });
2406
- metadata.aliases.forEach((alias) => command.alias(alias));
2407
- }
2408
- };
2409
- for (const name of selectedCommands) {
2410
- const register = registrars[name];
2411
- if (register) {
2412
- register();
2413
- }
2414
- }
2415
- return cli;
2416
- }
2417
- function createTailwindcssPatchCli(options = {}) {
2418
- const cli = _cac2.default.call(void 0, _nullishCoalesce(options.name, () => ( "tw-patch")));
2419
- mountTailwindcssPatchCommands(cli, options.mountOptions);
2420
- return cli;
2421
- }
2422
-
2423
-
2424
-
2425
-
2426
-
2427
-
2428
-
2429
-
2430
-
2431
-
2432
-
2433
-
2434
-
2435
-
2436
-
2437
-
2438
-
2439
-
2440
-
2441
- exports.logger_default = logger_default; exports.CacheStore = CacheStore; exports.extractRawCandidatesWithPositions = extractRawCandidatesWithPositions; exports.extractRawCandidates = extractRawCandidates; exports.extractValidCandidates = extractValidCandidates; exports.extractProjectCandidatesWithPositions = extractProjectCandidatesWithPositions; exports.groupTokensByFile = groupTokensByFile; exports.normalizeOptions = normalizeOptions; exports.getPatchStatusReport = getPatchStatusReport; exports.collectClassesFromContexts = collectClassesFromContexts; exports.collectClassesFromTailwindV4 = collectClassesFromTailwindV4; exports.loadRuntimeContexts = loadRuntimeContexts; exports.runTailwindBuild = runTailwindBuild; exports.TailwindcssPatcher = TailwindcssPatcher; exports.tailwindcssPatchCommands = tailwindcssPatchCommands; exports.mountTailwindcssPatchCommands = mountTailwindcssPatchCommands; exports.createTailwindcssPatchCli = createTailwindcssPatchCli;