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