tailwindcss-patch 5.0.2 → 6.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/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();
@@ -587,14 +568,14 @@ function findAstNode(content, options) {
587
568
  let arrayRef;
588
569
  let changed = false;
589
570
  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));
571
+ Identifier(path7) {
572
+ if (path7.node.name === variableName && t3.isVariableDeclarator(path7.parent) && t3.isArrayExpression(path7.parent.init)) {
573
+ arrayRef = path7.parent.init;
574
+ const set = new Set(path7.parent.init.elements.map((x) => x.value));
594
575
  for (let i = 0; i < units.length; i++) {
595
576
  const unit = units[i];
596
577
  if (!set.has(unit)) {
597
- path8.parent.init.elements = path8.parent.init.elements.map((x) => {
578
+ path7.parent.init.elements = path7.parent.init.elements.map((x) => {
598
579
  if (t3.isStringLiteral(x)) {
599
580
  return {
600
581
  type: x?.type,
@@ -603,7 +584,7 @@ function findAstNode(content, options) {
603
584
  }
604
585
  return x;
605
586
  });
606
- path8.parent.init.elements.push({
587
+ path7.parent.init.elements.push({
607
588
  type: "StringLiteral",
608
589
  value: unit
609
590
  });
@@ -688,108 +669,91 @@ function internalPatch(pkgJsonPath, options) {
688
669
 
689
670
  // src/core/patcher.ts
690
671
  import { createRequire as createRequire3 } from "node:module";
691
- import fs5 from "fs-extra";
692
- import path7 from "pathe";
672
+ import process5 from "node:process";
673
+ import fs4 from "fs-extra";
674
+ import { getPackageInfoSync } from "local-pkg";
675
+ import path6 from "pathe";
693
676
 
694
677
  // 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;
678
+ function isObject(val) {
679
+ return val !== null && typeof val === "object" && Array.isArray(val) === false;
719
680
  }
720
- function getTailwindcssEntry(name = "tailwindcss", opts) {
721
- return requireResolve(name, opts);
681
+
682
+ // src/core/candidates.ts
683
+ import process3 from "node:process";
684
+ function importNode() {
685
+ return import("@tailwindcss/node");
722
686
  }
723
- function getPackageJsonPath(name, options = {}) {
724
- const entry = getTailwindcssEntry(name, options);
725
- if (!entry) {
726
- return;
727
- }
728
- return searchPackageJSON(entry);
687
+ function importOxide() {
688
+ return import("@tailwindcss/oxide");
729
689
  }
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
- };
690
+ async function extractRawCandidates(sources) {
691
+ const { Scanner } = await importOxide();
692
+ const scanner = new Scanner({
693
+ sources
694
+ });
695
+ const candidates = scanner.scan();
696
+ return candidates;
743
697
  }
744
- function isObject(val) {
745
- return val !== null && typeof val === "object" && Array.isArray(val) === false;
698
+ async function extractValidCandidates(options) {
699
+ const cwd = process3.cwd();
700
+ const { sources, base, css } = defuOverrideArray(
701
+ // @ts-ignore
702
+ options,
703
+ {
704
+ css: '@import "tailwindcss";',
705
+ base: cwd,
706
+ sources: [
707
+ {
708
+ base: cwd,
709
+ pattern: "**/*"
710
+ }
711
+ ]
712
+ }
713
+ );
714
+ const { __unstable__loadDesignSystem } = await importNode();
715
+ const designSystem = await __unstable__loadDesignSystem(css, { base });
716
+ const candidates = await extractRawCandidates(sources);
717
+ const validCandidates = candidates.filter(
718
+ (rawCandidate) => designSystem.parseCandidate(rawCandidate).length > 0
719
+ );
720
+ return validCandidates;
746
721
  }
747
722
 
748
723
  // src/core/postcss.ts
749
724
  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";
725
+ import process4 from "node:process";
726
+ import path5 from "pathe";
754
727
  import postcss from "postcss";
755
- var jiti = createJiti(import.meta.url);
728
+ import { loadConfig } from "tailwindcss-config";
756
729
  var require3 = createRequire2(import.meta.url);
757
730
  async function processTailwindcss(options) {
758
- const { config: userConfig, cwd } = defu(options, {
759
- cwd: process3.cwd()
731
+ const { config: userConfig, cwd, majorVersion, postcssPlugin } = defu(options, {
732
+ cwd: process4.cwd(),
733
+ majorVersion: 3
760
734
  });
761
735
  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);
736
+ if (!(typeof config === "string" && path5.isAbsolute(config))) {
737
+ const result = await loadConfig({
738
+ cwd
739
+ });
783
740
  if (!result) {
784
741
  throw new Error(`No TailwindCSS Config found in: ${cwd}`);
785
742
  }
786
743
  config = result.filepath;
787
744
  }
788
- const id = requireResolve("tailwindcss", {
789
- basedir: cwd
790
- });
745
+ const targetPostcssPlugin = postcssPlugin ?? (majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss");
746
+ if (majorVersion === 4) {
747
+ return await postcss([
748
+ require3(targetPostcssPlugin)({
749
+ config
750
+ })
751
+ ]).process("@import 'tailwindcss';", {
752
+ from: void 0
753
+ });
754
+ }
791
755
  return await postcss([
792
- require3(id)({
756
+ require3(targetPostcssPlugin)({
793
757
  config
794
758
  })
795
759
  ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
@@ -812,10 +776,14 @@ var TailwindcssPatcher = class {
812
776
  this.cacheOptions = getCacheOptions(options.cache);
813
777
  this.patchOptions = getPatchOptions(options.patch);
814
778
  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]);
779
+ const packageInfo = getPackageInfoSync("tailwindcss");
780
+ if (!packageInfo) {
781
+ throw new Error("tailwindcss not found");
782
+ }
783
+ if (packageInfo.version) {
784
+ this.majorVersion = Number.parseInt(packageInfo.version[0]);
818
785
  }
786
+ this.packageInfo = packageInfo;
819
787
  this.patch = () => {
820
788
  try {
821
789
  return internalPatch(this.packageInfo?.packageJsonPath, this.patchOptions);
@@ -834,14 +802,14 @@ var TailwindcssPatcher = class {
834
802
  }
835
803
  getContexts() {
836
804
  if (this.packageInfo) {
837
- const distPath = path7.join(this.packageInfo.rootPath, "lib");
805
+ const distPath = path6.join(this.packageInfo.rootPath, "lib");
838
806
  let injectFilePath;
839
807
  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");
808
+ injectFilePath = path6.join(distPath, "jit/index.js");
809
+ } else if (this.majorVersion === 3) {
810
+ injectFilePath = path6.join(distPath, "plugin.js");
811
+ if (!fs4.existsSync(injectFilePath)) {
812
+ injectFilePath = path6.join(distPath, "index.js");
845
813
  }
846
814
  }
847
815
  if (injectFilePath) {
@@ -857,17 +825,62 @@ var TailwindcssPatcher = class {
857
825
  const contexts = this.getContexts();
858
826
  return contexts.filter((x) => isObject(x)).map((x) => x.classCache);
859
827
  }
860
- getClassCacheSet(options) {
861
- const classCaches = this.getClassCaches();
828
+ async getClassCacheSet(options) {
862
829
  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;
830
+ const { output, tailwindcss } = options ?? {};
831
+ if (this.majorVersion === 4) {
832
+ const { v4 } = tailwindcss ?? {};
833
+ if (Array.isArray(v4?.cssEntries)) {
834
+ const results = (await Promise.all(
835
+ v4.cssEntries.map(async (x) => {
836
+ if (await fs4.exists(x)) {
837
+ const css = await fs4.readFile(x, "utf8");
838
+ return css;
839
+ }
840
+ return false;
841
+ })
842
+ )).filter((x) => x);
843
+ for (const css of results) {
844
+ const candidates = await extractValidCandidates({
845
+ base: v4?.base,
846
+ css,
847
+ sources: v4?.sources?.map((x) => {
848
+ return {
849
+ base: x.base ?? v4?.base ?? process5.cwd(),
850
+ pattern: x.pattern
851
+ };
852
+ })
853
+ });
854
+ for (const candidate of candidates) {
855
+ classSet.add(candidate);
856
+ }
857
+ }
858
+ } else {
859
+ const candidates = await extractValidCandidates({
860
+ base: v4?.base,
861
+ css: v4?.css,
862
+ sources: v4?.sources?.map((x) => {
863
+ return {
864
+ base: x.base ?? v4?.base ?? process5.cwd(),
865
+ pattern: x.pattern
866
+ };
867
+ })
868
+ });
869
+ for (const candidate of candidates) {
870
+ classSet.add(candidate);
871
+ }
872
+ }
873
+ } else {
874
+ const classCaches = this.getClassCaches();
875
+ for (const classCacheMap of classCaches) {
876
+ const keys = classCacheMap.keys();
877
+ for (const key of keys) {
878
+ const v = key.toString();
879
+ if (output?.removeUniversalSelector && v === "*") {
880
+ continue;
881
+ }
882
+ classSet.add(v);
869
883
  }
870
- classSet.add(v);
871
884
  }
872
885
  }
873
886
  return classSet;
@@ -875,10 +888,12 @@ var TailwindcssPatcher = class {
875
888
  /**
876
889
  * @description 在多个 tailwindcss 上下文时,这个方法将被执行多次,所以策略上应该使用 append
877
890
  */
878
- getClassSet(options) {
879
- const { cacheStrategy = this.cacheOptions.strategy ?? "merge", removeUniversalSelector = true } = options ?? {};
880
- const set = this.getClassCacheSet({
881
- removeUniversalSelector
891
+ async getClassSet(options) {
892
+ const { output, tailwindcss } = options ?? {};
893
+ const cacheStrategy = this.cacheOptions.strategy ?? "merge";
894
+ const set = await this.getClassCacheSet({
895
+ output,
896
+ tailwindcss
882
897
  });
883
898
  if (cacheStrategy === "overwrite") {
884
899
  set.size > 0 && this.setCache(set);
@@ -896,25 +911,30 @@ var TailwindcssPatcher = class {
896
911
  async extract(options) {
897
912
  const { output, tailwindcss } = options ?? {};
898
913
  if (output && tailwindcss) {
899
- const { removeUniversalSelector, filename, loose } = output;
900
- await processTailwindcss(tailwindcss);
901
- const set = this.getClassSet({
902
- removeUniversalSelector
914
+ const { filename, loose } = output;
915
+ if (this.majorVersion === 3) {
916
+ await processTailwindcss({
917
+ ...tailwindcss,
918
+ majorVersion: this.majorVersion
919
+ });
920
+ }
921
+ const set = await this.getClassSet({
922
+ output,
923
+ tailwindcss
903
924
  });
904
925
  if (filename) {
905
- await fs5.ensureDir(path7.dirname(filename));
906
926
  const classList = [...set];
907
- await fs5.outputJSON(filename, classList, {
927
+ await fs4.outputJSON(filename, classList, {
908
928
  spaces: loose ? 2 : void 0
909
929
  });
910
930
  return filename;
911
931
  }
912
932
  }
913
933
  }
934
+ extractValidCandidates = extractValidCandidates;
914
935
  };
915
936
 
916
937
  export {
917
- config_exports,
918
938
  logger_default,
919
939
  getCacheOptions,
920
940
  CacheManager,