weapp-tailwindcss 5.0.11 → 5.0.13

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.
Files changed (109) hide show
  1. package/dist/{bundle-state-BwtEqxvU.js → bundle-state-CKWeTEhv.js} +2 -40
  2. package/dist/{bundle-state-CXzPknlT.mjs → bundle-state-zQ2MrDdi.mjs} +2 -34
  3. package/dist/bundlers/gulp/vinyl-transform.d.ts +1 -1
  4. package/dist/bundlers/shared/generator-css/generation-helpers.d.ts +7 -2
  5. package/dist/bundlers/shared/generator-css/source-files.d.ts +1 -0
  6. package/dist/bundlers/shared/generator-css/source-resolver/apply-reference.d.ts +3 -0
  7. package/dist/bundlers/shared/generator-css/source-resolver/config.d.ts +7 -0
  8. package/dist/bundlers/shared/generator-css/source-resolver/matching.d.ts +4 -0
  9. package/dist/bundlers/shared/generator-css/source-resolver/metadata.d.ts +15 -0
  10. package/dist/bundlers/shared/generator-css/source-resolver/postcss-source.d.ts +12 -0
  11. package/dist/bundlers/shared/generator-css/source-resolver/types.d.ts +22 -0
  12. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +5 -22
  13. package/dist/bundlers/shared/generator-css/types.d.ts +2 -0
  14. package/dist/bundlers/shared/generator-css/validate.d.ts +1 -0
  15. package/dist/bundlers/shared/hmr-timing.d.ts +1 -0
  16. package/dist/bundlers/vite/css-memory.d.ts +27 -0
  17. package/dist/bundlers/vite/generate-bundle/bundle-file-names.d.ts +2 -0
  18. package/dist/bundlers/vite/generate-bundle/configured-css-sources.d.ts +8 -0
  19. package/dist/bundlers/vite/generate-bundle/css-assets.d.ts +4 -0
  20. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +5 -0
  21. package/dist/bundlers/vite/generate-bundle/css-output.d.ts +9 -7
  22. package/dist/bundlers/vite/generate-bundle/env-flags.d.ts +7 -0
  23. package/dist/bundlers/vite/generate-bundle/finalize.d.ts +58 -0
  24. package/dist/bundlers/vite/generate-bundle/js-processing.d.ts +31 -0
  25. package/dist/bundlers/vite/generate-bundle/memory-debug.d.ts +77 -0
  26. package/dist/bundlers/vite/generate-bundle/remembered-css-replay.d.ts +53 -0
  27. package/dist/bundlers/vite/generate-bundle/remembered-css.d.ts +1 -1
  28. package/dist/bundlers/vite/generate-bundle/runtime-linked-css.d.ts +4 -0
  29. package/dist/bundlers/vite/generate-bundle/scoped-generator.d.ts +21 -0
  30. package/dist/bundlers/vite/generate-bundle/sfc-style-source.d.ts +2 -1
  31. package/dist/bundlers/vite/generate-bundle/source-candidate-scope.d.ts +29 -0
  32. package/dist/bundlers/vite/generate-bundle/timing.d.ts +1 -0
  33. package/dist/bundlers/vite/generate-bundle/types.d.ts +7 -0
  34. package/dist/bundlers/vite/generate-bundle/uni-app-x-postprocess.d.ts +20 -0
  35. package/dist/bundlers/vite/generate-bundle/vite-css-cache.d.ts +6 -0
  36. package/dist/bundlers/vite/generate-bundle.d.ts +2 -1
  37. package/dist/bundlers/vite/hot-css-modules.d.ts +5 -0
  38. package/dist/bundlers/vite/map-cache.d.ts +2 -0
  39. package/dist/bundlers/vite/processed-css-assets.d.ts +16 -0
  40. package/dist/bundlers/vite/resolve-app-type.d.ts +1 -2
  41. package/dist/bundlers/vite/source-candidate-scan-signature.d.ts +13 -0
  42. package/dist/bundlers/vite/source-candidates.d.ts +9 -0
  43. package/dist/bundlers/vite/source-scan/css-entries.d.ts +1 -0
  44. package/dist/bundlers/vite/source-scan.d.ts +1 -1
  45. package/dist/bundlers/vite/weapp-vite-config.d.ts +3 -0
  46. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/helpers.d.ts +11 -8
  47. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +2 -0
  48. package/dist/bundlers/webpack/loaders/runtime-registry.d.ts +5 -0
  49. package/dist/cache/index.d.ts +4 -0
  50. package/dist/cli.js +9 -2
  51. package/dist/cli.mjs +8 -1
  52. package/dist/core.d.ts +7 -0
  53. package/dist/core.js +8 -5
  54. package/dist/core.mjs +8 -5
  55. package/dist/css-macro.js +1 -1
  56. package/dist/css-macro.mjs +1 -1
  57. package/dist/{defaults-DH0ZQRhy.mjs → defaults-Bqx18S1f.mjs} +2 -35
  58. package/dist/{defaults-Boc26eel.js → defaults-C_J_kBpw.js} +2 -35
  59. package/dist/defaults.js +1 -1
  60. package/dist/defaults.mjs +1 -1
  61. package/dist/framework/index.d.ts +59 -0
  62. package/dist/framework.d.ts +1 -0
  63. package/dist/framework.js +198 -0
  64. package/dist/framework.mjs +180 -0
  65. package/dist/{generator-ChgOWNOj.js → generator-CzpArpCL.js} +1 -1
  66. package/dist/{generator-h2XRiJ9-.mjs → generator-ITLd7PTl.mjs} +1 -1
  67. package/dist/generator.js +2 -2
  68. package/dist/generator.mjs +2 -2
  69. package/dist/{gulp-Be88jhoY.mjs → gulp-DfOQERcV.mjs} +137 -23
  70. package/dist/{gulp-CHtZF-oT.js → gulp-XT8Jc7lH.js} +137 -23
  71. package/dist/gulp.js +1 -1
  72. package/dist/gulp.mjs +1 -1
  73. package/dist/{hmr-timing-BkivBZvN.js → hmr-timing-BMftW7Us.js} +354 -225
  74. package/dist/{hmr-timing-Ct5w4hdM.mjs → hmr-timing-DQIP_8qP.mjs} +341 -225
  75. package/dist/index.d.ts +1 -0
  76. package/dist/index.js +20 -4
  77. package/dist/index.mjs +6 -5
  78. package/dist/postcss.js +9 -10
  79. package/dist/postcss.mjs +7 -5
  80. package/dist/{precheck-CY9oaH49.js → precheck-B0Z8yW7E.js} +108 -27
  81. package/dist/{precheck-BpHxsWRd.mjs → precheck-CRI90iL1.mjs} +109 -28
  82. package/dist/presets.js +3 -3
  83. package/dist/presets.mjs +3 -3
  84. package/dist/tailwindcss/source-scan.d.ts +1 -0
  85. package/dist/tailwindcss/v3-engine/generator.d.ts +17 -0
  86. package/dist/tailwindcss/v3-engine/index.d.ts +1 -1
  87. package/dist/tailwindcss/v3-engine/types.d.ts +1 -0
  88. package/dist/tailwindcss/v4-engine/generator.d.ts +19 -0
  89. package/dist/tailwindcss/v4-engine/index.d.ts +1 -1
  90. package/dist/{tailwindcss-Bfy2egdX.mjs → tailwindcss-DTq3uYBK.mjs} +2 -2
  91. package/dist/{tailwindcss-DbbAKAZP.js → tailwindcss-DZEwT3C_.js} +3 -3
  92. package/dist/{transform-r5evL6Hn.mjs → transform-DfcEjsZF.mjs} +29 -21
  93. package/dist/{transform-Cd634UZV.js → transform-YmrmxuF3.js} +29 -21
  94. package/dist/types/user-defined-options/general.d.ts +3 -1
  95. package/dist/{utils-Dolmt8EO.js → utils-BCa37Wqj.js} +2 -17
  96. package/dist/{utils-DsaS975I.mjs → utils-DodxWHGz.mjs} +2 -17
  97. package/dist/{v3-engine-D0yA9ZkF.js → v3-engine-2rrgylhn.js} +194 -34
  98. package/dist/{v3-engine-CFkP6dWF.mjs → v3-engine-C6eJ0YzK.mjs} +176 -34
  99. package/dist/{vite-j9cB2Ff1.js → vite-CXHVsHmX.js} +2071 -1160
  100. package/dist/{vite-Bd8qf9dK.mjs → vite-DjI09vVN.mjs} +2071 -1160
  101. package/dist/vite.js +1 -1
  102. package/dist/vite.mjs +1 -1
  103. package/dist/weapp-tw-css-import-rewrite-loader.js +476 -217
  104. package/dist/weapp-tw-runtime-classset-loader.js +25 -0
  105. package/dist/{webpack-DPdrcC2X.mjs → webpack-BcPpnT90.mjs} +251 -40
  106. package/dist/{webpack-CJAOcYEO.js → webpack-CfkUkMXG.js} +254 -43
  107. package/dist/webpack.js +1 -1
  108. package/dist/webpack.mjs +1 -1
  109. package/package.json +10 -5
@@ -1,20 +1,22 @@
1
1
  const require_chunk = require("./chunk-emK7D4bc.js");
2
- const require_v3_engine = require("./v3-engine-D0yA9ZkF.js");
3
- const require_generator = require("./generator-ChgOWNOj.js");
4
- const require_precheck = require("./precheck-CY9oaH49.js");
5
- const require_utils = require("./utils-Dolmt8EO.js");
6
- const require_tailwindcss = require("./tailwindcss-DbbAKAZP.js");
7
- const require_hmr_timing = require("./hmr-timing-BkivBZvN.js");
8
- const require_bundle_state = require("./bundle-state-BwtEqxvU.js");
2
+ const require_framework = require("./framework.js");
3
+ const require_v3_engine = require("./v3-engine-2rrgylhn.js");
4
+ const require_generator = require("./generator-CzpArpCL.js");
5
+ const require_precheck = require("./precheck-B0Z8yW7E.js");
6
+ const require_utils = require("./utils-BCa37Wqj.js");
7
+ const require_tailwindcss = require("./tailwindcss-DZEwT3C_.js");
8
+ const require_hmr_timing = require("./hmr-timing-BMftW7Us.js");
9
+ const require_bundle_state = require("./bundle-state-CKWeTEhv.js");
9
10
  require("./logger-TlKT3xmR.js");
10
- let _weapp_tailwindcss_postcss = require("@weapp-tailwindcss/postcss");
11
- let tailwindcss_patch = require("tailwindcss-patch");
12
11
  let node_fs = require("node:fs");
13
12
  node_fs = require_chunk.__toESM(node_fs);
14
13
  let node_path = require("node:path");
15
14
  node_path = require_chunk.__toESM(node_path);
16
15
  let node_process = require("node:process");
17
16
  node_process = require_chunk.__toESM(node_process);
17
+ let _weapp_tailwindcss_postcss = require("@weapp-tailwindcss/postcss");
18
+ let lru_cache = require("lru-cache");
19
+ let tailwindcss_patch = require("tailwindcss-patch");
18
20
  let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
19
21
  let node_fs_promises = require("node:fs/promises");
20
22
  let node_buffer = require("node:buffer");
@@ -480,7 +482,7 @@ function resolveUniAppXStyleIsolationEnabled(root) {
480
482
  //#region src/uni-app-x/vite.ts
481
483
  let transformUVuePromise;
482
484
  function loadTransformUVue() {
483
- transformUVuePromise ?? (transformUVuePromise = Promise.resolve().then(() => require("./transform-Cd634UZV.js")).then((mod) => mod.transformUVue));
485
+ transformUVuePromise ?? (transformUVuePromise = Promise.resolve().then(() => require("./transform-YmrmxuF3.js")).then((mod) => mod.transformUVue));
484
486
  return transformUVuePromise;
485
487
  }
486
488
  const preprocessorLangs = new Set([
@@ -785,24 +787,155 @@ function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
785
787
  return new Set([...candidates, "container"]);
786
788
  }
787
789
  //#endregion
790
+ //#region src/bundlers/vite/generate-bundle/configured-css-sources.ts
791
+ function collectConfiguredTailwindV4CssSources(opts) {
792
+ const patcherCssSources = opts.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssSources ?? [];
793
+ return [...opts.tailwindcss?.v4?.cssSources ?? [], ...patcherCssSources];
794
+ }
795
+ function collectConfiguredTailwindV4CssSourceEntries(opts, fallbackBase) {
796
+ const entries = [];
797
+ for (const cssSource of collectConfiguredTailwindV4CssSources(opts)) {
798
+ if (typeof cssSource.css !== "string" || cssSource.css.length === 0) continue;
799
+ const base = require_v3_engine.resolveTailwindV4CssSourceBase(cssSource, fallbackBase);
800
+ const file = typeof cssSource.file === "string" && cssSource.file.length > 0 ? cssSource.file : node_path.default.join(base, "tailwind.css");
801
+ entries.push({
802
+ file: node_path.default.isAbsolute(file) ? node_path.default.resolve(file) : node_path.default.resolve(base, file),
803
+ source: cssSource.css
804
+ });
805
+ }
806
+ return entries;
807
+ }
808
+ //#endregion
809
+ //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
810
+ function createReplayCssAsset(fileName, source) {
811
+ return {
812
+ type: "asset",
813
+ fileName,
814
+ name: void 0,
815
+ source,
816
+ needsCodeReference: false,
817
+ names: [],
818
+ originalFileName: null,
819
+ originalFileNames: []
820
+ };
821
+ }
822
+ function isAddWatchFileInvalidRollupPhaseError$1(error) {
823
+ const candidate = error;
824
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
825
+ }
826
+ function registerGeneratorDependencies$1(ctx, dependencies) {
827
+ if (typeof ctx.addWatchFile !== "function") return;
828
+ for (const dependency of dependencies ?? []) try {
829
+ ctx.addWatchFile(dependency);
830
+ } catch (error) {
831
+ if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
832
+ _weapp_tailwindcss_logger.logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
833
+ continue;
834
+ }
835
+ throw error;
836
+ }
837
+ }
838
+ //#endregion
839
+ //#region src/bundlers/vite/generate-bundle/css-assets.ts
840
+ function createCssAssetEmitter(context) {
841
+ return (fileName, source) => {
842
+ const replayAsset = createReplayCssAsset(fileName, source);
843
+ if (context.emitFile) {
844
+ context.emitFile({
845
+ type: "asset",
846
+ fileName,
847
+ source
848
+ });
849
+ return replayAsset;
850
+ }
851
+ return replayAsset;
852
+ };
853
+ }
854
+ function resolveAssetSourceFile(asset, fallbackFile) {
855
+ return [asset.originalFileName, ...asset.originalFileNames ?? []].filter((item) => typeof item === "string" && item.length > 0)[0] ?? fallbackFile;
856
+ }
857
+ //#endregion
788
858
  //#region src/bundlers/vite/generate-bundle/css-output.ts
789
859
  const SOURCE_STYLE_OUTPUT_EXT_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss)$/i;
790
860
  const CSS_SOURCE_OUTPUT_EXT_RE = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)$/i;
791
- const MINI_PROGRAM_STYLE_OUTPUT_EXT_RE = /\.(?:wx|ac|jx|tt|q|ty)ss$/i;
792
861
  const SOURCE_STYLE_NON_CSS_SYNTAX_RE = /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@(?:use|forward|mixin|include|function)\b)/;
