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