tailwindcss-patch 1.2.7 → 2.0.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,554 @@
1
+ 'use strict';
2
+
3
+ const path = require('node:path');
4
+ const fs = require('node:fs');
5
+ const fs$1 = require('node:fs/promises');
6
+ const pkg = require('resolve');
7
+ const semver = require('semver');
8
+ const t = require('@babel/types');
9
+ const generate = require('@babel/generator');
10
+ const traverse = require('@babel/traverse');
11
+ const parser = require('@babel/parser');
12
+ const postcss = require('postcss');
13
+ const postcssrc = require('postcss-load-config');
14
+ const c12 = require('c12');
15
+
16
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
17
+
18
+ function _interopNamespaceCompat(e) {
19
+ if (e && typeof e === 'object' && 'default' in e) return e;
20
+ const n = Object.create(null);
21
+ if (e) {
22
+ for (const k in e) {
23
+ n[k] = e[k];
24
+ }
25
+ }
26
+ n.default = e;
27
+ return n;
28
+ }
29
+
30
+ const path__default = /*#__PURE__*/_interopDefaultCompat(path);
31
+ const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
32
+ const fs__default$1 = /*#__PURE__*/_interopDefaultCompat(fs$1);
33
+ const pkg__default = /*#__PURE__*/_interopDefaultCompat(pkg);
34
+ const t__namespace = /*#__PURE__*/_interopNamespaceCompat(t);
35
+ const generate__default = /*#__PURE__*/_interopDefaultCompat(generate);
36
+ const traverse__default = /*#__PURE__*/_interopDefaultCompat(traverse);
37
+ const postcss__default = /*#__PURE__*/_interopDefaultCompat(postcss);
38
+ const postcssrc__default = /*#__PURE__*/_interopDefaultCompat(postcssrc);
39
+
40
+ const { sync } = pkg__default;
41
+ function ensureFileContent(filepaths) {
42
+ if (typeof filepaths === "string") {
43
+ filepaths = [filepaths];
44
+ }
45
+ let content;
46
+ for (const filepath of filepaths) {
47
+ if (fs__default.existsSync(filepath)) {
48
+ content = fs__default.readFileSync(filepath, {
49
+ encoding: "utf8"
50
+ });
51
+ break;
52
+ }
53
+ }
54
+ return content;
55
+ }
56
+ function requireResolve(id, opts) {
57
+ return sync(id, opts);
58
+ }
59
+ async function ensureDir(p) {
60
+ try {
61
+ await fs__default$1.access(p);
62
+ } catch {
63
+ await fs__default$1.mkdir(p, {
64
+ recursive: true
65
+ });
66
+ }
67
+ }
68
+
69
+ function getTailwindcssEntry(basedir = process.cwd()) {
70
+ return requireResolve("tailwindcss");
71
+ }
72
+ function getContexts(basedir) {
73
+ const twPath = getTailwindcssEntry(basedir);
74
+ const distPath = path__default.dirname(twPath);
75
+ let injectFilePath = path__default.join(distPath, "plugin.js");
76
+ if (!fs__default.existsSync(injectFilePath)) {
77
+ injectFilePath = path__default.join(distPath, "index.js");
78
+ }
79
+ const mo = require(injectFilePath);
80
+ if (mo.contextRef) {
81
+ return mo.contextRef.value;
82
+ }
83
+ return [];
84
+ }
85
+ function getClassCaches(basedir) {
86
+ const contexts = getContexts(basedir);
87
+ return contexts.map((x) => x.classCache);
88
+ }
89
+ function getClassCacheSet(basedir, options) {
90
+ const classCaches = getClassCaches(basedir);
91
+ const classSet = /* @__PURE__ */ new Set();
92
+ for (const classCacheMap of classCaches) {
93
+ const keys = classCacheMap.keys();
94
+ for (const key of keys) {
95
+ if (options?.removeUniversalSelector && key.toString() === "*") {
96
+ continue;
97
+ }
98
+ classSet.add(key.toString());
99
+ }
100
+ }
101
+ return classSet;
102
+ }
103
+
104
+ const pkgName = "tailwindcss-patch";
105
+
106
+ function log(message, ...optionalParams) {
107
+ return console.log(`[${pkgName}]:` + message, ...optionalParams);
108
+ }
109
+
110
+ function getCacheOptions(options) {
111
+ let cache;
112
+ switch (typeof options) {
113
+ case "undefined": {
114
+ cache = {
115
+ enable: false
116
+ };
117
+ break;
118
+ }
119
+ case "boolean": {
120
+ cache = {
121
+ enable: options
122
+ };
123
+ break;
124
+ }
125
+ case "object": {
126
+ cache = { ...options, enable: true };
127
+ break;
128
+ }
129
+ }
130
+ return cache;
131
+ }
132
+ class CacheManager {
133
+ constructor(options = {}) {
134
+ this.options = this.getOptions(options);
135
+ }
136
+ mkdir(cacheDirectory) {
137
+ const exists = fs__default.existsSync(cacheDirectory);
138
+ if (!exists) {
139
+ fs__default.mkdirSync(cacheDirectory, {
140
+ recursive: true
141
+ });
142
+ }
143
+ return cacheDirectory;
144
+ }
145
+ getOptions(options = {}) {
146
+ const cwd = options.cwd ?? process.cwd();
147
+ const dir = options.dir ?? path__default.resolve(cwd, "node_modules/.cache", pkgName);
148
+ const file = options.file ?? "index.json";
149
+ const filename = path__default.resolve(dir, file);
150
+ return {
151
+ cwd,
152
+ dir,
153
+ file,
154
+ filename,
155
+ strategy: "merge"
156
+ };
157
+ }
158
+ write(data) {
159
+ try {
160
+ const { dir, filename } = this.options;
161
+ this.mkdir(dir);
162
+ fs__default.writeFileSync(filename, JSON.stringify([...data], void 0, 2), "utf8");
163
+ return filename;
164
+ } catch {
165
+ log("write cache file fail!");
166
+ }
167
+ }
168
+ read() {
169
+ const { filename } = this.options;
170
+ try {
171
+ if (fs__default.existsSync(filename)) {
172
+ const data = fs__default.readFileSync(filename, "utf8");
173
+ return new Set(JSON.parse(data));
174
+ }
175
+ } catch {
176
+ log("parse cache content fail! path:" + filename);
177
+ try {
178
+ fs__default.unlinkSync(filename);
179
+ } catch {
180
+ log("delete cache file fail! path:" + filename);
181
+ }
182
+ }
183
+ }
184
+ }
185
+
186
+ function inspectProcessTailwindFeaturesReturnContext(content) {
187
+ const ast = parser.parse(content);
188
+ let hasPatched = false;
189
+ traverse__default(ast, {
190
+ FunctionDeclaration(p) {
191
+ const n = p.node;
192
+ if (n.id?.name === "processTailwindFeatures" && n.body.body.length === 1 && t__namespace.isReturnStatement(n.body.body[0])) {
193
+ const rts = n.body.body[0];
194
+ if (t__namespace.isFunctionExpression(rts.argument)) {
195
+ const body = rts.argument.body.body;
196
+ const lastStatement = body.at(-1);
197
+ hasPatched = t__namespace.isReturnStatement(lastStatement) && t__namespace.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context";
198
+ if (!hasPatched) {
199
+ const rts2 = t__namespace.returnStatement(t__namespace.identifier("context"));
200
+ body.push(rts2);
201
+ }
202
+ }
203
+ }
204
+ }
205
+ });
206
+ return {
207
+ code: hasPatched ? content : generate__default(ast).code,
208
+ hasPatched
209
+ };
210
+ }
211
+ function inspectPostcssPlugin(content) {
212
+ const ast = parser.parse(content);
213
+ const exportKey = "contextRef";
214
+ const variableName = "contextRef";
215
+ const valueKey = "value";
216
+ let hasPatched = false;
217
+ traverse__default(ast, {
218
+ Program(p) {
219
+ const n = p.node;
220
+ const idx = n.body.findIndex((x) => {
221
+ return t__namespace.isExpressionStatement(x) && t__namespace.isAssignmentExpression(x.expression) && t__namespace.isMemberExpression(x.expression.left) && t__namespace.isFunctionExpression(x.expression.right) && x.expression.right.id?.name === "tailwindcss";
222
+ });
223
+ if (idx > -1) {
224
+ const prevStatement = n.body[idx - 1];
225
+ const lastStatement = n.body.at(-1);
226
+ const hasPatchedCondition0 = prevStatement && t__namespace.isVariableDeclaration(prevStatement) && prevStatement.declarations.length === 1 && t__namespace.isIdentifier(prevStatement.declarations[0].id) && prevStatement.declarations[0].id.name === variableName;
227
+ const hasPatchedCondition1 = t__namespace.isExpressionStatement(lastStatement) && t__namespace.isAssignmentExpression(lastStatement.expression) && t__namespace.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === variableName;
228
+ hasPatched = hasPatchedCondition0 || hasPatchedCondition1;
229
+ if (!hasPatched) {
230
+ const statement = t__namespace.variableDeclaration("const", [
231
+ t__namespace.variableDeclarator(t__namespace.identifier(variableName), t__namespace.objectExpression([t__namespace.objectProperty(t__namespace.identifier(valueKey), t__namespace.arrayExpression())]))
232
+ ]);
233
+ n.body.splice(idx, 0, statement);
234
+ n.body.push(
235
+ t__namespace.expressionStatement(
236
+ t__namespace.assignmentExpression(
237
+ "=",
238
+ t__namespace.memberExpression(t__namespace.memberExpression(t__namespace.identifier("module"), t__namespace.identifier("exports")), t__namespace.identifier(exportKey)),
239
+ t__namespace.identifier(variableName)
240
+ )
241
+ )
242
+ );
243
+ }
244
+ }
245
+ },
246
+ FunctionExpression(p) {
247
+ if (hasPatched) {
248
+ return;
249
+ }
250
+ const n = p.node;
251
+ if (n.id?.name === "tailwindcss" && n.body.body.length === 1 && t__namespace.isReturnStatement(n.body.body[0])) {
252
+ const returnStatement = n.body.body[0];
253
+ if (t__namespace.isObjectExpression(returnStatement.argument) && returnStatement.argument.properties.length === 2) {
254
+ const properties = returnStatement.argument.properties;
255
+ if (t__namespace.isObjectProperty(properties[0]) && t__namespace.isObjectProperty(properties[1])) {
256
+ const keyMatched = t__namespace.isIdentifier(properties[0].key) && properties[0].key.name === "postcssPlugin";
257
+ const pluginsMatched = t__namespace.isIdentifier(properties[1].key) && properties[1].key.name === "plugins";
258
+ if (pluginsMatched && keyMatched && t__namespace.isCallExpression(properties[1].value) && t__namespace.isMemberExpression(properties[1].value.callee) && t__namespace.isArrayExpression(properties[1].value.callee.object)) {
259
+ const pluginsCode = properties[1].value.callee.object.elements;
260
+ if (pluginsCode[1] && t__namespace.isFunctionExpression(pluginsCode[1])) {
261
+ const targetBlockStatement = pluginsCode[1].body;
262
+ const lastStatement = targetBlockStatement.body.at(-1);
263
+ if (t__namespace.isExpressionStatement(lastStatement)) {
264
+ const newExpressionStatement = t__namespace.expressionStatement(
265
+ t__namespace.callExpression(
266
+ t__namespace.memberExpression(
267
+ t__namespace.memberExpression(t__namespace.identifier(variableName), t__namespace.identifier("value")),
268
+ t__namespace.identifier("push")
269
+ ),
270
+ [lastStatement.expression]
271
+ )
272
+ );
273
+ targetBlockStatement.body[targetBlockStatement.body.length - 1] = newExpressionStatement;
274
+ }
275
+ const ifIdx = targetBlockStatement.body.findIndex((x) => t__namespace.isIfStatement(x));
276
+ if (ifIdx > -1) {
277
+ const ifRoot = targetBlockStatement.body[ifIdx];
278
+ if (t__namespace.isBlockStatement(ifRoot.consequent) && ifRoot.consequent.body[1] && t__namespace.isForOfStatement(ifRoot.consequent.body[1])) {
279
+ const forOf = ifRoot.consequent.body[1];
280
+ if (t__namespace.isBlockStatement(forOf.body) && forOf.body.body.length === 1 && t__namespace.isIfStatement(forOf.body.body[0])) {
281
+ const if2 = forOf.body.body[0];
282
+ if (t__namespace.isBlockStatement(if2.consequent) && if2.consequent.body.length === 1 && t__namespace.isExpressionStatement(if2.consequent.body[0])) {
283
+ const target = if2.consequent.body[0];
284
+ const newExpressionStatement = t__namespace.expressionStatement(
285
+ t__namespace.callExpression(t__namespace.memberExpression(t__namespace.memberExpression(t__namespace.identifier(variableName), t__namespace.identifier("value")), t__namespace.identifier("push")), [target.expression])
286
+ );
287
+ if2.consequent.body[0] = newExpressionStatement;
288
+ }
289
+ }
290
+ }
291
+ }
292
+ targetBlockStatement.body.unshift(
293
+ // contentRef.value = []
294
+ // t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression()))
295
+ // contentRef.value.length = 0
296
+ t__namespace.expressionStatement(
297
+ t__namespace.assignmentExpression(
298
+ "=",
299
+ t__namespace.memberExpression(t__namespace.memberExpression(t__namespace.identifier(variableName), t__namespace.identifier(valueKey)), t__namespace.identifier("length")),
300
+ t__namespace.numericLiteral(0)
301
+ )
302
+ )
303
+ );
304
+ }
305
+ }
306
+ }
307
+ }
308
+ }
309
+ }
310
+ // BlockStatement(p) {
311
+ // const n = p.node
312
+ // if (start && p.parent.type === 'FunctionExpression' && !p.parent.id) {
313
+ // n.body.unshift(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression())))
314
+ // }
315
+ // }
316
+ });
317
+ return {
318
+ code: hasPatched ? content : generate__default(ast).code,
319
+ hasPatched
320
+ };
321
+ }
322
+
323
+ function isObject(value) {
324
+ return value !== null && typeof value === "object";
325
+ }
326
+ function _defu(baseObject, defaults, namespace = ".", merger) {
327
+ if (!isObject(defaults)) {
328
+ return _defu(baseObject, {}, namespace, merger);
329
+ }
330
+ const object = Object.assign({}, defaults);
331
+ for (const key in baseObject) {
332
+ if (key === "__proto__" || key === "constructor") {
333
+ continue;
334
+ }
335
+ const value = baseObject[key];
336
+ if (value === null || value === void 0) {
337
+ continue;
338
+ }
339
+ if (merger && merger(object, key, value, namespace)) {
340
+ continue;
341
+ }
342
+ if (Array.isArray(value) && Array.isArray(object[key])) {
343
+ object[key] = [...value, ...object[key]];
344
+ } else if (isObject(value) && isObject(object[key])) {
345
+ object[key] = _defu(
346
+ value,
347
+ object[key],
348
+ (namespace ? `${namespace}.` : "") + key.toString(),
349
+ merger
350
+ );
351
+ } else {
352
+ object[key] = value;
353
+ }
354
+ }
355
+ return object;
356
+ }
357
+ function createDefu(merger) {
358
+ return (...arguments_) => (
359
+ // eslint-disable-next-line unicorn/no-array-reduce
360
+ arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
361
+ );
362
+ }
363
+ const defu = createDefu();
364
+
365
+ const defaultOptions = {
366
+ overwrite: true
367
+ };
368
+ function getDefaultUserConfig() {
369
+ return {
370
+ output: {
371
+ filename: ".tw-patch/tw-class-list.json",
372
+ removeUniversalSelector: true,
373
+ loose: true
374
+ },
375
+ postcss: {
376
+ configDir: process.cwd()
377
+ }
378
+ };
379
+ }
380
+
381
+ function getInstalledPkgJsonPath(options = {}) {
382
+ try {
383
+ const tmpJsonPath = requireResolve(`tailwindcss/package.json`, {
384
+ paths: options.paths
385
+ });
386
+ return tmpJsonPath;
387
+ } catch (error) {
388
+ if (error.code === "MODULE_NOT_FOUND") {
389
+ console.warn("Can't find npm pkg: `tailwindcss`, Please ensure it has been installed!");
390
+ }
391
+ }
392
+ }
393
+ function getPatchOptions(options = {}) {
394
+ return defu(
395
+ options,
396
+ {
397
+ basedir: process.cwd()
398
+ },
399
+ defaultOptions
400
+ );
401
+ }
402
+ function createPatch(opt) {
403
+ return () => {
404
+ try {
405
+ const pkgJsonPath = getInstalledPkgJsonPath(opt);
406
+ return internalPatch(pkgJsonPath, opt);
407
+ } catch (error) {
408
+ console.warn(`patch tailwindcss failed:` + error.message);
409
+ }
410
+ };
411
+ }
412
+ function monkeyPatchForExposingContext(twDir, opt) {
413
+ const processTailwindFeaturesFilePath = path__default.resolve(twDir, "lib/processTailwindFeatures.js");
414
+ const processTailwindFeaturesContent = ensureFileContent(processTailwindFeaturesFilePath);
415
+ const result = {};
416
+ if (processTailwindFeaturesContent) {
417
+ const { code, hasPatched } = inspectProcessTailwindFeaturesReturnContext(processTailwindFeaturesContent);
418
+ if (!hasPatched && opt.overwrite) {
419
+ fs__default.writeFileSync(processTailwindFeaturesFilePath, code, {
420
+ encoding: "utf8"
421
+ });
422
+ console.log("patch tailwindcss processTailwindFeatures for return content successfully!");
423
+ }
424
+ result.processTailwindFeatures = code;
425
+ }
426
+ const pluginFilePath = path__default.resolve(twDir, "lib/plugin.js");
427
+ const indexFilePath = path__default.resolve(twDir, "lib/index.js");
428
+ const pluginContent = ensureFileContent([pluginFilePath, indexFilePath]);
429
+ if (pluginContent) {
430
+ const { code, hasPatched } = inspectPostcssPlugin(pluginContent);
431
+ if (!hasPatched && opt.overwrite) {
432
+ fs__default.writeFileSync(pluginFilePath, code, {
433
+ encoding: "utf8"
434
+ });
435
+ console.log("patch tailwindcss for expose runtime content successfully!");
436
+ }
437
+ result.plugin = code;
438
+ }
439
+ opt.custom && typeof opt.custom === "function" && opt.custom(twDir, result);
440
+ return result;
441
+ }
442
+ function internalPatch(pkgJsonPath, options) {
443
+ if (pkgJsonPath) {
444
+ const pkgJson = require(pkgJsonPath);
445
+ const twDir = path__default.dirname(pkgJsonPath);
446
+ if (semver.gte(pkgJson.version, "3.0.0")) {
447
+ options.version = pkgJson.version;
448
+ const result = monkeyPatchForExposingContext(twDir, options);
449
+ return result;
450
+ }
451
+ }
452
+ }
453
+
454
+ async function getCss(p) {
455
+ const { options, plugins } = await postcssrc__default(void 0, p);
456
+ const res = await postcss__default(plugins).process("@tailwind base;@tailwind components;@tailwind utilities;", {
457
+ from: void 0,
458
+ ...options
459
+ });
460
+ return res;
461
+ }
462
+
463
+ class TailwindcssPatcher {
464
+ constructor(options = {}) {
465
+ this.rawOptions = options;
466
+ this.cacheOptions = getCacheOptions(options.cache);
467
+ this.patchOptions = getPatchOptions(options.patch);
468
+ this.patch = createPatch(this.patchOptions);
469
+ this.cacheManager = new CacheManager(this.cacheOptions);
470
+ }
471
+ getPkgEntry(basedir) {
472
+ return getTailwindcssEntry(basedir);
473
+ }
474
+ setCache(set) {
475
+ if (this.cacheOptions.enable) {
476
+ return this.cacheManager.write(set);
477
+ }
478
+ }
479
+ getCache() {
480
+ return this.cacheManager.read();
481
+ }
482
+ /**
483
+ * @description 在多个 tailwindcss 上下文时,这个方法将被执行多次,所以策略上应该使用 append
484
+ * 详见 taro weapp-tailwindcss 独立分包
485
+ * @param basedir
486
+ * @returns
487
+ */
488
+ getClassSet(options) {
489
+ const { basedir, cacheStrategy = this.cacheOptions.strategy ?? "merge", removeUniversalSelector = true } = options ?? {};
490
+ const set = getClassCacheSet(basedir, {
491
+ removeUniversalSelector
492
+ });
493
+ if (cacheStrategy === "overwrite") {
494
+ set.size > 0 && this.setCache(set);
495
+ } else if (cacheStrategy === "merge") {
496
+ const cacheSet = this.getCache();
497
+ if (cacheSet) {
498
+ for (const x of cacheSet) {
499
+ set.add(x);
500
+ }
501
+ }
502
+ this.setCache(set);
503
+ }
504
+ return set;
505
+ }
506
+ getContexts(basedir) {
507
+ return getContexts(basedir);
508
+ }
509
+ async extract(options) {
510
+ const { output, postcss } = options;
511
+ if (output && postcss) {
512
+ const { removeUniversalSelector, filename, loose } = output;
513
+ const { configDir } = postcss;
514
+ await getCss(configDir);
515
+ const set = this.getClassSet({
516
+ removeUniversalSelector
517
+ });
518
+ await ensureDir(path.dirname(filename));
519
+ const classList = [...set];
520
+ await fs__default$1.writeFile(filename, JSON.stringify(classList, null, loose ? 2 : void 0), "utf8");
521
+ return filename;
522
+ }
523
+ }
524
+ }
525
+
526
+ function getConfig() {
527
+ return c12.loadConfig({
528
+ name: "tailwindcss-patch",
529
+ defaults: {
530
+ ...getDefaultUserConfig()
531
+ }
532
+ });
533
+ }
534
+ const defineConfig = c12.createDefineConfig();
535
+
536
+ exports.CacheManager = CacheManager;
537
+ exports.TailwindcssPatcher = TailwindcssPatcher;
538
+ exports.createPatch = createPatch;
539
+ exports.defineConfig = defineConfig;
540
+ exports.ensureDir = ensureDir;
541
+ exports.ensureFileContent = ensureFileContent;
542
+ exports.getCacheOptions = getCacheOptions;
543
+ exports.getClassCacheSet = getClassCacheSet;
544
+ exports.getClassCaches = getClassCaches;
545
+ exports.getConfig = getConfig;
546
+ exports.getContexts = getContexts;
547
+ exports.getInstalledPkgJsonPath = getInstalledPkgJsonPath;
548
+ exports.getPatchOptions = getPatchOptions;
549
+ exports.getTailwindcssEntry = getTailwindcssEntry;
550
+ exports.inspectPostcssPlugin = inspectPostcssPlugin;
551
+ exports.inspectProcessTailwindFeaturesReturnContext = inspectProcessTailwindFeaturesReturnContext;
552
+ exports.internalPatch = internalPatch;
553
+ exports.monkeyPatchForExposingContext = monkeyPatchForExposingContext;
554
+ exports.requireResolve = requireResolve;