tailwindcss-patch 5.0.1 → 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,107 +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 { lilconfig } from "lilconfig";
752
- import path6 from "pathe";
725
+ import process4 from "node:process";
726
+ import path5 from "pathe";
753
727
  import postcss from "postcss";
728
+ import { loadConfig } from "tailwindcss-config";
754
729
  var require3 = createRequire2(import.meta.url);
755
730
  async function processTailwindcss(options) {
756
- const { config: userConfig, cwd } = defu(options, {
757
- cwd: process3.cwd()
731
+ const { config: userConfig, cwd, majorVersion, postcssPlugin } = defu(options, {
732
+ cwd: process4.cwd(),
733
+ majorVersion: 3
758
734
  });
759
735
  let config = userConfig;
760
- if (!(typeof config === "string" && path6.isAbsolute(config))) {
761
- const moduleName = "tailwind";
762
- const tsx = (await import("tsx/cjs/api")).require;
763
- const result = await lilconfig("tailwindcss", {
764
- searchPlaces: [
765
- `${moduleName}.config.js`,
766
- `${moduleName}.config.cjs`,
767
- `${moduleName}.config.mjs`,
768
- `${moduleName}.config.ts`,
769
- `${moduleName}.config.cts`,
770
- `${moduleName}.config.mts`
771
- ],
772
- loaders: {
773
- // 默认支持 js 和 cjs 2种格式
774
- ".js": tsx,
775
- ".cjs": tsx,
776
- ".mjs": tsx,
777
- ".ts": tsx,
778
- ".cts": tsx,
779
- ".mts": tsx
780
- }
781
- }).search(cwd);
736
+ if (!(typeof config === "string" && path5.isAbsolute(config))) {
737
+ const result = await loadConfig({
738
+ cwd
739
+ });
782
740
  if (!result) {
783
741
  throw new Error(`No TailwindCSS Config found in: ${cwd}`);
784
742
  }
785
743
  config = result.filepath;
786
744
  }
787
- const id = requireResolve("tailwindcss", {
788
- basedir: cwd
789
- });
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
+ }
790
755
  return await postcss([
791
- require3(id)({
756
+ require3(targetPostcssPlugin)({
792
757
  config
793
758
  })
794
759
  ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
@@ -811,10 +776,14 @@ var TailwindcssPatcher = class {
811
776
  this.cacheOptions = getCacheOptions(options.cache);
812
777
  this.patchOptions = getPatchOptions(options.patch);
813
778
  this.cacheManager = new CacheManager(this.cacheOptions);
814
- this.packageInfo = getPackageInfoSync("tailwindcss", { basedir: this.patchOptions.basedir });
815
- if (this.packageInfo && this.packageInfo.version) {
816
- 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]);
817
785
  }
786
+ this.packageInfo = packageInfo;
818
787
  this.patch = () => {
819
788
  try {
820
789
  return internalPatch(this.packageInfo?.packageJsonPath, this.patchOptions);
@@ -833,14 +802,14 @@ var TailwindcssPatcher = class {
833
802
  }
834
803
  getContexts() {
835
804
  if (this.packageInfo) {
836
- const distPath = path7.join(this.packageInfo.rootPath, "lib");
805
+ const distPath = path6.join(this.packageInfo.rootPath, "lib");
837
806
  let injectFilePath;
838
807
  if (this.majorVersion === 2) {
839
- injectFilePath = path7.join(distPath, "jit/index.js");
840
- } else {
841
- injectFilePath = path7.join(distPath, "plugin.js");
842
- if (!fs5.existsSync(injectFilePath)) {
843
- 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");
844
813
  }
845
814
  }
846
815
  if (injectFilePath) {
@@ -856,17 +825,62 @@ var TailwindcssPatcher = class {
856
825
  const contexts = this.getContexts();
857
826
  return contexts.filter((x) => isObject(x)).map((x) => x.classCache);
858
827
  }
859
- getClassCacheSet(options) {
860
- const classCaches = this.getClassCaches();
828
+ async getClassCacheSet(options) {
861
829
  const classSet = /* @__PURE__ */ new Set();
862
- for (const classCacheMap of classCaches) {
863
- const keys = classCacheMap.keys();
864
- for (const key of keys) {
865
- const v = key.toString();
866
- if (options?.removeUniversalSelector && v === "*") {
867
- 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);
868
883
  }
869
- classSet.add(v);
870
884
  }
871
885
  }
872
886
  return classSet;
@@ -874,10 +888,12 @@ var TailwindcssPatcher = class {
874
888
  /**
875
889
  * @description 在多个 tailwindcss 上下文时,这个方法将被执行多次,所以策略上应该使用 append
876
890
  */
877
- getClassSet(options) {
878
- const { cacheStrategy = this.cacheOptions.strategy ?? "merge", removeUniversalSelector = true } = options ?? {};
879
- const set = this.getClassCacheSet({
880
- 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
881
897
  });
882
898
  if (cacheStrategy === "overwrite") {
883
899
  set.size > 0 && this.setCache(set);
@@ -895,25 +911,30 @@ var TailwindcssPatcher = class {
895
911
  async extract(options) {
896
912
  const { output, tailwindcss } = options ?? {};
897
913
  if (output && tailwindcss) {
898
- const { removeUniversalSelector, filename, loose } = output;
899
- await processTailwindcss(tailwindcss);
900
- const set = this.getClassSet({
901
- 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
902
924
  });
903
925
  if (filename) {
904
- await fs5.ensureDir(path7.dirname(filename));
905
926
  const classList = [...set];
906
- await fs5.outputJSON(filename, classList, {
927
+ await fs4.outputJSON(filename, classList, {
907
928
  spaces: loose ? 2 : void 0
908
929
  });
909
930
  return filename;
910
931
  }
911
932
  }
912
933
  }
934
+ extractValidCandidates = extractValidCandidates;
913
935
  };
914
936
 
915
937
  export {
916
- config_exports,
917
938
  logger_default,
918
939
  getCacheOptions,
919
940
  CacheManager,