tailwindcss-patch 5.0.2 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,9 @@
1
1
  # tailwindcss-patch
2
2
 
3
- \[[中文(zh-cn)](./README-cn.md)\]
4
-
5
3
  get tailwindcss context at runtime ! extract all classes into file!
6
4
 
7
5
  - [tailwindcss-patch](#tailwindcss-patch)
6
+ - [Docs](#docs)
8
7
  - [Setup](#setup)
9
8
  - [Usage](#usage)
10
9
  - [Cli](#cli)
@@ -16,6 +15,10 @@ get tailwindcss context at runtime ! extract all classes into file!
16
15
 
17
16
  > Nodejs version should >= `16.6.0`
18
17
 
18
+ ## Docs
19
+
20
+ [mangle.icebreaker.top](https://mangle.icebreaker.top)
21
+
19
22
  ## Setup
20
23
 
21
24
  1. Install package
package/bin/tw-patch.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import '../dist/cli.js'
2
+ require('../dist/cli.js')
@@ -1,22 +1,3 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __copyProps = (to, from, except, desc) => {
6
- if (from && typeof from === "object" || typeof from === "function") {
7
- for (let key of __getOwnPropNames(from))
8
- if (!__hasOwnProp.call(to, key) && key !== except)
9
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
- }
11
- return to;
12
- };
13
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
14
-
15
- // src/config.ts
16
- var config_exports = {};
17
- __reExport(config_exports, config_star);
18
- import * as config_star from "@tailwindcss-mangle/config";
19
-
20
1
  // src/logger.ts
21
2
  import { createConsola } from "consola";
22
3
  var logger = createConsola();
@@ -71,22 +52,21 @@ var CacheManager = class {
71
52
  strategy: "merge"
72
53
  };
73
54
  }
74
- write(data) {
55
+ async write(data) {
75
56
  try {
76
- const { dir, filename } = this.options;
77
- fs.ensureDirSync(dir);
78
- fs.outputFileSync(filename, JSON.stringify([...data], void 0, 2), "utf8");
57
+ const { filename } = this.options;
58
+ await fs.outputJSON(filename, [...data]);
79
59
  return filename;
80
60
  } catch {
81
61
  logger_default.error("write cache file fail!");
82
62
  }
83
63
  }
84
- read() {
64
+ async read() {
85
65
  const { filename } = this.options;
86
66
  try {
87
- if (fs.existsSync(filename)) {
88
- const data = fs.readFileSync(filename, "utf8");
89
- return new Set(JSON.parse(data));
67
+ if (await fs.exists(filename)) {
68
+ const data = await fs.readJSON(filename);
69
+ return new Set(data);
90
70
  }
91
71
  } catch {
92
72
  logger_default.error(`parse cache content fail! path:${filename}`);
@@ -587,14 +567,14 @@ function findAstNode(content, options) {
587
567
  let arrayRef;
588
568
  let changed = false;
589
569
  traverse(ast, {
590
- Identifier(path8) {
591
- if (path8.node.name === variableName && t3.isVariableDeclarator(path8.parent) && t3.isArrayExpression(path8.parent.init)) {
592
- arrayRef = path8.parent.init;
593
- const set = new Set(path8.parent.init.elements.map((x) => x.value));
570
+ Identifier(path7) {
571
+ if (path7.node.name === variableName && t3.isVariableDeclarator(path7.parent) && t3.isArrayExpression(path7.parent.init)) {
572
+ arrayRef = path7.parent.init;
573
+ const set = new Set(path7.parent.init.elements.map((x) => x.value));
594
574
  for (let i = 0; i < units.length; i++) {
595
575
  const unit = units[i];
596
576
  if (!set.has(unit)) {
597
- path8.parent.init.elements = path8.parent.init.elements.map((x) => {
577
+ path7.parent.init.elements = path7.parent.init.elements.map((x) => {
598
578
  if (t3.isStringLiteral(x)) {
599
579
  return {
600
580
  type: x?.type,
@@ -603,7 +583,7 @@ function findAstNode(content, options) {
603
583
  }
604
584
  return x;
605
585
  });
606
- path8.parent.init.elements.push({
586
+ path7.parent.init.elements.push({
607
587
  type: "StringLiteral",
608
588
  value: unit
609
589
  });
@@ -688,108 +668,91 @@ function internalPatch(pkgJsonPath, options) {
688
668
 
689
669
  // src/core/patcher.ts
690
670
  import { createRequire as createRequire3 } from "node:module";
691
- import fs5 from "fs-extra";
692
- import path7 from "pathe";
671
+ import process5 from "node:process";
672
+ import fs4 from "fs-extra";
673
+ import { getPackageInfoSync } from "local-pkg";
674
+ import path6 from "pathe";
693
675
 
694
676
  // src/utils.ts
695
- import fs4 from "fs-extra";
696
- import path5 from "pathe";
697
- import pkg from "resolve";
698
- var { sync } = pkg;
699
- function requireResolve(id, opts) {
700
- return sync(id, opts);
701
- }
702
- function searchPackageJSON(dir) {
703
- let packageJsonPath;
704
- while (true) {
705
- if (!dir) {
706
- return;
707
- }
708
- const newDir = path5.dirname(dir);
709
- if (newDir === dir) {
710
- return;
711
- }
712
- dir = newDir;
713
- packageJsonPath = path5.join(dir, "package.json");
714
- if (fs4.existsSync(packageJsonPath)) {
715
- break;
716
- }
717
- }
718
- return packageJsonPath;
677
+ function isObject(val) {
678
+ return val !== null && typeof val === "object" && Array.isArray(val) === false;
719
679
  }
720
- function getTailwindcssEntry(name = "tailwindcss", opts) {
721
- return requireResolve(name, opts);
680
+
681
+ // src/core/candidates.ts
682
+ import process3 from "node:process";
683
+ function importNode() {
684
+ return import("@tailwindcss/node");
722
685
  }
723
- function getPackageJsonPath(name, options = {}) {
724
- const entry = getTailwindcssEntry(name, options);
725
- if (!entry) {
726
- return;
727
- }
728
- return searchPackageJSON(entry);
686
+ function importOxide() {
687
+ return import("@tailwindcss/oxide");
729
688
  }
730
- function getPackageInfoSync(name, options = {}) {
731
- const packageJsonPath = getPackageJsonPath(name, options);
732
- if (!packageJsonPath) {
733
- return;
734
- }
735
- const packageJson = JSON.parse(fs4.readFileSync(packageJsonPath, "utf8"));
736
- return {
737
- name,
738
- version: packageJson.version,
739
- rootPath: path5.dirname(packageJsonPath),
740
- packageJsonPath,
741
- packageJson
742
- };
689
+ async function extractRawCandidates(sources) {
690
+ const { Scanner } = await importOxide();
691
+ const scanner = new Scanner({
692
+ sources
693
+ });
694
+ const candidates = scanner.scan();
695
+ return candidates;
743
696
  }
744
- function isObject(val) {
745
- return val !== null && typeof val === "object" && Array.isArray(val) === false;
697
+ async function extractValidCandidates(options) {
698
+ const cwd = process3.cwd();
699
+ const { sources, base, css } = defuOverrideArray(
700
+ // @ts-ignore
701
+ options,
702
+ {
703
+ css: '@import "tailwindcss";',
704
+ base: cwd,
705
+ sources: [
706
+ {
707
+ base: cwd,
708
+ pattern: "**/*"
709
+ }
710
+ ]
711
+ }
712
+ );
713
+ const { __unstable__loadDesignSystem } = await importNode();
714
+ const designSystem = await __unstable__loadDesignSystem(css, { base });
715
+ const candidates = await extractRawCandidates(sources);
716
+ const validCandidates = candidates.filter(
717
+ (rawCandidate) => designSystem.parseCandidate(rawCandidate).length > 0
718
+ );
719
+ return validCandidates;
746
720
  }
747
721
 
748
722
  // src/core/postcss.ts
749
723
  import { createRequire as createRequire2 } from "node:module";
750
- import process3 from "node:process";
751
- import { createJiti } from "jiti";
752
- import { lilconfig } from "lilconfig";
753
- import path6 from "pathe";
724
+ import process4 from "node:process";
725
+ import path5 from "pathe";
754
726
  import postcss from "postcss";
755
- var jiti = createJiti(import.meta.url);
727
+ import { loadConfig } from "tailwindcss-config";
756
728
  var require3 = createRequire2(import.meta.url);
757
729
  async function processTailwindcss(options) {
758
- const { config: userConfig, cwd } = defu(options, {
759
- cwd: process3.cwd()
730
+ const { config: userConfig, cwd, majorVersion, postcssPlugin } = defu(options, {
731
+ cwd: process4.cwd(),
732
+ majorVersion: 3
760
733
  });
761
734
  let config = userConfig;
762
- if (!(typeof config === "string" && path6.isAbsolute(config))) {
763
- const moduleName = "tailwind";
764
- const result = await lilconfig("tailwindcss", {
765
- searchPlaces: [
766
- `${moduleName}.config.js`,
767
- `${moduleName}.config.cjs`,
768
- `${moduleName}.config.mjs`,
769
- `${moduleName}.config.ts`,
770
- `${moduleName}.config.cts`,
771
- `${moduleName}.config.mts`
772
- ],
773
- loaders: {
774
- // 默认支持 js 和 cjs 2种格式
775
- ".js": jiti,
776
- ".cjs": jiti,
777
- ".mjs": jiti,
778
- ".ts": jiti,
779
- ".cts": jiti,
780
- ".mts": jiti
781
- }
782
- }).search(cwd);
735
+ if (!(typeof config === "string" && path5.isAbsolute(config))) {
736
+ const result = await loadConfig({
737
+ cwd
738
+ });
783
739
  if (!result) {
784
740
  throw new Error(`No TailwindCSS Config found in: ${cwd}`);
785
741
  }
786
742
  config = result.filepath;
787
743
  }
788
- const id = requireResolve("tailwindcss", {
789
- basedir: cwd
790
- });
744
+ const targetPostcssPlugin = postcssPlugin ?? (majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss");
745
+ if (majorVersion === 4) {
746
+ return await postcss([
747
+ require3(targetPostcssPlugin)({
748
+ config
749
+ })
750
+ ]).process("@import 'tailwindcss';", {
751
+ from: void 0
752
+ });
753
+ }
791
754
  return await postcss([
792
- require3(id)({
755
+ require3(targetPostcssPlugin)({
793
756
  config
794
757
  })
795
758
  ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
@@ -812,10 +775,14 @@ var TailwindcssPatcher = class {
812
775
  this.cacheOptions = getCacheOptions(options.cache);
813
776
  this.patchOptions = getPatchOptions(options.patch);
814
777
  this.cacheManager = new CacheManager(this.cacheOptions);
815
- this.packageInfo = getPackageInfoSync("tailwindcss", { basedir: this.patchOptions.basedir });
816
- if (this.packageInfo && this.packageInfo.version) {
817
- this.majorVersion = Number.parseInt(this.packageInfo.version[0]);
778
+ const packageInfo = getPackageInfoSync("tailwindcss");
779
+ if (!packageInfo) {
780
+ throw new Error("tailwindcss not found");
781
+ }
782
+ if (packageInfo.version) {
783
+ this.majorVersion = Number.parseInt(packageInfo.version[0]);
818
784
  }
785
+ this.packageInfo = packageInfo;
819
786
  this.patch = () => {
820
787
  try {
821
788
  return internalPatch(this.packageInfo?.packageJsonPath, this.patchOptions);
@@ -834,14 +801,14 @@ var TailwindcssPatcher = class {
834
801
  }
835
802
  getContexts() {
836
803
  if (this.packageInfo) {
837
- const distPath = path7.join(this.packageInfo.rootPath, "lib");
804
+ const distPath = path6.join(this.packageInfo.rootPath, "lib");
838
805
  let injectFilePath;
839
806
  if (this.majorVersion === 2) {
840
- injectFilePath = path7.join(distPath, "jit/index.js");
841
- } else {
842
- injectFilePath = path7.join(distPath, "plugin.js");
843
- if (!fs5.existsSync(injectFilePath)) {
844
- injectFilePath = path7.join(distPath, "index.js");
807
+ injectFilePath = path6.join(distPath, "jit/index.js");
808
+ } else if (this.majorVersion === 3) {
809
+ injectFilePath = path6.join(distPath, "plugin.js");
810
+ if (!fs4.existsSync(injectFilePath)) {
811
+ injectFilePath = path6.join(distPath, "index.js");
845
812
  }
846
813
  }
847
814
  if (injectFilePath) {
@@ -857,17 +824,62 @@ var TailwindcssPatcher = class {
857
824
  const contexts = this.getContexts();
858
825
  return contexts.filter((x) => isObject(x)).map((x) => x.classCache);
859
826
  }
860
- getClassCacheSet(options) {
861
- const classCaches = this.getClassCaches();
827
+ async getClassCacheSet() {
862
828
  const classSet = /* @__PURE__ */ new Set();
863
- for (const classCacheMap of classCaches) {
864
- const keys = classCacheMap.keys();
865
- for (const key of keys) {
866
- const v = key.toString();
867
- if (options?.removeUniversalSelector && v === "*") {
868
- continue;
829
+ const { output, tailwindcss } = this.patchOptions;
830
+ if (this.majorVersion === 4) {
831
+ const { v4 } = tailwindcss ?? {};
832
+ if (Array.isArray(v4?.cssEntries)) {
833
+ const results = (await Promise.all(
834
+ v4.cssEntries.map(async (x) => {
835
+ if (await fs4.exists(x)) {
836
+ const css = await fs4.readFile(x, "utf8");
837
+ return css;
838
+ }
839
+ return false;
840
+ })
841
+ )).filter((x) => x);
842
+ for (const css of results) {
843
+ const candidates = await extractValidCandidates({
844
+ base: v4?.base,
845
+ css,
846
+ sources: v4?.sources?.map((x) => {
847
+ return {
848
+ base: x.base ?? v4?.base ?? process5.cwd(),
849
+ pattern: x.pattern
850
+ };
851
+ })
852
+ });
853
+ for (const candidate of candidates) {
854
+ classSet.add(candidate);
855
+ }
856
+ }
857
+ } else {
858
+ const candidates = await extractValidCandidates({
859
+ base: v4?.base,
860
+ css: v4?.css,
861
+ sources: v4?.sources?.map((x) => {
862
+ return {
863
+ base: x.base ?? v4?.base ?? process5.cwd(),
864
+ pattern: x.pattern
865
+ };
866
+ })
867
+ });
868
+ for (const candidate of candidates) {
869
+ classSet.add(candidate);
870
+ }
871
+ }
872
+ } else {
873
+ const classCaches = this.getClassCaches();
874
+ for (const classCacheMap of classCaches) {
875
+ const keys = classCacheMap.keys();
876
+ for (const key of keys) {
877
+ const v = key.toString();
878
+ if (output?.removeUniversalSelector && v === "*") {
879
+ continue;
880
+ }
881
+ classSet.add(v);
869
882
  }
870
- classSet.add(v);
871
883
  }
872
884
  }
873
885
  return classSet;
@@ -875,15 +887,13 @@ var TailwindcssPatcher = class {
875
887
  /**
876
888
  * @description 在多个 tailwindcss 上下文时,这个方法将被执行多次,所以策略上应该使用 append
877
889
  */
878
- getClassSet(options) {
879
- const { cacheStrategy = this.cacheOptions.strategy ?? "merge", removeUniversalSelector = true } = options ?? {};
880
- const set = this.getClassCacheSet({
881
- removeUniversalSelector
882
- });
890
+ async getClassSet() {
891
+ const cacheStrategy = this.cacheOptions.strategy ?? "merge";
892
+ const set = await this.getClassCacheSet();
883
893
  if (cacheStrategy === "overwrite") {
884
894
  set.size > 0 && this.setCache(set);
885
895
  } else if (cacheStrategy === "merge") {
886
- const cacheSet = this.getCache();
896
+ const cacheSet = await this.getCache();
887
897
  if (cacheSet) {
888
898
  for (const x of cacheSet) {
889
899
  set.add(x);
@@ -896,25 +906,27 @@ var TailwindcssPatcher = class {
896
906
  async extract(options) {
897
907
  const { output, tailwindcss } = options ?? {};
898
908
  if (output && tailwindcss) {
899
- const { removeUniversalSelector, filename, loose } = output;
900
- await processTailwindcss(tailwindcss);
901
- const set = this.getClassSet({
902
- removeUniversalSelector
903
- });
909
+ const { filename, loose } = output;
910
+ if (this.majorVersion === 3) {
911
+ await processTailwindcss({
912
+ ...tailwindcss,
913
+ majorVersion: this.majorVersion
914
+ });
915
+ }
916
+ const set = await this.getClassSet();
904
917
  if (filename) {
905
- await fs5.ensureDir(path7.dirname(filename));
906
918
  const classList = [...set];
907
- await fs5.outputJSON(filename, classList, {
919
+ await fs4.outputJSON(filename, classList, {
908
920
  spaces: loose ? 2 : void 0
909
921
  });
910
922
  return filename;
911
923
  }
912
924
  }
913
925
  }
926
+ extractValidCandidates = extractValidCandidates;
914
927
  };
915
928
 
916
929
  export {
917
- config_exports,
918
930
  logger_default,
919
931
  getCacheOptions,
920
932
  CacheManager,