862
+ const FALLBACK_STYLE_OUTPUT_EXTENSION = ".css";
863
+ const COMMON_MINI_PROGRAM_STYLE_OUTPUT_EXTENSIONS = [
864
+ ".wxss",
865
+ ".acss",
866
+ ".ttss",
867
+ ".qss",
868
+ ".jxss",
869
+ ".tyss"
870
+ ];
871
+ function normalizeStyleOutputExtension(value) {
872
+ if (typeof value !== "string" || value.trim().length === 0) return;
873
+ const normalized = value.trim().toLowerCase();
874
+ return normalized.startsWith(".") ? normalized : `.${normalized}`;
875
+ }
876
+ function getMatchedStyleOutputExtension(file, cssMatcher) {
877
+ const cleanFile = file.replace(/[?#].*$/, "");
878
+ if (!cssMatcher?.(cleanFile)) return;
879
+ const ext = node_path.default.extname(cleanFile);
880
+ if (!ext || ext === ".css") return;
881
+ return ext;
882
+ }
883
+ function resolveStyleOutputExtensionFromFiles(files, cssMatcher, stem) {
884
+ let extension;
885
+ for (const file of files ?? []) {
886
+ const cleanFile = file.replace(/[?#].*$/, "");
887
+ const matchedExtension = getMatchedStyleOutputExtension(cleanFile, cssMatcher);
888
+ if (!matchedExtension) continue;
889
+ if (stem && cleanFile.slice(0, -matchedExtension.length) !== stem) continue;
890
+ if (extension && extension !== matchedExtension) return;
891
+ extension = matchedExtension;
892
+ }
893
+ return extension;
894
+ }
895
+ function resolveStyleOutputExtensionFromMatcher(cssMatcher, stem) {
896
+ if (!cssMatcher || !stem) return;
897
+ return COMMON_MINI_PROGRAM_STYLE_OUTPUT_EXTENSIONS.find((extension) => cssMatcher(`${stem}${extension}`));
898
+ }
899
+ function resolveMiniProgramStyleOutputExtension(options = {}) {
900
+ return resolveStyleOutputExtensionFromFiles(options.files, options.cssMatcher, options.stem) ?? resolveStyleOutputExtensionFromMatcher(options.cssMatcher, options.stem) ?? normalizeStyleOutputExtension(options.fallback) ?? resolveStyleOutputExtensionFromFiles(options.files, options.cssMatcher) ?? FALLBACK_STYLE_OUTPUT_EXTENSION;
901
+ }
793
902
  function resolveReplayCssOutputFile(rootDir, file) {
794
903
  const normalizedFile = require_bundle_state.normalizeOutputPathKey(node_path.default.isAbsolute(file) ? node_path.default.relative(rootDir, file) : file);
795
904
  if (normalizedFile.length === 0 || normalizedFile === "." || normalizedFile === ".." || normalizedFile.startsWith("../")) return require_bundle_state.normalizeOutputPathKey(node_path.default.basename(file));
796
905
  return normalizedFile;
797
906
  }
798
- function resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, preserveCssExtension = false) {
907
+ function normalizeViteSourceRoot(rootDir, sourceRoot) {
908
+ if (typeof sourceRoot !== "string" || sourceRoot.trim().length === 0) return;
909
+ return require_bundle_state.normalizeOutputPathKey(node_path.default.isAbsolute(sourceRoot) ? node_path.default.relative(rootDir, sourceRoot) : sourceRoot).replace(/\/+$/, "");
910
+ }
911
+ function resolveReplayCssOutputFileFromSourceRoot(rootDir, file, sourceRoot) {
912
+ const outputFile = resolveReplayCssOutputFile(rootDir, file);
913
+ const normalizedSourceRoot = normalizeViteSourceRoot(rootDir, sourceRoot);
914
+ if (!normalizedSourceRoot) return outputFile;
915
+ if (outputFile === normalizedSourceRoot) return node_path.default.posix.basename(outputFile);
916
+ if (outputFile.startsWith(`${normalizedSourceRoot}/`)) return outputFile.slice(normalizedSourceRoot.length + 1);
917
+ return outputFile;
918
+ }
919
+ function resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, preserveCssExtension = false, styleOutputExtension, styleOutputFiles) {
799
920
  if (isWebGeneratorTarget || preserveCssExtension || opts.cssMatcher(file) || !SOURCE_STYLE_OUTPUT_EXT_RE.test(file) || !require_bundle_state.isCSSRequest(file)) return file;
800
- return file.replace(SOURCE_STYLE_OUTPUT_EXT_RE, ".wxss");
921
+ const stem = file.replace(/[?#].*$/, "").replace(SOURCE_STYLE_OUTPUT_EXT_RE, "");
922
+ return file.replace(SOURCE_STYLE_OUTPUT_EXT_RE, resolveMiniProgramStyleOutputExtension({
923
+ cssMatcher: opts.cssMatcher,
924
+ fallback: styleOutputExtension,
925
+ files: styleOutputFiles,
926
+ stem
927
+ }));
801
928
  }
802
- function resolveViteCssPipelineOutputFile(file, _opts, rootDir, isWebGeneratorTarget = false, preserveCssExtension = false) {
803
- const normalizedFile = resolveReplayCssOutputFile(rootDir, file);
804
- if (isWebGeneratorTarget || preserveCssExtension || MINI_PROGRAM_STYLE_OUTPUT_EXT_RE.test(normalizedFile) || !CSS_SOURCE_OUTPUT_EXT_RE.test(normalizedFile) || !require_bundle_state.isCSSRequest(normalizedFile)) return normalizedFile;
805
- return normalizedFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, ".wxss");
929
+ function resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget = false, preserveCssExtension = false, sourceRoot, styleOutputExtension, styleOutputFiles) {
930
+ const normalizedFile = resolveReplayCssOutputFileFromSourceRoot(rootDir, file, sourceRoot);
931
+ const cleanFile = normalizedFile.replace(/[?#].*$/, "");
932
+ const stem = cleanFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, "");
933
+ const matchedStyleExtension = !isWebGeneratorTarget && !preserveCssExtension ? resolveStyleOutputExtensionFromFiles(styleOutputFiles, opts.cssMatcher, stem) : void 0;
934
+ if (matchedStyleExtension && CSS_SOURCE_OUTPUT_EXT_RE.test(cleanFile) && require_bundle_state.isCSSRequest(normalizedFile)) return normalizedFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, matchedStyleExtension);
935
+ if (isWebGeneratorTarget || preserveCssExtension || opts.cssMatcher(normalizedFile) || !CSS_SOURCE_OUTPUT_EXT_RE.test(normalizedFile) || !require_bundle_state.isCSSRequest(normalizedFile)) return normalizedFile;
936
+ const fallbackExtension = normalizeStyleOutputExtension(styleOutputExtension);
937
+ if (!fallbackExtension && !SOURCE_STYLE_OUTPUT_EXT_RE.test(normalizedFile)) return normalizedFile;
938
+ return normalizedFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, fallbackExtension ?? FALLBACK_STYLE_OUTPUT_EXTENSION);
806
939
  }
807
940
  function canProcessViteSourceStyleAsCss(source, file) {
808
941
  if (SOURCE_STYLE_NON_CSS_SYNTAX_RE.test(source)) return false;
@@ -821,19 +954,6 @@ function stripStyleFileExtension(file) {
821
954
  const ext = node_path.default.extname(normalized);
822
955
  return ext ? normalized.slice(0, -ext.length) : normalized;
823
956
  }
824
- function isAppOriginCssFile(file) {
825
- return node_path.default.basename(stripStyleFileExtension(file)) === "app-origin";
826
- }
827
- function isMainAppCssFile(file) {
828
- return node_path.default.basename(stripStyleFileExtension(file)) === "app";
829
- }
830
- function isMainStyleEntryCssFile(file) {
831
- const basename = node_path.default.basename(stripStyleFileExtension(file));
832
- return basename === "app" || basename === "main";
833
- }
834
- function isTailwindEntryCssFile(file) {
835
- return node_path.default.basename(stripStyleFileExtension(file)) === "tailwind";
836
- }
837
957
  //#endregion
838
958
  //#region src/bundlers/vite/generate-bundle/style-matching.ts
839
959
  function isMatchingCssSourceFile(outputFile, cssSourceFile, outputRoot) {
@@ -888,10 +1008,6 @@ function normalizeMatchedCssSourcePath(file) {
888
1008
  if (!file || !node_path.default.isAbsolute(file)) return;
889
1009
  return node_path.default.resolve(file.replace(/[?#].*$/, ""));
890
1010
  }
891
- function collectConfiguredTailwindV4CssSources(opts) {
892
- const patcherCssSources = opts.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssSources ?? [];
893
- return [...opts.tailwindcss?.v4?.cssSources ?? [], ...patcherCssSources ?? []];
894
- }
895
1011
  function collectConfiguredCssEntries(opts) {
896
1012
  const patcherCssEntries = opts.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssEntries ?? [];
897
1013
  return [
@@ -943,6 +1059,9 @@ function normalizeRelativeCssConfigDirectives(source, file, outputRoot, opts) {
943
1059
  }
944
1060
  //#endregion
945
1061
  //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
1062
+ function resolveViteCssHandlerExtraOptions(file) {
1063
+ return require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, "")).includes("/") ? { isMainChunk: false } : {};
1064
+ }
946
1065
  function createCssHandlerOptionsCache(options) {
947
1066
  const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
948
1067
  const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
@@ -957,8 +1076,8 @@ function createCssHandlerOptionsCache(options) {
957
1076
  const cached = cssHandlerOptionsCache.get(cacheKey);
958
1077
  if (cached) return cached;
959
1078
  const created = {
960
- ...extraOptions,
961
1079
  isMainChunk,
1080
+ ...extraOptions,
962
1081
  postcssOptions: { options: { from } },
963
1082
  majorVersion,
964
1083
  sourceOptions: { outputRoot }
@@ -1023,414 +1142,16 @@ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
1023
1142
  return false;
1024
1143
  }
1025
1144
  //#endregion
1026
- //#region src/bundlers/vite/generate-bundle/js-entries.ts
1027
- function createJsEntryResolver(jsEntries) {
1028
- const normalizedJsEntries = /* @__PURE__ */ new Map();
1029
- for (const [id, entry] of jsEntries) normalizedJsEntries.set(require_bundle_state.normalizeOutputPathKey(id), entry);
1030
- return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(require_bundle_state.normalizeOutputPathKey(id));
1031
- }
1032
- //#endregion
1033
- //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
1034
- function resolveUniAppXJsTransformEnabled(uniAppX) {
1035
- return uniAppX === void 0 ? true : require_tailwindcss.isUniAppXEnabled(uniAppX);
1036
- }
1037
- function createJsHandlerOptionsFactory(options) {
1038
- return (absoluteFilename, extra) => ({
1039
- ...extra,
1040
- filename: absoluteFilename,
1041
- tailwindcssMajorVersion: options.getMajorVersion(),
1042
- moduleGraph: options.moduleGraph,
1043
- babelParserOptions: {
1044
- ...extra?.babelParserOptions ?? {},
1045
- sourceFilename: absoluteFilename
1046
- }
1047
- });
1048
- }
1049
- //#endregion
1050
- //#region src/bundlers/vite/generate-bundle/js-linking.ts
1051
- function createLinkedUpdateHelpers(options) {
1052
- const pendingLinkedUpdates = [];
1053
- const handleLinkedUpdate = (fileName, previous, next) => {
1054
- options.onUpdate(fileName, previous, next);
1055
- options.debug("js linked handle: %s", fileName);
1056
- };
1057
- const scheduleLinkedApply = (entry, code) => {
1058
- pendingLinkedUpdates.push(() => {
1059
- if (entry.output.type === "chunk") entry.output.code = code;
1060
- else entry.output.source = code;
1061
- });
1062
- };
1063
- const applyLinkedUpdates = (linked) => {
1064
- require_bundle_state.applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
1065
- };
1066
- return {
1067
- applyLinkedUpdates,
1068
- pendingLinkedUpdates
1069
- };
1070
- }
1071
- function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
1072
- if (!linked || !linkedSet) return;
1073
- for (const id of Object.keys(linked)) {
1074
- const linkedEntry = getJsEntry(id);
1075
- if (linkedEntry) linkedSet.add(linkedEntry.fileName);
1076
- }
1077
- }
1078
- //#endregion
1079
- //#region src/bundlers/vite/generate-bundle/metrics.ts
1080
- function formatDebugFileList(files, limit = 8) {
1081
- if (files.size === 0) return "-";
1082
- const sorted = [...files].sort();
1083
- if (sorted.length <= limit) return sorted.join(",");
1084
- return `${sorted.slice(0, limit).join(",")},...(+${sorted.length - limit})`;
1085
- }
1086
- function createEmptyMetric() {
1087
- return {
1088
- total: 0,
1089
- transformed: 0,
1090
- cacheHits: 0,
1091
- elapsed: 0
1092
- };
1093
- }
1094
- function createEmptyMetrics() {
1145
+ //#region src/bundlers/vite/generate-bundle/env-flags.ts
1146
+ function resolveGenerateBundleEnvFlags() {
1095
1147
  return {
1096
- runtimeSet: 0,
1097
- html: createEmptyMetric(),
1098
- js: createEmptyMetric(),
1099
- css: createEmptyMetric()
1148
+ forceRuntimeRefreshByEnv: node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1",
1149
+ disableDirtyOptimization: node_process.default.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1",
1150
+ disableJsPrecheck: node_process.default.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1",
1151
+ debugCssDiff: node_process.default.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1",
1152
+ disableV3OxideSourceRuntime: node_process.default.env["WEAPP_TW_VITE_DISABLE_V3_OXIDE_RUNTIME"] === "1"
1100
1153
  };
1101
1154
  }
1102
- function measureElapsed(start) {
1103
- return performance.now() - start;
1104
- }
1105
- function formatCacheHitRate(metric) {
1106
- if (metric.total === 0) return "0.00%";
1107
- return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
1108
- }
1109
- function formatMs(value) {
1110
- return value.toFixed(2);
1111
- }
1112
- //#endregion
1113
- //#region src/bundlers/vite/generate-bundle/process-plan.ts
1114
- function logBundleProcessPlan(options) {
1115
- const { debug, snapshot, useIncrementalMode, iteration } = options;
1116
- const { processFiles } = snapshot;
1117
- if (useIncrementalMode) {
1118
- debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", iteration, snapshot.changedByType.html.size, formatDebugFileList(snapshot.changedByType.html), snapshot.changedByType.js.size, formatDebugFileList(snapshot.changedByType.js), snapshot.changedByType.css.size, formatDebugFileList(snapshot.changedByType.css), snapshot.changedByType.other.size, formatDebugFileList(snapshot.changedByType.other));
1119
- debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", iteration, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
1120
- return;
1121
- }
1122
- debug("build mode full process html=%d[%s] js=%d[%s] css=%d[%s]", processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
1123
- }
1124
- //#endregion
1125
- //#region src/bundlers/vite/generate-bundle/sfc-style-source.ts
1126
- const SFC_STYLE_SOURCE_EXTENSIONS = [
1127
- ".vue",
1128
- ".uvue",
1129
- ".nvue",
1130
- ".svelte",
1131
- ".mpx"
1132
- ];
1133
- const SFC_STYLE_BLOCK_RE$1 = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
1134
- function extractSfcStyleSources(source) {
1135
- const styleSources = [];
1136
- SFC_STYLE_BLOCK_RE$1.lastIndex = 0;
1137
- let match = SFC_STYLE_BLOCK_RE$1.exec(source);
1138
- while (match !== null) {
1139
- styleSources.push(match[1] ?? "");
1140
- match = SFC_STYLE_BLOCK_RE$1.exec(source);
1141
- }
1142
- return styleSources;
1143
- }
1144
- function hasSfcStyleSources(source) {
1145
- return extractSfcStyleSources(source).length > 0;
1146
- }
1147
- function hasTailwindGenerationSource(source) {
1148
- return require_v3_engine.hasTailwindSourceDirectives(source, { importFallback: true }) || require_v3_engine.hasTailwindRootDirectives(source, { importFallback: true }) || require_v3_engine.hasTailwindApplyDirective(source);
1149
- }
1150
- async function resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outputRoot, sourceRoot, getSfcSource, debug) {
1151
- const sourceFile = resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug);
1152
- if (!sourceFile) {
1153
- debug("sfc style source infer skipped: no source file for %s", outputFile);
1154
- return;
1155
- }
1156
- const source = getSfcSource?.(sourceFile);
1157
- if (source == null) {
1158
- debug("sfc style source infer skipped: missing known source for %s -> %s", outputFile, sourceFile);
1159
- return;
1160
- }
1161
- const rawSource = extractSfcStyleSources(source).join("\n");
1162
- if (!rawSource || !hasTailwindGenerationSource(rawSource)) {
1163
- debug("sfc style source infer skipped: no tailwind generation source for %s -> %s", outputFile, sourceFile);
1164
- return;
1165
- }
1166
- debug("sfc style source inferred: %s -> %s", outputFile, sourceFile);
1167
- return {
1168
- outputFile,
1169
- rawSource,
1170
- sourceFile
1171
- };
1172
- }
1173
- function normalizeSfcSourceFileForCompare(file) {
1174
- return require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1175
- }
1176
- function collectChunkModuleIds(output) {
1177
- const moduleIds = Array.isArray(output.moduleIds) ? output.moduleIds : [];
1178
- return [
1179
- output.facadeModuleId,
1180
- ...moduleIds,
1181
- ...Object.keys(output.modules ?? {})
1182
- ].filter((id, index, ids) => typeof id === "string" && id.length > 0 && ids.indexOf(id) === index);
1183
- }
1184
- function resolveSiblingJsChunkFile(outputFile) {
1185
- const normalizedOutputFile = outputFile.replace(/[?#].*$/, "");
1186
- if (MINI_PROGRAM_STYLE_OUTPUT_EXT_RE.test(normalizedOutputFile)) return normalizedOutputFile.replace(MINI_PROGRAM_STYLE_OUTPUT_EXT_RE, ".js");
1187
- if (CSS_SOURCE_OUTPUT_EXT_RE.test(normalizedOutputFile)) return normalizedOutputFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, ".js");
1188
- }
1189
- function normalizeSfcModuleId(id) {
1190
- const file = id.replace(/[?#].*$/, "");
1191
- if (!SFC_STYLE_SOURCE_EXTENSIONS.some((extension) => file.endsWith(extension))) return;
1192
- if (!node_path.default.isAbsolute(file)) return;
1193
- return node_path.default.resolve(file);
1194
- }
1195
- function resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug) {
1196
- const siblingJsFile = resolveSiblingJsChunkFile(outputFile);
1197
- if (!siblingJsFile) {
1198
- debug("sfc style sibling chunk skipped: no sibling js for %s", outputFile);
1199
- return;
1200
- }
1201
- const normalizedSiblingJsFile = require_bundle_state.normalizeOutputPathKey(siblingJsFile);
1202
- const siblingChunk = snapshot.entries.find((entry) => entry.type === "js" && entry.output.type === "chunk" && require_bundle_state.normalizeOutputPathKey(entry.file) === normalizedSiblingJsFile);
1203
- if (!siblingChunk || siblingChunk.output.type !== "chunk") {
1204
- debug("sfc style sibling chunk skipped: missing chunk for %s -> %s", outputFile, siblingJsFile);
1205
- return;
1206
- }
1207
- const sourceFiles = collectChunkModuleIds(siblingChunk.output).map(normalizeSfcModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
1208
- if (sourceFiles.length === 0) {
1209
- debug("sfc style sibling chunk skipped: no sfc modules for %s -> %s", outputFile, siblingJsFile);
1210
- return;
1211
- }
1212
- const scoredSources = sourceFiles.map((sourceFile) => ({
1213
- sourceFile,
1214
- score: scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot)
1215
- })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
1216
- debug("sfc style sibling chunk candidates: %s -> %s %O", outputFile, siblingJsFile, scoredSources);
1217
- const bestScore = scoredSources[0]?.score;
1218
- if (!bestScore) return;
1219
- const bestSources = scoredSources.filter((item) => item.score === bestScore);
1220
- if (bestSources.length !== 1) {
1221
- debug("sfc style sibling chunk skipped: ambiguous best sources for %s %O", outputFile, bestSources);
1222
- return;
1223
- }
1224
- return bestSources[0]?.sourceFile;
1225
- }
1226
- //#endregion
1227
- //#region src/bundlers/vite/generate-bundle/remembered-css.ts
1228
- function createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash) {
1229
- return `${cssRuntimeSignature}:${cssRuntimeAffectingHash}`;
1230
- }
1231
- function findRememberedCssSources(sources, outputFile, file, originalSource, outputRoot, sourceRoot) {
1232
- if (!sources) return [];
1233
- const rememberedSources = [...sources].map(([, remembered]) => remembered);
1234
- const source = typeof originalSource.source === "string" ? originalSource.source : originalSource.source.toString();
1235
- const markerFiles = new Set(require_bundle_state.parseBundlerGeneratedCssMarkerBlocks(source).filter((block) => block.bundler === "vite" && typeof block.file === "string" && block.file.length > 0).map((block) => require_bundle_state.normalizeOutputPathKey(block.file)));
1236
- if (markerFiles.size > 0) {
1237
- const markerMatched = rememberedSources.filter((remembered) => markerFiles.has(require_bundle_state.normalizeOutputPathKey(remembered.sourceFile.replace(/[?#].*$/, ""))));
1238
- if (markerMatched.length > 0) return markerMatched;
1239
- }
1240
- const originalFiles = [
1241
- file,
1242
- originalSource.originalFileName,
1243
- ...originalSource.originalFileNames ?? []
1244
- ].filter((item) => typeof item === "string" && item.length > 0);
1245
- const sourceMatched = rememberedSources.filter((remembered) => originalFiles.some((originalFile) => require_bundle_state.normalizeOutputPathKey(remembered.sourceFile) === require_bundle_state.normalizeOutputPathKey(originalFile)));
1246
- if (sourceMatched.length > 0) return sourceMatched;
1247
- const outputMatched = rememberedSources.filter((remembered) => require_bundle_state.normalizeOutputPathKey(remembered.outputFile) === require_bundle_state.normalizeOutputPathKey(outputFile));
1248
- if (outputMatched.length > 0) return outputMatched;
1249
- const shouldUseRememberedApplyFallback = !require_bundle_state.hasBundlerGeneratedCssMarker(source) && !hasTailwindGenerationSource(source);
1250
- if (shouldUseRememberedApplyFallback && !rememberedSources.some((remembered) => require_v3_engine.hasTailwindApplyDirective(remembered.rawSource))) return [];
1251
- const scoredMatches = rememberedSources.filter((remembered) => !shouldUseRememberedApplyFallback || require_v3_engine.hasTailwindApplyDirective(remembered.rawSource)).filter((remembered) => !(isMainAppCssFile(outputFile) && isAppOriginCssFile(remembered.outputFile))).map((remembered) => ({
1252
- remembered,
1253
- score: Math.max(scoreMatchingStyleFileBase(outputFile, remembered.sourceFile, outputRoot, sourceRoot), scoreMatchingStyleFileBase(outputFile, remembered.outputFile, outputRoot, sourceRoot))
1254
- })).filter((match) => match.score > 0).sort((a, b) => b.score - a.score);
1255
- const bestScore = scoredMatches[0]?.score;
1256
- return bestScore ? scoredMatches.filter((match) => match.score === bestScore).map((match) => match.remembered) : [];
1257
- }
1258
- function mergeRememberedCssSources(sources, outputFile) {
1259
- if (sources.length <= 1) return sources[0];
1260
- const seen = /* @__PURE__ */ new Set();
1261
- const rawSources = [];
1262
- for (const source of sources) {
1263
- const key = `${source.sourceFile}\0${source.rawSource}`;
1264
- if (seen.has(key)) continue;
1265
- seen.add(key);
1266
- rawSources.push(source.rawSource);
1267
- }
1268
- return {
1269
- outputFile,
1270
- rawSource: rawSources.join("\n"),
1271
- sourceFile: sources[0]?.sourceFile ?? outputFile
1272
- };
1273
- }
1274
- function collectRememberedCssReplayGroups(sources, opts, rootDir, isWebGeneratorTarget, preserveCssExtension) {
1275
- const groups = /* @__PURE__ */ new Map();
1276
- for (const [key, remembered] of sources ?? []) {
1277
- const outputKey = require_bundle_state.normalizeOutputPathKey(resolveViteCssPipelineOutputFile(remembered.outputFile, opts, rootDir, isWebGeneratorTarget, preserveCssExtension));
1278
- const group = groups.get(outputKey) ?? [];
1279
- group.push({
1280
- key,
1281
- remembered
1282
- });
1283
- groups.set(outputKey, group);
1284
- }
1285
- return groups;
1286
- }
1287
- //#endregion
1288
- //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
1289
- function createReplayCssAsset(fileName, source) {
1290
- return {
1291
- type: "asset",
1292
- fileName,
1293
- name: void 0,
1294
- source,
1295
- needsCodeReference: false,
1296
- names: [],
1297
- originalFileName: null,
1298
- originalFileNames: []
1299
- };
1300
- }
1301
- function isAddWatchFileInvalidRollupPhaseError$1(error) {
1302
- const candidate = error;
1303
- return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
1304
- }
1305
- function registerGeneratorDependencies$1(ctx, dependencies) {
1306
- if (typeof ctx.addWatchFile !== "function") return;
1307
- for (const dependency of dependencies ?? []) try {
1308
- ctx.addWatchFile(dependency);
1309
- } catch (error) {
1310
- if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
1311
- _weapp_tailwindcss_logger.logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
1312
- continue;
1313
- }
1314
- throw error;
1315
- }
1316
- }
1317
- //#endregion
1318
- //#region src/bundlers/vite/generate-bundle/signatures.ts
1319
- function summarizeStringDiff(previous, next) {
1320
- if (previous === next) return "same";
1321
- const previousLength = previous.length;
1322
- const nextLength = next.length;
1323
- const minLength = Math.min(previousLength, nextLength);
1324
- let prefixLength = 0;
1325
- while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) prefixLength += 1;
1326
- let previousSuffixCursor = previousLength - 1;
1327
- let nextSuffixCursor = nextLength - 1;
1328
- while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) {
1329
- previousSuffixCursor -= 1;
1330
- nextSuffixCursor -= 1;
1331
- }
1332
- const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0;
1333
- const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0;
1334
- return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`;
1335
- }
1336
- function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) {
1337
- const changedLinkedFiles = linkedImpactsByEntry.get(entry);
1338
- if (!changedLinkedFiles || changedLinkedFiles.size === 0) return;
1339
- return [...changedLinkedFiles].sort().map((file) => {
1340
- return `${file}:${sourceHashByFile.get(file) ?? "missing"}`;
1341
- }).join(",");
1342
- }
1343
- function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
1344
- if (!linkedImpactSignature) return runtimeSignature;
1345
- return `${runtimeSignature}:linked:${linkedImpactSignature}`;
1346
- }
1347
- function createStableTextSignature(input) {
1348
- let hash = 2166136261;
1349
- for (let i = 0; i < input.length; i++) {
1350
- hash ^= input.charCodeAt(i);
1351
- hash = Math.imul(hash, 16777619);
1352
- }
1353
- return (hash >>> 0).toString(36);
1354
- }
1355
- function createCandidateSignature(candidates) {
1356
- if (candidates.size === 0) return "empty";
1357
- return createStableTextSignature([...candidates].sort().join("\n"));
1358
- }
1359
- function getSnapshotHash(snapshotMap, file, fallback) {
1360
- return snapshotMap.get(file) ?? fallback;
1361
- }
1362
- function hasRuntimeAffectingSourceChanges(changedByType) {
1363
- return changedByType.html.size > 0 || changedByType.js.size > 0;
1364
- }
1365
- //#endregion
1366
- //#region src/bundlers/vite/generate-bundle/subpackages.ts
1367
- function readBundleAssetSource(output) {
1368
- if (output.type !== "asset") return;
1369
- return typeof output.source === "string" ? output.source : output.source.toString();
1370
- }
1371
- function normalizePackageRoot(root) {
1372
- return require_bundle_state.normalizeOutputPathKey(root).replace(/\/+$/, "");
1373
- }
1374
- function collectMiniProgramSubpackageRoots(bundle) {
1375
- let hasAppJson = false;
1376
- const roots = /* @__PURE__ */ new Set();
1377
- for (const [file, output] of Object.entries(bundle)) {
1378
- const outputFile = output.fileName || file;
1379
- if (node_path.default.basename(outputFile) !== "app.json") continue;
1380
- const source = readBundleAssetSource(output);
1381
- if (!source) continue;
1382
- hasAppJson = true;
1383
- try {
1384
- const appJson = JSON.parse(source);
1385
- const subPackages = Array.isArray(appJson.subPackages) ? appJson.subPackages : Array.isArray(appJson.subpackages) ? appJson.subpackages : [];
1386
- for (const subPackage of subPackages) {
1387
- if (typeof subPackage.root !== "string" || subPackage.root.length === 0) continue;
1388
- roots.add(normalizePackageRoot(subPackage.root));
1389
- }
1390
- } catch {}
1391
- }
1392
- return hasAppJson ? roots : void 0;
1393
- }
1394
- function isSubpackageOutputFile(file, subpackageRoots) {
1395
- const normalizedFile = require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1396
- for (const root of subpackageRoots) if (root.length > 0 && (normalizedFile === root || normalizedFile.startsWith(`${root}/`) || normalizedFile.endsWith(`/${root}`) || normalizedFile.includes(`/${root}/`))) return true;
1397
- return false;
1398
- }
1399
- function resolveSubpackageSourceRootFromModuleId(moduleId, subpackageRoot) {
1400
- const file = require_bundle_state.slash(node_path.default.resolve(moduleId.replace(/[?#].*$/, "")));
1401
- const normalizedRoot = normalizePackageRoot(subpackageRoot);
1402
- const rootSegment = `/${normalizedRoot}/`;
1403
- const rootIndex = file.lastIndexOf(rootSegment);
1404
- if (rootIndex >= 0) return file.slice(0, rootIndex + rootSegment.length - 1);
1405
- const rootSuffix = `/${normalizedRoot}`;
1406
- if (file.endsWith(rootSuffix)) return file;
1407
- }
1408
- function collectMiniProgramSubpackageSourceEntries(snapshot, subpackageRoots, sourceBaseRoots) {
1409
- const sourceRoots = /* @__PURE__ */ new Set();
1410
- const sourceEntries = [];
1411
- for (const entry of snapshot.entries) {
1412
- if (entry.output.type !== "chunk" || !isSubpackageOutputFile(entry.file, subpackageRoots)) continue;
1413
- const matchedSubpackageRoot = [...subpackageRoots].find((root) => isSubpackageOutputFile(entry.file, new Set([root])));
1414
- if (!matchedSubpackageRoot) continue;
1415
- for (const moduleId of collectChunkModuleIds(entry.output)) {
1416
- if (!node_path.default.isAbsolute(moduleId.replace(/[?#].*$/, ""))) continue;
1417
- const sourceRoot = resolveSubpackageSourceRootFromModuleId(moduleId, matchedSubpackageRoot);
1418
- if (sourceRoot) sourceRoots.add(sourceRoot);
1419
- }
1420
- }
1421
- sourceEntries.push(...[...sourceRoots].map((sourceRoot) => ({
1422
- base: sourceRoot,
1423
- negated: false,
1424
- pattern: "**/*"
1425
- })));
1426
- const resolvedBaseRoots = sourceBaseRoots.filter((baseRoot) => typeof baseRoot === "string" && baseRoot.length > 0).map((baseRoot) => node_path.default.resolve(baseRoot)).filter((baseRoot, index, roots) => roots.indexOf(baseRoot) === index);
1427
- for (const baseRoot of resolvedBaseRoots) for (const subpackageRoot of subpackageRoots) sourceEntries.push({
1428
- base: baseRoot,
1429
- negated: false,
1430
- pattern: `**/${normalizePackageRoot(subpackageRoot)}/**`
1431
- });
1432
- return sourceEntries;
1433
- }
1434
1155
  //#endregion
1435
1156
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
1436
1157
  let _lazyMatch = () => {
@@ -1878,23 +1599,261 @@ const mix = (del = delimiter) => {
1878
1599
  const posix = /* @__PURE__ */ mix(":");
1879
1600
  const win32 = /* @__PURE__ */ mix(";");
1880
1601
  //#endregion
1881
- //#region src/bundlers/vite/processed-css-assets.ts
1882
- const CSS_OUTPUT_FILE_RE = /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i;
1883
- function isCssOutputFile(file) {
1884
- return CSS_OUTPUT_FILE_RE.test(file);
1602
+ //#region src/bundlers/vite/generate-bundle/sfc-style-source.ts
1603
+ const SFC_STYLE_SOURCE_EXTENSIONS = [
1604
+ ".vue",
1605
+ ".uvue",
1606
+ ".nvue",
1607
+ ".svelte",
1608
+ ".mpx"
1609
+ ];
1610
+ const SFC_STYLE_BLOCK_RE$1 = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
1611
+ function extractSfcStyleSources(source) {
1612
+ const styleSources = [];
1613
+ SFC_STYLE_BLOCK_RE$1.lastIndex = 0;
1614
+ let match = SFC_STYLE_BLOCK_RE$1.exec(source);
1615
+ while (match !== null) {
1616
+ styleSources.push(match[1] ?? "");
1617
+ match = SFC_STYLE_BLOCK_RE$1.exec(source);
1618
+ }
1619
+ return styleSources;
1885
1620
  }
1886
- function isMainStyleAssetFile(file) {
1887
- const basename = require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, "")).replace(/\.(?:css|wxss|acss|ttss|qss|jxss|tyss)$/i, "").split("/").pop();
1888
- return basename === "app" || basename === "main";
1621
+ function hasSfcStyleSources(source) {
1622
+ return extractSfcStyleSources(source).length > 0;
1889
1623
  }
1890
- function getAssetFile(bundleFile, asset) {
1891
- return asset.fileName || bundleFile;
1624
+ function hasTailwindGenerationSource(source) {
1625
+ return require_v3_engine.hasTailwindSourceDirectives(source, { importFallback: true }) || require_v3_engine.hasTailwindRootDirectives(source, { importFallback: true }) || require_v3_engine.hasTailwindApplyDirective(source);
1892
1626
  }
1893
- function readAssetSource(asset) {
1894
- return typeof asset.source === "string" ? asset.source : asset.source.toString();
1627
+ async function resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outputRoot, sourceRoot, cssMatcher, getSfcSource, debug) {
1628
+ const sourceFile = resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, cssMatcher, debug);
1629
+ if (!sourceFile) {
1630
+ debug("sfc style source infer skipped: no source file for %s", outputFile);
1631
+ return;
1632
+ }
1633
+ const source = getSfcSource?.(sourceFile);
1634
+ if (source == null) {
1635
+ debug("sfc style source infer skipped: missing known source for %s -> %s", outputFile, sourceFile);
1636
+ return;
1637
+ }
1638
+ const rawSource = extractSfcStyleSources(source).join("\n");
1639
+ if (!rawSource || !hasTailwindGenerationSource(rawSource)) {
1640
+ debug("sfc style source infer skipped: no tailwind generation source for %s -> %s", outputFile, sourceFile);
1641
+ return;
1642
+ }
1643
+ debug("sfc style source inferred: %s -> %s", outputFile, sourceFile);
1644
+ return {
1645
+ outputFile,
1646
+ rawSource,
1647
+ sourceFile
1648
+ };
1895
1649
  }
1896
- function appendCss(baseCss, css) {
1897
- if (baseCss.length === 0) return css;
1650
+ function normalizeSfcSourceFileForCompare(file) {
1651
+ return require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1652
+ }
1653
+ function collectChunkModuleIds$1(output) {
1654
+ const moduleIds = Array.isArray(output.moduleIds) ? output.moduleIds : [];
1655
+ return [
1656
+ output.facadeModuleId,
1657
+ ...moduleIds,
1658
+ ...Object.keys(output.modules ?? {})
1659
+ ].filter((id, index, ids) => typeof id === "string" && id.length > 0 && ids.indexOf(id) === index);
1660
+ }
1661
+ function normalizeSourceStyleModuleId(id) {
1662
+ const file = id.replace(/[?#].*$/, "");
1663
+ if (!CSS_SOURCE_OUTPUT_EXT_RE.test(file)) return;
1664
+ if (!node_path.default.isAbsolute(file)) return;
1665
+ return node_path.default.resolve(file);
1666
+ }
1667
+ function resolveSiblingJsChunkFile(outputFile, cssMatcher) {
1668
+ const normalizedOutputFile = outputFile.replace(/[?#].*$/, "");
1669
+ if (cssMatcher?.(normalizedOutputFile)) {
1670
+ const extension = node_path.default.extname(normalizedOutputFile);
1671
+ return extension ? `${normalizedOutputFile.slice(0, -extension.length)}.js` : void 0;
1672
+ }
1673
+ if (CSS_SOURCE_OUTPUT_EXT_RE.test(normalizedOutputFile)) return normalizedOutputFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, ".js");
1674
+ }
1675
+ function normalizeSfcModuleId(id) {
1676
+ const file = id.replace(/[?#].*$/, "");
1677
+ if (!SFC_STYLE_SOURCE_EXTENSIONS.some((extension) => file.endsWith(extension))) return;
1678
+ if (!node_path.default.isAbsolute(file)) return;
1679
+ return node_path.default.resolve(file);
1680
+ }
1681
+ function resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, cssMatcher, debug) {
1682
+ const siblingJsFile = resolveSiblingJsChunkFile(outputFile, cssMatcher);
1683
+ if (!siblingJsFile) {
1684
+ debug("sfc style sibling chunk skipped: no sibling js for %s", outputFile);
1685
+ return;
1686
+ }
1687
+ const normalizedSiblingJsFile = require_bundle_state.normalizeOutputPathKey(siblingJsFile);
1688
+ const siblingChunk = snapshot.entries.find((entry) => entry.type === "js" && entry.output.type === "chunk" && require_bundle_state.normalizeOutputPathKey(entry.file) === normalizedSiblingJsFile);
1689
+ if (!siblingChunk || siblingChunk.output.type !== "chunk") {
1690
+ debug("sfc style sibling chunk skipped: missing chunk for %s -> %s", outputFile, siblingJsFile);
1691
+ return;
1692
+ }
1693
+ const sourceFiles = collectChunkModuleIds$1(siblingChunk.output).map(normalizeSfcModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
1694
+ if (sourceFiles.length === 0) {
1695
+ debug("sfc style sibling chunk skipped: no sfc modules for %s -> %s", outputFile, siblingJsFile);
1696
+ return;
1697
+ }
1698
+ const scoredSources = sourceFiles.map((sourceFile) => ({
1699
+ sourceFile,
1700
+ score: scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot)
1701
+ })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
1702
+ debug("sfc style sibling chunk candidates: %s -> %s %O", outputFile, siblingJsFile, scoredSources);
1703
+ const bestScore = scoredSources[0]?.score;
1704
+ if (!bestScore) return;
1705
+ const bestSources = scoredSources.filter((item) => item.score === bestScore);
1706
+ if (bestSources.length !== 1) {
1707
+ debug("sfc style sibling chunk skipped: ambiguous best sources for %s %O", outputFile, bestSources);
1708
+ return;
1709
+ }
1710
+ return bestSources[0]?.sourceFile;
1711
+ }
1712
+ function resolveSourceStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug) {
1713
+ const siblingJsFile = resolveSiblingJsChunkFile(outputFile);
1714
+ if (!siblingJsFile) {
1715
+ debug("source style sibling chunk skipped: no sibling js for %s", outputFile);
1716
+ return;
1717
+ }
1718
+ const normalizedSiblingJsFile = require_bundle_state.normalizeOutputPathKey(siblingJsFile);
1719
+ const siblingChunk = snapshot.entries.find((entry) => entry.type === "js" && entry.output.type === "chunk" && require_bundle_state.normalizeOutputPathKey(entry.file) === normalizedSiblingJsFile);
1720
+ if (!siblingChunk || siblingChunk.output.type !== "chunk") {
1721
+ debug("source style sibling chunk skipped: missing chunk for %s -> %s", outputFile, siblingJsFile);
1722
+ return;
1723
+ }
1724
+ const sourceFiles = collectChunkModuleIds$1(siblingChunk.output).map(normalizeSourceStyleModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
1725
+ if (sourceFiles.length === 0) {
1726
+ debug("source style sibling chunk skipped: no source style modules for %s -> %s", outputFile, siblingJsFile);
1727
+ return;
1728
+ }
1729
+ const scoredSources = sourceFiles.map((sourceFile) => ({
1730
+ sourceFile,
1731
+ score: scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot)
1732
+ })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
1733
+ debug("source style sibling chunk candidates: %s -> %s %O", outputFile, siblingJsFile, scoredSources);
1734
+ const bestScore = scoredSources[0]?.score;
1735
+ if (!bestScore) return;
1736
+ const bestSources = scoredSources.filter((item) => item.score === bestScore);
1737
+ if (bestSources.length !== 1) {
1738
+ debug("source style sibling chunk skipped: ambiguous best sources for %s %O", outputFile, bestSources);
1739
+ return;
1740
+ }
1741
+ return bestSources[0]?.sourceFile;
1742
+ }
1743
+ function resolveSourceStyleSourceFromOutputFile(outputFile, snapshot, outputRoot, sourceRoot, getSourceStyleSource, getSourceStyleSources, configuredSourceEntries, debug) {
1744
+ let sourceFile = resolveSourceStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug);
1745
+ let rawSource = sourceFile ? getSourceStyleSource?.(sourceFile) : void 0;
1746
+ if (!rawSource || !hasTailwindGenerationSource(rawSource)) {
1747
+ const scoredSources = [...getSourceStyleSources?.() ?? [], ...configuredSourceEntries ?? []].filter(([file, source]) => CSS_SOURCE_OUTPUT_EXT_RE.test(file) && hasTailwindGenerationSource(source)).map(([file, source]) => ({
1748
+ file,
1749
+ source,
1750
+ score: scoreMatchingStyleFileBase(outputFile, file, outputRoot, sourceRoot)
1751
+ })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
1752
+ const bestScore = scoredSources[0]?.score;
1753
+ const bestSources = bestScore ? scoredSources.filter((item) => item.score === bestScore) : [];
1754
+ if (bestSources.length === 1) {
1755
+ sourceFile = bestSources[0].file;
1756
+ rawSource = bestSources[0].source;
1757
+ debug("source style source inferred from cache: %s -> %s", outputFile, sourceFile);
1758
+ }
1759
+ }
1760
+ if (!sourceFile || !rawSource) return;
1761
+ if (!hasTailwindGenerationSource(rawSource)) {
1762
+ debug("source style source infer skipped: no tailwind generation source for %s -> %s", outputFile, sourceFile);
1763
+ return;
1764
+ }
1765
+ return {
1766
+ outputFile,
1767
+ rawSource,
1768
+ sourceFile
1769
+ };
1770
+ }
1771
+ //#endregion
1772
+ //#region src/bundlers/vite/generate-bundle/subpackages.ts
1773
+ function readBundleAssetSource(output) {
1774
+ if (output.type !== "asset") return;
1775
+ return typeof output.source === "string" ? output.source : output.source.toString();
1776
+ }
1777
+ function normalizePackageRoot(root) {
1778
+ return require_bundle_state.normalizeOutputPathKey(root).replace(/\/+$/, "");
1779
+ }
1780
+ function collectMiniProgramSubpackageRoots(bundle) {
1781
+ let hasAppJson = false;
1782
+ const roots = /* @__PURE__ */ new Set();
1783
+ for (const [file, output] of Object.entries(bundle)) {
1784
+ const outputFile = output.fileName || file;
1785
+ if (node_path.default.basename(outputFile) !== "app.json") continue;
1786
+ const source = readBundleAssetSource(output);
1787
+ if (!source) continue;
1788
+ hasAppJson = true;
1789
+ try {
1790
+ const appJson = JSON.parse(source);
1791
+ const subPackages = Array.isArray(appJson.subPackages) ? appJson.subPackages : Array.isArray(appJson.subpackages) ? appJson.subpackages : [];
1792
+ for (const subPackage of subPackages) {
1793
+ if (typeof subPackage.root !== "string" || subPackage.root.length === 0) continue;
1794
+ roots.add(normalizePackageRoot(subPackage.root));
1795
+ }
1796
+ } catch {}
1797
+ }
1798
+ return hasAppJson ? roots : void 0;
1799
+ }
1800
+ function isSubpackageOutputFile(file, subpackageRoots) {
1801
+ const normalizedFile = require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1802
+ for (const root of subpackageRoots) if (root.length > 0 && (normalizedFile === root || normalizedFile.startsWith(`${root}/`) || normalizedFile.endsWith(`/${root}`) || normalizedFile.includes(`/${root}/`))) return true;
1803
+ return false;
1804
+ }
1805
+ function resolveSubpackageSourceRootFromModuleId(moduleId, subpackageRoot) {
1806
+ const file = require_bundle_state.slash(node_path.default.resolve(moduleId.replace(/[?#].*$/, "")));
1807
+ const normalizedRoot = normalizePackageRoot(subpackageRoot);
1808
+ const rootSegment = `/${normalizedRoot}/`;
1809
+ const rootIndex = file.lastIndexOf(rootSegment);
1810
+ if (rootIndex >= 0) return file.slice(0, rootIndex + rootSegment.length - 1);
1811
+ const rootSuffix = `/${normalizedRoot}`;
1812
+ if (file.endsWith(rootSuffix)) return file;
1813
+ }
1814
+ function collectMiniProgramSubpackageSourceEntries(snapshot, subpackageRoots, sourceBaseRoots) {
1815
+ const sourceRoots = /* @__PURE__ */ new Set();
1816
+ const sourceEntries = [];
1817
+ for (const entry of snapshot.entries) {
1818
+ if (entry.output.type !== "chunk" || !isSubpackageOutputFile(entry.file, subpackageRoots)) continue;
1819
+ const matchedSubpackageRoot = [...subpackageRoots].find((root) => isSubpackageOutputFile(entry.file, new Set([root])));
1820
+ if (!matchedSubpackageRoot) continue;
1821
+ for (const moduleId of collectChunkModuleIds$1(entry.output)) {
1822
+ if (!node_path.default.isAbsolute(moduleId.replace(/[?#].*$/, ""))) continue;
1823
+ const sourceRoot = resolveSubpackageSourceRootFromModuleId(moduleId, matchedSubpackageRoot);
1824
+ if (sourceRoot) sourceRoots.add(sourceRoot);
1825
+ }
1826
+ }
1827
+ sourceEntries.push(...[...sourceRoots].map((sourceRoot) => ({
1828
+ base: sourceRoot,
1829
+ negated: false,
1830
+ pattern: "**/*"
1831
+ })));
1832
+ const resolvedBaseRoots = sourceBaseRoots.filter((baseRoot) => typeof baseRoot === "string" && baseRoot.length > 0).map((baseRoot) => node_path.default.resolve(baseRoot)).filter((baseRoot, index, roots) => roots.indexOf(baseRoot) === index);
1833
+ for (const baseRoot of resolvedBaseRoots) for (const subpackageRoot of subpackageRoots) sourceEntries.push({
1834
+ base: baseRoot,
1835
+ negated: false,
1836
+ pattern: `**/${normalizePackageRoot(subpackageRoot)}/**`
1837
+ });
1838
+ return sourceEntries;
1839
+ }
1840
+ //#endregion
1841
+ //#region src/bundlers/vite/processed-css-assets.ts
1842
+ const CSS_OUTPUT_FILE_RE = /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i;
1843
+ function isCssOutputFile(file) {
1844
+ return CSS_OUTPUT_FILE_RE.test(file);
1845
+ }
1846
+ function getAssetFile(bundleFile, asset) {
1847
+ return asset.fileName || bundleFile;
1848
+ }
1849
+ function readAssetSource(asset) {
1850
+ return typeof asset.source === "string" ? asset.source : asset.source.toString();
1851
+ }
1852
+ function clearAssetSource(asset) {
1853
+ asset.source = "";
1854
+ }
1855
+ function appendCss(baseCss, css) {
1856
+ if (baseCss.length === 0) return css;
1898
1857
  if (css.length === 0) return baseCss;
1899
1858
  return `${baseCss}\n${css}`;
1900
1859
  }
@@ -1962,13 +1921,85 @@ function resolveViteProcessedCssAssetSource(file, rawSource, resolveViteProcesse
1962
1921
  function collectMatchingGeneratedCssMarkerFiles(file, rawSource, resolveViteProcessedCssOutputFile) {
1963
1922
  return require_bundle_state.parseBundlerGeneratedCssMarkerBlocks(rawSource).filter((block) => block.bundler === "vite").filter((block) => isMatchingGeneratedCssMarkerFile(file, block.file, resolveViteProcessedCssOutputFile)).map((block) => block.file).filter((markerFile) => typeof markerFile === "string" && markerFile.length > 0);
1964
1923
  }
1924
+ function collectRootStyleBundleCssSources(bundle, excludedFile) {
1925
+ const sources = [];
1926
+ const excludedFileKey = require_bundle_state.normalizeOutputPathKey(excludedFile);
1927
+ for (const [bundleFile, output] of Object.entries(bundle)) {
1928
+ if (output.type !== "asset") continue;
1929
+ const file = require_bundle_state.normalizeOutputPathKey(getAssetFile(bundleFile, output));
1930
+ if (file === excludedFileKey || !isRootStyleOutputFile(file)) continue;
1931
+ const source = require_bundle_state.stripBundlerGeneratedCssMarkers(readAssetSource(output)).trim();
1932
+ if (source.length > 0) sources.push(source);
1933
+ }
1934
+ return sources;
1935
+ }
1936
+ function collectSingleViteGeneratedCssMarkerFile(rawSource) {
1937
+ const blocks = require_bundle_state.parseBundlerGeneratedCssMarkerBlocks(rawSource).filter((block) => block.bundler === "vite");
1938
+ if (blocks.length !== 1) return;
1939
+ const file = blocks[0]?.file;
1940
+ return typeof file === "string" && file.length > 0 ? file : void 0;
1941
+ }
1942
+ function shouldFilterRootGeneratedCssMarkerForScopedAsset(targetFile, markerFile, resolveViteProcessedCssOutputFile) {
1943
+ const resolvedTargetFile = normalizeMarkerOutputFile(targetFile, resolveViteProcessedCssOutputFile);
1944
+ if (!isRootStyleOutputFile(normalizeMarkerOutputFile(markerFile, resolveViteProcessedCssOutputFile)) || isRootStyleOutputFile(resolvedTargetFile)) return false;
1945
+ return !isMatchingGeneratedCssMarkerFile(targetFile, markerFile, resolveViteProcessedCssOutputFile);
1946
+ }
1947
+ function removeCssCoveredByRootStyleBundleSources(bundle, file, css) {
1948
+ return removeDanglingCssSourceTraceComments(removeCssCoveredByImportedViteResults(css, collectRootStyleBundleCssSources(bundle, file)));
1949
+ }
1950
+ function removeDanglingCssSourceTraceComments(css) {
1951
+ if (!css.includes("/* tokens:")) return css;
1952
+ try {
1953
+ const root = _weapp_tailwindcss_postcss.postcss.parse(css);
1954
+ let changed = false;
1955
+ root.each((node) => {
1956
+ if (node.type !== "comment" || !node.text.trim().startsWith("tokens:")) return;
1957
+ const next = node.next();
1958
+ if (next?.type === "rule" || next?.type === "atrule") return;
1959
+ node.remove();
1960
+ changed = true;
1961
+ });
1962
+ return changed ? root.toString().trim() : css;
1963
+ } catch {
1964
+ return css;
1965
+ }
1966
+ }
1967
+ function removeCssCoveredByRootStyleAssets(bundle, options) {
1968
+ let updated = 0;
1969
+ for (const [bundleFile, output] of Object.entries(bundle)) {
1970
+ if (output.type !== "asset") continue;
1971
+ const file = getAssetFile(bundleFile, output);
1972
+ if (!options.cssMatcher(file) || isRootStyleOutputFile(file) || options.isViteProcessedCssAsset?.(output, file) === true || options.subpackageRoots != null && isSubpackageOutputFile(file, options.subpackageRoots)) continue;
1973
+ const rawSource = readAssetSource(output);
1974
+ const nextCss = removeCssCoveredByRootStyleBundleSources(bundle, file, rawSource);
1975
+ if (nextCss === rawSource) continue;
1976
+ output.source = nextCss;
1977
+ options.recordCssAssetResult?.(file, nextCss);
1978
+ options.onUpdate?.(file, rawSource, nextCss);
1979
+ options.debug?.("remove root-covered css rules from scoped asset: %s bytes=%d", file, nextCss.length);
1980
+ updated++;
1981
+ }
1982
+ return updated;
1983
+ }
1965
1984
  function shouldInjectViteProcessedCssResult(opts, targetFile, sourceFile, options) {
1966
- if (options.injectIntoMain === true) return true;
1985
+ if (options.injectIntoMain === true) return isRootStyleOutputFile(targetFile) || typeof options.outputFile === "string" && require_bundle_state.normalizeOutputPathKey(options.outputFile) === require_bundle_state.normalizeOutputPathKey(targetFile);
1967
1986
  if (options.injectIntoMain === false) return false;
1968
1987
  const targetFileKey = require_bundle_state.normalizeOutputPathKey(targetFile);
1969
- const sourceFileKey = require_bundle_state.normalizeOutputPathKey(sourceFile);
1970
- const sourceBaseName = sourceFileKey.replace(/\.(?:css|wxss|acss|ttss|qss|jxss|tyss)$/i, "").split("/").pop();
1971
- return sourceFileKey !== targetFileKey && (opts.mainCssChunkMatcher(sourceFile, opts.appType) || sourceBaseName === "app" || sourceBaseName === "main");
1988
+ return require_bundle_state.normalizeOutputPathKey(sourceFile) !== targetFileKey && (opts.mainCssChunkMatcher(sourceFile, opts.appType) || typeof options.outputFile === "string" && require_bundle_state.normalizeOutputPathKey(options.outputFile) !== targetFileKey && opts.mainCssChunkMatcher(options.outputFile, opts.appType));
1989
+ }
1990
+ function isRootStyleOutputFile(file) {
1991
+ const normalized = require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1992
+ return isCssOutputFile(normalized) && !normalized.includes("/");
1993
+ }
1994
+ function shouldUseCssAssetAsMainInjectionTarget(opts, file, records) {
1995
+ const fileKey = require_bundle_state.normalizeOutputPathKey(file);
1996
+ if (records.some((record) => {
1997
+ if (record.injectIntoMain !== true) return false;
1998
+ return isRootStyleOutputFile(file) || typeof record.outputFile === "string" && require_bundle_state.normalizeOutputPathKey(record.outputFile) === fileKey;
1999
+ })) return true;
2000
+ if (records.some((record) => record.injectIntoMain === true)) return false;
2001
+ if (opts.mainCssChunkMatcher(file, opts.appType)) return true;
2002
+ return isRootStyleOutputFile(file) && records.some((record) => record.injectIntoMain === true);
1972
2003
  }
1973
2004
  function isViteProcessedCssResultImported(record, importedStyleFiles) {
1974
2005
  const importedFileNames = new Set([...importedStyleFiles].map((file) => posix.posix.basename(file)));
@@ -1992,29 +2023,73 @@ function collectImportedBundleCssSources(bundle, importedStyleFiles) {
1992
2023
  }
1993
2024
  return importedSources;
1994
2025
  }
2026
+ function collectBundleAssetFiles(bundle) {
2027
+ const files = /* @__PURE__ */ new Set();
2028
+ for (const [bundleFile, output] of Object.entries(bundle)) {
2029
+ if (output.type !== "asset") continue;
2030
+ files.add(require_bundle_state.normalizeOutputPathKey(getAssetFile(bundleFile, output)));
2031
+ }
2032
+ return files;
2033
+ }
2034
+ function isCssImportOnlyBundleAsset(bundle, file, css) {
2035
+ const importedStyleFiles = collectImportedStyleFiles(css, file);
2036
+ if (importedStyleFiles.size === 0) return false;
2037
+ let hasNonImportNode = false;
2038
+ try {
2039
+ _weapp_tailwindcss_postcss.postcss.parse(css).each((node) => {
2040
+ if (node.type === "comment") return;
2041
+ if (node.type !== "atrule" || node.name !== "import") hasNonImportNode = true;
2042
+ });
2043
+ } catch {
2044
+ return false;
2045
+ }
2046
+ if (hasNonImportNode) return false;
2047
+ return collectImportedBundleCssSources(bundle, importedStyleFiles).length > 0;
2048
+ }
2049
+ function isCoveredViteGeneratedSourceAsset(file, existingAssetFiles, resolveViteProcessedCssOutputFile) {
2050
+ const resolvedOutputFile = require_bundle_state.normalizeOutputPathKey(resolveViteProcessedCssOutputFile?.(file) ?? file);
2051
+ return resolvedOutputFile !== require_bundle_state.normalizeOutputPathKey(file) && existingAssetFiles.has(resolvedOutputFile);
2052
+ }
1995
2053
  function collectViteProcessedCssAssetResults(bundle, options) {
1996
2054
  let collected = 0;
2055
+ const existingAssetFiles = collectBundleAssetFiles(bundle);
1997
2056
  for (const [bundleFile, output] of Object.entries(bundle)) {
1998
2057
  if (output.type !== "asset") continue;
1999
2058
  const file = getAssetFile(bundleFile, output);
2000
2059
  if (!isCssOutputFile(file) || !options.isViteProcessedCssAsset?.(output, file)) continue;
2001
2060
  const rawSource = readAssetSource(output);
2002
- const nextCss = resolveViteProcessedCssAssetSource(file, rawSource, options.resolveViteProcessedCssOutputFile);
2061
+ let nextCss = resolveViteProcessedCssAssetSource(file, rawSource, options.resolveViteProcessedCssOutputFile);
2062
+ const singleMarkerFile = collectSingleViteGeneratedCssMarkerFile(rawSource);
2063
+ if (singleMarkerFile && (options.subpackageRoots == null || !isSubpackageOutputFile(file, options.subpackageRoots)) && shouldFilterRootGeneratedCssMarkerForScopedAsset(file, singleMarkerFile, options.resolveViteProcessedCssOutputFile)) nextCss = removeCssCoveredByRootStyleBundleSources(bundle, file, nextCss);
2003
2064
  if (nextCss !== rawSource) output.source = nextCss;
2004
2065
  options.markCssAssetProcessed?.(output, file);
2005
2066
  options.recordCssAssetResult?.(file, nextCss);
2006
2067
  const resolvedOutputFile = options.resolveViteProcessedCssOutputFile?.(file) ?? file;
2007
- const shouldReplayIntoMainCss = options.opts != null && isMainStyleAssetFile(file) && (require_bundle_state.normalizeOutputPathKey(resolvedOutputFile) !== require_bundle_state.normalizeOutputPathKey(file) || !options.opts.mainCssChunkMatcher(file, options.opts.appType));
2068
+ const shouldReplayIntoMainCss = options.opts != null && (options.opts.mainCssChunkMatcher(file, options.opts.appType) || require_bundle_state.normalizeOutputPathKey(resolvedOutputFile) !== require_bundle_state.normalizeOutputPathKey(file) && (isRootStyleOutputFile(file) || posix.posix.basename(require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, ""))) === posix.posix.basename(require_bundle_state.normalizeOutputPathKey(resolvedOutputFile.replace(/[?#].*$/, "")))) && options.opts.mainCssChunkMatcher(resolvedOutputFile, options.opts.appType));
2008
2069
  options.recordViteProcessedCssAssetResult?.(file, nextCss, {
2009
2070
  injectIntoMain: shouldReplayIntoMainCss || void 0,
2010
2071
  outputFile: resolvedOutputFile
2011
2072
  });
2073
+ if (require_bundle_state.normalizeOutputPathKey(resolvedOutputFile) !== require_bundle_state.normalizeOutputPathKey(file)) options.recordViteProcessedCssAssetResult?.(resolvedOutputFile, nextCss, {
2074
+ injectIntoMain: shouldReplayIntoMainCss || void 0,
2075
+ outputFile: resolvedOutputFile
2076
+ });
2012
2077
  for (const markerFile of collectMatchingGeneratedCssMarkerFiles(file, rawSource, options.resolveViteProcessedCssOutputFile)) {
2013
2078
  if (require_bundle_state.normalizeOutputPathKey(markerFile) === require_bundle_state.normalizeOutputPathKey(file)) continue;
2014
2079
  options.recordViteProcessedCssAssetResult?.(markerFile, nextCss, {
2015
2080
  injectIntoMain: shouldReplayIntoMainCss || void 0,
2016
2081
  outputFile: resolvedOutputFile
2017
2082
  });
2083
+ if (require_bundle_state.normalizeOutputPathKey(resolvedOutputFile) !== require_bundle_state.normalizeOutputPathKey(markerFile) && require_bundle_state.normalizeOutputPathKey(resolvedOutputFile) !== require_bundle_state.normalizeOutputPathKey(file)) options.recordViteProcessedCssAssetResult?.(resolvedOutputFile, nextCss, {
2084
+ injectIntoMain: shouldReplayIntoMainCss || void 0,
2085
+ outputFile: resolvedOutputFile
2086
+ });
2087
+ }
2088
+ if (isCoveredViteGeneratedSourceAsset(file, existingAssetFiles, options.resolveViteProcessedCssOutputFile)) {
2089
+ delete bundle[bundleFile];
2090
+ options.debug?.("skip covered vite-generated source css asset: %s", file);
2091
+ collected++;
2092
+ continue;
2018
2093
  }
2019
2094
  options.debug?.("collect vite-processed css asset: %s bytes=%d", file, nextCss.length);
2020
2095
  collected++;
@@ -2038,7 +2113,7 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
2038
2113
  for (const [bundleFile, output] of Object.entries(bundle)) {
2039
2114
  if (output.type !== "asset") continue;
2040
2115
  const file = getAssetFile(bundleFile, output);
2041
- if (!options.opts.cssMatcher(file) || !options.opts.mainCssChunkMatcher(file, options.opts.appType)) continue;
2116
+ if (!options.opts.cssMatcher(file) || !shouldUseCssAssetAsMainInjectionTarget(options.opts, file, viteCssResults)) continue;
2042
2117
  const mainFileKey = require_bundle_state.normalizeOutputPathKey(file);
2043
2118
  const originalSource = readAssetSource(output);
2044
2119
  let nextCss = removeTailwindEntryDirectivesFromCss(originalSource);
@@ -2083,15 +2158,842 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
2083
2158
  if (missingCss.length === 0 || (0, _weapp_tailwindcss_postcss.containsCssAfterMinify)(nextCss, missingCss)) continue;
2084
2159
  nextCss = appendCss(nextCss, missingCss);
2085
2160
  }
2086
- if (nextCss === originalSource) continue;
2087
- output.source = nextCss;
2088
- options.markCssAssetProcessed?.(output, file);
2089
- options.recordCssAssetResult?.(file, nextCss);
2090
- options.onUpdate?.(file, originalSource, nextCss);
2091
- options.debug?.("inject vite-processed css into main css asset: %s bytes=%d", file, nextCss.length);
2092
- injected++;
2093
- }
2094
- return injected;
2161
+ if (nextCss === originalSource) continue;
2162
+ output.source = nextCss;
2163
+ options.markCssAssetProcessed?.(output, file);
2164
+ options.recordCssAssetResult?.(file, nextCss);
2165
+ options.onUpdate?.(file, originalSource, nextCss);
2166
+ options.debug?.("inject vite-processed css into main css asset: %s bytes=%d", file, nextCss.length);
2167
+ for (const record of viteCssResults) {
2168
+ if (!options.shouldRemoveInjectedSourceAsset?.(file, record)) continue;
2169
+ const recordFileKey = require_bundle_state.normalizeOutputPathKey(record.file);
2170
+ for (const [candidateFile, candidateOutput] of Object.entries(bundle)) {
2171
+ if (candidateOutput.type !== "asset") continue;
2172
+ const candidateKey = require_bundle_state.normalizeOutputPathKey(getAssetFile(candidateFile, candidateOutput));
2173
+ const isRecordFile = candidateKey === recordFileKey;
2174
+ const isProcessedSource = readAssetSource(candidateOutput).trim() === record.css.trim();
2175
+ if (!isRecordFile && !isProcessedSource || candidateKey === require_bundle_state.normalizeOutputPathKey(file)) continue;
2176
+ clearAssetSource(candidateOutput);
2177
+ options.debug?.("remove injected vite-processed source css asset: %s -> %s", candidateKey, file);
2178
+ }
2179
+ }
2180
+ injected++;
2181
+ }
2182
+ return injected;
2183
+ }
2184
+ //#endregion
2185
+ //#region src/bundlers/vite/generate-bundle/bundle-file-names.ts
2186
+ function normalizeBundleFileNameKeysForTest(bundle) {
2187
+ for (const [file, output] of Object.entries(bundle)) {
2188
+ if (!output.fileName || output.fileName === file) continue;
2189
+ const existing = bundle[output.fileName];
2190
+ if (existing != null && existing !== output) continue;
2191
+ bundle[output.fileName] = output;
2192
+ delete bundle[file];
2193
+ }
2194
+ }
2195
+ //#endregion
2196
+ //#region src/bundlers/vite/generate-bundle/memory-debug.ts
2197
+ function toMb(bytes) {
2198
+ return Math.round(bytes / 1024 / 1024);
2199
+ }
2200
+ function summarizeStringMapCache(map) {
2201
+ let bytes = 0;
2202
+ for (const value of map.values()) bytes += value.length;
2203
+ return {
2204
+ bytes,
2205
+ mb: toMb(bytes),
2206
+ size: map.size
2207
+ };
2208
+ }
2209
+ function resolveViteMemoryDebugStats(context) {
2210
+ if (node_process.default.env["WEAPP_TW_HMR_MEMORY_DEBUG"] !== "1") return;
2211
+ const memory = node_process.default.memoryUsage();
2212
+ return {
2213
+ phase: context.phase,
2214
+ mode: context.useIncrementalMode ? "incremental" : "full",
2215
+ process: {
2216
+ rssMb: toMb(memory.rss),
2217
+ heapTotalMb: toMb(memory.heapTotal),
2218
+ heapUsedMb: toMb(memory.heapUsed),
2219
+ externalMb: toMb(memory.external),
2220
+ arrayBuffersMb: toMb(memory.arrayBuffers)
2221
+ },
2222
+ runtime: {
2223
+ sourceCandidates: context.sourceCandidatesSize,
2224
+ runtime: context.runtimeSize,
2225
+ transformRuntime: context.transformRuntimeSize,
2226
+ generatorRuntime: context.generatorRuntimeSize
2227
+ },
2228
+ processCache: {
2229
+ instance: context.cache.instance.size,
2230
+ hashMap: context.cache.hashMap.size,
2231
+ activeCacheKeys: context.activeProcessCacheKeys.size,
2232
+ activeHashKeys: context.activeProcessHashKeys.size
2233
+ },
2234
+ viteCss: {
2235
+ ...context.getViteCssCacheStats?.(),
2236
+ lastCssResultByFile: summarizeStringMapCache(context.lastCssResultByFile)
2237
+ },
2238
+ tailwind: {
2239
+ v3: require_v3_engine.getTailwindV3IncrementalGenerateCacheStats(),
2240
+ v4: require_v3_engine.getTailwindV4IncrementalGenerateCacheStats()
2241
+ }
2242
+ };
2243
+ }
2244
+ //#endregion
2245
+ //#region src/bundlers/vite/generate-bundle/metrics.ts
2246
+ function formatDebugFileList(files, limit = 8) {
2247
+ if (files.size === 0) return "-";
2248
+ const sorted = [...files].sort();
2249
+ if (sorted.length <= limit) return sorted.join(",");
2250
+ return `${sorted.slice(0, limit).join(",")},...(+${sorted.length - limit})`;
2251
+ }
2252
+ function createEmptyMetric() {
2253
+ return {
2254
+ total: 0,
2255
+ transformed: 0,
2256
+ cacheHits: 0,
2257
+ elapsed: 0
2258
+ };
2259
+ }
2260
+ function createEmptyMetrics() {
2261
+ return {
2262
+ runtimeSet: 0,
2263
+ html: createEmptyMetric(),
2264
+ js: createEmptyMetric(),
2265
+ css: createEmptyMetric()
2266
+ };
2267
+ }
2268
+ function measureElapsed(start) {
2269
+ return performance.now() - start;
2270
+ }
2271
+ function formatCacheHitRate(metric) {
2272
+ if (metric.total === 0) return "0.00%";
2273
+ return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
2274
+ }
2275
+ function formatMs(value) {
2276
+ return value.toFixed(2);
2277
+ }
2278
+ //#endregion
2279
+ //#region src/bundlers/vite/generate-bundle/uni-app-x-postprocess.ts
2280
+ async function handleUniAppXPostCssTasks(options) {
2281
+ const { bundle, debug, generatorRuntime, getCssHandlerOptions, getSourceCandidateSourcesForEntries, getSourceCandidatesForEntries, getViteProcessedCssAssetResults, isHarmonyAppStyleTarget, isNativeAppStyleTarget, onUpdate, opts, runtimeState, styleHandler } = options;
2282
+ const applyStyleSources = collectUniAppXHarmonyApplyStyleSources(bundle);
2283
+ if (opts.appType !== "uni-app-x" && !isNativeAppStyleTarget && !isHarmonyAppStyleTarget) return applyStyleSources;
2284
+ const getAssetSource = createUniAppXBundleAssetSourceGetter(bundle);
2285
+ const viteProcessedCssSources = [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css);
2286
+ const applyUtilities = collectUniAppXHarmonyApplyUtilities(bundle);
2287
+ if (isHarmonyAppStyleTarget && applyUtilities.size > 0 && applyStyleSources.length > 0) {
2288
+ const outputFile = "uni-app-x-harmony-apply.css";
2289
+ const cssHandlerOptions = getCssHandlerOptions(outputFile);
2290
+ const generated = await require_hmr_timing.generateCssByGenerator({
2291
+ opts,
2292
+ runtimeState,
2293
+ runtime: new Set([...generatorRuntime, ...applyUtilities]),
2294
+ rawSource: createUniAppXHarmonyApplyGeneratorSource(applyStyleSources, applyUtilities),
2295
+ file: outputFile,
2296
+ cssHandlerOptions,
2297
+ cssUserHandlerOptions: {
2298
+ ...cssHandlerOptions,
2299
+ isMainChunk: false
2300
+ },
2301
+ getSourceCandidatesForEntries,
2302
+ styleHandler,
2303
+ debug
2304
+ });
2305
+ if (generated?.css) viteProcessedCssSources.push(require_hmr_timing.annotateCssSourceTrace(generated.css, {
2306
+ opts,
2307
+ tokenSources: getSourceCandidateSourcesForEntries ? require_hmr_timing.createCssTokenSourceMap(getSourceCandidateSourcesForEntries(void 0), opts) : void 0
2308
+ }));
2309
+ }
2310
+ if (isHarmonyAppStyleTarget && injectUniAppXHarmonyBundleStyles(bundle, { cssSources: viteProcessedCssSources })) debug("uni-app-x harmony bundle styles inject");
2311
+ for (const [file, item] of Object.entries(bundle)) {
2312
+ if (item.type !== "asset" || !file.endsWith(".uvue.ts")) continue;
2313
+ const currentSource = String(item.source);
2314
+ const nextSource = injectUniAppXStylePlaceholder(file, currentSource, getAssetSource);
2315
+ if (nextSource !== currentSource) {
2316
+ item.source = nextSource;
2317
+ onUpdate(file, currentSource, nextSource);
2318
+ debug("uni-app-x style placeholder inject: %s", file);
2319
+ }
2320
+ }
2321
+ return applyStyleSources;
2322
+ }
2323
+ //#endregion
2324
+ //#region src/bundlers/vite/generate-bundle/vite-css-cache.ts
2325
+ const VITE_LAST_CSS_RESULT_CACHE_MAX = 64;
2326
+ function resolveViteCssTaskConcurrency(useIncrementalMode) {
2327
+ const configured = Number.parseInt(node_process.default.env["WEAPP_TW_VITE_CSS_CONCURRENCY"] ?? "", 10);
2328
+ if (Number.isFinite(configured) && configured > 0) return configured;
2329
+ return useIncrementalMode ? 1 : 2;
2330
+ }
2331
+ function normalizeViteCssCacheKey(file) {
2332
+ return require_bundle_state.normalizeOutputPathKey(file);
2333
+ }
2334
+ function rememberLastCssResult(resultByFile, sourceHashByFile, file, css, sourceHash) {
2335
+ const key = normalizeViteCssCacheKey(file);
2336
+ resultByFile.delete(key);
2337
+ sourceHashByFile.delete(key);
2338
+ resultByFile.set(key, css);
2339
+ sourceHashByFile.set(key, sourceHash);
2340
+ while (resultByFile.size > VITE_LAST_CSS_RESULT_CACHE_MAX) {
2341
+ const oldestKey = resultByFile.keys().next().value;
2342
+ if (typeof oldestKey !== "string") break;
2343
+ resultByFile.delete(oldestKey);
2344
+ sourceHashByFile.delete(oldestKey);
2345
+ }
2346
+ }
2347
+ function getLastCssResult(resultByFile, ...files) {
2348
+ for (const file of files) {
2349
+ if (!file) continue;
2350
+ const key = normalizeViteCssCacheKey(file);
2351
+ const css = resultByFile.get(key);
2352
+ if (css == null) continue;
2353
+ resultByFile.delete(key);
2354
+ resultByFile.set(key, css);
2355
+ return css;
2356
+ }
2357
+ }
2358
+ function getLastCssSourceHash(sourceHashByFile, file) {
2359
+ return sourceHashByFile.get(normalizeViteCssCacheKey(file));
2360
+ }
2361
+ function pruneLastCssResults(resultByFile, sourceHashByFile, activeFiles) {
2362
+ for (const key of resultByFile.keys()) {
2363
+ if (activeFiles.has(key)) continue;
2364
+ resultByFile.delete(key);
2365
+ sourceHashByFile.delete(key);
2366
+ }
2367
+ }
2368
+ //#endregion
2369
+ //#region src/bundlers/vite/generate-bundle/finalize.ts
2370
+ async function finalizeGenerateBundle(options) {
2371
+ const { activeProcessCacheKeys, activeProcessHashKeys, activeViteCssCacheFiles, bundle, bundleFiles, cache, cssTaskFactories, debug, defaultStyleOutputExtension, formatIteration, generatorCandidateSignature, generatorRuntime, getCssHandlerOptions, getSourceCandidateSourcesForEntries, getSourceCandidatesForEntries, getViteCssCacheStats, getViteProcessedCssAssetResults, hmrTimingRecorder, hmrTimingStartedAt, isHarmonyAppStyleTarget, isNativeAppStyleTarget, isViteProcessedCssAsset, isWebGeneratorTarget, lastCssResultByFile, lastCssSourceHashByFile, linkedByEntry, markCssAssetProcessed, metrics, onEnd, onUpdate, opts, pendingLinkedUpdates, pruneViteCssCaches, recordCssAssetResult, recordTimingDetail, recordViteProcessedCssAssetResult, rootDir, runtime, runtimeState, shouldPreserveAppCssExtension, snapshot, sourceCandidates, sourceRoot, state, styleHandler, tasks, timingDetails, transformRuntime, useIncrementalMode } = options;
2372
+ if (cssTaskFactories.length > 0) {
2373
+ const cssConcurrency = resolveViteCssTaskConcurrency(useIncrementalMode);
2374
+ tasks.push(require_hmr_timing.runWithConcurrency(cssTaskFactories, cssConcurrency).then(() => void 0));
2375
+ }
2376
+ const tasksStart = performance.now();
2377
+ await Promise.all(tasks);
2378
+ recordTimingDetail("tasks", tasksStart);
2379
+ for (const apply of pendingLinkedUpdates) apply();
2380
+ const applyStyleSources = await handleUniAppXPostCssTasks({
2381
+ bundle,
2382
+ debug,
2383
+ generatorRuntime,
2384
+ getCssHandlerOptions,
2385
+ getSourceCandidateSourcesForEntries,
2386
+ getSourceCandidatesForEntries,
2387
+ getViteProcessedCssAssetResults,
2388
+ isHarmonyAppStyleTarget,
2389
+ isNativeAppStyleTarget,
2390
+ onUpdate,
2391
+ opts,
2392
+ runtimeState,
2393
+ styleHandler
2394
+ });
2395
+ const syncViteProcessedCssIntoMainCssAssets = () => {
2396
+ collectViteProcessedCssAssetResults(bundle, {
2397
+ opts,
2398
+ isViteProcessedCssAsset,
2399
+ markCssAssetProcessed,
2400
+ recordCssAssetResult,
2401
+ recordViteProcessedCssAssetResult,
2402
+ resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension, sourceRoot, defaultStyleOutputExtension, bundleFiles),
2403
+ subpackageRoots: collectMiniProgramSubpackageRoots(bundle),
2404
+ debug
2405
+ });
2406
+ return injectViteProcessedCssIntoMainCssAssets(bundle, {
2407
+ opts,
2408
+ getViteProcessedCssAssetResults,
2409
+ markCssAssetProcessed,
2410
+ recordCssAssetResult,
2411
+ shouldRemoveInjectedSourceAsset: (_targetFile, record) => {
2412
+ if (record.injectIntoMain !== true || typeof record.outputFile !== "string") return false;
2413
+ return require_bundle_state.normalizeOutputPathKey(record.file) !== require_bundle_state.normalizeOutputPathKey(record.outputFile);
2414
+ },
2415
+ debug,
2416
+ onUpdate
2417
+ });
2418
+ };
2419
+ syncViteProcessedCssIntoMainCssAssets();
2420
+ if (isHarmonyAppStyleTarget && applyStyleSources.length > 0) {
2421
+ if (injectUniAppXHarmonyBundleStyles(bundle, { cssSources: [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css) })) debug("uni-app-x harmony bundle styles inject after css assets");
2422
+ syncViteProcessedCssIntoMainCssAssets();
2423
+ }
2424
+ normalizeBundleFileNameKeysForTest(bundle);
2425
+ removeCssCoveredByRootStyleAssets(bundle, {
2426
+ cssMatcher: opts.cssMatcher,
2427
+ debug,
2428
+ isViteProcessedCssAsset,
2429
+ onUpdate,
2430
+ recordCssAssetResult,
2431
+ subpackageRoots: collectMiniProgramSubpackageRoots(bundle)
2432
+ });
2433
+ const stateUpdateStart = performance.now();
2434
+ require_bundle_state.updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
2435
+ state.generatorCandidateSignature = generatorCandidateSignature;
2436
+ if (useIncrementalMode && !snapshot.hasOmittedKnownFiles) cache.prune?.({
2437
+ cacheKeys: activeProcessCacheKeys,
2438
+ hashKeys: activeProcessHashKeys
2439
+ });
2440
+ pruneLastCssResults(lastCssResultByFile, lastCssSourceHashByFile, activeViteCssCacheFiles);
2441
+ pruneViteCssCaches?.({
2442
+ activeFiles: activeViteCssCacheFiles,
2443
+ activeKnownSfcFiles: new Set([...snapshot.sourceHashByFile.keys(), ...snapshot.entries.map((entry) => entry.file)])
2444
+ });
2445
+ recordTimingDetail("state.update", stateUpdateStart);
2446
+ debug("metrics iteration=%d runtime=%sms html(total=%d transform=%d hit=%d rate=%s elapsed=%sms) js(total=%d transform=%d hit=%d rate=%s elapsed=%sms) css(total=%d transform=%d hit=%d rate=%s elapsed=%sms)", formatIteration, formatMs(metrics.runtimeSet), metrics.html.total, metrics.html.transformed, metrics.html.cacheHits, formatCacheHitRate(metrics.html), formatMs(metrics.html.elapsed), metrics.js.total, metrics.js.transformed, metrics.js.cacheHits, formatCacheHitRate(metrics.js), formatMs(metrics.js.elapsed), metrics.css.total, metrics.css.transformed, metrics.css.cacheHits, formatCacheHitRate(metrics.css), formatMs(metrics.css.elapsed));
2447
+ if (hmrTimingRecorder) {
2448
+ hmrTimingRecorder.record("generateBundle", performance.now() - hmrTimingStartedAt, {
2449
+ ...timingDetails,
2450
+ memoryDebug: resolveViteMemoryDebugStats({
2451
+ activeProcessCacheKeys,
2452
+ activeProcessHashKeys,
2453
+ cache,
2454
+ generatorRuntimeSize: generatorRuntime.size,
2455
+ getViteCssCacheStats,
2456
+ lastCssResultByFile,
2457
+ phase: "generateBundle",
2458
+ runtimeSize: runtime.size,
2459
+ sourceCandidatesSize: sourceCandidates.size,
2460
+ transformRuntimeSize: transformRuntime.size,
2461
+ useIncrementalMode
2462
+ })
2463
+ });
2464
+ hmrTimingRecorder.emitTotal();
2465
+ }
2466
+ onEnd();
2467
+ debug("end");
2468
+ }
2469
+ //#endregion
2470
+ //#region src/bundlers/vite/generate-bundle/js-entries.ts
2471
+ function createJsEntryResolver(jsEntries) {
2472
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
2473
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(require_bundle_state.normalizeOutputPathKey(id), entry);
2474
+ return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(require_bundle_state.normalizeOutputPathKey(id));
2475
+ }
2476
+ //#endregion
2477
+ //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
2478
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
2479
+ return uniAppX === void 0 ? true : require_tailwindcss.isUniAppXEnabled(uniAppX);
2480
+ }
2481
+ function createJsHandlerOptionsFactory(options) {
2482
+ return (absoluteFilename, extra) => ({
2483
+ ...extra,
2484
+ filename: absoluteFilename,
2485
+ tailwindcssMajorVersion: options.getMajorVersion(),
2486
+ moduleGraph: options.moduleGraph,
2487
+ babelParserOptions: {
2488
+ ...extra?.babelParserOptions ?? {},
2489
+ sourceFilename: absoluteFilename
2490
+ }
2491
+ });
2492
+ }
2493
+ //#endregion
2494
+ //#region src/bundlers/vite/generate-bundle/js-linking.ts
2495
+ function createLinkedUpdateHelpers(options) {
2496
+ const pendingLinkedUpdates = [];
2497
+ const handleLinkedUpdate = (fileName, previous, next) => {
2498
+ options.onUpdate(fileName, previous, next);
2499
+ options.debug("js linked handle: %s", fileName);
2500
+ };
2501
+ const scheduleLinkedApply = (entry, code) => {
2502
+ pendingLinkedUpdates.push(() => {
2503
+ if (entry.output.type === "chunk") entry.output.code = code;
2504
+ else entry.output.source = code;
2505
+ });
2506
+ };
2507
+ const applyLinkedUpdates = (linked) => {
2508
+ require_bundle_state.applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
2509
+ };
2510
+ return {
2511
+ applyLinkedUpdates,
2512
+ pendingLinkedUpdates
2513
+ };
2514
+ }
2515
+ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
2516
+ if (!linked || !linkedSet) return;
2517
+ for (const id of Object.keys(linked)) {
2518
+ const linkedEntry = getJsEntry(id);
2519
+ if (linkedEntry) linkedSet.add(linkedEntry.fileName);
2520
+ }
2521
+ }
2522
+ //#endregion
2523
+ //#region src/bundlers/vite/generate-bundle/signatures.ts
2524
+ function summarizeStringDiff(previous, next) {
2525
+ if (previous === next) return "same";
2526
+ const previousLength = previous.length;
2527
+ const nextLength = next.length;
2528
+ const minLength = Math.min(previousLength, nextLength);
2529
+ let prefixLength = 0;
2530
+ while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) prefixLength += 1;
2531
+ let previousSuffixCursor = previousLength - 1;
2532
+ let nextSuffixCursor = nextLength - 1;
2533
+ while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) {
2534
+ previousSuffixCursor -= 1;
2535
+ nextSuffixCursor -= 1;
2536
+ }
2537
+ const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0;
2538
+ const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0;
2539
+ return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`;
2540
+ }
2541
+ function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) {
2542
+ const changedLinkedFiles = linkedImpactsByEntry.get(entry);
2543
+ if (!changedLinkedFiles || changedLinkedFiles.size === 0) return;
2544
+ return [...changedLinkedFiles].sort().map((file) => {
2545
+ return `${file}:${sourceHashByFile.get(file) ?? "missing"}`;
2546
+ }).join(",");
2547
+ }
2548
+ function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
2549
+ if (!linkedImpactSignature) return runtimeSignature;
2550
+ return `${runtimeSignature}:linked:${linkedImpactSignature}`;
2551
+ }
2552
+ function createStableTextSignature(input) {
2553
+ let hash = 2166136261;
2554
+ for (let i = 0; i < input.length; i++) {
2555
+ hash ^= input.charCodeAt(i);
2556
+ hash = Math.imul(hash, 16777619);
2557
+ }
2558
+ return (hash >>> 0).toString(36);
2559
+ }
2560
+ function createCandidateSignature(candidates) {
2561
+ if (candidates.size === 0) return "empty";
2562
+ return createStableTextSignature([...candidates].sort().join("\n"));
2563
+ }
2564
+ function getSnapshotHash(snapshotMap, file, fallback) {
2565
+ return snapshotMap.get(file) ?? fallback;
2566
+ }
2567
+ function hasRuntimeAffectingSourceChanges(changedByType) {
2568
+ return changedByType.html.size > 0 || changedByType.js.size > 0;
2569
+ }
2570
+ //#endregion
2571
+ //#region src/bundlers/vite/generate-bundle/js-processing.ts
2572
+ function processJsBundleEntry(options) {
2573
+ const { applyLinkedUpdates, bundle, cache, createHandlerOptions, debug, disableJsPrecheck, entry, getJsEntry, jsHandler, jsTaskFactories, linkedByEntry, metrics, onUpdate, outDir, processFiles, rememberProcessCacheKey, runtimeSignature, snapshot, timeTask, transformRuntime, uniAppX, useIncrementalMode } = options;
2574
+ const { file, output: originalSource, source: originalEntrySource } = entry;
2575
+ metrics.js.total++;
2576
+ const shouldTransformJs = !useIncrementalMode || processFiles.js.has(file);
2577
+ if (!shouldTransformJs) debug("js skip transform (clean), replay cache: %s", file);
2578
+ if (originalSource.type === "chunk") {
2579
+ const absoluteFile = node_path.default.resolve(outDir, file);
2580
+ const initialRawSource = originalEntrySource;
2581
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
2582
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
2583
+ jsTaskFactories.push(async () => {
2584
+ await timeTask("js", async () => {
2585
+ const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
2586
+ const hashKey = `${file}:js`;
2587
+ rememberProcessCacheKey(file, hashKey);
2588
+ await require_hmr_timing.processCachedTask({
2589
+ cache,
2590
+ cacheKey: file,
2591
+ hashKey,
2592
+ hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
2593
+ applyResult(source) {
2594
+ originalSource.code = source;
2595
+ },
2596
+ onCacheHit() {
2597
+ metrics.js.cacheHits++;
2598
+ debug("js cache hit: %s", file);
2599
+ },
2600
+ async transform() {
2601
+ const start = performance.now();
2602
+ const rawSource = originalSource.code;
2603
+ if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
2604
+ const handlerOptions = createHandlerOptions(absoluteFile);
2605
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(rawSource, handlerOptions)) {
2606
+ metrics.js.elapsed += measureElapsed(start);
2607
+ metrics.js.transformed++;
2608
+ return { result: rawSource };
2609
+ }
2610
+ const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
2611
+ metrics.js.elapsed += measureElapsed(start);
2612
+ metrics.js.transformed++;
2613
+ onUpdate(file, rawSource, code);
2614
+ debug("js handle: %s", file);
2615
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
2616
+ applyLinkedUpdates(linked);
2617
+ return { result: code };
2618
+ }
2619
+ });
2620
+ });
2621
+ });
2622
+ } else if (uniAppX && originalSource.type === "asset") {
2623
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
2624
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
2625
+ const wrappedApplyLinkedUpdates = (linked) => {
2626
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
2627
+ applyLinkedUpdates(linked);
2628
+ };
2629
+ const uniAppXJsHashKey = `${file}:js`;
2630
+ rememberProcessCacheKey(file, uniAppXJsHashKey);
2631
+ const factory = createUniAppXAssetTask(file, originalSource, outDir, {
2632
+ cache,
2633
+ hashKey: uniAppXJsHashKey,
2634
+ hashSalt: createJsHashSalt(runtimeSignature, [UNI_APP_X_STYLE_PLACEHOLDER_VERSION, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0].filter(Boolean).join(":")),
2635
+ createHandlerOptions,
2636
+ debug,
2637
+ getAssetSource: createUniAppXBundleAssetSourceGetter(bundle),
2638
+ jsHandler,
2639
+ onUpdate,
2640
+ runtimeSet: transformRuntime,
2641
+ applyLinkedResults: wrappedApplyLinkedUpdates,
2642
+ uniAppX
2643
+ });
2644
+ jsTaskFactories.push(async () => {
2645
+ await timeTask("js", async () => {
2646
+ const start = performance.now();
2647
+ if (!shouldTransformJs) {
2648
+ debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
2649
+ await factory();
2650
+ metrics.js.elapsed += measureElapsed(start);
2651
+ metrics.js.transformed++;
2652
+ return;
2653
+ }
2654
+ const currentSource = originalEntrySource;
2655
+ const precheckOptions = createHandlerOptions(node_path.default.resolve(outDir, file), {
2656
+ uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
2657
+ babelParserOptions: {
2658
+ plugins: ["typescript"],
2659
+ sourceType: "unambiguous"
2660
+ }
2661
+ });
2662
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(currentSource, precheckOptions)) {
2663
+ metrics.js.elapsed += measureElapsed(start);
2664
+ metrics.js.transformed++;
2665
+ return;
2666
+ }
2667
+ await factory();
2668
+ metrics.js.elapsed += measureElapsed(start);
2669
+ metrics.js.transformed++;
2670
+ });
2671
+ });
2672
+ }
2673
+ }
2674
+ //#endregion
2675
+ //#region src/bundlers/vite/generate-bundle/process-plan.ts
2676
+ function logBundleProcessPlan(options) {
2677
+ const { debug, snapshot, useIncrementalMode, iteration } = options;
2678
+ const { processFiles } = snapshot;
2679
+ if (useIncrementalMode) {
2680
+ debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", iteration, snapshot.changedByType.html.size, formatDebugFileList(snapshot.changedByType.html), snapshot.changedByType.js.size, formatDebugFileList(snapshot.changedByType.js), snapshot.changedByType.css.size, formatDebugFileList(snapshot.changedByType.css), snapshot.changedByType.other.size, formatDebugFileList(snapshot.changedByType.other));
2681
+ debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", iteration, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
2682
+ return;
2683
+ }
2684
+ debug("build mode full process html=%d[%s] js=%d[%s] css=%d[%s]", processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
2685
+ }
2686
+ //#endregion
2687
+ //#region src/bundlers/vite/generate-bundle/remembered-css.ts
2688
+ function createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash) {
2689
+ return `${cssRuntimeSignature}:${cssRuntimeAffectingHash}`;
2690
+ }
2691
+ function normalizeRememberedSourceIdentity(file) {
2692
+ return require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
2693
+ }
2694
+ function findRememberedCssSources(sources, outputFile, file, originalSource, outputRoot, sourceRoot) {
2695
+ if (!sources) return [];
2696
+ const rememberedSources = [...sources].map(([, remembered]) => remembered);
2697
+ const source = typeof originalSource.source === "string" ? originalSource.source : originalSource.source.toString();
2698
+ const markerFiles = new Set(require_bundle_state.parseBundlerGeneratedCssMarkerBlocks(source).filter((block) => block.bundler === "vite" && typeof block.file === "string" && block.file.length > 0).map((block) => require_bundle_state.normalizeOutputPathKey(block.file)));
2699
+ if (markerFiles.size > 0) {
2700
+ const markerMatched = rememberedSources.filter((remembered) => markerFiles.has(normalizeRememberedSourceIdentity(remembered.sourceFile)));
2701
+ if (markerMatched.length > 0) return markerMatched;
2702
+ }
2703
+ const originalFiles = [
2704
+ file,
2705
+ originalSource.originalFileName,
2706
+ ...originalSource.originalFileNames ?? []
2707
+ ].filter((item) => typeof item === "string" && item.length > 0);
2708
+ const sourceMatched = rememberedSources.filter((remembered) => originalFiles.some((originalFile) => normalizeRememberedSourceIdentity(remembered.sourceFile) === normalizeRememberedSourceIdentity(originalFile)));
2709
+ if (sourceMatched.length > 0) return sourceMatched;
2710
+ const outputMatched = rememberedSources.filter((remembered) => require_bundle_state.normalizeOutputPathKey(remembered.outputFile) === require_bundle_state.normalizeOutputPathKey(outputFile));
2711
+ if (outputMatched.length > 0) return outputMatched;
2712
+ if (!require_bundle_state.hasBundlerGeneratedCssMarker(source) && !hasTailwindGenerationSource(source)) return [];
2713
+ const scoredMatches = rememberedSources.map((remembered) => ({
2714
+ remembered,
2715
+ score: Math.max(scoreMatchingStyleFileBase(outputFile, remembered.sourceFile, outputRoot, sourceRoot), scoreMatchingStyleFileBase(outputFile, remembered.outputFile, outputRoot, sourceRoot))
2716
+ })).filter((match) => match.score > 0).sort((a, b) => b.score - a.score);
2717
+ const bestScore = scoredMatches[0]?.score;
2718
+ return bestScore ? scoredMatches.filter((match) => match.score === bestScore).map((match) => match.remembered) : [];
2719
+ }
2720
+ function mergeRememberedCssSources(sources, outputFile) {
2721
+ if (sources.length <= 1) return sources[0];
2722
+ const seen = /* @__PURE__ */ new Set();
2723
+ const rawSources = [];
2724
+ for (const source of sources) {
2725
+ const key = `${source.sourceFile}\0${source.rawSource}`;
2726
+ if (seen.has(key)) continue;
2727
+ seen.add(key);
2728
+ rawSources.push(source.rawSource);
2729
+ }
2730
+ return {
2731
+ outputFile,
2732
+ rawSource: rawSources.join("\n"),
2733
+ sourceFile: sources[0]?.sourceFile ?? outputFile
2734
+ };
2735
+ }
2736
+ function collectRememberedCssReplayGroups(sources, opts, rootDir, isWebGeneratorTarget, preserveCssExtension, sourceRoot, styleOutputExtension, styleOutputFiles) {
2737
+ const groups = /* @__PURE__ */ new Map();
2738
+ for (const [key, remembered] of sources ?? []) {
2739
+ const outputKey = require_bundle_state.normalizeOutputPathKey(resolveViteCssPipelineOutputFile(remembered.outputFile, opts, rootDir, isWebGeneratorTarget, preserveCssExtension, sourceRoot, styleOutputExtension, styleOutputFiles));
2740
+ const group = groups.get(outputKey) ?? [];
2741
+ group.push({
2742
+ key,
2743
+ remembered
2744
+ });
2745
+ groups.set(outputKey, group);
2746
+ }
2747
+ return groups;
2748
+ }
2749
+ //#endregion
2750
+ //#region src/bundlers/vite/generate-bundle/scoped-generator.ts
2751
+ function hasOwnSourceDirectives(rawSource) {
2752
+ return rawSource.includes("@source") || rawSource.includes("@config");
2753
+ }
2754
+ async function createScopedGeneratorCandidateSignature(rawSource, sourceFile, fallbackSignature, getSourceCandidatesForEntries, options = {}) {
2755
+ if (!getSourceCandidatesForEntries || !hasOwnSourceDirectives(rawSource)) return fallbackSignature;
2756
+ const sourceBase = node_path.default.dirname(node_path.default.resolve(sourceFile.replace(/[?#].*$/, "")));
2757
+ const resolved = options.majorVersion === 3 ? await require_v3_engine.resolveTailwindConfigEntriesFromCssCached(rawSource, sourceBase) : await require_v3_engine.resolveTailwindV4EntriesFromCssCached(rawSource, sourceBase);
2758
+ if (resolved?.entries === void 0) return fallbackSignature;
2759
+ const scopedSignature = createCandidateSignature(getSourceCandidatesForEntries(resolved.entries));
2760
+ return options.includeFallbackSignature === true ? `${scopedSignature}:${fallbackSignature}` : scopedSignature;
2761
+ }
2762
+ async function createScopedGeneratorRuntime(options) {
2763
+ const { cssHandlerOptions, fallbackRuntime, getSourceCandidatesForEntries, majorVersion, outputFile, rawSource, shouldExcludeSubpackageSourceCandidates, sourceFile, scopedSourceCandidateGetter } = options;
2764
+ if (getSourceCandidatesForEntries && rawSource && sourceFile) {
2765
+ const sourceBase = node_path.default.dirname(node_path.default.resolve(sourceFile.replace(/[?#].*$/, "")));
2766
+ const resolved = majorVersion === 3 ? await require_v3_engine.resolveTailwindConfigEntriesFromCssCached(rawSource, sourceBase) : await require_v3_engine.resolveTailwindV4EntriesFromCssCached(rawSource, sourceBase);
2767
+ if (resolved?.entries !== void 0 && (resolved.entries.length > 0 || hasOwnSourceDirectives(rawSource))) return scopedSourceCandidateGetter?.(resolved.entries) ?? getSourceCandidatesForEntries(resolved.entries);
2768
+ }
2769
+ const scopedCandidates = scopedSourceCandidateGetter?.(void 0);
2770
+ if (scopedCandidates && (scopedCandidates.size > 0 || shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions))) return scopedCandidates;
2771
+ if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return fallbackRuntime;
2772
+ return fallbackRuntime;
2773
+ }
2774
+ //#endregion
2775
+ //#region src/bundlers/vite/generate-bundle/remembered-css-replay.ts
2776
+ async function processRememberedCssReplay(options) {
2777
+ const { addWatchFile, activeViteCssCacheFiles, bundleFiles, cache, createScopedGeneratorRuntime, createScopedSourceCandidateGetter, createScopedSourceCandidateSourceGetter, cssTaskFactories, debug, defaultStyleOutputExtension, emitOrReplayCssAsset, generatorRuntime, getCssHandlerOptions, getCssUserHandlerOptions, getRememberedCssSignature, getRememberedCssSources, isNativeAppStyleTarget, isWebGeneratorTarget, lastCssResultByFile, lastCssSourceHashByFile, markCssAssetProcessed, metrics, normalizeViteCssCacheKey, onUpdate, opts, recordCssAssetResult, recordViteProcessedCssAssetResult, refreshRememberedCssSource, rootDir, runtimeState, setRememberedCssSignature, shouldInjectCssIntoMainFromOutput, shouldPreserveAppCssExtension, sourceRoot, styleHandler, timeTask, useIncrementalMode } = options;
2778
+ const rememberedReplayGroups = collectRememberedCssReplayGroups(getRememberedCssSources?.(), opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension, sourceRoot, defaultStyleOutputExtension, bundleFiles);
2779
+ for (const [outputFile, rememberedGroup] of rememberedReplayGroups) {
2780
+ const refreshedRememberedGroup = await Promise.all(rememberedGroup.map(async (item) => ({
2781
+ key: item.key,
2782
+ remembered: await refreshRememberedCssSource?.(item.remembered) ?? item.remembered
2783
+ })));
2784
+ const rememberedCssSource = mergeRememberedCssSources(refreshedRememberedGroup.map((item) => item.remembered), outputFile);
2785
+ if (!rememberedCssSource) continue;
2786
+ const { rawSource, sourceFile } = rememberedCssSource;
2787
+ activeViteCssCacheFiles.add(normalizeViteCssCacheKey(outputFile));
2788
+ activeViteCssCacheFiles.add(normalizeViteCssCacheKey(sourceFile));
2789
+ const outputCssHandlerOptions = getCssHandlerOptions(outputFile);
2790
+ const cssHandlerOptions = {
2791
+ ...getCssHandlerOptions(sourceFile),
2792
+ isMainChunk: outputCssHandlerOptions.isMainChunk
2793
+ };
2794
+ const scopedSourceCandidateGetter = createScopedSourceCandidateGetter(outputFile, cssHandlerOptions);
2795
+ const scopedSourceCandidateSourceGetter = createScopedSourceCandidateSourceGetter(outputFile, cssHandlerOptions);
2796
+ const sourceTraceTokenSources = scopedSourceCandidateSourceGetter ? require_hmr_timing.createCssTokenSourceMap(scopedSourceCandidateSourceGetter(void 0), opts) : void 0;
2797
+ const annotateCss = (css) => require_hmr_timing.annotateCssSourceTrace(css, {
2798
+ opts,
2799
+ tokenSources: sourceTraceTokenSources
2800
+ });
2801
+ const scopedGeneratorRuntime = await createScopedGeneratorRuntime(outputFile, cssHandlerOptions, generatorRuntime, rawSource, sourceFile);
2802
+ const cssRuntimeSignature = createCssRuntimeSignature(createCandidateSignature(scopedGeneratorRuntime), await createScopedGeneratorCandidateSignature(rawSource, sourceFile, createCandidateSignature(scopedGeneratorRuntime), scopedSourceCandidateGetter, {
2803
+ includeFallbackSignature: cssHandlerOptions.isMainChunk,
2804
+ majorVersion: runtimeState.twPatcher.majorVersion
2805
+ }));
2806
+ const cssRuntimeAffectingHash = cache.computeHash(require_bundle_state.createRuntimeAffectingSourceSignature(rawSource, "css"));
2807
+ const rememberedCssRuntimeSignature = createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash);
2808
+ const previousCss = useIncrementalMode && getLastCssSourceHash(lastCssSourceHashByFile, outputFile) === cssRuntimeAffectingHash ? getLastCssResult(lastCssResultByFile, outputFile) : void 0;
2809
+ const rememberedKeys = refreshedRememberedGroup.map((item) => item.key);
2810
+ const allRememberedSignaturesFresh = rememberedKeys.length > 0 && rememberedKeys.every((key) => getRememberedCssSignature?.(key) === rememberedCssRuntimeSignature);
2811
+ if (bundleFiles.includes(outputFile) || bundleFiles.includes(sourceFile) || allRememberedSignaturesFresh) continue;
2812
+ const shouldRecordRememberedReplayCss = useIncrementalMode || isNativeAppStyleTarget;
2813
+ const shouldEmitRememberedReplayCssAsset = shouldRecordRememberedReplayCss;
2814
+ if (!shouldRecordRememberedReplayCss) continue;
2815
+ cssTaskFactories.push(() => timeTask("css.replay", async () => {
2816
+ const start = performance.now();
2817
+ const generated = await require_hmr_timing.generateCssByGenerator({
2818
+ opts,
2819
+ runtimeState,
2820
+ runtime: scopedGeneratorRuntime,
2821
+ rawSource,
2822
+ file: sourceFile,
2823
+ cssHandlerOptions,
2824
+ cssUserHandlerOptions: getCssUserHandlerOptions(sourceFile),
2825
+ getSourceCandidatesForEntries: scopedSourceCandidateGetter,
2826
+ styleHandler,
2827
+ debug,
2828
+ previousCss
2829
+ });
2830
+ const css = annotateCss(generated?.css ?? (await styleHandler(rawSource, cssHandlerOptions)).css);
2831
+ rememberLastCssResult(lastCssResultByFile, lastCssSourceHashByFile, outputFile, css, cssRuntimeAffectingHash);
2832
+ for (const key of rememberedKeys) setRememberedCssSignature?.(key, rememberedCssRuntimeSignature);
2833
+ if (generated) {
2834
+ registerGeneratorDependencies$1({ addWatchFile }, generated.dependencies);
2835
+ recordCssAssetResult?.(outputFile, css);
2836
+ const shouldInjectReplayCssIntoMain = shouldInjectCssIntoMainFromOutput(outputFile, sourceFile, outputCssHandlerOptions);
2837
+ recordViteProcessedCssAssetResult?.(sourceFile, css, {
2838
+ injectIntoMain: outputCssHandlerOptions.isMainChunk ? false : shouldInjectReplayCssIntoMain,
2839
+ outputFile
2840
+ });
2841
+ debug("css replay generated result: %s bytes=%d", outputFile, css.length);
2842
+ }
2843
+ if (shouldEmitRememberedReplayCssAsset) {
2844
+ const replayAsset = emitOrReplayCssAsset(outputFile, css);
2845
+ markCssAssetProcessed?.(replayAsset, outputFile);
2846
+ }
2847
+ metrics.css.elapsed += measureElapsed(start);
2848
+ metrics.css.transformed++;
2849
+ onUpdate(outputFile, rawSource, css);
2850
+ debug("css replay handle: %s", outputFile);
2851
+ }));
2852
+ }
2853
+ }
2854
+ //#endregion
2855
+ //#region src/bundlers/vite/generate-bundle/runtime-linked-css.ts
2856
+ const MINI_PROGRAM_TEMPLATE_OUTPUT_EXT_RE = /\.(?:wxml|axml|jxml|ksml|ttml|qml|tyml|xhsml|swan)$/i;
2857
+ const JS_STYLE_IMPORT_RE = /\b(?:import|require)\s*(?:\(\s*)?["']([^"']+\.(?:css|less|sass|scss|styl|stylus|pcss|postcss))(?:[?#][^"']*)?["']/g;
2858
+ function addSiblingCssFile(files, file, extensionByStem, fallbackExtension) {
2859
+ const templateMatch = file.replace(/[?#].*$/, "").match(MINI_PROGRAM_TEMPLATE_OUTPUT_EXT_RE);
2860
+ if (templateMatch?.[0]) {
2861
+ const stem = file.slice(0, -templateMatch[0].length);
2862
+ files.add(`${stem}${extensionByStem.get(stem) ?? fallbackExtension}`);
2863
+ } else if (file.endsWith(".js")) {
2864
+ const stem = file.slice(0, -3);
2865
+ files.add(`${stem}${extensionByStem.get(stem) ?? fallbackExtension}`);
2866
+ }
2867
+ }
2868
+ function collectCssExtensionByStem(files, cssMatcher) {
2869
+ const extensionByStem = /* @__PURE__ */ new Map();
2870
+ for (const file of files) {
2871
+ const cleanFile = file.replace(/[?#].*$/, "");
2872
+ if (!cssMatcher(cleanFile)) continue;
2873
+ const extension = node_path.default.extname(cleanFile);
2874
+ if (!extension || extension === ".css") continue;
2875
+ extensionByStem.set(file.slice(0, -extension.length), extension);
2876
+ }
2877
+ return extensionByStem;
2878
+ }
2879
+ function collectRuntimeLinkedCssFiles(snapshot, extensionByStem, fallbackExtension) {
2880
+ const files = /* @__PURE__ */ new Set();
2881
+ for (const file of snapshot.runtimeAffectingChangedByType.html) addSiblingCssFile(files, file, extensionByStem, fallbackExtension);
2882
+ for (const file of snapshot.runtimeAffectingChangedByType.js) addSiblingCssFile(files, file, extensionByStem, fallbackExtension);
2883
+ return files;
2884
+ }
2885
+ function collectJsImportedCssFiles(snapshot) {
2886
+ const files = /* @__PURE__ */ new Set();
2887
+ for (const entry of snapshot.entries) {
2888
+ if (entry.type !== "js" || entry.output.type !== "chunk") continue;
2889
+ JS_STYLE_IMPORT_RE.lastIndex = 0;
2890
+ let match = JS_STYLE_IMPORT_RE.exec(entry.source);
2891
+ while (match !== null) {
2892
+ const request = match[1];
2893
+ if (request?.startsWith(".")) files.add(require_bundle_state.normalizeOutputPathKey(node_path.default.posix.join(node_path.default.posix.dirname(entry.file), request)));
2894
+ match = JS_STYLE_IMPORT_RE.exec(entry.source);
2895
+ }
2896
+ }
2897
+ return files;
2898
+ }
2899
+ //#endregion
2900
+ //#region src/bundlers/vite/generate-bundle/source-candidate-scope.ts
2901
+ function intersectCandidateSets(left, right) {
2902
+ if (left.size === 0 || right.size === 0) return /* @__PURE__ */ new Set();
2903
+ const [small, large] = left.size <= right.size ? [left, right] : [right, left];
2904
+ const matched = /* @__PURE__ */ new Set();
2905
+ for (const candidate of small) if (large.has(candidate)) matched.add(candidate);
2906
+ return matched;
2907
+ }
2908
+ function intersectCandidateSourceMaps(left, right) {
2909
+ if (left.size === 0 || right.size === 0) return /* @__PURE__ */ new Map();
2910
+ const matched = /* @__PURE__ */ new Map();
2911
+ for (const [candidate, sources] of left) if (right.has(candidate)) matched.set(candidate, sources);
2912
+ return matched;
2913
+ }
2914
+ function createSubpackageSourceCandidateScope(options) {
2915
+ const subpackageSourceExcludeEntries = options.subpackageRoots ? collectMiniProgramSubpackageSourceEntries(options.snapshot, options.subpackageRoots, [
2916
+ options.rootDir,
2917
+ options.tailwindcssBasedir,
2918
+ options.projectRoot
2919
+ ]) : [];
2920
+ const isMainPackageStyleOutputFile = (file) => options.subpackageRoots != null && !isSubpackageOutputFile(file, options.subpackageRoots);
2921
+ const resolveSubpackageOutputSourceEntries = (outputFile) => {
2922
+ if (!options.subpackageRoots) return;
2923
+ const matchedRoots = [...options.subpackageRoots].filter((root) => isSubpackageOutputFile(outputFile, new Set([root])));
2924
+ if (matchedRoots.length !== 1) return;
2925
+ const root = matchedRoots[0];
2926
+ if (!root) return;
2927
+ return options.sourceRoot ? [{
2928
+ base: options.sourceRoot,
2929
+ negated: false,
2930
+ pattern: `${root}/**/*`
2931
+ }] : [{
2932
+ base: options.rootDir,
2933
+ negated: false,
2934
+ pattern: `**/${root}/**/*`
2935
+ }];
2936
+ };
2937
+ const shouldExcludeSubpackageSourceCandidates = (outputFile, cssHandlerOptions) => cssHandlerOptions.isMainChunk === true && subpackageSourceExcludeEntries.length > 0 && isMainPackageStyleOutputFile(outputFile);
2938
+ const createScopedSourceCandidateGetter = (outputFile, cssHandlerOptions) => {
2939
+ if (!options.getSourceCandidatesForEntries) return;
2940
+ const subpackageEntries = resolveSubpackageOutputSourceEntries(outputFile);
2941
+ if (subpackageEntries) return (entries, filterOptions) => {
2942
+ if (entries !== void 0) {
2943
+ const scopedCandidates = options.getSourceCandidatesForEntries?.(entries, filterOptions) ?? /* @__PURE__ */ new Set();
2944
+ if (entries.length === 0) return scopedCandidates;
2945
+ const subpackageCandidates = options.getSourceCandidatesForEntries?.(subpackageEntries, filterOptions) ?? /* @__PURE__ */ new Set();
2946
+ const matchedCandidates = intersectCandidateSets(scopedCandidates, subpackageCandidates);
2947
+ if (matchedCandidates.size > 0 || subpackageCandidates.size > 0) return matchedCandidates;
2948
+ if (scopedCandidates.size > 0) return scopedCandidates;
2949
+ }
2950
+ return options.getSourceCandidatesForEntries?.(subpackageEntries, filterOptions) ?? /* @__PURE__ */ new Set();
2951
+ };
2952
+ if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return options.getSourceCandidatesForEntries;
2953
+ return (entries, filterOptions) => options.getSourceCandidatesForEntries?.(entries, {
2954
+ ...filterOptions,
2955
+ excludeEntries: [...filterOptions?.excludeEntries ?? [], ...subpackageSourceExcludeEntries]
2956
+ }) ?? /* @__PURE__ */ new Set();
2957
+ };
2958
+ const createScopedSourceCandidateSourceGetter = (outputFile, cssHandlerOptions) => {
2959
+ if (!options.getSourceCandidateSourcesForEntries) return;
2960
+ const subpackageEntries = resolveSubpackageOutputSourceEntries(outputFile);
2961
+ if (subpackageEntries) return (entries, filterOptions) => {
2962
+ if (entries !== void 0) {
2963
+ const scopedSources = options.getSourceCandidateSourcesForEntries?.(entries, filterOptions) ?? /* @__PURE__ */ new Map();
2964
+ if (entries.length === 0) return scopedSources;
2965
+ const subpackageSources = options.getSourceCandidateSourcesForEntries?.(subpackageEntries, filterOptions) ?? /* @__PURE__ */ new Map();
2966
+ const matchedSources = intersectCandidateSourceMaps(scopedSources, subpackageSources);
2967
+ if (matchedSources.size > 0 || subpackageSources.size > 0) return matchedSources;
2968
+ if (scopedSources.size > 0) return scopedSources;
2969
+ }
2970
+ return options.getSourceCandidateSourcesForEntries?.(subpackageEntries, filterOptions) ?? /* @__PURE__ */ new Map();
2971
+ };
2972
+ if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return options.getSourceCandidateSourcesForEntries;
2973
+ return (entries, filterOptions) => options.getSourceCandidateSourcesForEntries?.(entries, {
2974
+ ...filterOptions,
2975
+ excludeEntries: [...filterOptions?.excludeEntries ?? [], ...subpackageSourceExcludeEntries]
2976
+ }) ?? /* @__PURE__ */ new Map();
2977
+ };
2978
+ const shouldInjectCssIntoMainFromOutput = (outputFile, _sourceFile, outputCssHandlerOptions) => outputCssHandlerOptions.isMainChunk === true || options.useIncrementalMode && isMainPackageStyleOutputFile(outputFile);
2979
+ return {
2980
+ createScopedSourceCandidateGetter,
2981
+ createScopedSourceCandidateSourceGetter,
2982
+ shouldExcludeSubpackageSourceCandidates,
2983
+ shouldInjectCssIntoMainFromOutput
2984
+ };
2985
+ }
2986
+ //#endregion
2987
+ //#region src/bundlers/vite/generate-bundle/timing.ts
2988
+ function createBundleTaskTimer(recordTimingDetail) {
2989
+ return async (name, task) => {
2990
+ const start = performance.now();
2991
+ try {
2992
+ await task();
2993
+ } finally {
2994
+ recordTimingDetail(`tasks.${name}`, start);
2995
+ }
2996
+ };
2095
2997
  }
2096
2998
  //#endregion
2097
2999
  //#region src/bundlers/vite/uni-app-x-css-options.ts
@@ -2104,27 +3006,65 @@ function resolveUniAppXNativeCssHandlerOptions(opts) {
2104
3006
  };
2105
3007
  }
2106
3008
  //#endregion
2107
- //#region src/bundlers/vite/generate-bundle.ts
2108
- function addSiblingCssFile(files, file) {
2109
- if (file.endsWith(".wxml")) files.add(file.replace(/\.wxml$/, ".wxss"));
2110
- else if (file.endsWith(".js")) files.add(file.replace(/\.js$/, ".wxss"));
2111
- }
2112
- function collectRuntimeLinkedCssFiles(snapshot) {
2113
- const files = /* @__PURE__ */ new Set();
2114
- for (const file of snapshot.runtimeAffectingChangedByType.html) addSiblingCssFile(files, file);
2115
- for (const file of snapshot.runtimeAffectingChangedByType.js) addSiblingCssFile(files, file);
2116
- return files;
3009
+ //#region src/bundlers/vite/weapp-vite-config.ts
3010
+ function resolveSourceRootCandidate(root, value) {
3011
+ if (typeof value !== "string" || value.trim().length === 0) return;
3012
+ const resolved = node_path.default.isAbsolute(value) ? value : node_path.default.resolve(root, value);
3013
+ return (0, node_fs.existsSync)(resolved) ? resolved : void 0;
3014
+ }
3015
+ function resolveWeappViteSourceRoot(config, _appType) {
3016
+ const viteConfig = config;
3017
+ const root = typeof viteConfig?.root === "string" && viteConfig.root.length > 0 ? node_path.default.resolve(viteConfig.root) : node_process.default.cwd();
3018
+ const configuredSrcRoot = resolveSourceRootCandidate(root, viteConfig?.weapp?.srcRoot);
3019
+ if (configuredSrcRoot) return configuredSrcRoot;
3020
+ const envSrcRoot = resolveSourceRootCandidate(root, node_process.default.env.UNI_INPUT_DIR) ?? resolveSourceRootCandidate(root, node_process.default.env.UNI_INPUT_ROOT) ?? resolveSourceRootCandidate(root, node_process.default.env.UNI_APP_INPUT_DIR);
3021
+ if (envSrcRoot) return envSrcRoot;
3022
+ }
3023
+ function stripFileExtension(file) {
3024
+ return file.replace(/[?#].*$/, "").replace(/\.[^.\\/]+$/u, "");
3025
+ }
3026
+ function isUsefulModuleId(id) {
3027
+ return !id.includes("\0") && !id.includes("/node_modules/") && !id.includes("\\node_modules\\") && !/[?&]type=style\b/u.test(id);
3028
+ }
3029
+ function collectChunkModuleIds(chunk) {
3030
+ const ids = /* @__PURE__ */ new Set();
3031
+ if (typeof chunk.facadeModuleId === "string" && chunk.facadeModuleId.length > 0) ids.add(chunk.facadeModuleId);
3032
+ for (const id of chunk.moduleIds ?? []) if (typeof id === "string" && id.length > 0) ids.add(id);
3033
+ return ids;
3034
+ }
3035
+ function resolveSourceRootFromChunk(root, fileName, chunk) {
3036
+ const outputBase = stripFileExtension(require_bundle_state.normalizeOutputPathKey(fileName));
3037
+ if (!outputBase.includes("/")) return;
3038
+ for (const id of collectChunkModuleIds(chunk)) {
3039
+ if (!isUsefulModuleId(id)) continue;
3040
+ const cleanId = id.replace(/[?#].*$/, "");
3041
+ const relativeModule = require_bundle_state.normalizeOutputPathKey(node_path.default.relative(root, cleanId));
3042
+ if (relativeModule.length === 0 || relativeModule === "." || relativeModule.startsWith("../") || node_path.default.isAbsolute(relativeModule)) continue;
3043
+ const moduleBase = stripFileExtension(relativeModule);
3044
+ if (!moduleBase.endsWith(outputBase)) continue;
3045
+ const sourceRoot = moduleBase.slice(0, moduleBase.length - outputBase.length).replace(/\/+$/u, "");
3046
+ if (sourceRoot.length === 0) continue;
3047
+ const resolved = node_path.default.resolve(root, sourceRoot);
3048
+ if ((0, node_fs.existsSync)(resolved)) return resolved;
3049
+ }
2117
3050
  }
2118
- async function createScopedGeneratorCandidateSignature(rawSource, sourceFile, fallbackSignature, getSourceCandidatesForEntries, options = {}) {
2119
- if (!getSourceCandidatesForEntries || !rawSource.includes("@source")) return fallbackSignature;
2120
- const resolved = await require_v3_engine.resolveTailwindV4EntriesFromCssCached(rawSource, node_path.default.dirname(node_path.default.resolve(sourceFile.replace(/[?#].*$/, ""))));
2121
- if (resolved?.entries === void 0) return fallbackSignature;
2122
- const scopedSignature = createCandidateSignature(getSourceCandidatesForEntries(resolved.entries));
2123
- return options.includeFallbackSignature === true ? `${scopedSignature}:${fallbackSignature}` : scopedSignature;
3051
+ function resolveSourceRootFromBundleGraph(config, bundle) {
3052
+ const viteConfig = config;
3053
+ const root = typeof viteConfig?.root === "string" && viteConfig.root.length > 0 ? node_path.default.resolve(viteConfig.root) : node_process.default.cwd();
3054
+ const sourceRoots = /* @__PURE__ */ new Set();
3055
+ for (const output of Object.values(bundle)) {
3056
+ if (output.type !== "chunk") continue;
3057
+ const sourceRoot = resolveSourceRootFromChunk(root, output.fileName, output);
3058
+ if (sourceRoot) sourceRoots.add(sourceRoot);
3059
+ }
3060
+ return sourceRoots.size === 1 ? [...sourceRoots][0] : void 0;
2124
3061
  }
3062
+ //#endregion
3063
+ //#region src/bundlers/vite/generate-bundle.ts
2125
3064
  function createGenerateBundleHook(context) {
2126
3065
  const state = require_bundle_state.createBundleBuildState();
2127
3066
  const lastCssResultByFile = /* @__PURE__ */ new Map();
3067
+ const lastCssSourceHashByFile = /* @__PURE__ */ new Map();
2128
3068
  let currentOutDir;
2129
3069
  let currentSubpackageRoots;
2130
3070
  const cssHandlerOptions = createCssHandlerOptionsCache({
@@ -2132,11 +3072,15 @@ function createGenerateBundleHook(context) {
2132
3072
  mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
2133
3073
  getMajorVersion: () => context.runtimeState.twPatcher.majorVersion,
2134
3074
  getOutputRoot: () => currentOutDir,
2135
- getExtraOptions: () => resolveUniAppXNativeCssHandlerOptions(context.opts)
3075
+ getExtraOptions: (file) => ({
3076
+ ...resolveViteCssHandlerExtraOptions(file),
3077
+ ...resolveUniAppXNativeCssHandlerOptions(context.opts),
3078
+ ...currentSubpackageRoots && isSubpackageOutputFile(file, currentSubpackageRoots) ? { isMainChunk: false } : {}
3079
+ })
2136
3080
  });
2137
3081
  return async function generateBundle(_opt, bundle) {
2138
3082
  const addWatchFile = (id) => this.addWatchFile?.(id);
2139
- const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, isCssAssetProcessed, isViteProcessedCssAsset, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getViteProcessedCssAssetResult, getSourceCandidates, getSourceCandidatesForEntries, getSourceCandidateSourcesForEntries, waitForSourceCandidateSyncs, rememberCssSource, refreshRememberedCssSource, getRememberedCssSources, getRememberedCssSignature, setRememberedCssSignature, getKnownSfcSource, recordGeneratorCandidates, hmrTimingRecorder } = context;
3083
+ const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, isCssAssetProcessed, isViteProcessedCssAsset, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getViteProcessedCssAssetResult, getSourceCandidates, getSourceCandidateSource, getSourceCandidateSources, getSourceCandidatesForEntries, getSourceCandidateSourcesForEntries, waitForSourceCandidateSyncs, rememberCssSource, refreshRememberedCssSource, getRememberedCssSources, getRememberedCssSignature, setRememberedCssSignature, getKnownSfcSource, recordGeneratorCandidates, pruneViteCssCaches, getViteCssCacheStats, hmrTimingRecorder } = context;
2140
3084
  const getBundlerSfcSource = (sourceFile) => {
2141
3085
  const code = this.getModuleInfo?.(sourceFile)?.code;
2142
3086
  return typeof code === "string" && hasSfcStyleSources(code) ? code : void 0;
@@ -2154,18 +3098,23 @@ function createGenerateBundleHook(context) {
2154
3098
  const shouldGenerateWebCssByGenerator = isWebGeneratorTarget && runtimeState.twPatcher.majorVersion === 3;
2155
3099
  const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
2156
3100
  const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
3101
+ const sourceRoot = resolveWeappViteSourceRoot(resolvedConfig, opts.appType) ?? resolveSourceRootFromBundleGraph(resolvedConfig, bundle);
2157
3102
  const outDir = resolvedConfig?.build?.outDir ? node_path.default.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
3103
+ const defaultStyleOutputExtension = resolveMiniProgramStyleOutputExtension({ files: Object.keys(bundle) });
2158
3104
  await runtimeState.readyPromise;
2159
3105
  debug("start");
2160
3106
  onStart();
2161
3107
  const collectedBundlerGeneratedCssFiles = new Set(Object.entries(bundle).filter(([, output]) => output.type === "asset" && require_bundle_state.hasBundlerGeneratedCssMarker(output.source)).map(([file]) => file));
3108
+ const subpackageRoots = collectMiniProgramSubpackageRoots(bundle);
3109
+ if (subpackageRoots) currentSubpackageRoots = subpackageRoots;
2162
3110
  collectViteProcessedCssAssetResults(bundle, {
2163
3111
  opts,
2164
3112
  isViteProcessedCssAsset,
2165
3113
  markCssAssetProcessed,
2166
3114
  recordCssAssetResult,
2167
3115
  recordViteProcessedCssAssetResult,
2168
- resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension),
3116
+ resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension, sourceRoot, defaultStyleOutputExtension, Object.keys(bundle)),
3117
+ subpackageRoots: currentSubpackageRoots,
2169
3118
  debug
2170
3119
  });
2171
3120
  const hmrTimingStartedAt = performance.now();
@@ -2173,64 +3122,31 @@ function createGenerateBundleHook(context) {
2173
3122
  const recordTimingDetail = (name, startedAt) => {
2174
3123
  timingDetails[name] = (timingDetails[name] ?? 0) + Math.max(0, performance.now() - startedAt);
2175
3124
  };
2176
- const timeTask = async (name, task) => {
2177
- const start = performance.now();
2178
- try {
2179
- await task();
2180
- } finally {
2181
- recordTimingDetail(`tasks.${name}`, start);
2182
- }
2183
- };
2184
- const emitOrReplayCssAsset = (fileName, source) => {
2185
- const replayAsset = createReplayCssAsset(fileName, source);
2186
- if (typeof this.emitFile === "function") this.emitFile({
2187
- type: "asset",
2188
- fileName,
2189
- source
2190
- });
2191
- else bundle[fileName] = replayAsset;
2192
- return replayAsset;
2193
- };
3125
+ const timeTask = createBundleTaskTimer(recordTimingDetail);
3126
+ const emitOrReplayCssAsset = createCssAssetEmitter(this);
2194
3127
  const metrics = createEmptyMetrics();
2195
- const forceRuntimeRefreshByEnv = node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
2196
- const disableDirtyOptimization = node_process.default.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1";
2197
- const disableJsPrecheck = node_process.default.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1";
2198
- const debugCssDiff = node_process.default.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1";
2199
- const disableV3OxideSourceRuntime = node_process.default.env["WEAPP_TW_VITE_DISABLE_V3_OXIDE_RUNTIME"] === "1";
3128
+ const envFlags = resolveGenerateBundleEnvFlags();
2200
3129
  const bundleFiles = Object.keys(bundle);
2201
- const subpackageRoots = collectMiniProgramSubpackageRoots(bundle);
2202
- if (subpackageRoots) currentSubpackageRoots = subpackageRoots;
2203
- const isMainPackageStyleOutputFile = (file) => currentSubpackageRoots != null && !isSubpackageOutputFile(file, currentSubpackageRoots);
3130
+ const activeViteCssCacheFiles = new Set(bundleFiles.map(normalizeViteCssCacheKey));
3131
+ const configuredTailwindV4CssSourceEntries = collectConfiguredTailwindV4CssSourceEntries(opts, opts.tailwindcssBasedir ?? rootDir);
2204
3132
  const buildCommand = resolvedConfig?.command === "build";
2205
3133
  const hasPreviousBundleState = state.iteration > 0 || state.sourceHashByFile.size > 0;
2206
3134
  const hasOmittedKnownFiles = hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
2207
3135
  const useIncrementalMode = !buildCommand || hasPreviousBundleState || hasOmittedKnownFiles;
2208
3136
  currentOutDir = outDir;
2209
3137
  const snapshotStart = performance.now();
2210
- const snapshot = require_bundle_state.buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode, { hasOmittedKnownFiles });
2211
- const subpackageSourceExcludeEntries = currentSubpackageRoots ? collectMiniProgramSubpackageSourceEntries(snapshot, currentSubpackageRoots, [
3138
+ const snapshot = require_bundle_state.buildBundleSnapshot(bundle, opts, outDir, state, envFlags.disableDirtyOptimization || !useIncrementalMode, { hasOmittedKnownFiles });
3139
+ const { createScopedSourceCandidateGetter, createScopedSourceCandidateSourceGetter, shouldExcludeSubpackageSourceCandidates, shouldInjectCssIntoMainFromOutput } = createSubpackageSourceCandidateScope({
3140
+ getSourceCandidateSourcesForEntries,
3141
+ getSourceCandidatesForEntries,
3142
+ projectRoot: opts.tailwindcssPatcherOptions?.projectRoot,
2212
3143
  rootDir,
2213
- opts.tailwindcssBasedir,
2214
- opts.tailwindcssPatcherOptions?.projectRoot
2215
- ]) : [];
2216
- const shouldExcludeSubpackageSourceCandidates = (outputFile, cssHandlerOptions) => cssHandlerOptions.isMainChunk === true && subpackageSourceExcludeEntries.length > 0 && isMainPackageStyleOutputFile(outputFile);
2217
- const createScopedSourceCandidateGetter = (outputFile, cssHandlerOptions) => {
2218
- if (!getSourceCandidatesForEntries) return;
2219
- if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return getSourceCandidatesForEntries;
2220
- return (entries, options) => getSourceCandidatesForEntries(entries, {
2221
- ...options,
2222
- excludeEntries: [...options?.excludeEntries ?? [], ...subpackageSourceExcludeEntries]
2223
- });
2224
- };
2225
- const createScopedSourceCandidateSourceGetter = (outputFile, cssHandlerOptions) => {
2226
- if (!getSourceCandidateSourcesForEntries) return;
2227
- if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return getSourceCandidateSourcesForEntries;
2228
- return (entries, options) => getSourceCandidateSourcesForEntries(entries, {
2229
- ...options,
2230
- excludeEntries: [...options?.excludeEntries ?? [], ...subpackageSourceExcludeEntries]
2231
- });
2232
- };
2233
- const shouldInjectCssIntoMainFromOutput = (outputFile, sourceFile, outputCssHandlerOptions) => isMainStyleEntryCssFile(sourceFile) || isTailwindEntryCssFile(outputFile) || useIncrementalMode && (outputCssHandlerOptions.isMainChunk || isMainPackageStyleOutputFile(outputFile));
3144
+ snapshot,
3145
+ sourceRoot,
3146
+ subpackageRoots: currentSubpackageRoots,
3147
+ tailwindcssBasedir: opts.tailwindcssBasedir,
3148
+ useIncrementalMode
3149
+ });
2234
3150
  recordTimingDetail("snapshot", snapshotStart);
2235
3151
  const useBundleRuntimeClassSet = !isWebGeneratorTarget && (useIncrementalMode || runtimeState.twPatcher.majorVersion === 4);
2236
3152
  const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
@@ -2245,32 +3161,59 @@ function createGenerateBundleHook(context) {
2245
3161
  await waitForSourceCandidateSyncs?.();
2246
3162
  recordTimingDetail("sourceCandidates.wait", sourceCandidateWaitStart);
2247
3163
  const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
2248
- const createScopedGeneratorRuntime = (outputFile, cssHandlerOptions, runtime) => {
2249
- if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return runtime;
2250
- const filteredSourceCandidates = createScopedSourceCandidateGetter(outputFile, cssHandlerOptions)?.(void 0);
2251
- if (!filteredSourceCandidates) return runtime;
2252
- return filteredSourceCandidates.size > 0 ? filteredSourceCandidates : runtime;
2253
- };
3164
+ const createScopedGeneratorRuntime$1 = (outputFile, cssHandlerOptions, runtime, rawSource, sourceFile) => createScopedGeneratorRuntime({
3165
+ cssHandlerOptions,
3166
+ fallbackRuntime: runtime,
3167
+ getSourceCandidatesForEntries,
3168
+ majorVersion: runtimeState.twPatcher.majorVersion,
3169
+ outputFile,
3170
+ rawSource,
3171
+ shouldExcludeSubpackageSourceCandidates,
3172
+ sourceFile,
3173
+ scopedSourceCandidateGetter: createScopedSourceCandidateGetter(outputFile, cssHandlerOptions)
3174
+ });
2254
3175
  const jsEntries = snapshot.jsEntries;
2255
3176
  const getJsEntry = createJsEntryResolver(jsEntries);
2256
3177
  const moduleGraphOptions = require_bundle_state.createBundleModuleGraphOptions(outDir, jsEntries);
2257
3178
  const hasCssAssetEntry = snapshot.entries.some((entry) => entry.type === "css" && entry.output.type === "asset");
2258
3179
  const hasRuntimeAffectingChanges = hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
2259
- const useV3OxideSourceRuntime = runtimeState.twPatcher.majorVersion === 3 && sourceCandidates.size > 0 && hasCssAssetEntry && !forceRuntimeRefreshByEnv && !disableV3OxideSourceRuntime;
3180
+ const useV3OxideSourceRuntime = runtimeState.twPatcher.majorVersion === 3 && sourceCandidates.size > 0 && hasCssAssetEntry && !envFlags.forceRuntimeRefreshByEnv && !envFlags.disableV3OxideSourceRuntime;
2260
3181
  const runtimeStart = performance.now();
2261
- const transformBaseRuntime = useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, { transformOnly: true }) : void 0;
3182
+ const transformBaseRuntime = useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, envFlags.forceRuntimeRefreshByEnv, { transformOnly: true }) : void 0;
2262
3183
  const forceV4RuntimeRefreshBySource = runtimeState.twPatcher.majorVersion === 4 && forceRuntimeRefreshBySource;
2263
- const runtime = isWebGeneratorTarget && !shouldGenerateWebCssByGenerator ? /* @__PURE__ */ new Set() : useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, {
3184
+ const runtime = isWebGeneratorTarget && !shouldGenerateWebCssByGenerator ? /* @__PURE__ */ new Set() : useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, envFlags.forceRuntimeRefreshByEnv, {
2264
3185
  allowBaselineOnlyInitialSync: true,
2265
3186
  baseClassSet: sourceCandidates
2266
- }) : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv || forceV4RuntimeRefreshBySource, { allowBaselineOnlyInitialSync: buildCommand }) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
3187
+ }) : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, envFlags.forceRuntimeRefreshByEnv || forceV4RuntimeRefreshBySource, { allowBaselineOnlyInitialSync: buildCommand }) : await context.ensureRuntimeClassSet(envFlags.forceRuntimeRefreshByEnv);
2267
3188
  if (useV3OxideSourceRuntime) debug("[tailwindcss:v3] use oxide source candidates as runtime input, candidates=%d", sourceCandidates.size);
2268
3189
  const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
2269
3190
  const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
2270
3191
  const filteredGeneratorCandidates = shouldFilterTailwindV4MiniProgramCandidates ? require_v3_engine.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
2271
3192
  let transformRuntime = transformBaseRuntime ?? runtime;
2272
3193
  let generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, runtimeState.twPatcher.majorVersion === 3 && hasRuntimeAffectingChanges && transformBaseRuntime ? new Set([...filteredGeneratorCandidates, ...transformBaseRuntime]) : filteredGeneratorCandidates);
3194
+ if (runtimeState.twPatcher.majorVersion === 3 && generatorRuntime.size === 0) {
3195
+ generatorRuntime = await context.ensureRuntimeClassSet(envFlags.forceRuntimeRefreshByEnv);
3196
+ transformRuntime = generatorRuntime;
3197
+ }
2273
3198
  const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
3199
+ if (runtimeState.twPatcher.majorVersion === 4 && sourceCandidates.size > 0 && jsEntries.size > 0) {
3200
+ const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
3201
+ if (mainCssEntry) {
3202
+ const validatedSourceRuntime = await require_hmr_timing.validateCandidatesByGenerator({
3203
+ opts,
3204
+ runtimeState,
3205
+ candidates: filteredGeneratorCandidates,
3206
+ rawSource: mainCssEntry.source,
3207
+ file: mainCssEntry.file,
3208
+ cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
3209
+ cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
3210
+ styleHandler,
3211
+ debug,
3212
+ skipGenerateFallback: true
3213
+ });
3214
+ if (validatedSourceRuntime.size > 0) transformRuntime = new Set([...transformRuntime, ...validatedSourceRuntime]);
3215
+ }
3216
+ }
2274
3217
  if (runtimeState.twPatcher.majorVersion === 3 && useV3OxideSourceRuntime && generatorRuntime.size > 0 && (state.iteration === 0 || !hasRuntimeAffectingChanges) && cssEntries.length <= 1) {
2275
3218
  const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
2276
3219
  if (mainCssEntry) {
@@ -2288,15 +3231,29 @@ function createGenerateBundleHook(context) {
2288
3231
  if (validatedRuntime.size > 0) {
2289
3232
  generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, validatedRuntime);
2290
3233
  transformRuntime = generatorRuntime;
2291
- } else {
2292
- generatorRuntime = validatedRuntime;
2293
- transformRuntime = validatedRuntime;
2294
3234
  }
2295
3235
  }
2296
3236
  }
2297
3237
  const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
2298
3238
  const generatorCandidatesChanged = state.generatorCandidateSignature !== generatorCandidateSignature;
2299
- const runtimeLinkedCssFiles = collectRuntimeLinkedCssFiles(snapshot);
3239
+ const cssExtensionByStem = collectCssExtensionByStem(bundleFiles, opts.cssMatcher);
3240
+ const jsImportedCssFiles = collectJsImportedCssFiles(snapshot);
3241
+ const runtimeLinkedCssFiles = new Set([...collectRuntimeLinkedCssFiles(snapshot, cssExtensionByStem, defaultStyleOutputExtension), ...jsImportedCssFiles]);
3242
+ for (const file of runtimeLinkedCssFiles) {
3243
+ if (snapshot.sourceHashByFile.has(file)) {
3244
+ processFiles.css.add(file);
3245
+ continue;
3246
+ }
3247
+ const outputFile = resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension, sourceRoot, defaultStyleOutputExtension, bundleFiles);
3248
+ const inferredSourceStyle = resolveSourceStyleSourceFromOutputFile(outputFile, snapshot, outDir, sourceRoot, getSourceCandidateSource, jsImportedCssFiles.has(file) ? getSourceCandidateSources : void 0, configuredTailwindV4CssSourceEntries.map((entry) => [entry.file, entry.source]), debug);
3249
+ const rawSource = inferredSourceStyle?.rawSource ?? getSourceCandidateSource?.(node_path.default.resolve(outDir, file)) ?? getSourceCandidateSource?.(file);
3250
+ if (rawSource === void 0 || !hasTailwindGenerationSource(rawSource)) continue;
3251
+ rememberCssSource?.({
3252
+ outputFile,
3253
+ rawSource,
3254
+ sourceFile: inferredSourceStyle?.sourceFile ?? node_path.default.resolve(outDir, file)
3255
+ });
3256
+ }
2300
3257
  recordGeneratorCandidates?.(generatorRuntime);
2301
3258
  const dynamicRetryCandidates = new Set([
2302
3259
  ...sourceCandidates,
@@ -2321,7 +3278,14 @@ function createGenerateBundleHook(context) {
2321
3278
  });
2322
3279
  const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
2323
3280
  const sharedCssResultCache = /* @__PURE__ */ new Map();
3281
+ const activeProcessCacheKeys = /* @__PURE__ */ new Set();
3282
+ const activeProcessHashKeys = /* @__PURE__ */ new Set();
3283
+ const rememberProcessCacheKey = (cacheKey, hashKey = cacheKey) => {
3284
+ activeProcessCacheKeys.add(cacheKey);
3285
+ activeProcessHashKeys.add(hashKey);
3286
+ };
2324
3287
  const tasks = [];
3288
+ const cssTaskFactories = [];
2325
3289
  const jsTaskFactories = [];
2326
3290
  for (const entry of snapshot.entries) {
2327
3291
  const { file, output: originalSource, source: originalEntrySource, type } = entry;
@@ -2333,10 +3297,13 @@ function createGenerateBundleHook(context) {
2333
3297
  }
2334
3298
  if (!processFiles.html.has(file)) continue;
2335
3299
  const rawSource = originalEntrySource;
3300
+ const cacheKey = file;
3301
+ const hashKey = `${file}:html:${runtimeSignature}`;
3302
+ rememberProcessCacheKey(cacheKey, hashKey);
2336
3303
  tasks.push(timeTask("html", () => require_hmr_timing.processCachedTask({
2337
3304
  cache,
2338
- cacheKey: file,
2339
- hashKey: `${file}:html:${runtimeSignature}`,
3305
+ cacheKey,
3306
+ hashKey,
2340
3307
  hash: getSnapshotHash(snapshot.sourceHashByFile, file, rawSource),
2341
3308
  applyResult(source) {
2342
3309
  originalSource.source = source;
@@ -2373,8 +3340,10 @@ function createGenerateBundleHook(context) {
2373
3340
  }
2374
3341
  if (type === "css" && originalSource.type === "asset") {
2375
3342
  metrics.css.total++;
2376
- const rawSource = normalizeRelativeCssConfigDirectives(originalEntrySource, file, outDir, opts);
2377
- const outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, shouldPreserveAppCssExtension);
3343
+ const assetSourceFile = resolveAssetSourceFile(originalSource, file);
3344
+ const rawSource = normalizeRelativeCssConfigDirectives(originalEntrySource, assetSourceFile, outDir, opts);
3345
+ const outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, shouldPreserveAppCssExtension, defaultStyleOutputExtension, bundleFiles);
3346
+ activeViteCssCacheFiles.add(normalizeViteCssCacheKey(outputFile));
2378
3347
  if (outputFile !== file && !canProcessViteSourceStyleAsCss(rawSource, file)) {
2379
3348
  delete bundle[file];
2380
3349
  debug("css skip raw source style asset: %s -> %s", file, outputFile);
@@ -2382,9 +3351,10 @@ function createGenerateBundleHook(context) {
2382
3351
  }
2383
3352
  const applyCssResult = (source) => {
2384
3353
  if (outputFile !== file) {
2385
- delete bundle[file];
2386
3354
  emitOrReplayCssAsset(outputFile, source);
2387
- originalSource.fileName = outputFile;
3355
+ if (!viteProcessedCssAsset && SOURCE_STYLE_OUTPUT_EXT_RE.test(file)) delete bundle[file];
3356
+ else originalSource.source = "";
3357
+ return;
2388
3358
  }
2389
3359
  originalSource.source = source;
2390
3360
  };
@@ -2402,32 +3372,47 @@ function createGenerateBundleHook(context) {
2402
3372
  let rememberedCssSources = findRememberedCssSources(getRememberedCssSources?.(), outputFile, file, originalSource, outDir, opts.tailwindcssBasedir);
2403
3373
  if (rememberedCssSources.length > 0) rememberedCssSources = await Promise.all(rememberedCssSources.map(async (remembered) => await refreshRememberedCssSource?.(remembered) ?? remembered));
2404
3374
  const hasUsableRememberedTailwindSource = rememberedCssSources.some((remembered) => hasTailwindGenerationSource(remembered.rawSource) && require_bundle_state.normalizeOutputPathKey(remembered.sourceFile.replace(/[?#].*$/, "")) !== require_bundle_state.normalizeOutputPathKey(file));
2405
- const inferredSfcStyleSource = await resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outDir, opts.tailwindcssBasedir, getSfcSource, debug);
3375
+ const inferredSfcStyleSource = await resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outDir, opts.tailwindcssBasedir, opts.cssMatcher, getSfcSource, debug);
2406
3376
  if (inferredSfcStyleSource) {
2407
3377
  const inferredSourceFile = normalizeSfcSourceFileForCompare(inferredSfcStyleSource.sourceFile);
2408
3378
  const rememberedSourcesBelongToInferredSfc = rememberedCssSources.length > 0 && rememberedCssSources.every((remembered) => normalizeSfcSourceFileForCompare(remembered.sourceFile) === inferredSourceFile);
2409
3379
  if (!hasUsableRememberedTailwindSource || rememberedSourcesBelongToInferredSfc) rememberedCssSources = [inferredSfcStyleSource];
2410
3380
  }
3381
+ if (!rememberedCssSources.some((remembered) => hasTailwindGenerationSource(remembered.rawSource))) {
3382
+ const inferredSourceStyle = resolveSourceStyleSourceFromOutputFile(outputFile, snapshot, outDir, sourceRoot, getSourceCandidateSource, getSourceCandidateSources, configuredTailwindV4CssSourceEntries.map((entry) => [entry.file, entry.source]), debug);
3383
+ if (inferredSourceStyle) rememberedCssSources = [inferredSourceStyle];
3384
+ }
2411
3385
  const rememberedCssSource = mergeRememberedCssSources(rememberedCssSources, outputFile);
2412
- const useRememberedCssSource = rememberedCssSource != null && require_bundle_state.normalizeOutputPathKey(rememberedCssSource.sourceFile) !== require_bundle_state.normalizeOutputPathKey(file);
3386
+ const shouldKeepImportedCssShell = isCssImportOnlyBundleAsset(bundle, file, rawSource);
3387
+ const useRememberedCssSource = !shouldKeepImportedCssShell && rememberedCssSource != null && (require_bundle_state.normalizeOutputPathKey(rememberedCssSource.sourceFile) !== require_bundle_state.normalizeOutputPathKey(file) || !hasTailwindGenerationSource(rawSource) && hasTailwindGenerationSource(rememberedCssSource.rawSource));
2413
3388
  const vitePipelineCssAsset = viteProcessedCssAsset || useRememberedCssSource;
2414
3389
  const generatorRawSource = vitePipelineCssAsset ? rememberedCssSource?.rawSource ?? rawSource : rawSource;
2415
3390
  const hasRememberedApplySource = vitePipelineCssAsset && rememberedCssSource != null && require_v3_engine.hasTailwindApplyDirective(generatorRawSource);
2416
3391
  const hasDifferentRememberedCssSource = rememberedCssSource != null && normalizeCssSourceForCompare(rememberedCssSource.rawSource) !== normalizeCssSourceForCompare(rawSource);
2417
3392
  const hasCurrentTailwindGenerationDirective = require_v3_engine.hasTailwindSourceDirectives(rawSource, { importFallback: true }) || require_v3_engine.hasTailwindRootDirectives(rawSource, { importFallback: true }) || require_v3_engine.hasTailwindApplyDirective(rawSource);
3393
+ if (shouldKeepImportedCssShell && !hasCurrentTailwindGenerationDirective) {
3394
+ applyCssResult(rawSource);
3395
+ markCssAssetProcessed?.(originalSource, outputFile);
3396
+ recordCssAssetResult?.(outputFile, rawSource);
3397
+ onUpdate(outputFile, rawSource, rawSource);
3398
+ debug("css preserve imported shell asset: %s", outputFile);
3399
+ continue;
3400
+ }
2418
3401
  const hasRememberedApplyDirective = rememberedCssSource != null && require_v3_engine.hasTailwindApplyDirective(rememberedCssSource.rawSource);
2419
- const hasStaleViteProcessedCssSource = vitePipelineCssAsset && hasDifferentRememberedCssSource && (hasCurrentTailwindGenerationDirective || hasRememberedApplyDirective);
2420
- const generatorSourceFile = vitePipelineCssAsset ? rememberedCssSource?.sourceFile ?? file : file;
3402
+ const hasRememberedTailwindGenerationSource = rememberedCssSource != null && hasTailwindGenerationSource(rememberedCssSource.rawSource);
3403
+ const hasSameOutputRememberedTailwindGenerationSource = hasRememberedTailwindGenerationSource && rememberedCssSource != null && require_bundle_state.normalizeOutputPathKey(rememberedCssSource.outputFile) === require_bundle_state.normalizeOutputPathKey(outputFile);
3404
+ const hasStaleViteProcessedCssSource = vitePipelineCssAsset && hasDifferentRememberedCssSource && (hasCurrentTailwindGenerationDirective || hasRememberedApplyDirective || runtimeState.twPatcher.majorVersion === 4 && hasRememberedTailwindGenerationSource);
3405
+ const generatorSourceFile = vitePipelineCssAsset ? rememberedCssSource?.sourceFile ?? assetSourceFile : assetSourceFile;
2421
3406
  const outputCssHandlerOptions = getCssHandlerOptions(outputFile);
2422
3407
  const cssHandlerOptions = vitePipelineCssAsset ? {
2423
3408
  ...getCssHandlerOptions(generatorSourceFile),
2424
- isMainChunk: outputCssHandlerOptions.isMainChunk || isAppOriginCssFile(file) || isMainStyleEntryCssFile(generatorSourceFile)
3409
+ isMainChunk: outputCssHandlerOptions.isMainChunk
2425
3410
  } : getCssHandlerOptions(file);
2426
3411
  const scopedSourceCandidateGetter = createScopedSourceCandidateGetter(outputFile, cssHandlerOptions);
2427
3412
  const scopedSourceCandidateSourceGetter = createScopedSourceCandidateSourceGetter(outputFile, cssHandlerOptions);
2428
3413
  const sourceTraceTokenSources = scopedSourceCandidateSourceGetter ? require_hmr_timing.createCssTokenSourceMap(scopedSourceCandidateSourceGetter(void 0), opts) : void 0;
2429
3414
  const sourceTraceSignature = require_hmr_timing.createCssSourceTraceCacheSignature(sourceTraceTokenSources, opts);
2430
- const scopedGeneratorRuntime = createScopedGeneratorRuntime(outputFile, cssHandlerOptions, generatorRuntime);
3415
+ const scopedGeneratorRuntime = await createScopedGeneratorRuntime$1(outputFile, cssHandlerOptions, generatorRuntime, generatorRawSource, generatorSourceFile);
2431
3416
  const annotateCss = (css) => require_hmr_timing.annotateCssSourceTrace(css, {
2432
3417
  opts,
2433
3418
  tokenSources: sourceTraceTokenSources
@@ -2437,17 +3422,18 @@ function createGenerateBundleHook(context) {
2437
3422
  const cssRuntimeAffectingSignature = vitePipelineCssAsset ? require_bundle_state.createRuntimeAffectingSourceSignature(generatorRawSource, "css") : snapshot.runtimeAffectingSignatureByFile.get(file) ?? require_bundle_state.createRuntimeAffectingSourceSignature(generatorRawSource, "css");
2438
3423
  const cssRuntimeAffectingHash = vitePipelineCssAsset ? cache.computeHash(cssRuntimeAffectingSignature) : snapshot.runtimeAffectingHashByFile.get(file) ?? cache.computeHash(cssRuntimeAffectingSignature);
2439
3424
  const cssShareScope = createCssTransformShareScopeKey(opts, generatorSourceFile, generatorRawSource);
2440
- const shouldRegenerateAppOriginCss = viteProcessedCssAsset && isAppOriginCssFile(file);
2441
- const shouldTrackGeneratorRuntime = hasStaleViteProcessedCssSource || shouldRegenerateMainPackageCssWithScopedCandidates || hasCurrentTailwindGenerationDirective || shouldProcessTailwindGeneration && (!useIncrementalMode || cssHandlerOptions.isMainChunk || processFiles.css.has(file) || runtimeLinkedCssFiles.has(file) || shouldRegenerateAppOriginCss || hasRuntimeAffectingChanges && (alreadyProcessedCssAsset || vitePipelineCssAsset));
2442
- const shouldPreserveCollectedViteCssAsset = !shouldRegenerateAppOriginCss && (collectedBundlerGeneratedCssFiles.has(file) || require_bundle_state.hasBundlerGeneratedCssMarker(rawSource));
2443
- if (alreadyProcessedCssAsset && !hasStaleViteProcessedCssSource && !hasRememberedApplySource && !shouldRegenerateMainPackageCssWithScopedCandidates && (!shouldTrackGeneratorRuntime || shouldPreserveCollectedViteCssAsset)) {
3425
+ const shouldRegenerateCollectedViteCss = viteProcessedCssAsset && useIncrementalMode && state.generatorCandidateSignature !== void 0 && generatorCandidatesChanged && (hasTailwindGenerationSource(generatorRawSource) || require_bundle_state.hasBundlerGeneratedCssMarker(rawSource) || rememberedCssSource != null && hasTailwindGenerationSource(rememberedCssSource.rawSource));
3426
+ const shouldRefreshViteProcessedCssByCandidates = viteProcessedCssAsset && useIncrementalMode && state.generatorCandidateSignature !== void 0 && generatorCandidatesChanged;
3427
+ const shouldInjectVitePipelineCssIntoMain = vitePipelineCssAsset && outputCssHandlerOptions.isMainChunk !== true && shouldInjectCssIntoMainFromOutput(outputFile, generatorSourceFile, outputCssHandlerOptions);
3428
+ const shouldTrackGeneratorRuntime = hasStaleViteProcessedCssSource || shouldRegenerateMainPackageCssWithScopedCandidates || hasCurrentTailwindGenerationDirective || hasSameOutputRememberedTailwindGenerationSource || shouldProcessTailwindGeneration && (!useIncrementalMode || cssHandlerOptions.isMainChunk || processFiles.css.has(file) || runtimeLinkedCssFiles.has(file) || runtimeLinkedCssFiles.has(outputFile) || shouldRegenerateCollectedViteCss || hasRuntimeAffectingChanges && (alreadyProcessedCssAsset || vitePipelineCssAsset));
3429
+ const shouldPreserveCollectedViteCssAsset = !shouldRegenerateCollectedViteCss && (state.generatorCandidateSignature === void 0 || !generatorCandidatesChanged) && (collectedBundlerGeneratedCssFiles.has(file) || require_bundle_state.hasBundlerGeneratedCssMarker(rawSource));
3430
+ if (alreadyProcessedCssAsset && !shouldRefreshViteProcessedCssByCandidates && !hasStaleViteProcessedCssSource && !hasRememberedApplySource && !shouldRegenerateMainPackageCssWithScopedCandidates && (!shouldTrackGeneratorRuntime || shouldPreserveCollectedViteCssAsset)) {
2444
3431
  const nextCss = require_bundle_state.stripBundlerGeneratedCssMarkers(rawSource);
2445
3432
  applyCssResult(nextCss);
2446
3433
  markCssAssetProcessed?.(originalSource, outputFile);
2447
3434
  recordCssAssetResult?.(outputFile, nextCss);
2448
- const shouldInjectPreservedViteCssIntoMain = vitePipelineCssAsset && !isAppOriginCssFile(file) && shouldInjectCssIntoMainFromOutput(outputFile, generatorSourceFile, outputCssHandlerOptions);
2449
3435
  recordViteProcessedCssAssetResult?.(outputFile, nextCss, {
2450
- injectIntoMain: isAppOriginCssFile(file) ? false : shouldInjectPreservedViteCssIntoMain,
3436
+ injectIntoMain: outputCssHandlerOptions.isMainChunk ? false : shouldInjectVitePipelineCssIntoMain,
2451
3437
  outputFile
2452
3438
  });
2453
3439
  onUpdate(outputFile, rawSource, nextCss);
@@ -2455,12 +3441,18 @@ function createGenerateBundleHook(context) {
2455
3441
  continue;
2456
3442
  }
2457
3443
  const trackedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? createCandidateSignature(scopedGeneratorRuntime) : "generator:stable";
2458
- const scopedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? await createScopedGeneratorCandidateSignature(generatorRawSource, generatorSourceFile, trackedGeneratorCandidateSignature, scopedSourceCandidateGetter, { includeFallbackSignature: cssHandlerOptions.isMainChunk }) : trackedGeneratorCandidateSignature;
3444
+ const scopedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? await createScopedGeneratorCandidateSignature(generatorRawSource, generatorSourceFile, trackedGeneratorCandidateSignature, scopedSourceCandidateGetter, {
3445
+ includeFallbackSignature: cssHandlerOptions.isMainChunk,
3446
+ majorVersion: runtimeState.twPatcher.majorVersion
3447
+ }) : trackedGeneratorCandidateSignature;
2459
3448
  const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, scopedGeneratorCandidateSignature);
2460
3449
  const rememberedCssRuntimeSignature = createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash);
2461
3450
  const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}:${sourceTraceSignature}`;
2462
- if (!shouldTrackGeneratorRuntime) {
2463
- const lastCss = lastCssResultByFile.get(outputFile) ?? lastCssResultByFile.get(file);
3451
+ const cssCacheKey = file;
3452
+ const cssHashKey = `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`;
3453
+ const cssLinkedImpactSignature = runtimeLinkedCssFiles.has(file) || runtimeLinkedCssFiles.has(outputFile) ? [...[...snapshot.runtimeAffectingChangedByType.html].sort().map((changedFile) => snapshot.runtimeAffectingSignatureByFile.get(changedFile) ?? ""), ...[...snapshot.runtimeAffectingChangedByType.js].sort().map((changedFile) => snapshot.runtimeAffectingSignatureByFile.get(changedFile) ?? "")].join(":") : "";
3454
+ if (!shouldTrackGeneratorRuntime && !runtimeLinkedCssFiles.has(file) && !runtimeLinkedCssFiles.has(outputFile)) {
3455
+ const lastCss = getLastCssResult(lastCssResultByFile, outputFile, file);
2464
3456
  if (lastCss != null) {
2465
3457
  applyCssResult(lastCss);
2466
3458
  markCssAssetProcessed?.(originalSource, outputFile);
@@ -2469,14 +3461,15 @@ function createGenerateBundleHook(context) {
2469
3461
  continue;
2470
3462
  }
2471
3463
  }
2472
- tasks.push(timeTask("css", () => require_hmr_timing.processCachedTask({
3464
+ rememberProcessCacheKey(cssCacheKey, cssHashKey);
3465
+ cssTaskFactories.push(() => timeTask("css", () => require_hmr_timing.processCachedTask({
2473
3466
  cache,
2474
- cacheKey: file,
2475
- hashKey: `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
2476
- hash: `${cssRuntimeAffectingHash}:${scopedGeneratorCandidateSignature}:${sourceTraceSignature}`,
3467
+ cacheKey: cssCacheKey,
3468
+ hashKey: cssHashKey,
3469
+ hash: `${cssRuntimeAffectingHash}:${scopedGeneratorCandidateSignature}:${sourceTraceSignature}:${cssLinkedImpactSignature}`,
2477
3470
  applyResult(source) {
2478
3471
  applyCssResult(source);
2479
- lastCssResultByFile.set(outputFile, source);
3472
+ rememberLastCssResult(lastCssResultByFile, lastCssSourceHashByFile, outputFile, source, cssRuntimeAffectingHash);
2480
3473
  markCssAssetProcessed?.(originalSource, outputFile);
2481
3474
  if (rememberedCssSources.length <= 1) rememberCssSource?.({
2482
3475
  outputFile,
@@ -2513,21 +3506,20 @@ function createGenerateBundleHook(context) {
2513
3506
  getSourceCandidatesForEntries: scopedSourceCandidateGetter,
2514
3507
  styleHandler,
2515
3508
  debug,
2516
- previousCss: !vitePipelineCssAsset && useIncrementalMode && !hasRuntimeAffectingChanges && !snapshot.changedByType.css.has(file) ? lastCssResultByFile.get(outputFile) ?? lastCssResultByFile.get(file) : void 0
3509
+ previousCss: !vitePipelineCssAsset && useIncrementalMode && !hasRuntimeAffectingChanges && !snapshot.changedByType.css.has(file) ? getLastCssResult(lastCssResultByFile, outputFile, file) : void 0
2517
3510
  });
2518
3511
  if (generated) {
2519
3512
  const tracedCss = annotateCss(generated.css);
2520
3513
  registerGeneratorDependencies$1({ addWatchFile }, generated.dependencies);
2521
- if (debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, tracedCss));
3514
+ if (envFlags.debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, tracedCss));
2522
3515
  debug("css generated result: %s bytes=%d", file, tracedCss.length);
2523
3516
  recordCssAssetResult?.(outputFile, tracedCss);
2524
- const shouldInjectVitePipelineCssIntoMain = vitePipelineCssAsset && !isAppOriginCssFile(file) && shouldInjectCssIntoMainFromOutput(outputFile, generatorSourceFile, outputCssHandlerOptions);
2525
3517
  recordViteProcessedCssAssetResult?.(outputFile, tracedCss, {
2526
- injectIntoMain: isAppOriginCssFile(file) ? false : shouldInjectVitePipelineCssIntoMain,
3518
+ injectIntoMain: outputCssHandlerOptions.isMainChunk ? false : shouldInjectVitePipelineCssIntoMain,
2527
3519
  outputFile
2528
3520
  });
2529
3521
  if (vitePipelineCssAsset && shouldInjectVitePipelineCssIntoMain) recordViteProcessedCssAssetResult?.(file, tracedCss, {
2530
- injectIntoMain: isAppOriginCssFile(file) ? false : shouldInjectVitePipelineCssIntoMain,
3522
+ injectIntoMain: shouldInjectVitePipelineCssIntoMain,
2531
3523
  outputFile
2532
3524
  });
2533
3525
  metrics.css.elapsed += measureElapsed(start);
@@ -2543,7 +3535,7 @@ function createGenerateBundleHook(context) {
2543
3535
  }
2544
3536
  const { css } = await styleHandler(generatorRawSource, cssHandlerOptions);
2545
3537
  const tracedCss = annotateCss(css);
2546
- if (debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, tracedCss));
3538
+ if (envFlags.debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, tracedCss));
2547
3539
  metrics.css.elapsed += measureElapsed(start);
2548
3540
  metrics.css.transformed++;
2549
3541
  return tracedCss;
@@ -2559,251 +3551,128 @@ function createGenerateBundleHook(context) {
2559
3551
  continue;
2560
3552
  }
2561
3553
  if (type !== "js") continue;
2562
- metrics.js.total++;
2563
3554
  if (isWebGeneratorTarget) {
2564
3555
  debug("js skip web target: %s", file);
2565
3556
  continue;
2566
3557
  }
2567
- const shouldTransformJs = !useIncrementalMode || processFiles.js.has(file);
2568
- if (!shouldTransformJs) debug("js skip transform (clean), replay cache: %s", file);
2569
- if (originalSource.type === "chunk") {
2570
- const absoluteFile = node_path.default.resolve(outDir, file);
2571
- const initialRawSource = originalEntrySource;
2572
- const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
2573
- if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
2574
- jsTaskFactories.push(async () => {
2575
- await timeTask("js", async () => {
2576
- const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
2577
- await require_hmr_timing.processCachedTask({
2578
- cache,
2579
- cacheKey: file,
2580
- hashKey: `${file}:js`,
2581
- hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
2582
- applyResult(source) {
2583
- originalSource.code = source;
2584
- },
2585
- onCacheHit() {
2586
- metrics.js.cacheHits++;
2587
- debug("js cache hit: %s", file);
2588
- },
2589
- async transform() {
2590
- const start = performance.now();
2591
- const rawSource = originalSource.code;
2592
- if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
2593
- const handlerOptions = createHandlerOptions(absoluteFile);
2594
- if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(rawSource, handlerOptions)) {
2595
- metrics.js.elapsed += measureElapsed(start);
2596
- metrics.js.transformed++;
2597
- return { result: rawSource };
2598
- }
2599
- const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
2600
- metrics.js.elapsed += measureElapsed(start);
2601
- metrics.js.transformed++;
2602
- onUpdate(file, rawSource, code);
2603
- debug("js handle: %s", file);
2604
- collectLinkedFileNames(linked, getJsEntry, linkedSet);
2605
- applyLinkedUpdates(linked);
2606
- return { result: code };
2607
- }
2608
- });
2609
- });
2610
- });
2611
- } else if (uniAppX && originalSource.type === "asset") {
2612
- const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
2613
- if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
2614
- const baseApplyLinkedUpdates = applyLinkedUpdates;
2615
- const wrappedApplyLinkedUpdates = (linked) => {
2616
- collectLinkedFileNames(linked, getJsEntry, linkedSet);
2617
- baseApplyLinkedUpdates(linked);
2618
- };
2619
- const factory = createUniAppXAssetTask(file, originalSource, outDir, {
2620
- cache,
2621
- hashKey: `${file}:js`,
2622
- hashSalt: createJsHashSalt(runtimeSignature, [UNI_APP_X_STYLE_PLACEHOLDER_VERSION, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0].filter(Boolean).join(":")),
2623
- createHandlerOptions,
2624
- debug,
2625
- getAssetSource: createUniAppXBundleAssetSourceGetter(bundle),
2626
- jsHandler,
2627
- onUpdate,
2628
- runtimeSet: transformRuntime,
2629
- applyLinkedResults: wrappedApplyLinkedUpdates,
2630
- uniAppX
2631
- });
2632
- jsTaskFactories.push(async () => {
2633
- await timeTask("js", async () => {
2634
- const start = performance.now();
2635
- if (!shouldTransformJs) {
2636
- debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
2637
- await factory();
2638
- metrics.js.elapsed += measureElapsed(start);
2639
- metrics.js.transformed++;
2640
- return;
2641
- }
2642
- const currentSource = originalEntrySource;
2643
- const precheckOptions = createHandlerOptions(node_path.default.resolve(outDir, file), {
2644
- uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
2645
- babelParserOptions: {
2646
- plugins: ["typescript"],
2647
- sourceType: "unambiguous"
2648
- }
2649
- });
2650
- if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(currentSource, precheckOptions)) {
2651
- metrics.js.elapsed += measureElapsed(start);
2652
- metrics.js.transformed++;
2653
- return;
2654
- }
2655
- await factory();
2656
- metrics.js.elapsed += measureElapsed(start);
2657
- metrics.js.transformed++;
2658
- });
2659
- });
2660
- }
2661
- }
2662
- if (useIncrementalMode || isNativeAppStyleTarget) {
2663
- const rememberedReplayGroups = collectRememberedCssReplayGroups(getRememberedCssSources?.(), opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension);
2664
- for (const [outputFile, rememberedGroup] of rememberedReplayGroups) {
2665
- const refreshedRememberedGroup = await Promise.all(rememberedGroup.map(async (item) => ({
2666
- key: item.key,
2667
- remembered: await refreshRememberedCssSource?.(item.remembered) ?? item.remembered
2668
- })));
2669
- const rememberedCssSource = mergeRememberedCssSources(refreshedRememberedGroup.map((item) => item.remembered), outputFile);
2670
- if (!rememberedCssSource) continue;
2671
- const { rawSource, sourceFile } = rememberedCssSource;
2672
- const outputCssHandlerOptions = getCssHandlerOptions(outputFile);
2673
- const cssHandlerOptions = {
2674
- ...getCssHandlerOptions(sourceFile),
2675
- isMainChunk: outputCssHandlerOptions.isMainChunk || isMainStyleEntryCssFile(sourceFile)
2676
- };
2677
- const scopedSourceCandidateGetter = createScopedSourceCandidateGetter(outputFile, cssHandlerOptions);
2678
- const scopedSourceCandidateSourceGetter = createScopedSourceCandidateSourceGetter(outputFile, cssHandlerOptions);
2679
- const sourceTraceTokenSources = scopedSourceCandidateSourceGetter ? require_hmr_timing.createCssTokenSourceMap(scopedSourceCandidateSourceGetter(void 0), opts) : void 0;
2680
- const annotateCss = (css) => require_hmr_timing.annotateCssSourceTrace(css, {
2681
- opts,
2682
- tokenSources: sourceTraceTokenSources
2683
- });
2684
- const scopedGeneratorRuntime = createScopedGeneratorRuntime(outputFile, cssHandlerOptions, generatorRuntime);
2685
- const rememberedCssRuntimeSignature = createRememberedCssRuntimeSignature(createCssRuntimeSignature(createCandidateSignature(scopedGeneratorRuntime), await createScopedGeneratorCandidateSignature(rawSource, sourceFile, createCandidateSignature(scopedGeneratorRuntime), scopedSourceCandidateGetter, { includeFallbackSignature: cssHandlerOptions.isMainChunk })), cache.computeHash(require_bundle_state.createRuntimeAffectingSourceSignature(rawSource, "css")));
2686
- const rememberedKeys = refreshedRememberedGroup.map((item) => item.key);
2687
- const allRememberedSignaturesFresh = rememberedKeys.length > 0 && rememberedKeys.every((key) => getRememberedCssSignature?.(key) === rememberedCssRuntimeSignature);
2688
- if (bundleFiles.includes(outputFile) || bundleFiles.includes(sourceFile) || allRememberedSignaturesFresh) continue;
2689
- tasks.push(timeTask("css.replay", async () => {
2690
- const start = performance.now();
2691
- const generated = await require_hmr_timing.generateCssByGenerator({
2692
- opts,
2693
- runtimeState,
2694
- runtime: scopedGeneratorRuntime,
2695
- rawSource,
2696
- file: sourceFile,
2697
- cssHandlerOptions,
2698
- cssUserHandlerOptions: getCssUserHandlerOptions(sourceFile),
2699
- getSourceCandidatesForEntries: scopedSourceCandidateGetter,
2700
- styleHandler,
2701
- debug
2702
- });
2703
- const css = annotateCss(generated?.css ?? (await styleHandler(rawSource, cssHandlerOptions)).css);
2704
- for (const key of rememberedKeys) setRememberedCssSignature?.(key, rememberedCssRuntimeSignature);
2705
- if (generated) {
2706
- registerGeneratorDependencies$1({ addWatchFile }, generated.dependencies);
2707
- recordCssAssetResult?.(outputFile, css);
2708
- const shouldInjectReplayCssIntoMain = shouldInjectCssIntoMainFromOutput(outputFile, sourceFile, outputCssHandlerOptions);
2709
- recordViteProcessedCssAssetResult?.(sourceFile, css, {
2710
- injectIntoMain: isAppOriginCssFile(outputFile) ? false : shouldInjectReplayCssIntoMain,
2711
- outputFile
2712
- });
2713
- debug("css replay generated result: %s bytes=%d", outputFile, css.length);
2714
- }
2715
- const replayAsset = emitOrReplayCssAsset(outputFile, css);
2716
- markCssAssetProcessed?.(replayAsset, outputFile);
2717
- metrics.css.elapsed += measureElapsed(start);
2718
- metrics.css.transformed++;
2719
- onUpdate(outputFile, rawSource, css);
2720
- debug("css replay handle: %s", outputFile);
2721
- }));
2722
- }
2723
- }
2724
- require_bundle_state.pushConcurrentTaskFactories(tasks, jsTaskFactories);
2725
- const tasksStart = performance.now();
2726
- await Promise.all(tasks);
2727
- recordTimingDetail("tasks", tasksStart);
2728
- for (const apply of pendingLinkedUpdates) apply();
2729
- const applyStyleSources = collectUniAppXHarmonyApplyStyleSources(bundle);
2730
- if (opts.appType === "uni-app-x" || isNativeAppStyleTarget || isHarmonyAppStyleTarget) {
2731
- const getAssetSource = createUniAppXBundleAssetSourceGetter(bundle);
2732
- const viteProcessedCssSources = [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css);
2733
- const applyUtilities = collectUniAppXHarmonyApplyUtilities(bundle);
2734
- const shouldInjectHarmonyBundleStyles = isHarmonyAppStyleTarget;
2735
- if (shouldInjectHarmonyBundleStyles) {
2736
- if (applyUtilities.size > 0 && applyStyleSources.length > 0) {
2737
- const outputFile = "uni-app-x-harmony-apply.css";
2738
- const cssHandlerOptions = getCssHandlerOptions(outputFile);
2739
- const generated = await require_hmr_timing.generateCssByGenerator({
2740
- opts,
2741
- runtimeState,
2742
- runtime: new Set([...generatorRuntime, ...applyUtilities]),
2743
- rawSource: createUniAppXHarmonyApplyGeneratorSource(applyStyleSources, applyUtilities),
2744
- file: outputFile,
2745
- cssHandlerOptions,
2746
- cssUserHandlerOptions: {
2747
- ...cssHandlerOptions,
2748
- isMainChunk: false
2749
- },
2750
- getSourceCandidatesForEntries,
2751
- styleHandler,
2752
- debug
2753
- });
2754
- if (generated?.css) viteProcessedCssSources.push(require_hmr_timing.annotateCssSourceTrace(generated.css, {
2755
- opts,
2756
- tokenSources: getSourceCandidateSourcesForEntries ? require_hmr_timing.createCssTokenSourceMap(getSourceCandidateSourcesForEntries(void 0), opts) : void 0
2757
- }));
2758
- }
2759
- }
2760
- if (shouldInjectHarmonyBundleStyles && injectUniAppXHarmonyBundleStyles(bundle, { cssSources: viteProcessedCssSources })) debug("uni-app-x harmony bundle styles inject");
2761
- for (const [file, item] of Object.entries(bundle)) {
2762
- if (item.type !== "asset" || !file.endsWith(".uvue.ts")) continue;
2763
- const currentSource = String(item.source);
2764
- const nextSource = injectUniAppXStylePlaceholder(file, currentSource, getAssetSource);
2765
- if (nextSource !== currentSource) {
2766
- item.source = nextSource;
2767
- onUpdate(file, currentSource, nextSource);
2768
- debug("uni-app-x style placeholder inject: %s", file);
2769
- }
2770
- }
2771
- }
2772
- const syncViteProcessedCssIntoMainCssAssets = () => {
2773
- collectViteProcessedCssAssetResults(bundle, {
2774
- opts,
2775
- isViteProcessedCssAsset,
2776
- markCssAssetProcessed,
2777
- recordCssAssetResult,
2778
- recordViteProcessedCssAssetResult,
2779
- resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension),
2780
- debug
2781
- });
2782
- return injectViteProcessedCssIntoMainCssAssets(bundle, {
2783
- opts,
2784
- getViteProcessedCssAssetResults,
2785
- markCssAssetProcessed,
2786
- recordCssAssetResult,
3558
+ processJsBundleEntry({
3559
+ applyLinkedUpdates,
3560
+ bundle,
3561
+ cache,
3562
+ createHandlerOptions,
2787
3563
  debug,
2788
- onUpdate
3564
+ disableJsPrecheck: envFlags.disableJsPrecheck,
3565
+ entry,
3566
+ getJsEntry,
3567
+ jsHandler,
3568
+ jsTaskFactories,
3569
+ linkedByEntry,
3570
+ metrics,
3571
+ onUpdate,
3572
+ outDir,
3573
+ processFiles,
3574
+ rememberProcessCacheKey,
3575
+ runtimeSignature,
3576
+ snapshot,
3577
+ timeTask,
3578
+ transformRuntime,
3579
+ uniAppX,
3580
+ useIncrementalMode
2789
3581
  });
2790
- };
2791
- syncViteProcessedCssIntoMainCssAssets();
2792
- if (isHarmonyAppStyleTarget && applyStyleSources.length > 0) {
2793
- if (injectUniAppXHarmonyBundleStyles(bundle, { cssSources: [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css) })) debug("uni-app-x harmony bundle styles inject after css assets");
2794
- syncViteProcessedCssIntoMainCssAssets();
2795
- }
2796
- const stateUpdateStart = performance.now();
2797
- require_bundle_state.updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
2798
- state.generatorCandidateSignature = generatorCandidateSignature;
2799
- recordTimingDetail("state.update", stateUpdateStart);
2800
- debug("metrics iteration=%d runtime=%sms html(total=%d transform=%d hit=%d rate=%s elapsed=%sms) js(total=%d transform=%d hit=%d rate=%s elapsed=%sms) css(total=%d transform=%d hit=%d rate=%s elapsed=%sms)", useIncrementalMode ? state.iteration : 0, formatMs(metrics.runtimeSet), metrics.html.total, metrics.html.transformed, metrics.html.cacheHits, formatCacheHitRate(metrics.html), formatMs(metrics.html.elapsed), metrics.js.total, metrics.js.transformed, metrics.js.cacheHits, formatCacheHitRate(metrics.js), formatMs(metrics.js.elapsed), metrics.css.total, metrics.css.transformed, metrics.css.cacheHits, formatCacheHitRate(metrics.css), formatMs(metrics.css.elapsed));
2801
- if (hmrTimingRecorder) {
2802
- hmrTimingRecorder.record("generateBundle", performance.now() - hmrTimingStartedAt, timingDetails);
2803
- hmrTimingRecorder.emitTotal();
2804
3582
  }
2805
- onEnd();
2806
- debug("end");
3583
+ if (shouldProcessTailwindGeneration || useIncrementalMode || isNativeAppStyleTarget) await processRememberedCssReplay({
3584
+ addWatchFile,
3585
+ activeViteCssCacheFiles,
3586
+ bundle,
3587
+ bundleFiles,
3588
+ cache,
3589
+ createScopedGeneratorRuntime: createScopedGeneratorRuntime$1,
3590
+ createScopedSourceCandidateGetter,
3591
+ createScopedSourceCandidateSourceGetter,
3592
+ cssTaskFactories,
3593
+ debug,
3594
+ defaultStyleOutputExtension,
3595
+ emitOrReplayCssAsset,
3596
+ generatorRuntime,
3597
+ getCssHandlerOptions,
3598
+ getCssUserHandlerOptions,
3599
+ getRememberedCssSignature,
3600
+ getRememberedCssSources,
3601
+ isNativeAppStyleTarget,
3602
+ isWebGeneratorTarget,
3603
+ lastCssResultByFile,
3604
+ lastCssSourceHashByFile,
3605
+ markCssAssetProcessed,
3606
+ metrics,
3607
+ normalizeViteCssCacheKey,
3608
+ onUpdate,
3609
+ opts,
3610
+ recordCssAssetResult,
3611
+ recordViteProcessedCssAssetResult,
3612
+ refreshRememberedCssSource,
3613
+ rootDir,
3614
+ runtimeState,
3615
+ setRememberedCssSignature,
3616
+ shouldInjectCssIntoMainFromOutput,
3617
+ shouldPreserveAppCssExtension,
3618
+ sourceRoot,
3619
+ styleHandler,
3620
+ timeTask,
3621
+ useIncrementalMode
3622
+ });
3623
+ require_hmr_timing.pushConcurrentTaskFactories(tasks, jsTaskFactories);
3624
+ await finalizeGenerateBundle({
3625
+ activeProcessCacheKeys,
3626
+ activeProcessHashKeys,
3627
+ activeViteCssCacheFiles,
3628
+ bundle,
3629
+ bundleFiles,
3630
+ cache,
3631
+ cssTaskFactories,
3632
+ debug,
3633
+ defaultStyleOutputExtension,
3634
+ formatIteration: useIncrementalMode ? state.iteration : 0,
3635
+ generatorCandidateSignature,
3636
+ generatorRuntime,
3637
+ getCssHandlerOptions,
3638
+ getSourceCandidateSourcesForEntries,
3639
+ getSourceCandidatesForEntries,
3640
+ getViteCssCacheStats,
3641
+ getViteProcessedCssAssetResults,
3642
+ hmrTimingRecorder,
3643
+ hmrTimingStartedAt,
3644
+ isHarmonyAppStyleTarget,
3645
+ isNativeAppStyleTarget,
3646
+ isViteProcessedCssAsset,
3647
+ isWebGeneratorTarget,
3648
+ lastCssResultByFile,
3649
+ lastCssSourceHashByFile,
3650
+ linkedByEntry,
3651
+ markCssAssetProcessed,
3652
+ metrics,
3653
+ onEnd,
3654
+ onUpdate,
3655
+ opts,
3656
+ outDir,
3657
+ pendingLinkedUpdates,
3658
+ pruneViteCssCaches,
3659
+ recordCssAssetResult,
3660
+ recordTimingDetail,
3661
+ recordViteProcessedCssAssetResult,
3662
+ rootDir,
3663
+ runtime,
3664
+ runtimeState,
3665
+ shouldPreserveAppCssExtension,
3666
+ snapshot,
3667
+ sourceCandidates,
3668
+ sourceRoot,
3669
+ state,
3670
+ styleHandler,
3671
+ tasks,
3672
+ timingDetails,
3673
+ transformRuntime,
3674
+ useIncrementalMode
3675
+ });
2807
3676
  };
2808
3677
  }
2809
3678
  //#endregion
@@ -2863,6 +3732,7 @@ function createViteCssFinalizerOutputPlugin(context) {
2863
3732
  const isNativeAppStyleTarget = uniUtsPlatform.isApp || isHarmonyAppStyleTarget;
2864
3733
  if (resolvedConfig?.command !== "build" && !isNativeAppStyleTarget) return;
2865
3734
  const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
3735
+ const sourceRoot = resolveWeappViteSourceRoot(resolvedConfig, opts.appType) ?? resolveSourceRootFromBundleGraph(resolvedConfig, bundle);
2866
3736
  const sourceTraceTokenSources = getSourceCandidateSourcesForEntries ? require_hmr_timing.createCssTokenSourceMap(getSourceCandidateSourcesForEntries(void 0), opts) : void 0;
2867
3737
  const annotateCss = (css) => require_hmr_timing.annotateCssSourceTrace(css, {
2868
3738
  opts,
@@ -2875,7 +3745,7 @@ function createViteCssFinalizerOutputPlugin(context) {
2875
3745
  markCssAssetProcessed,
2876
3746
  recordCssAssetResult,
2877
3747
  recordViteProcessedCssAssetResult,
2878
- resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, isNativeAppStyleTarget),
3748
+ resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, isNativeAppStyleTarget, sourceRoot, resolveMiniProgramStyleOutputExtension({ files: Object.keys(bundle) }), Object.keys(bundle)),
2879
3749
  debug
2880
3750
  });
2881
3751
  };
@@ -2992,6 +3862,278 @@ function createViteCssFinalizerOutputPlugin(context) {
2992
3862
  };
2993
3863
  }
2994
3864
  //#endregion
3865
+ //#region src/bundlers/vite/map-cache.ts
3866
+ function touchMapEntry(map, key, value) {
3867
+ map.delete(key);
3868
+ map.set(key, value);
3869
+ }
3870
+ function pruneMapToMaxSize(map, maxSize, onDelete) {
3871
+ while (map.size > maxSize) {
3872
+ const key = map.keys().next().value;
3873
+ if (key === void 0) break;
3874
+ map.delete(key);
3875
+ onDelete?.(key);
3876
+ }
3877
+ }
3878
+ //#endregion
3879
+ //#region src/bundlers/vite/css-memory.ts
3880
+ const VITE_REMEMBERED_CSS_CACHE_MAX = 96;
3881
+ const VITE_KNOWN_SFC_SOURCE_CACHE_MAX = 128;
3882
+ const SFC_STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
3883
+ const SFC_COMPONENT_FILE_RE = /\.(?:vue|uvue|nvue|svelte|mpx)$/i;
3884
+ function stripSourceHash(sourceFile) {
3885
+ const hashIndex = sourceFile.indexOf("#");
3886
+ return hashIndex === -1 ? sourceFile : sourceFile.slice(0, hashIndex);
3887
+ }
3888
+ function normalizeCssSourceIdentity(sourceFile) {
3889
+ const cleanSourceFile = stripSourceHash(sourceFile);
3890
+ const { filename, query } = parseVueRequest(cleanSourceFile);
3891
+ const normalizedFile = require_bundle_state.normalizeOutputPathKey(filename);
3892
+ if (query.type === "style") return `${normalizedFile}?type=style&index=${query.index ?? 0}`;
3893
+ return require_bundle_state.normalizeOutputPathKey(require_bundle_state.stripRequestQuery(cleanSourceFile));
3894
+ }
3895
+ function hasSfcStyleBlocks(source) {
3896
+ SFC_STYLE_BLOCK_RE.lastIndex = 0;
3897
+ return SFC_STYLE_BLOCK_RE.test(source);
3898
+ }
3899
+ function extractSfcStyleBlock(source, index) {
3900
+ const targetIndex = index ?? 0;
3901
+ SFC_STYLE_BLOCK_RE.lastIndex = 0;
3902
+ let currentIndex = 0;
3903
+ let match = SFC_STYLE_BLOCK_RE.exec(source);
3904
+ while (match !== null) {
3905
+ if (currentIndex === targetIndex) return match[1] ?? "";
3906
+ currentIndex++;
3907
+ match = SFC_STYLE_BLOCK_RE.exec(source);
3908
+ }
3909
+ }
3910
+ function extractSfcStyleSource(source, index) {
3911
+ if (index !== void 0) return extractSfcStyleBlock(source, index);
3912
+ const styleSources = [];
3913
+ SFC_STYLE_BLOCK_RE.lastIndex = 0;
3914
+ let match = SFC_STYLE_BLOCK_RE.exec(source);
3915
+ while (match !== null) {
3916
+ styleSources.push(match[1] ?? "");
3917
+ match = SFC_STYLE_BLOCK_RE.exec(source);
3918
+ }
3919
+ return styleSources.length > 0 ? styleSources.join("\n") : void 0;
3920
+ }
3921
+ function normalizeKnownSfcSourceKey(file) {
3922
+ return require_bundle_state.normalizeOutputPathKey(node_path.default.resolve((0, _weapp_tailwindcss_shared.cleanUrl)(file)));
3923
+ }
3924
+ function shouldCollectTransformedSourceCandidates(id) {
3925
+ if (id.search(/[?#]/) < 0) return true;
3926
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
3927
+ return !SFC_COMPONENT_FILE_RE.test(file);
3928
+ }
3929
+ function createViteCssMemory(options) {
3930
+ const rememberedCssSources = /* @__PURE__ */ new Map();
3931
+ const rememberedCssSignatureByFile = /* @__PURE__ */ new Map();
3932
+ const knownSfcSources = /* @__PURE__ */ new Map();
3933
+ const rememberKnownSfcSource = (id, code) => {
3934
+ if (id.search(/[?#]/) >= 0) return;
3935
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
3936
+ if (!SFC_COMPONENT_FILE_RE.test(file)) return;
3937
+ if (!hasSfcStyleBlocks(code)) return;
3938
+ touchMapEntry(knownSfcSources, normalizeKnownSfcSourceKey(file), code);
3939
+ pruneMapToMaxSize(knownSfcSources, VITE_KNOWN_SFC_SOURCE_CACHE_MAX);
3940
+ };
3941
+ const getKnownSfcSource = (file) => {
3942
+ const scanSource = options.getSourceCandidateSource(file);
3943
+ if (scanSource && hasSfcStyleBlocks(scanSource)) return scanSource;
3944
+ const key = normalizeKnownSfcSourceKey(file);
3945
+ const source = knownSfcSources.get(key);
3946
+ if (source != null) touchMapEntry(knownSfcSources, key, source);
3947
+ return source;
3948
+ };
3949
+ const rememberCssSource = (entry, cssRuntimeSignature) => {
3950
+ const outputKey = require_bundle_state.normalizeOutputPathKey(entry.outputFile);
3951
+ const normalizedSourceFile = normalizeCssSourceIdentity(entry.sourceFile);
3952
+ const previousOutputEntry = rememberedCssSources.get(outputKey);
3953
+ const key = previousOutputEntry != null && normalizeCssSourceIdentity(previousOutputEntry.sourceFile) !== normalizedSourceFile ? `${outputKey}\0${normalizedSourceFile}` : outputKey;
3954
+ const previous = rememberedCssSources.get(key);
3955
+ touchMapEntry(rememberedCssSources, key, entry);
3956
+ const relatedRememberedEntries = [...rememberedCssSources].filter(([rememberedKey, remembered]) => rememberedKey !== key && normalizeCssSourceIdentity(remembered.sourceFile) === normalizedSourceFile);
3957
+ for (const [rememberedKey, remembered] of relatedRememberedEntries) {
3958
+ touchMapEntry(rememberedCssSources, rememberedKey, {
3959
+ ...remembered,
3960
+ rawSource: entry.rawSource,
3961
+ sourceFile: entry.sourceFile
3962
+ });
3963
+ rememberedCssSignatureByFile.delete(rememberedKey);
3964
+ }
3965
+ if (cssRuntimeSignature) rememberedCssSignatureByFile.set(key, cssRuntimeSignature);
3966
+ else if (previous?.rawSource !== entry.rawSource || previous?.sourceFile !== entry.sourceFile) rememberedCssSignatureByFile.delete(key);
3967
+ pruneMapToMaxSize(rememberedCssSources, VITE_REMEMBERED_CSS_CACHE_MAX, (rememberedKey) => {
3968
+ rememberedCssSignatureByFile.delete(String(rememberedKey));
3969
+ });
3970
+ };
3971
+ const refreshRememberedCssSourceEntry = (rememberedKey, remembered, sourceFile, rawSource) => {
3972
+ if (remembered.rawSource === rawSource && remembered.sourceFile === sourceFile) return remembered;
3973
+ const nextRemembered = {
3974
+ ...remembered,
3975
+ rawSource,
3976
+ sourceFile
3977
+ };
3978
+ touchMapEntry(rememberedCssSources, rememberedKey, nextRemembered);
3979
+ rememberedCssSignatureByFile.delete(rememberedKey);
3980
+ return nextRemembered;
3981
+ };
3982
+ const refreshRememberedCssSourceBySourceFile = (sourceFile, rawSource) => {
3983
+ const normalizedSourceFile = normalizeCssSourceIdentity(sourceFile);
3984
+ const relatedRememberedEntries = [...rememberedCssSources].filter(([, remembered]) => normalizeCssSourceIdentity(remembered.sourceFile) === normalizedSourceFile);
3985
+ for (const [rememberedKey, remembered] of relatedRememberedEntries) refreshRememberedCssSourceEntry(rememberedKey, remembered, sourceFile, rawSource);
3986
+ };
3987
+ const resolveCachedStyleSource = (sourceFile) => {
3988
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(require_bundle_state.stripRequestQuery(sourceFile));
3989
+ if (SFC_COMPONENT_FILE_RE.test(file)) return getKnownSfcSource(file);
3990
+ if (require_bundle_state.isSourceStyleRequest(file)) return options.getSourceCandidateSource(file);
3991
+ };
3992
+ const refreshRememberedCssSourceByCurrentFile = async (sourceFile) => {
3993
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(sourceFile);
3994
+ const normalizedSourceFile = require_bundle_state.normalizeOutputPathKey(file);
3995
+ const matchedRememberedSources = [...rememberedCssSources.values()].filter((remembered) => require_bundle_state.normalizeOutputPathKey(require_bundle_state.stripRequestQuery((0, _weapp_tailwindcss_shared.cleanUrl)(remembered.sourceFile))) === normalizedSourceFile);
3996
+ if (matchedRememberedSources.length === 0) return;
3997
+ const source = resolveCachedStyleSource(file);
3998
+ if (source == null) {
3999
+ options.debug("refresh remembered css source skipped: missing cached source for %s", file);
4000
+ return;
4001
+ }
4002
+ if (SFC_COMPONENT_FILE_RE.test(file)) {
4003
+ for (const remembered of matchedRememberedSources) {
4004
+ const { query } = parseVueRequest(remembered.sourceFile);
4005
+ const styleSource = extractSfcStyleSource(source, query.type === "style" ? query.index : void 0);
4006
+ if (styleSource !== void 0) refreshRememberedCssSourceBySourceFile(remembered.sourceFile, styleSource);
4007
+ }
4008
+ return;
4009
+ }
4010
+ if (require_bundle_state.isSourceStyleRequest(file)) refreshRememberedCssSourceBySourceFile(file, source);
4011
+ };
4012
+ const refreshRememberedCssSource = async (remembered) => {
4013
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(require_bundle_state.stripRequestQuery(remembered.sourceFile));
4014
+ const rememberedKey = [...rememberedCssSources.entries()].find(([, entry]) => entry === remembered)?.[0];
4015
+ if (!rememberedKey || !node_path.default.isAbsolute(file)) return;
4016
+ const source = resolveCachedStyleSource(file);
4017
+ if (source == null) {
4018
+ options.debug("refresh remembered css source before bundle replay skipped: missing cached source for %s", file);
4019
+ return;
4020
+ }
4021
+ if (SFC_COMPONENT_FILE_RE.test(file)) {
4022
+ const { query } = parseVueRequest(remembered.sourceFile);
4023
+ const styleSource = extractSfcStyleSource(source, query.type === "style" ? query.index : void 0);
4024
+ return styleSource === void 0 ? void 0 : refreshRememberedCssSourceEntry(rememberedKey, remembered, remembered.sourceFile, styleSource);
4025
+ }
4026
+ if (require_bundle_state.isSourceStyleRequest(file)) return refreshRememberedCssSourceEntry(rememberedKey, remembered, remembered.sourceFile, source);
4027
+ };
4028
+ const prune = (pruneOptions) => {
4029
+ const activeFiles = new Set([...pruneOptions.activeFiles].map(require_bundle_state.normalizeOutputPathKey));
4030
+ for (const [key, remembered] of rememberedCssSources) {
4031
+ const outputKey = require_bundle_state.normalizeOutputPathKey(remembered.outputFile);
4032
+ const sourceKey = require_bundle_state.normalizeOutputPathKey(remembered.sourceFile);
4033
+ if (!activeFiles.has(key) && !activeFiles.has(outputKey) && !activeFiles.has(sourceKey)) {
4034
+ rememberedCssSources.delete(key);
4035
+ rememberedCssSignatureByFile.delete(key);
4036
+ }
4037
+ }
4038
+ if (pruneOptions.activeKnownSfcFiles) {
4039
+ const activeKnownSfcFiles = new Set([...pruneOptions.activeKnownSfcFiles].map((file) => normalizeKnownSfcSourceKey(file)).filter((file) => SFC_COMPONENT_FILE_RE.test(file)));
4040
+ for (const key of knownSfcSources.keys()) if (!activeKnownSfcFiles.has(key)) knownSfcSources.delete(key);
4041
+ }
4042
+ pruneMapToMaxSize(rememberedCssSources, VITE_REMEMBERED_CSS_CACHE_MAX, (rememberedKey) => {
4043
+ rememberedCssSignatureByFile.delete(String(rememberedKey));
4044
+ });
4045
+ pruneMapToMaxSize(knownSfcSources, VITE_KNOWN_SFC_SOURCE_CACHE_MAX);
4046
+ };
4047
+ return {
4048
+ getKnownSfcSource,
4049
+ getRememberedCssSignature: (file) => rememberedCssSignatureByFile.get(require_bundle_state.normalizeOutputPathKey(file)),
4050
+ getRememberedCssSourceEntry: (file) => rememberedCssSources.get(require_bundle_state.normalizeOutputPathKey(file)),
4051
+ getRememberedCssSources: () => rememberedCssSources,
4052
+ getStats: () => ({
4053
+ rememberedCssSources: rememberedCssSources.size,
4054
+ rememberedCssSignatureByFile: rememberedCssSignatureByFile.size,
4055
+ knownSfcSources: knownSfcSources.size
4056
+ }),
4057
+ rememberCssSource,
4058
+ rememberKnownSfcSource,
4059
+ refreshRememberedCssSource,
4060
+ refreshRememberedCssSourceByCurrentFile,
4061
+ refreshRememberedCssSourceBySourceFile,
4062
+ setRememberedCssSignature: (file, cssRuntimeSignature) => {
4063
+ rememberedCssSignatureByFile.set(require_bundle_state.normalizeOutputPathKey(file), cssRuntimeSignature);
4064
+ },
4065
+ prune
4066
+ };
4067
+ }
4068
+ //#endregion
4069
+ //#region src/bundlers/vite/hot-css-modules.ts
4070
+ function resolveHotTailwindCssModules(ctx, tailwindRootCssModuleIds) {
4071
+ const modules = [];
4072
+ const seenModules = /* @__PURE__ */ new Set();
4073
+ const collectModule = (mod) => {
4074
+ if (mod == null || seenModules.has(mod)) return;
4075
+ if (!require_bundle_state.isSourceStyleRequest(mod.id ?? mod.url)) return;
4076
+ seenModules.add(mod);
4077
+ ctx.server.moduleGraph.invalidateModule(mod);
4078
+ modules.push(mod);
4079
+ };
4080
+ for (const id of tailwindRootCssModuleIds) {
4081
+ const candidates = [
4082
+ ctx.server.moduleGraph.getModuleById(id),
4083
+ ctx.server.moduleGraph.getModuleById((0, _weapp_tailwindcss_shared.cleanUrl)(id)),
4084
+ ...ctx.server.moduleGraph.getModulesByFile(id) ?? [],
4085
+ ...ctx.server.moduleGraph.getModulesByFile((0, _weapp_tailwindcss_shared.cleanUrl)(id)) ?? []
4086
+ ];
4087
+ for (const mod of candidates) collectModule(mod);
4088
+ }
4089
+ return modules;
4090
+ }
4091
+ function resolveModuleHotUrl(mod) {
4092
+ if (typeof mod.url === "string" && mod.url.length > 0) return mod.url;
4093
+ if (typeof mod.id === "string" && mod.id.startsWith("/")) return mod.id;
4094
+ }
4095
+ function includesHotModule(modules, target) {
4096
+ const targetUrl = resolveModuleHotUrl(target);
4097
+ const targetId = target.id;
4098
+ return modules.some((mod) => {
4099
+ if (mod === target) return true;
4100
+ return targetUrl !== void 0 && resolveModuleHotUrl(mod) === targetUrl || typeof targetId === "string" && targetId.length > 0 && mod.id === targetId;
4101
+ });
4102
+ }
4103
+ function hasSelfAcceptingNonStyleHotModule(modules) {
4104
+ return modules.some((mod) => {
4105
+ return !require_bundle_state.isSourceStyleRequest(mod.id ?? mod.url) && mod.isSelfAccepting === true;
4106
+ });
4107
+ }
4108
+ function sendSupplementalCssHotUpdates(ctx, cssModules) {
4109
+ const updates = cssModules.filter((mod) => !includesHotModule(ctx.modules, mod)).map((mod) => {
4110
+ const hotUrl = resolveModuleHotUrl(mod);
4111
+ if (!hotUrl) return;
4112
+ return {
4113
+ type: "js-update",
4114
+ timestamp: ctx.timestamp,
4115
+ path: hotUrl,
4116
+ acceptedPath: hotUrl,
4117
+ explicitImportRequired: false,
4118
+ isWithinCircularImport: false
4119
+ };
4120
+ }).filter((update) => update !== void 0);
4121
+ if (updates.length === 0) return;
4122
+ queueMicrotask(() => {
4123
+ ctx.server.ws?.send?.({
4124
+ type: "update",
4125
+ updates
4126
+ });
4127
+ });
4128
+ }
4129
+ function sendFullReloadForUnresolvedHotUpdate(ctx) {
4130
+ ctx.server.ws?.send?.({
4131
+ type: "full-reload",
4132
+ path: "*",
4133
+ triggeredBy: ctx.file
4134
+ });
4135
+ }
4136
+ //#endregion
2995
4137
  //#region src/bundlers/vite/official-tailwind-plugins.ts
2996
4138
  function isTailwindVitePlugin(plugin) {
2997
4139
  if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
@@ -3035,67 +4177,6 @@ function disableAndRemoveTailwindVitePlugins(plugins) {
3035
4177
  return removed;
3036
4178
  }
3037
4179
  //#endregion
3038
- //#region src/bundlers/vite/resolve-app-type.ts
3039
- const PACKAGE_JSON_FILE$1 = "package.json";
3040
- const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
3041
- const TARO_SCRIPT_RE = /\btaro\b/u;
3042
- const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
3043
- function resolveDependencyNames(pkg) {
3044
- return new Set([
3045
- ...Object.keys(pkg.dependencies ?? {}),
3046
- ...Object.keys(pkg.devDependencies ?? {}),
3047
- ...Object.keys(pkg.peerDependencies ?? {}),
3048
- ...Object.keys(pkg.optionalDependencies ?? {})
3049
- ]);
3050
- }
3051
- function hasScriptMatch(pkg, pattern) {
3052
- return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
3053
- }
3054
- function resolveAppTypeFromPackageJson(pkg) {
3055
- const dependencyNames = resolveDependencyNames(pkg);
3056
- if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
3057
- if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
3058
- if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
3059
- if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
3060
- if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
3061
- }
3062
- function tryReadUniAppManifest(root) {
3063
- const manifestPath = node_path.default.join(root, "manifest.json");
3064
- if (!(0, node_fs.existsSync)(manifestPath)) return;
3065
- try {
3066
- return JSON.parse((0, node_fs.readFileSync)(manifestPath, "utf8"));
3067
- } catch {}
3068
- }
3069
- function tryReadPackageJson(root) {
3070
- const packageJsonPath = node_path.default.join(root, PACKAGE_JSON_FILE$1);
3071
- if (!(0, node_fs.existsSync)(packageJsonPath)) return;
3072
- try {
3073
- return JSON.parse((0, node_fs.readFileSync)(packageJsonPath, "utf8"));
3074
- } catch {}
3075
- }
3076
- function resolveAppTypeFromMarkers(root) {
3077
- for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if ((0, node_fs.existsSync)(node_path.default.join(root, relativePath))) return appType;
3078
- }
3079
- function resolveImplicitAppTypeFromViteRoot(root) {
3080
- const resolvedRoot = node_path.default.resolve(root);
3081
- if (!(0, node_fs.existsSync)(resolvedRoot)) return;
3082
- const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
3083
- if (markerDetected) return markerDetected;
3084
- let current = resolvedRoot;
3085
- while (true) {
3086
- const manifest = tryReadUniAppManifest(current);
3087
- if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
3088
- const pkg = tryReadPackageJson(current);
3089
- if (pkg) {
3090
- const detected = resolveAppTypeFromPackageJson(pkg);
3091
- if (detected) return detected;
3092
- }
3093
- const parent = node_path.default.dirname(current);
3094
- if (parent === current) break;
3095
- current = parent;
3096
- }
3097
- }
3098
- //#endregion
3099
4180
  //#region src/bundlers/shared/css-imports.ts
3100
4181
  const tailwindcssImportRE = /^(?:tailwindcss|weapp-tailwindcss)(?:\/.*)?$/;
3101
4182
  const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])((?:tailwindcss|weapp-tailwindcss)(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
@@ -3363,7 +4444,7 @@ function isViteServeStyleRequest(id, command) {
3363
4444
  return command === "serve" && require_bundle_state.isSourceStyleRequest(id) && !SPECIAL_QUERY_RE.test(id) && !COMMON_JS_PROXY_RE.test(id);
3364
4445
  }
3365
4446
  function isViteServeCssRootRequest(id, command) {
3366
- return command === "serve" && require_bundle_state.isCSSRequest(id) && !SPECIAL_QUERY_RE.test(id) && !COMMON_JS_PROXY_RE.test(id);
4447
+ return command === "serve" && require_bundle_state.isSourceStyleRequest(id) && !SPECIAL_QUERY_RE.test(id) && !COMMON_JS_PROXY_RE.test(id);
3367
4448
  }
3368
4449
  function isViteCssHmrModule(code, id, command) {
3369
4450
  return isViteServeStyleRequest(id, command) && VITE_CSS_HMR_MODULE_RE.test(code) && /[?&](?:direct|vue)(?:&|$)/.test(id);
@@ -3405,33 +4486,7 @@ function createViteServeCssGenerationPlugins(options) {
3405
4486
  }];
3406
4487
  }
3407
4488
  //#endregion
3408
- //#region src/bundlers/vite/tailwind-basedir.ts
3409
- const PACKAGE_JSON_FILE = "package.json";
3410
- function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
3411
- const resolvedRoot = node_path.default.resolve(root);
3412
- if (!(0, node_fs.existsSync)(resolvedRoot)) return resolvedRoot;
3413
- const searchRoots = [];
3414
- let current = resolvedRoot;
3415
- while (true) {
3416
- searchRoots.push(current);
3417
- const parent = node_path.default.dirname(current);
3418
- if (parent === current) break;
3419
- current = parent;
3420
- }
3421
- const tailwindConfigPath = require_v3_engine.findTailwindConfig(searchRoots);
3422
- if (tailwindConfigPath) return node_path.default.dirname(tailwindConfigPath);
3423
- const packageRoot = require_v3_engine.findNearestPackageRoot(resolvedRoot);
3424
- if (packageRoot && (0, node_fs.existsSync)(node_path.default.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
3425
- return resolvedRoot;
3426
- }
3427
- //#endregion
3428
- //#region src/bundlers/vite/index.ts
3429
- const debug = require_v3_engine.createDebug();
3430
- const weappTailwindcssPackageDir = require_bundle_state.resolvePackageDir("weapp-tailwindcss");
3431
- const weappTailwindcssDirPosix = require_bundle_state.slash(weappTailwindcssPackageDir);
3432
- const sourceCandidateScanSnapshotCache = /* @__PURE__ */ new Map();
3433
- const SFC_STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
3434
- const SFC_COMPONENT_FILE_RE = /\.(?:vue|uvue|nvue|svelte|mpx)$/i;
4489
+ //#region src/bundlers/vite/source-candidate-scan-signature.ts
3435
4490
  function normalizeSignaturePath(value) {
3436
4491
  return require_bundle_state.slash(node_path.default.resolve(value));
3437
4492
  }
@@ -3459,20 +4514,35 @@ function createSourceCandidateScanSignature(input) {
3459
4514
  scanAllSources: input.scanAllSources ?? false
3460
4515
  });
3461
4516
  }
3462
- function stripSourceHash(sourceFile) {
3463
- const hashIndex = sourceFile.indexOf("#");
3464
- return hashIndex === -1 ? sourceFile : sourceFile.slice(0, hashIndex);
3465
- }
3466
- function isMainStyleEntryFile(file) {
3467
- const name = node_path.default.basename(require_bundle_state.stripRequestQuery((0, _weapp_tailwindcss_shared.cleanUrl)(file))).replace(/\.[^.]+$/, "");
3468
- return name === "app" || name === "main";
4517
+ //#endregion
4518
+ //#region src/bundlers/vite/tailwind-basedir.ts
4519
+ const PACKAGE_JSON_FILE = "package.json";
4520
+ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
4521
+ const resolvedRoot = node_path.default.resolve(root);
4522
+ if (!(0, node_fs.existsSync)(resolvedRoot)) return resolvedRoot;
4523
+ const searchRoots = [];
4524
+ let current = resolvedRoot;
4525
+ while (true) {
4526
+ searchRoots.push(current);
4527
+ const parent = node_path.default.dirname(current);
4528
+ if (parent === current) break;
4529
+ current = parent;
4530
+ }
4531
+ const tailwindConfigPath = require_v3_engine.findTailwindConfig(searchRoots);
4532
+ if (tailwindConfigPath) return node_path.default.dirname(tailwindConfigPath);
4533
+ const packageRoot = require_v3_engine.findNearestPackageRoot(resolvedRoot);
4534
+ if (packageRoot && (0, node_fs.existsSync)(node_path.default.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
4535
+ return resolvedRoot;
3469
4536
  }
3470
- function normalizeCssSourceIdentity(sourceFile) {
3471
- const cleanSourceFile = stripSourceHash(sourceFile);
3472
- const { filename, query } = parseVueRequest(cleanSourceFile);
3473
- const normalizedFile = require_bundle_state.normalizeOutputPathKey(filename);
3474
- if (query.type === "style") return `${normalizedFile}?type=style&index=${query.index ?? 0}`;
3475
- return require_bundle_state.normalizeOutputPathKey(require_bundle_state.stripRequestQuery(cleanSourceFile));
4537
+ //#endregion
4538
+ //#region src/bundlers/vite/index.ts
4539
+ const debug = require_v3_engine.createDebug();
4540
+ const weappTailwindcssPackageDir = require_bundle_state.resolvePackageDir("weapp-tailwindcss");
4541
+ const weappTailwindcssDirPosix = require_bundle_state.slash(weappTailwindcssPackageDir);
4542
+ const SOURCE_CANDIDATE_SCAN_CACHE_MAX = 8;
4543
+ const sourceCandidateScanSnapshotCache = new lru_cache.LRUCache({ max: SOURCE_CANDIDATE_SCAN_CACHE_MAX });
4544
+ function normalizeVitePersistentCacheKey(file) {
4545
+ return require_bundle_state.normalizeOutputPathKey(file);
3476
4546
  }
3477
4547
  /**
3478
4548
  * @name WeappTailwindcss
@@ -3507,6 +4577,7 @@ function WeappTailwindcss(options = {}) {
3507
4577
  cssEntries: opts.cssEntries ?? options.cssEntries
3508
4578
  });
3509
4579
  const autoCssSourceContent = /* @__PURE__ */ new Map();
4580
+ const transientAutoCssSources = /* @__PURE__ */ new Map();
3510
4581
  let refreshRuntimeStateForAutoCssSources;
3511
4582
  let autoCssSourcesRefresh;
3512
4583
  let autoCssSourcesDiscovered = false;
@@ -3515,7 +4586,7 @@ function WeappTailwindcss(options = {}) {
3515
4586
  cacheCurrentSourceCandidateScan();
3516
4587
  };
3517
4588
  const registerAutoCssSource = async (id, css, options = {}) => {
3518
- if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots) return;
4589
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration) return;
3519
4590
  const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
3520
4591
  if (!node_path.default.isAbsolute(file)) return;
3521
4592
  const sourceFile = node_path.default.normalize(file);
@@ -3524,11 +4595,24 @@ function WeappTailwindcss(options = {}) {
3524
4595
  if (autoCssSourceContent.get(sourceFile) === sourceCss) return;
3525
4596
  autoCssSourceContent.set(sourceFile, sourceCss);
3526
4597
  await syncTailwindCssSourceCandidates(sourceFile, sourceCss);
4598
+ const transientSource = {
4599
+ file: sourceFile,
4600
+ base: sourceBase,
4601
+ css: sourceCss,
4602
+ dependencies: []
4603
+ };
4604
+ if (hasInitialTailwindCssRoots) {
4605
+ transientAutoCssSources.set(sourceFile, transientSource);
4606
+ return;
4607
+ }
4608
+ const dependencies = await require_v3_engine.resolveViteTailwindV4CssDependencies(sourceCss, sourceBase);
4609
+ transientSource.dependencies = dependencies;
4610
+ transientAutoCssSources.set(sourceFile, transientSource);
3527
4611
  if (!require_tailwindcss.upsertTailwindV4CssSource(opts, {
3528
4612
  file: sourceFile,
3529
4613
  base: sourceBase,
3530
4614
  css: sourceCss,
3531
- dependencies: await require_v3_engine.resolveViteTailwindV4CssDependencies(sourceCss, sourceBase)
4615
+ dependencies
3532
4616
  })) return;
3533
4617
  invalidateSourceCandidateScan();
3534
4618
  debug("detected tailwindcss v4 css source from vite css module: %s", sourceFile);
@@ -3570,7 +4654,7 @@ function WeappTailwindcss(options = {}) {
3570
4654
  bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues,
3571
4655
  extractor: sourceCandidateExtractor
3572
4656
  });
3573
- const sourceCandidateScanCache = /* @__PURE__ */ new Map();
4657
+ const sourceCandidateScanCache = new lru_cache.LRUCache({ max: SOURCE_CANDIDATE_SCAN_CACHE_MAX });
3574
4658
  let sourceScanEntries;
3575
4659
  let sourceScanMatcher;
3576
4660
  let sourceScanDependencies = /* @__PURE__ */ new Set();
@@ -3583,9 +4667,10 @@ function WeappTailwindcss(options = {}) {
3583
4667
  const viteProcessedCssSourceFiles = /* @__PURE__ */ new Set();
3584
4668
  const viteGeneratedCssByFile = /* @__PURE__ */ new Map();
3585
4669
  const viteProcessedCssAssetResults = /* @__PURE__ */ new Map();
3586
- const rememberedCssSources = /* @__PURE__ */ new Map();
3587
- const rememberedCssSignatureByFile = /* @__PURE__ */ new Map();
3588
- const knownSfcSources = /* @__PURE__ */ new Map();
4670
+ const cssMemory = createViteCssMemory({
4671
+ debug,
4672
+ getSourceCandidateSource: (file) => sourceCandidateCollector.source(file)
4673
+ });
3589
4674
  const tailwindRootCssModuleIds = /* @__PURE__ */ new Set();
3590
4675
  const { runtimeState, refreshRuntimeState, ensureRuntimeClassSet, ensureBundleRuntimeClassSet } = createViteRuntimeClassSet({
3591
4676
  opts,
@@ -3634,7 +4719,7 @@ function WeappTailwindcss(options = {}) {
3634
4719
  explicit: sourceScanExplicit,
3635
4720
  root
3636
4721
  }];
3637
- if (sourceScanExplicit) return [];
4722
+ if (sourceScanExplicit && entries !== void 0) return [];
3638
4723
  const roots = [{
3639
4724
  entries,
3640
4725
  root
@@ -3711,7 +4796,8 @@ function WeappTailwindcss(options = {}) {
3711
4796
  sourceCandidateScanInvalidated = false;
3712
4797
  return;
3713
4798
  }
3714
- sourceCandidateCollector.clear();
4799
+ if (isWatchLikeBuild()) sourceCandidateCollector.resetScan();
4800
+ else sourceCandidateCollector.clearScan();
3715
4801
  sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
3716
4802
  await scanSourceCandidateRoots(roots, outDir);
3717
4803
  sourceCandidateScanSignature = nextScanSignature;
@@ -3731,14 +4817,10 @@ function WeappTailwindcss(options = {}) {
3731
4817
  if (sourceScanMatcher && !sourceScanMatcher(file)) {
3732
4818
  sourceCandidateCollector.remove(file);
3733
4819
  cacheCurrentSourceCandidateScan();
3734
- return refreshRememberedCssSourceByCurrentFile(file);
3735
- }
3736
- if (sourceScanExplicit && sourceScanEntries?.length === 0) {
3737
- cacheCurrentSourceCandidateScan();
3738
- return refreshRememberedCssSourceByCurrentFile(file);
4820
+ return cssMemory.refreshRememberedCssSourceByCurrentFile(file);
3739
4821
  }
3740
4822
  const existingTask = pendingSourceCandidateSyncByFile.get(file);
3741
- if (existingTask) return existingTask.then(() => refreshRememberedCssSourceByCurrentFile(file)).then(() => void 0);
4823
+ if (existingTask) return existingTask.then(() => cssMemory.refreshRememberedCssSourceByCurrentFile(file)).then(() => void 0);
3742
4824
  const task = sourceCandidateCollector.syncCurrentFile(id).catch((error) => {
3743
4825
  debug("source candidate watch sync failed: %s %O", id, error);
3744
4826
  }).then(() => {
@@ -3749,150 +4831,39 @@ function WeappTailwindcss(options = {}) {
3749
4831
  });
3750
4832
  pendingSourceCandidateSyncs.add(task);
3751
4833
  pendingSourceCandidateSyncByFile.set(file, task);
3752
- return task.then(() => refreshRememberedCssSourceByCurrentFile(file)).then(() => void 0);
3753
- };
3754
- const shouldCollectTransformedSourceCandidates = (id) => {
3755
- if (id.search(/[?#]/) < 0) return true;
3756
- const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
3757
- return !SFC_COMPONENT_FILE_RE.test(file);
3758
- };
3759
- const hasSfcStyleBlocks = (source) => {
3760
- SFC_STYLE_BLOCK_RE.lastIndex = 0;
3761
- return SFC_STYLE_BLOCK_RE.test(source);
3762
- };
3763
- const normalizeKnownSfcSourceKey = (file) => require_bundle_state.normalizeOutputPathKey(node_path.default.resolve((0, _weapp_tailwindcss_shared.cleanUrl)(file)));
3764
- const rememberKnownSfcSource = (id, code) => {
3765
- if (id.search(/[?#]/) >= 0) return;
3766
- const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
3767
- if (!SFC_COMPONENT_FILE_RE.test(file)) return;
3768
- if (!hasSfcStyleBlocks(code)) return;
3769
- knownSfcSources.set(normalizeKnownSfcSourceKey(file), code);
3770
- };
3771
- const getKnownSfcSource = (file) => {
3772
- const scanSource = sourceCandidateCollector.source(file);
3773
- if (scanSource && hasSfcStyleBlocks(scanSource)) return scanSource;
3774
- return knownSfcSources.get(normalizeKnownSfcSourceKey(file));
3775
- };
3776
- const rememberCssSource = (entry, cssRuntimeSignature) => {
3777
- const outputKey = require_bundle_state.normalizeOutputPathKey(entry.outputFile);
3778
- const normalizedSourceFile = normalizeCssSourceIdentity(entry.sourceFile);
3779
- const previousOutputEntry = rememberedCssSources.get(outputKey);
3780
- const key = previousOutputEntry != null && normalizeCssSourceIdentity(previousOutputEntry.sourceFile) !== normalizedSourceFile ? `${outputKey}\0${normalizedSourceFile}` : outputKey;
3781
- const previous = rememberedCssSources.get(key);
3782
- rememberedCssSources.set(key, entry);
3783
- for (const [rememberedKey, remembered] of rememberedCssSources) {
3784
- if (rememberedKey === key || normalizeCssSourceIdentity(remembered.sourceFile) !== normalizedSourceFile) continue;
3785
- rememberedCssSources.set(rememberedKey, {
3786
- ...remembered,
3787
- rawSource: entry.rawSource,
3788
- sourceFile: entry.sourceFile
3789
- });
3790
- rememberedCssSignatureByFile.delete(rememberedKey);
3791
- }
3792
- if (cssRuntimeSignature) rememberedCssSignatureByFile.set(key, cssRuntimeSignature);
3793
- else if (previous?.rawSource !== entry.rawSource || previous?.sourceFile !== entry.sourceFile) rememberedCssSignatureByFile.delete(key);
3794
- };
3795
- const refreshRememberedCssSourceEntry = (rememberedKey, remembered, sourceFile, rawSource) => {
3796
- if (remembered.rawSource === rawSource && remembered.sourceFile === sourceFile) return remembered;
3797
- const nextRemembered = {
3798
- ...remembered,
3799
- rawSource,
3800
- sourceFile
3801
- };
3802
- rememberedCssSources.set(rememberedKey, nextRemembered);
3803
- rememberedCssSignatureByFile.delete(rememberedKey);
3804
- return nextRemembered;
3805
- };
3806
- const refreshRememberedCssSourceBySourceFile = (sourceFile, rawSource) => {
3807
- const normalizedSourceFile = normalizeCssSourceIdentity(sourceFile);
3808
- for (const [rememberedKey, remembered] of rememberedCssSources) {
3809
- if (normalizeCssSourceIdentity(remembered.sourceFile) !== normalizedSourceFile) continue;
3810
- refreshRememberedCssSourceEntry(rememberedKey, remembered, sourceFile, rawSource);
3811
- }
3812
- };
3813
- const extractSfcStyleBlock = (source, index) => {
3814
- const targetIndex = index ?? 0;
3815
- SFC_STYLE_BLOCK_RE.lastIndex = 0;
3816
- let currentIndex = 0;
3817
- let match = SFC_STYLE_BLOCK_RE.exec(source);
3818
- while (match !== null) {
3819
- if (currentIndex === targetIndex) return match[1] ?? "";
3820
- currentIndex++;
3821
- match = SFC_STYLE_BLOCK_RE.exec(source);
3822
- }
3823
- };
3824
- const extractSfcStyleSource = (source, index) => {
3825
- if (index !== void 0) return extractSfcStyleBlock(source, index);
3826
- const styleSources = [];
3827
- SFC_STYLE_BLOCK_RE.lastIndex = 0;
3828
- let match = SFC_STYLE_BLOCK_RE.exec(source);
3829
- while (match !== null) {
3830
- styleSources.push(match[1] ?? "");
3831
- match = SFC_STYLE_BLOCK_RE.exec(source);
3832
- }
3833
- return styleSources.length > 0 ? styleSources.join("\n") : void 0;
3834
- };
3835
- const resolveCachedStyleSource = (sourceFile) => {
3836
- const file = (0, _weapp_tailwindcss_shared.cleanUrl)(require_bundle_state.stripRequestQuery(sourceFile));
3837
- if (SFC_COMPONENT_FILE_RE.test(file)) return getKnownSfcSource(file);
3838
- if (require_bundle_state.isSourceStyleRequest(file)) return sourceCandidateCollector.source(file);
3839
- };
3840
- const refreshRememberedCssSourceByCurrentFile = async (sourceFile) => {
3841
- const file = (0, _weapp_tailwindcss_shared.cleanUrl)(sourceFile);
3842
- const normalizedSourceFile = require_bundle_state.normalizeOutputPathKey(file);
3843
- const matchedRememberedSources = [...rememberedCssSources.values()].filter((remembered) => require_bundle_state.normalizeOutputPathKey(require_bundle_state.stripRequestQuery((0, _weapp_tailwindcss_shared.cleanUrl)(remembered.sourceFile))) === normalizedSourceFile);
3844
- if (matchedRememberedSources.length === 0) return;
3845
- const source = resolveCachedStyleSource(file);
3846
- if (source == null) {
3847
- debug("refresh remembered css source skipped: missing cached source for %s", file);
3848
- return;
3849
- }
3850
- if (SFC_COMPONENT_FILE_RE.test(file)) {
3851
- for (const remembered of matchedRememberedSources) {
3852
- const { query } = parseVueRequest(remembered.sourceFile);
3853
- const styleSource = extractSfcStyleSource(source, query.type === "style" ? query.index : void 0);
3854
- if (styleSource !== void 0) refreshRememberedCssSourceBySourceFile(remembered.sourceFile, styleSource);
3855
- }
3856
- return;
3857
- }
3858
- if (require_bundle_state.isSourceStyleRequest(file)) refreshRememberedCssSourceBySourceFile(file, source);
3859
- };
3860
- const refreshRememberedCssSource = async (remembered) => {
3861
- const file = (0, _weapp_tailwindcss_shared.cleanUrl)(require_bundle_state.stripRequestQuery(remembered.sourceFile));
3862
- const rememberedKey = [...rememberedCssSources.entries()].find(([, entry]) => entry === remembered)?.[0];
3863
- if (!rememberedKey || !node_path.default.isAbsolute(file)) return;
3864
- const source = resolveCachedStyleSource(file);
3865
- if (source == null) {
3866
- debug("refresh remembered css source before bundle replay skipped: missing cached source for %s", file);
3867
- return;
3868
- }
3869
- if (SFC_COMPONENT_FILE_RE.test(file)) {
3870
- const { query } = parseVueRequest(remembered.sourceFile);
3871
- const styleSource = extractSfcStyleSource(source, query.type === "style" ? query.index : void 0);
3872
- return styleSource === void 0 ? void 0 : refreshRememberedCssSourceEntry(rememberedKey, remembered, remembered.sourceFile, styleSource);
3873
- }
3874
- if (require_bundle_state.isSourceStyleRequest(file)) return refreshRememberedCssSourceEntry(rememberedKey, remembered, remembered.sourceFile, source);
3875
- };
3876
- const getRememberedCssSources = () => rememberedCssSources;
3877
- const getRememberedCssSourceEntry = (file) => rememberedCssSources.get(require_bundle_state.normalizeOutputPathKey(file));
3878
- const getRememberedCssSignature = (file) => rememberedCssSignatureByFile.get(require_bundle_state.normalizeOutputPathKey(file));
3879
- const setRememberedCssSignature = (file, cssRuntimeSignature) => {
3880
- rememberedCssSignatureByFile.set(require_bundle_state.normalizeOutputPathKey(file), cssRuntimeSignature);
4834
+ return task.then(() => cssMemory.refreshRememberedCssSourceByCurrentFile(file)).then(() => void 0);
3881
4835
  };
3882
4836
  const recordCssAssetResult = (file, css) => {
3883
- viteGeneratedCssByFile.set(file, css);
4837
+ touchMapEntry(viteGeneratedCssByFile, normalizeVitePersistentCacheKey(file), css);
3884
4838
  };
3885
4839
  const recordViteProcessedCssAssetResult = (file, css, options = {}) => {
3886
- const key = require_bundle_state.normalizeOutputPathKey(file);
4840
+ const key = normalizeVitePersistentCacheKey(file);
3887
4841
  const previous = viteProcessedCssAssetResults.get(key);
3888
- viteProcessedCssAssetResults.set(key, {
4842
+ touchMapEntry(viteProcessedCssAssetResults, key, {
3889
4843
  css,
3890
- injectIntoMain: options.injectIntoMain ?? previous?.injectIntoMain,
4844
+ injectIntoMain: previous?.injectIntoMain === true ? true : options.injectIntoMain ?? previous?.injectIntoMain,
3891
4845
  outputFile: options.outputFile ?? previous?.outputFile
3892
4846
  });
3893
4847
  };
3894
4848
  const getViteProcessedCssAssetResults = () => viteProcessedCssAssetResults.entries();
3895
- const getViteProcessedCssAssetResult = (file) => viteProcessedCssAssetResults.get(require_bundle_state.normalizeOutputPathKey(file));
4849
+ const getViteProcessedCssAssetResult = (file) => viteProcessedCssAssetResults.get(normalizeVitePersistentCacheKey(file));
4850
+ const getViteCssCacheStats = () => ({
4851
+ viteGeneratedCssByFile: viteGeneratedCssByFile.size,
4852
+ viteProcessedCssAssetResults: viteProcessedCssAssetResults.size,
4853
+ ...cssMemory.getStats(),
4854
+ sourceCandidateScanCache: sourceCandidateScanCache.size,
4855
+ pendingSourceCandidateSyncs: pendingSourceCandidateSyncs.size,
4856
+ pendingSourceCandidateSyncByFile: pendingSourceCandidateSyncByFile.size
4857
+ });
4858
+ const pruneViteCssCaches = (options) => {
4859
+ const activeFiles = new Set([...options.activeFiles].map(normalizeVitePersistentCacheKey));
4860
+ for (const key of viteGeneratedCssByFile.keys()) if (!activeFiles.has(key)) viteGeneratedCssByFile.delete(key);
4861
+ for (const [key, record] of viteProcessedCssAssetResults) {
4862
+ const outputKey = typeof record.outputFile === "string" ? normalizeVitePersistentCacheKey(record.outputFile) : void 0;
4863
+ if (!activeFiles.has(key) && (outputKey == null || !activeFiles.has(outputKey))) viteProcessedCssAssetResults.delete(key);
4864
+ }
4865
+ cssMemory.prune(options);
4866
+ };
3896
4867
  const normalizeViteProcessedCssFile = (file) => node_path.default.resolve((0, _weapp_tailwindcss_shared.cleanUrl)(file));
3897
4868
  const markViteProcessedCssSource = (file) => {
3898
4869
  viteProcessedCssSourceFiles.add(normalizeViteProcessedCssFile(file));
@@ -3902,44 +4873,6 @@ function WeappTailwindcss(options = {}) {
3902
4873
  tailwindRootCssModuleIds.add(id);
3903
4874
  tailwindRootCssModuleIds.add((0, _weapp_tailwindcss_shared.cleanUrl)(id));
3904
4875
  };
3905
- const resolveHotTailwindCssModules = (ctx) => {
3906
- const modules = [];
3907
- const seenModules = /* @__PURE__ */ new Set();
3908
- const collectModule = (mod) => {
3909
- if (mod == null || seenModules.has(mod)) return;
3910
- if (!require_bundle_state.isSourceStyleRequest(mod.id ?? mod.url)) return;
3911
- seenModules.add(mod);
3912
- ctx.server.moduleGraph.invalidateModule(mod);
3913
- modules.push(mod);
3914
- };
3915
- for (const id of tailwindRootCssModuleIds) {
3916
- const candidates = [
3917
- ctx.server.moduleGraph.getModuleById(id),
3918
- ctx.server.moduleGraph.getModuleById((0, _weapp_tailwindcss_shared.cleanUrl)(id)),
3919
- ...ctx.server.moduleGraph.getModulesByFile(id) ?? [],
3920
- ...ctx.server.moduleGraph.getModulesByFile((0, _weapp_tailwindcss_shared.cleanUrl)(id)) ?? []
3921
- ];
3922
- for (const mod of candidates) collectModule(mod);
3923
- }
3924
- return modules;
3925
- };
3926
- const resolveModuleHotUrl = (mod) => {
3927
- if (typeof mod.url === "string" && mod.url.length > 0) return mod.url;
3928
- if (typeof mod.id === "string" && mod.id.startsWith("/")) return mod.id;
3929
- };
3930
- const includesHotModule = (modules, target) => {
3931
- const targetUrl = resolveModuleHotUrl(target);
3932
- const targetId = target.id;
3933
- return modules.some((mod) => {
3934
- if (mod === target) return true;
3935
- return targetUrl !== void 0 && resolveModuleHotUrl(mod) === targetUrl || typeof targetId === "string" && targetId.length > 0 && mod.id === targetId;
3936
- });
3937
- };
3938
- const hasSelfAcceptingNonStyleHotModule = (modules) => {
3939
- return modules.some((mod) => {
3940
- return !require_bundle_state.isSourceStyleRequest(mod.id ?? mod.url) && mod.isSelfAccepting === true;
3941
- });
3942
- };
3943
4876
  const isUniViteProject = () => {
3944
4877
  return resolvedConfig?.plugins?.some((plugin) => plugin.name.includes("uni")) ?? false;
3945
4878
  };
@@ -3947,34 +4880,6 @@ function WeappTailwindcss(options = {}) {
3947
4880
  if (require_utils.resolveUniUtsPlatform().isAppHarmony) return true;
3948
4881
  return isUniAppXHarmonyOutDir(resolvedConfig?.build?.outDir);
3949
4882
  };
3950
- const sendSupplementalCssHotUpdates = (ctx, cssModules) => {
3951
- const updates = cssModules.filter((mod) => !includesHotModule(ctx.modules, mod)).map((mod) => {
3952
- const hotUrl = resolveModuleHotUrl(mod);
3953
- if (!hotUrl) return;
3954
- return {
3955
- type: "js-update",
3956
- timestamp: ctx.timestamp,
3957
- path: hotUrl,
3958
- acceptedPath: hotUrl,
3959
- explicitImportRequired: false,
3960
- isWithinCircularImport: false
3961
- };
3962
- }).filter((update) => update !== void 0);
3963
- if (updates.length === 0) return;
3964
- queueMicrotask(() => {
3965
- ctx.server.ws?.send?.({
3966
- type: "update",
3967
- updates
3968
- });
3969
- });
3970
- };
3971
- const sendFullReloadForUnresolvedHotUpdate = (ctx) => {
3972
- ctx.server.ws?.send?.({
3973
- type: "full-reload",
3974
- path: "*",
3975
- triggeredBy: ctx.file
3976
- });
3977
- };
3978
4883
  const matchesViteProcessedCssSource = (candidate) => {
3979
4884
  const normalized = normalizeViteProcessedCssFile(candidate);
3980
4885
  return viteProcessedCssSourceFiles.has(normalized);
@@ -3992,7 +4897,10 @@ function WeappTailwindcss(options = {}) {
3992
4897
  mainCssChunkMatcher,
3993
4898
  getMajorVersion: () => runtimeState.twPatcher.majorVersion,
3994
4899
  getOutputRoot: () => resolvedConfig?.build?.outDir ? node_path.default.resolve(resolvedConfig.root, resolvedConfig.build.outDir) : resolvedConfig?.root,
3995
- getExtraOptions: () => resolveUniAppXNativeCssHandlerOptions(opts)
4900
+ getExtraOptions: (file) => ({
4901
+ ...resolveViteCssHandlerExtraOptions(file),
4902
+ ...resolveUniAppXNativeCssHandlerOptions(opts)
4903
+ })
3996
4904
  });
3997
4905
  const generateTailwindCssForVitePipeline = async (id, code, hookContext) => {
3998
4906
  if (!shouldOwnTailwindGeneration) return;
@@ -4002,14 +4910,16 @@ function WeappTailwindcss(options = {}) {
4002
4910
  const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
4003
4911
  const isHarmonyAppStyleTarget = isHarmonyAppBuildTarget();
4004
4912
  const isNativeAppStyleTarget = require_utils.resolveUniUtsPlatform().isApp || isHarmonyAppStyleTarget;
4005
- const outputFile = resolveViteCssPipelineOutputFile(file, opts, rootDir, generatorOptions.target === "web", isNativeAppStyleTarget);
4913
+ const sourceRoot = resolveWeappViteSourceRoot(resolvedConfig, opts.appType);
4914
+ const outputFile = resolveViteCssPipelineOutputFile(file, opts, rootDir, generatorOptions.target === "web", isNativeAppStyleTarget, sourceRoot);
4006
4915
  const runtime = getRecordedGeneratorCandidates() ?? getSourceCandidates() ?? await ensureRuntimeClassSet();
4007
4916
  const outputCssHandlerOptions = transformCssHandlerOptions.getCssHandlerOptions(outputFile);
4008
4917
  const cssHandlerOptions = {
4009
4918
  ...transformCssHandlerOptions.getCssHandlerOptions(file),
4010
- isMainChunk: outputCssHandlerOptions.isMainChunk || isMainStyleEntryFile(file)
4919
+ isMainChunk: outputCssHandlerOptions.isMainChunk
4011
4920
  };
4012
- const shouldDeferEmptyScopedCssSource = !(opts.appType === "uni-app-x" && !cssHandlerOptions.isMainChunk && require_v3_engine.hasTailwindApplyDirective(code));
4921
+ const transientCssSource = transientAutoCssSources.get(file);
4922
+ const shouldDeferEmptyScopedCssSource = transientCssSource == null && !(opts.appType === "uni-app-x" && !cssHandlerOptions.isMainChunk && require_v3_engine.hasTailwindApplyDirective(code));
4013
4923
  const generated = await require_hmr_timing.generateCssByGenerator({
4014
4924
  opts,
4015
4925
  runtimeState,
@@ -4018,6 +4928,7 @@ function WeappTailwindcss(options = {}) {
4018
4928
  file,
4019
4929
  cssHandlerOptions,
4020
4930
  cssUserHandlerOptions: transformCssHandlerOptions.getCssUserHandlerOptions(file),
4931
+ cssSources: transientCssSource ? [transientCssSource] : void 0,
4021
4932
  getSourceCandidatesForEntries,
4022
4933
  styleHandler,
4023
4934
  debug,
@@ -4031,7 +4942,7 @@ function WeappTailwindcss(options = {}) {
4031
4942
  });
4032
4943
  for (const dependency of generated.dependencies) hookContext?.addWatchFile?.(dependency);
4033
4944
  viteGeneratedCssByFile.set(file, tracedCss);
4034
- const shouldInjectGeneratedCssIntoMain = isMainStyleEntryFile(file) || mainCssChunkMatcher(outputFile, opts.appType);
4945
+ const shouldInjectGeneratedCssIntoMain = mainCssChunkMatcher(outputFile, opts.appType) || require_v3_engine.hasTailwindRootDirectives(code, { importFallback: generatorOptions.importFallback }) && !require_bundle_state.normalizeOutputPathKey(outputFile).includes("/");
4035
4946
  recordViteProcessedCssAssetResult(file, tracedCss, {
4036
4947
  injectIntoMain: shouldInjectGeneratedCssIntoMain,
4037
4948
  outputFile
@@ -4048,7 +4959,7 @@ function WeappTailwindcss(options = {}) {
4048
4959
  markViteProcessedCssSource(file);
4049
4960
  rememberTailwindRootCssModule(id);
4050
4961
  recordGeneratorCandidates(runtime);
4051
- rememberCssSource({
4962
+ cssMemory.rememberCssSource({
4052
4963
  outputFile,
4053
4964
  rawSource: code,
4054
4965
  sourceFile: id
@@ -4061,7 +4972,7 @@ function WeappTailwindcss(options = {}) {
4061
4972
  generateTailwindCss: generateTailwindCssForVitePipeline,
4062
4973
  rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
4063
4974
  onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
4064
- onCssSourceTransform: (id, code) => refreshRememberedCssSourceBySourceFile(id, code),
4975
+ onCssSourceTransform: (id, code) => cssMemory.refreshRememberedCssSourceBySourceFile(id, code),
4065
4976
  shouldGenerateCss: (_id, code) => hasVitePipelineTailwindGenerationDirective(code),
4066
4977
  shouldOwnTailwindGeneration,
4067
4978
  shouldRewrite: shouldRewriteCssImports,
@@ -4083,16 +4994,20 @@ function WeappTailwindcss(options = {}) {
4083
4994
  getViteProcessedCssAssetResults,
4084
4995
  getViteProcessedCssAssetResult,
4085
4996
  getSourceCandidates,
4997
+ getSourceCandidateSource: (file) => sourceCandidateCollector.source(file),
4998
+ getSourceCandidateSources: () => sourceCandidateCollector.sources(),
4086
4999
  getSourceCandidatesForEntries,
4087
5000
  getSourceCandidateSourcesForEntries,
4088
5001
  waitForSourceCandidateSyncs,
4089
- rememberCssSource,
4090
- refreshRememberedCssSource,
4091
- getRememberedCssSources,
4092
- getRememberedCssSignature,
4093
- setRememberedCssSignature,
4094
- getKnownSfcSource,
5002
+ rememberCssSource: cssMemory.rememberCssSource,
5003
+ refreshRememberedCssSource: cssMemory.refreshRememberedCssSource,
5004
+ getRememberedCssSources: cssMemory.getRememberedCssSources,
5005
+ getRememberedCssSignature: cssMemory.getRememberedCssSignature,
5006
+ setRememberedCssSignature: cssMemory.setRememberedCssSignature,
5007
+ getKnownSfcSource: cssMemory.getKnownSfcSource,
4095
5008
  recordGeneratorCandidates,
5009
+ pruneViteCssCaches,
5010
+ getViteCssCacheStats,
4096
5011
  hmrTimingRecorder
4097
5012
  });
4098
5013
  const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
@@ -4112,12 +5027,12 @@ function WeappTailwindcss(options = {}) {
4112
5027
  getSourceCandidatesForEntries,
4113
5028
  getSourceCandidateSourcesForEntries,
4114
5029
  waitForSourceCandidateSyncs,
4115
- rememberMainCssSource: (file, rawSource) => rememberCssSource({
5030
+ rememberMainCssSource: (file, rawSource) => cssMemory.rememberCssSource({
4116
5031
  outputFile: file,
4117
5032
  rawSource,
4118
5033
  sourceFile: file
4119
5034
  }),
4120
- getRememberedMainCssSource: getRememberedCssSourceEntry
5035
+ getRememberedMainCssSource: cssMemory.getRememberedCssSourceEntry
4121
5036
  });
4122
5037
  const isIosPlatform = require_utils.resolveUniUtsPlatform().isAppIos;
4123
5038
  const prepareTailwindGeneration = async () => {
@@ -4144,7 +5059,7 @@ function WeappTailwindcss(options = {}) {
4144
5059
  name: `${require_precheck.vitePluginName}:source-candidates`,
4145
5060
  enforce: "pre",
4146
5061
  async transform(code, id) {
4147
- if (shouldOwnTailwindGeneration) rememberKnownSfcSource(id, code);
5062
+ if (shouldOwnTailwindGeneration) cssMemory.rememberKnownSfcSource(id, code);
4148
5063
  if (!shouldOwnTailwindGeneration || !require_hmr_timing.isSourceCandidateRequest(id) || !shouldCollectTransformedSourceCandidates(id)) return;
4149
5064
  return hmrTimingRecorder.measure("sourceCandidates.transform", async () => {
4150
5065
  invalidateRecordedGeneratorCandidates();
@@ -4154,10 +5069,6 @@ function WeappTailwindcss(options = {}) {
4154
5069
  cacheCurrentSourceCandidateScan();
4155
5070
  return;
4156
5071
  }
4157
- if (sourceScanExplicit && sourceScanEntries?.length === 0) {
4158
- cacheCurrentSourceCandidateScan();
4159
- return;
4160
- }
4161
5072
  await sourceCandidateCollector.merge(id, code);
4162
5073
  cacheCurrentSourceCandidateScan();
4163
5074
  }, { emit: false });
@@ -4179,7 +5090,7 @@ function WeappTailwindcss(options = {}) {
4179
5090
  const isSourceCandidateHotUpdate = shouldOwnTailwindGeneration && require_hmr_timing.isSourceCandidateRequest(ctx.file);
4180
5091
  await syncChangedSourceCandidateFile(ctx.file);
4181
5092
  if (isSourceCandidateHotUpdate) invalidateRecordedGeneratorCandidates();
4182
- const cssModules = resolveHotTailwindCssModules(ctx);
5093
+ const cssModules = resolveHotTailwindCssModules(ctx, tailwindRootCssModuleIds);
4183
5094
  if (isSourceCandidateHotUpdate && !require_bundle_state.isSourceStyleRequest(ctx.file) && (!hasSelfAcceptingNonStyleHotModule(ctx.modules) && cssModules.length === 0 || cssModules.length > 0 && isUniViteProject())) {
4184
5095
  sendFullReloadForUnresolvedHotUpdate(ctx);
4185
5096
  return [];
@@ -4246,7 +5157,7 @@ function WeappTailwindcss(options = {}) {
4246
5157
  }
4247
5158
  }
4248
5159
  if (shouldInferAppType && resolvedRoot) {
4249
- const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
5160
+ const nextAppType = require_framework.resolveImplicitAppTypeFromViteRoot(resolvedRoot);
4250
5161
  if (nextAppType && opts.appType !== nextAppType) {
4251
5162
  const previousAppType = opts.appType;
4252
5163
  opts.appType = nextAppType;