weapp-tailwindcss 5.1.0 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/bundlers/shared/generator-css/class-selectors.d.ts +2 -0
  2. package/dist/bundlers/shared/generator-css/generation-helpers.d.ts +6 -14
  3. package/dist/bundlers/shared/generator-css/source-resolver/metadata.d.ts +1 -1
  4. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +2 -2
  5. package/dist/bundlers/shared/generator-css/validate.d.ts +1 -0
  6. package/dist/bundlers/vite/css-memory.d.ts +6 -0
  7. package/dist/bundlers/vite/generate-bundle/css-assets.d.ts +1 -1
  8. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +1 -1
  9. package/dist/bundlers/vite/generate-bundle/css-output-helpers.d.ts +39 -0
  10. package/dist/bundlers/vite/generate-bundle/env-flags.d.ts +1 -0
  11. package/dist/bundlers/vite/generate-bundle/final-css-assets.d.ts +2 -1
  12. package/dist/bundlers/vite/generate-bundle/finalize.d.ts +2 -0
  13. package/dist/bundlers/vite/generate-bundle/html-processing.d.ts +26 -0
  14. package/dist/bundlers/vite/generate-bundle/js-processing.d.ts +4 -0
  15. package/dist/bundlers/vite/generate-bundle/remembered-css-replay.d.ts +1 -1
  16. package/dist/bundlers/vite/generate-bundle/remembered-css.d.ts +1 -1
  17. package/dist/bundlers/vite/generate-bundle/root-style-output.d.ts +6 -0
  18. package/dist/bundlers/vite/generate-bundle/runtime-linked-source-memory.d.ts +25 -0
  19. package/dist/bundlers/vite/generate-bundle/source-candidate-source.d.ts +9 -0
  20. package/dist/bundlers/vite/generate-bundle/tailwind-v4-css-source.d.ts +9 -0
  21. package/dist/bundlers/vite/generate-bundle/transform-filter.d.ts +15 -0
  22. package/dist/bundlers/vite/generate-bundle/types.d.ts +1 -0
  23. package/dist/bundlers/vite/generate-bundle.d.ts +1 -2
  24. package/dist/bundlers/vite/plugin-cache.d.ts +15 -0
  25. package/dist/bundlers/vite/runtime-class-set.d.ts +2 -1
  26. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +3 -3
  27. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/css-source-resolvers.d.ts +34 -0
  28. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/js-module-graph.d.ts +37 -0
  29. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/pipeline-helpers.d.ts +199 -0
  30. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/source-candidate-refresh.d.ts +11 -0
  31. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +1 -0
  32. package/dist/cli.js +15 -8
  33. package/dist/cli.mjs +15 -8
  34. package/dist/context/style-options.d.ts +1 -0
  35. package/dist/{context-BHxLe743.js → context-B6hVF7dr.js} +20 -9
  36. package/dist/{context-Mbzkek1q.mjs → context-DlpKD7aN.mjs} +15 -10
  37. package/dist/core.js +1 -1
  38. package/dist/core.mjs +1 -1
  39. package/dist/css-macro/index.d.ts +3 -7
  40. package/dist/{defaults-ZElj1zKc.mjs → defaults-BhE26nSw.mjs} +7 -3
  41. package/dist/{defaults-CVcKbXBG.js → defaults-CmFBmxsr.js} +7 -3
  42. package/dist/defaults.d.ts +1 -1
  43. package/dist/defaults.js +1 -1
  44. package/dist/defaults.mjs +1 -1
  45. package/dist/generator/types.d.ts +1 -1
  46. package/dist/{generator-9rUz4Hcb.js → generator-6oMJtTDO.js} +1 -1
  47. package/dist/{generator-Dc4qaPmT.mjs → generator-CjzBK7h-.mjs} +1 -1
  48. package/dist/generator.js +2 -2
  49. package/dist/generator.mjs +2 -2
  50. package/dist/{gulp-B_sdP6dx.js → gulp-BtGq6LP9.js} +11 -9
  51. package/dist/{gulp-uM36oIJs.mjs → gulp-DNU10Vtc.mjs} +11 -9
  52. package/dist/gulp.js +1 -1
  53. package/dist/gulp.mjs +1 -1
  54. package/dist/{hmr-timing-BXMLsF4b.mjs → hmr-timing-B0KuWDjV.mjs} +121 -85
  55. package/dist/{hmr-timing-CogqkFaF.js → hmr-timing-CegXR9O4.js} +132 -84
  56. package/dist/index.js +4 -4
  57. package/dist/index.mjs +4 -4
  58. package/dist/postcss.js +2 -2
  59. package/dist/postcss.mjs +2 -2
  60. package/dist/presets.js +2 -2
  61. package/dist/presets.mjs +2 -2
  62. package/dist/{source-candidate-scan-signature-Cvb5z1ha.mjs → source-candidate-scan-signature-B5af2Ahe.mjs} +3 -3
  63. package/dist/{source-candidate-scan-signature-2ybpptAK.js → source-candidate-scan-signature-BKYb9jxa.js} +3 -3
  64. package/dist/tailwindcss/runtime-types.d.ts +1 -0
  65. package/dist/tailwindcss/v4-engine/source.d.ts +5 -14
  66. package/dist/tailwindcss/v4-engine/types.d.ts +10 -2
  67. package/dist/{tailwindcss-wyUHrfil.mjs → tailwindcss-B5mRo0-M.mjs} +12 -7
  68. package/dist/{tailwindcss-DHIYcqXT.js → tailwindcss-dbrbY4cd.js} +11 -6
  69. package/dist/{transform-tExdt40m.mjs → transform-fRBeuuK-.mjs} +1 -1
  70. package/dist/{transform-CQVOgmzM.js → transform-vLwZpiTE.js} +1 -1
  71. package/dist/types/user-defined-options/matcher.d.ts +7 -0
  72. package/dist/{v4-engine-CF9zt4Cw.mjs → v4-engine-C3qSwQ-e.mjs} +7 -27
  73. package/dist/{v4-engine-D4ubP7N5.js → v4-engine-ON_oSLfO.js} +5 -31
  74. package/dist/{vite-CPO83EhA.mjs → vite-CWRooooa.mjs} +730 -393
  75. package/dist/{vite-CP0ylSxZ.js → vite-w-RkgaTY.js} +730 -392
  76. package/dist/vite.js +1 -1
  77. package/dist/vite.mjs +1 -1
  78. package/dist/weapp-tw-css-import-rewrite-loader.js +122 -85
  79. package/dist/{webpack-BzqhJ8yK.mjs → webpack-8PaV1gG3.mjs} +923 -671
  80. package/dist/{webpack-Bsek8VhR.js → webpack-CGgBOx9l.js} +923 -671
  81. package/dist/webpack.js +1 -1
  82. package/dist/webpack.mjs +1 -1
  83. package/package.json +5 -5
@@ -1,19 +1,20 @@
1
1
  import { resolveImplicitAppTypeFromViteRoot } from "./framework.mjs";
2
- import { A as removeTailwindSourceDirectives, C as hasTailwindRootDirectives, E as normalizeTailwindConfigDirectives, I as hasTailwindGeneratedCssMarkers, K as getTailwindV4IncrementalGenerateCacheStats, O as normalizeTailwindSourceForGenerator, S as hasTailwindNonRootGenerationDirectives, T as hasTailwindSourceDirectives, _ as resolveTailwindcssOptions, a as filterTailwindV4CssSourceRoots, b as hasLocalCssImport, ct as omitUndefined, d as normalizeCssEntries, f as findNearestPackageRoot, it as resolveTailwindV4CssSourceBase, k as parseImportRequest, o as hasConfiguredTailwindV4CssRoots, s as upsertTailwindV4CssSource, st as filterUnsupportedMiniProgramTailwindV4Candidates, u as isTailwindV4CssEntry, w as hasTailwindRootImportDirectives, x as hasTailwindApplyDirective } from "./v4-engine-CF9zt4Cw.mjs";
3
- import { a as resolveGeneratorRuntimeBranch, c as shouldUseNativeAppCssBranch, i as normalizeWeappTailwindcssGeneratorOptions, s as shouldUseMiniProgramCssBranch } from "./generator-Dc4qaPmT.mjs";
2
+ import { C as hasTailwindRootDirectives, D as normalizeTailwindSourceForGenerator, F as hasTailwindGeneratedCssMarkers, G as getTailwindV4IncrementalGenerateCacheStats, O as parseImportRequest, S as hasTailwindNonRootGenerationDirectives, T as normalizeTailwindConfigDirectives, _ as resolveTailwindcssOptions, a as filterTailwindV4CssSourceRoots, b as hasLocalCssImport, d as normalizeCssEntries, f as findNearestPackageRoot, k as removeTailwindSourceDirectives, o as hasConfiguredTailwindV4CssRoots, ot as filterUnsupportedMiniProgramTailwindV4Candidates, rt as resolveTailwindV4CssSourceBase, s as upsertTailwindV4CssSource, st as omitUndefined, u as isTailwindV4CssEntry, w as hasTailwindSourceDirectives, x as hasTailwindApplyDirective } from "./v4-engine-C3qSwQ-e.mjs";
3
+ import { a as resolveGeneratorRuntimeBranch, c as shouldUseNativeAppCssBranch, i as normalizeWeappTailwindcssGeneratorOptions, s as shouldUseMiniProgramCssBranch } from "./generator-CjzBK7h-.mjs";
4
4
  import { o as resolveUniUtsPlatform } from "./utils-DodxWHGz.mjs";
5
- import { _ as collectRuntimeClassSet, b as refreshTailwindRuntimeState, c as shouldSkipJsTransform, g as toCustomAttributesEntities, i as vitePluginName, p as replaceWxml, t as getCompilerContext, v as createTailwindRuntimeReadyPromise, x as createDebug } from "./context-Mbzkek1q.mjs";
6
- import { _ as resolveViteTailwindV4CssDependencies, a as findTailwindConfig, f as createViteSourceScanMatcher, g as resolveTailwindV4EntriesFromCssCached, i as resolveUniAppXOptions, l as getRuntimeClassSetSignature, m as discoverTailwindV4CssEntries, p as resolveViteSourceScanEntries, r as isUniAppXEnabled } from "./tailwindcss-wyUHrfil.mjs";
7
- import { A as stripMiniProgramCssSpecificityPlaceholders, F as processCachedTask, M as createCssSourceTraceCacheSignature, N as createCssTokenSourceMap, O as hasMiniProgramCssSpecificityPlaceholders, _ as isPureLocalCssImportWrapper, a as isSourceCandidateRequest, d as validateCandidatesByGenerator, f as pushConcurrentTaskFactories, g as mergeMarkedUserLayerComponentsCss, h as extractMarkedUserLayerComponentsCss, j as annotateCssSourceTrace, m as runWithConcurrency, r as createSourceCandidateCollector, s as createBundleRuntimeClassSetManager, t as createHmrTimingRecorder } from "./hmr-timing-BXMLsF4b.mjs";
8
- import { A as isSourceStyleRequest, C as resolvePluginDisabledState, D as isHTMLRequest, E as isCSSRequest, M as normalizeOutputPathKey, O as normalizePath, P as toAbsoluteOutputPath, S as resolvePackageDir, T as formatPostcssSourceMap, _ as generateTailwindV4Css, a as createJsHashSalt, b as parseBundlerGeneratedCssMarkerBlocks, c as hasRuntimeAffectingSourceChanges, f as createBundleBuildState, g as createBundleModuleGraphOptions, h as applyLinkedResults, i as createCandidateSignature, j as stripRequestQuery, k as slash, l as summarizeStringDiff, m as createRuntimeAffectingSourceSignature, n as createScopedGeneratorCandidateSignature, o as createLinkedImpactSignature, p as updateBundleBuildState, r as createScopedGeneratorRuntime, s as getSnapshotHash, t as createSourceCandidateScanSignature, u as buildBundleSnapshot, v as createBundlerGeneratedCssMarker, w as cleanUrl, x as stripBundlerGeneratedCssMarkers, y as hasBundlerGeneratedCssMarker } from "./source-candidate-scan-signature-Cvb5z1ha.mjs";
5
+ import { S as createDebug, _ as toCustomAttributesEntities, a as vitePluginName, l as shouldSkipJsTransform, m as replaceWxml, n as normalizeStyleHandlerMajorVersion, t as getCompilerContext, v as collectRuntimeClassSet, x as refreshTailwindRuntimeState, y as createTailwindRuntimeReadyPromise } from "./context-DlpKD7aN.mjs";
6
+ import { _ as resolveViteTailwindV4CssDependencies, a as findTailwindConfig, f as createViteSourceScanMatcher, g as resolveTailwindV4EntriesFromCssCached, i as resolveUniAppXOptions, l as getRuntimeClassSetSignature, m as discoverTailwindV4CssEntries, p as resolveViteSourceScanEntries, r as isUniAppXEnabled } from "./tailwindcss-B5mRo0-M.mjs";
7
+ import { A as hasMiniProgramCssSpecificityPlaceholders, F as createCssTokenSourceMap, L as processCachedTask, M as stripMiniProgramCssSpecificityPlaceholders, N as annotateCssSourceTrace, P as createCssSourceTraceCacheSignature, _ as isPureLocalCssImportWrapper, a as isSourceCandidateRequest, d as validateCandidatesByGenerator, g as mergeMarkedUserLayerComponentsCss, h as extractMarkedUserLayerComponentsCss, m as runWithConcurrency, r as createSourceCandidateCollector, s as createBundleRuntimeClassSetManager, t as createHmrTimingRecorder } from "./hmr-timing-B0KuWDjV.mjs";
8
+ import { A as isSourceStyleRequest, C as resolvePluginDisabledState, D as isHTMLRequest, E as isCSSRequest, M as normalizeOutputPathKey, O as normalizePath, P as toAbsoluteOutputPath, S as resolvePackageDir, T as formatPostcssSourceMap, _ as generateTailwindV4Css, a as createJsHashSalt, b as parseBundlerGeneratedCssMarkerBlocks, c as hasRuntimeAffectingSourceChanges, f as createBundleBuildState, g as createBundleModuleGraphOptions, h as applyLinkedResults, i as createCandidateSignature, j as stripRequestQuery, k as slash, l as summarizeStringDiff, m as createRuntimeAffectingSourceSignature, n as createScopedGeneratorCandidateSignature, o as createLinkedImpactSignature, p as updateBundleBuildState, r as createScopedGeneratorRuntime, s as getSnapshotHash, t as createSourceCandidateScanSignature, u as buildBundleSnapshot, v as createBundlerGeneratedCssMarker, w as cleanUrl, x as stripBundlerGeneratedCssMarkers, y as hasBundlerGeneratedCssMarker } from "./source-candidate-scan-signature-B5af2Ahe.mjs";
9
9
  import { t as logger$1 } from "./logger-BNzxZbZj.mjs";
10
- import fs, { existsSync } from "node:fs";
10
+ import fs, { existsSync, realpathSync } from "node:fs";
11
11
  import path from "node:path";
12
12
  import process$1 from "node:process";
13
13
  import { splitCandidateTokens } from "@tailwindcss-mangle/engine";
14
14
  import { containsCssAfterMinify, filterExistingCssRules, mergeCoveredCssRuleDeclarations, mergeMiniProgramPreflightRuleDeclarations, mergeMiniProgramThemeScopeRuleDeclarations, postcss, removeTailwindPostcssPlugins, resolveFilteredPostcssConfig } from "@weapp-tailwindcss/postcss";
15
15
  import { LRUCache } from "lru-cache";
16
16
  import { readFile } from "node:fs/promises";
17
+ import micromatch from "micromatch";
17
18
  import { Buffer } from "node:buffer";
18
19
  import { logger } from "@weapp-tailwindcss/logger";
19
20
  import { parse } from "comment-json";
@@ -508,7 +509,7 @@ function resolveUniAppXStyleIsolationEnabled(root) {
508
509
  //#region src/uni-app-x/vite.ts
509
510
  let transformUVuePromise;
510
511
  function loadTransformUVue() {
511
- transformUVuePromise ?? (transformUVuePromise = import("./transform-tExdt40m.mjs").then((mod) => mod.transformUVue));
512
+ transformUVuePromise ?? (transformUVuePromise = import("./transform-fRBeuuK-.mjs").then((mod) => mod.transformUVue));
512
513
  return transformUVuePromise;
513
514
  }
514
515
  const preprocessorLangs = new Set([
@@ -743,71 +744,6 @@ function createUniAppXAssetTask(file, originalSource, outDir, options) {
743
744
  };
744
745
  }
745
746
  //#endregion
746
- //#region src/bundlers/vite/generate-bundle/candidates.ts
747
- const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
748
- const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
749
- const CLASS_ATTRIBUTE_RE = /\bclass\s*=\s*/g;
750
- const MUSTACHE_OPEN = "{{";
751
- const MUSTACHE_CLOSE = "}}";
752
- function isUrlLikeCandidate(candidate) {
753
- return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
754
- }
755
- function isArbitraryValueCandidate(candidate) {
756
- return candidate.includes("[") && candidate.includes("]") && !isUrlLikeCandidate(candidate.trim());
757
- }
758
- function collectClassAttributeValues(source) {
759
- const values = [];
760
- CLASS_ATTRIBUTE_RE.lastIndex = 0;
761
- let matched = CLASS_ATTRIBUTE_RE.exec(source);
762
- while (matched !== null) {
763
- const quoteIndex = CLASS_ATTRIBUTE_RE.lastIndex;
764
- const quote = source[quoteIndex];
765
- if (quote !== "\"" && quote !== "'") {
766
- matched = CLASS_ATTRIBUTE_RE.exec(source);
767
- continue;
768
- }
769
- let expressionDepth = 0;
770
- for (let index = quoteIndex + 1; index < source.length; index++) {
771
- if (source.startsWith(MUSTACHE_OPEN, index)) {
772
- expressionDepth++;
773
- index += 1;
774
- continue;
775
- }
776
- if (expressionDepth > 0 && source.startsWith(MUSTACHE_CLOSE, index)) {
777
- expressionDepth--;
778
- index += 1;
779
- continue;
780
- }
781
- if (expressionDepth === 0 && source[index] === quote) {
782
- values.push(source.slice(quoteIndex + 1, index));
783
- CLASS_ATTRIBUTE_RE.lastIndex = index + 1;
784
- break;
785
- }
786
- }
787
- matched = CLASS_ATTRIBUTE_RE.exec(source);
788
- }
789
- return values;
790
- }
791
- function collectUnescapedDynamicCandidates(source, allowedCandidates) {
792
- const matches = /* @__PURE__ */ new Set();
793
- const shouldFilterByAllowedCandidates = allowedCandidates !== void 0 && allowedCandidates.size > 0;
794
- for (const classValue of collectClassAttributeValues(source)) for (const expression of classValue.match(MUSTACHE_EXPRESSION_RE) ?? []) {
795
- QUOTED_LITERAL_RE.lastIndex = 0;
796
- let quoted = QUOTED_LITERAL_RE.exec(expression);
797
- while (quoted !== null) {
798
- const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
799
- for (const candidate of splitCandidateTokens(literal)) {
800
- const normalized = candidate.trim();
801
- if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
802
- if (shouldFilterByAllowedCandidates && !allowedCandidates.has(normalized)) continue;
803
- matches.add(normalized);
804
- }
805
- quoted = QUOTED_LITERAL_RE.exec(expression);
806
- }
807
- }
808
- return [...matches];
809
- }
810
- //#endregion
811
747
  //#region src/bundlers/vite/generate-bundle/configured-css-sources.ts
812
748
  function collectConfiguredTailwindV4CssSources(opts) {
813
749
  const runtimeCssSources = opts.tailwindcssRuntimeOptions?.tailwindcss?.v4?.cssSources ?? [];
@@ -865,16 +801,15 @@ function registerGeneratorDependencies$1(ctx, dependencies) {
865
801
  //#region src/bundlers/vite/generate-bundle/css-assets.ts
866
802
  function createCssAssetEmitter(context) {
867
803
  return (fileName, source) => {
868
- const replayAsset = createReplayCssAsset(fileName, source);
869
804
  if (context.emitFile) {
870
805
  context.emitFile({
871
806
  type: "asset",
872
807
  fileName,
873
808
  source
874
809
  });
875
- return replayAsset;
810
+ return;
876
811
  }
877
- return replayAsset;
812
+ return createReplayCssAsset(fileName, source);
878
813
  };
879
814
  }
880
815
  function resolveAssetSourceFile(asset, fallbackFile) {
@@ -894,6 +829,23 @@ const COMMON_MINI_PROGRAM_STYLE_OUTPUT_EXTENSIONS = [
894
829
  ".jxss",
895
830
  ".tyss"
896
831
  ];
832
+ function resolveCssOutputRealPath(value) {
833
+ const resolved = path.resolve(value);
834
+ let current = resolved;
835
+ const pendingSegments = [];
836
+ while (!existsSync(current)) {
837
+ const parent = path.dirname(current);
838
+ if (parent === current) return resolved;
839
+ pendingSegments.unshift(path.basename(current));
840
+ current = parent;
841
+ }
842
+ try {
843
+ const realPath = realpathSync.native(current);
844
+ return pendingSegments.length > 0 ? path.join(realPath, ...pendingSegments) : realPath;
845
+ } catch {
846
+ return resolved;
847
+ }
848
+ }
897
849
  function normalizeStyleOutputExtension(value) {
898
850
  if (typeof value !== "string" || value.trim().length === 0) return;
899
851
  const normalized = value.trim().toLowerCase();
@@ -933,7 +885,7 @@ function resolveStyleOutputFileFromFiles(files, cssMatcher, stem) {
933
885
  if (!extension || extension === ".css") continue;
934
886
  const outputStem = cleanFile.slice(0, -extension.length);
935
887
  const outputStemSuffix = `/${outputStem}`;
936
- if (outputStem === cleanStem || outputStem.endsWith(stemSuffix) || cleanStem.endsWith(outputStemSuffix)) matchedFiles.add(cleanFile);
888
+ if (outputStem === cleanStem || outputStem.endsWith(stemSuffix) || cleanStem.endsWith(outputStemSuffix) || cleanStem.endsWith(`/${outputStem}`)) matchedFiles.add(cleanFile);
937
889
  }
938
890
  return matchedFiles.size === 1 ? [...matchedFiles][0] : void 0;
939
891
  }
@@ -941,7 +893,7 @@ function resolveMiniProgramStyleOutputExtension(options = {}) {
941
893
  return resolveStyleOutputExtensionFromFiles(options.files, options.cssMatcher, options.stem) ?? resolveStyleOutputExtensionFromFiles(options.files, options.cssMatcher) ?? resolveStyleOutputExtensionFromMatcher(options.cssMatcher, options.stem) ?? normalizeStyleOutputExtension(options.fallback) ?? FALLBACK_STYLE_OUTPUT_EXTENSION;
942
894
  }
943
895
  function resolveReplayCssOutputFile(rootDir, file) {
944
- const normalizedFile = normalizeOutputPathKey(path.isAbsolute(file) ? path.relative(rootDir, file) : file);
896
+ const normalizedFile = normalizeOutputPathKey(path.isAbsolute(file) ? path.relative(resolveCssOutputRealPath(rootDir), resolveCssOutputRealPath(file)) : file);
945
897
  if (normalizedFile.length === 0 || normalizedFile === "." || normalizedFile === ".." || normalizedFile.startsWith("../")) return normalizeOutputPathKey(path.basename(file));
946
898
  return normalizedFile;
947
899
  }
@@ -1012,6 +964,23 @@ function stripStyleFileExtension(file) {
1012
964
  }
1013
965
  //#endregion
1014
966
  //#region src/bundlers/vite/generate-bundle/style-matching.ts
967
+ function resolveStyleMatchingRealPath(value) {
968
+ const resolved = path.resolve(value);
969
+ let current = resolved;
970
+ const pendingSegments = [];
971
+ while (!existsSync(current)) {
972
+ const parent = path.dirname(current);
973
+ if (parent === current) return resolved;
974
+ pendingSegments.unshift(path.basename(current));
975
+ current = parent;
976
+ }
977
+ try {
978
+ const realPath = realpathSync.native(current);
979
+ return pendingSegments.length > 0 ? path.join(realPath, ...pendingSegments) : realPath;
980
+ } catch {
981
+ return resolved;
982
+ }
983
+ }
1015
984
  function isMatchingCssSourceFile(outputFile, cssSourceFile, outputRoot) {
1016
985
  return stripStyleFileExtension(path.resolve(outputRoot, outputFile)) === stripStyleFileExtension(path.resolve(cssSourceFile));
1017
986
  }
@@ -1025,7 +994,7 @@ function collectStyleFileMatchBases(file, roots) {
1025
994
  addBase(normalizedFile);
1026
995
  const resolvedRoots = roots.filter((root) => typeof root === "string" && root.length > 0).map((root) => path.resolve(root));
1027
996
  if (path.isAbsolute(normalizedFile)) for (const root of resolvedRoots) {
1028
- const relative = path.relative(root, normalizedFile);
997
+ const relative = path.relative(resolveStyleMatchingRealPath(root), resolveStyleMatchingRealPath(normalizedFile));
1029
998
  if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) addBase(relative);
1030
999
  }
1031
1000
  else for (const root of resolvedRoots) addBase(path.resolve(root, normalizedFile));
@@ -1135,7 +1104,7 @@ function createCssHandlerOptionsCache(options) {
1135
1104
  isMainChunk,
1136
1105
  ...extraOptions,
1137
1106
  postcssOptions: { options: { from } },
1138
- majorVersion,
1107
+ majorVersion: normalizeStyleHandlerMajorVersion(majorVersion),
1139
1108
  sourceOptions: { outputRoot }
1140
1109
  };
1141
1110
  cssHandlerOptionsCache.set(cacheKey, created);
@@ -1160,6 +1129,91 @@ function createCssHandlerOptionsCache(options) {
1160
1129
  };
1161
1130
  }
1162
1131
  //#endregion
1132
+ //#region src/bundlers/vite/generate-bundle/root-style-output.ts
1133
+ function isRootMiniProgramStyleOutputFile$1(file) {
1134
+ const normalized = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1135
+ return !normalized.includes("/") && /\.(?:wxss|acss|ttss|qss|jxss|tyss)$/i.test(normalized);
1136
+ }
1137
+ function createRelativeCssImportRequest$1(targetFile, importedFile) {
1138
+ const normalizedTargetFile = normalizeOutputPathKey(targetFile.replace(/[?#].*$/, ""));
1139
+ const normalizedImportedFile = normalizeOutputPathKey(importedFile.replace(/[?#].*$/, ""));
1140
+ const targetDir = path.posix.dirname(normalizedTargetFile);
1141
+ const baseDir = targetDir === "." ? "" : targetDir;
1142
+ const relative = path.posix.relative(baseDir, normalizedImportedFile);
1143
+ return relative.startsWith(".") ? relative : `./${relative}`;
1144
+ }
1145
+ function createCssImportShell$1(targetFile, importedFile) {
1146
+ return `@import "${createRelativeCssImportRequest$1(targetFile, importedFile)}";\n`;
1147
+ }
1148
+ function createRootMiniProgramOriginStyleOutputFile(file) {
1149
+ const normalized = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1150
+ if (/(?:^|\/)[^/]+-origin\.[^.]+$/i.test(normalized)) return normalized;
1151
+ return normalized.replace(/(\.[^.]+)$/, "-origin$1");
1152
+ }
1153
+ function shouldKeepRootMiniProgramStyleAsImportShell(appType) {
1154
+ return appType === "uni-app-vite" || appType === "uni-app-x" || appType === "taro";
1155
+ }
1156
+ function shouldMoveRootMiniProgramStyleToImportShellOrigin(appType) {
1157
+ return appType === "taro";
1158
+ }
1159
+ //#endregion
1160
+ //#region src/bundlers/vite/generate-bundle/css-output-helpers.ts
1161
+ function resolveCssBundleOutputFile(options) {
1162
+ const { bundleFiles, defaultStyleOutputExtension, file, isWebGeneratorTarget, opts, shouldPreserveAppCssExtension } = options;
1163
+ let outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, shouldPreserveAppCssExtension, defaultStyleOutputExtension, bundleFiles);
1164
+ if (outputFile === file && isRootMiniProgramStyleOutputFile$1(file) && shouldMoveRootMiniProgramStyleToImportShellOrigin(opts.appType)) outputFile = createRootMiniProgramOriginStyleOutputFile(file);
1165
+ return outputFile;
1166
+ }
1167
+ function shouldSkipRawSourceStyleAsset(outputFile, file, rawSource) {
1168
+ return rawSource.trim().length > 0 && outputFile !== file && !canProcessViteSourceStyleAsCss(rawSource, file);
1169
+ }
1170
+ function resolveOutputFileFromMatchedCssSource(options) {
1171
+ const { bundleFiles, defaultStyleOutputExtension, isWebGeneratorTarget, opts, rootDir, shouldPreserveAppCssExtension, sourceFile, sourceRoot } = options;
1172
+ if (!sourceFile) return;
1173
+ if (isWebGeneratorTarget) return;
1174
+ const outputFile = resolveViteCssPipelineOutputFileFromSourceFile(sourceFile, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension, sourceRoot, defaultStyleOutputExtension, bundleFiles);
1175
+ return opts.cssMatcher(outputFile) ? outputFile : void 0;
1176
+ }
1177
+ function createMatchedCssSourceOutputResolver(options) {
1178
+ const { assetSourceFile, file, originalFileNames, resolveOutputFileFromMatchedCssSource } = options;
1179
+ return (sourceFile) => {
1180
+ if (!sourceFile) return;
1181
+ if (normalizeOutputPathKey(assetSourceFile.replace(/[?#].*$/, "")) === normalizeOutputPathKey(sourceFile.replace(/[?#].*$/, "")) || originalFileNames?.some((originalFile) => normalizeOutputPathKey(originalFile.replace(/[?#].*$/, "")) === normalizeOutputPathKey(sourceFile.replace(/[?#].*$/, "")))) return file;
1182
+ return resolveOutputFileFromMatchedCssSource(sourceFile);
1183
+ };
1184
+ }
1185
+ function hasViteProcessedCssResultForSource(sourceFile, getViteProcessedCssAssetResults) {
1186
+ const sourceKey = normalizeOutputPathKey(sourceFile);
1187
+ for (const [file] of getViteProcessedCssAssetResults?.() ?? []) if (normalizeOutputPathKey(file) === sourceKey) return true;
1188
+ return false;
1189
+ }
1190
+ function applyCssResultToBundle(options) {
1191
+ const { appType, assetSourceFile, bundle, emitOrReplayCssAsset, file, originalSource, outputFile, source, viteProcessedCssAsset } = options;
1192
+ if (outputFile === file) {
1193
+ originalSource.source = source;
1194
+ return;
1195
+ }
1196
+ const importShellSource = isRootMiniProgramStyleOutputFile$1(file) && isRootMiniProgramStyleOutputFile$1(outputFile) && shouldKeepRootMiniProgramStyleAsImportShell(appType) ? createCssImportShell$1(file, outputFile) : void 0;
1197
+ if (bundle[file] === originalSource && originalSource.originalFileNames?.includes(assetSourceFile)) {
1198
+ const existingOutput = bundle[outputFile];
1199
+ if (existingOutput?.type === "asset") existingOutput.source = source;
1200
+ else {
1201
+ const replayAsset = emitOrReplayCssAsset(outputFile, source);
1202
+ if (replayAsset) bundle[outputFile] = replayAsset;
1203
+ }
1204
+ originalSource.source = importShellSource ?? source;
1205
+ return;
1206
+ }
1207
+ const existingOutput = bundle[outputFile];
1208
+ if (existingOutput?.type === "asset") existingOutput.source = source;
1209
+ else {
1210
+ const replayAsset = emitOrReplayCssAsset(outputFile, source);
1211
+ if (replayAsset) bundle[outputFile] = replayAsset;
1212
+ }
1213
+ if (!viteProcessedCssAsset && SOURCE_STYLE_OUTPUT_EXT_RE.test(file)) delete bundle[file];
1214
+ else originalSource.source = importShellSource ?? "";
1215
+ }
1216
+ //#endregion
1163
1217
  //#region src/bundlers/vite/generate-bundle/css-share-scope.ts
1164
1218
  const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
1165
1219
  const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
@@ -1200,11 +1254,13 @@ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
1200
1254
  //#endregion
1201
1255
  //#region src/bundlers/vite/generate-bundle/env-flags.ts
1202
1256
  function resolveGenerateBundleEnvFlags() {
1257
+ const slowJsAstWarnMs = Number(process$1.env["WEAPP_TW_VITE_SLOW_JS_AST_WARN_MS"] ?? 1e3);
1203
1258
  return {
1204
1259
  forceRuntimeRefreshByEnv: process$1.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1",
1205
1260
  disableDirtyOptimization: process$1.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1",
1206
1261
  disableJsPrecheck: process$1.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1",
1207
- debugCssDiff: process$1.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1"
1262
+ debugCssDiff: process$1.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1",
1263
+ slowJsAstWarnMs: Number.isFinite(slowJsAstWarnMs) && slowJsAstWarnMs >= 0 ? slowJsAstWarnMs : 1e3
1208
1264
  };
1209
1265
  }
1210
1266
  //#endregion
@@ -1682,7 +1738,6 @@ function hasTailwindGenerationSource(source, options = {}) {
1682
1738
  }
1683
1739
  function hasTailwindGenerationSourceForFile(file, source) {
1684
1740
  if (isTailwindV4CssEntry(file)) return hasTailwindGenerationSource(source);
1685
- if (hasTailwindRootImportDirectives(source, { importFallback: true })) return false;
1686
1741
  return hasTailwindGenerationSource(source, { allowRootDirectives: false });
1687
1742
  }
1688
1743
  async function resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outputRoot, sourceRoot, cssMatcher, getSfcSource, debug) {
@@ -1711,7 +1766,7 @@ async function resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outputR
1711
1766
  function normalizeSfcSourceFileForCompare(file) {
1712
1767
  return normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1713
1768
  }
1714
- function collectChunkModuleIds$1(output) {
1769
+ function collectChunkModuleIds$2(output) {
1715
1770
  const moduleIds = Array.isArray(output.moduleIds) ? output.moduleIds : [];
1716
1771
  return [
1717
1772
  output.facadeModuleId,
@@ -1751,7 +1806,7 @@ function resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, s
1751
1806
  debug("sfc style sibling chunk skipped: missing chunk for %s -> %s", outputFile, siblingJsFile);
1752
1807
  return;
1753
1808
  }
1754
- const sourceFiles = collectChunkModuleIds$1(siblingChunk.output).map(normalizeSfcModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
1809
+ const sourceFiles = collectChunkModuleIds$2(siblingChunk.output).map(normalizeSfcModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
1755
1810
  if (sourceFiles.length === 0) {
1756
1811
  debug("sfc style sibling chunk skipped: no sfc modules for %s -> %s", outputFile, siblingJsFile);
1757
1812
  return;
@@ -1771,7 +1826,7 @@ function resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, s
1771
1826
  return bestSources[0]?.sourceFile;
1772
1827
  }
1773
1828
  function resolveSourceStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug) {
1774
- const siblingJsFile = resolveSiblingJsChunkFile(outputFile);
1829
+ const siblingJsFile = resolveSiblingJsChunkFile(outputFile, void 0);
1775
1830
  if (!siblingJsFile) {
1776
1831
  debug("source style sibling chunk skipped: no sibling js for %s", outputFile);
1777
1832
  return;
@@ -1782,7 +1837,7 @@ function resolveSourceStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot
1782
1837
  debug("source style sibling chunk skipped: missing chunk for %s -> %s", outputFile, siblingJsFile);
1783
1838
  return;
1784
1839
  }
1785
- const sourceFiles = collectChunkModuleIds$1(siblingChunk.output).map(normalizeSourceStyleModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
1840
+ const sourceFiles = collectChunkModuleIds$2(siblingChunk.output).map(normalizeSourceStyleModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
1786
1841
  if (sourceFiles.length === 0) {
1787
1842
  debug("source style sibling chunk skipped: no source style modules for %s -> %s", outputFile, siblingJsFile);
1788
1843
  return;
@@ -1804,7 +1859,7 @@ function resolveSourceStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot
1804
1859
  function resolveSourceStyleSourceFromOutputFile(outputFile, snapshot, outputRoot, sourceRoot, getSourceStyleSource, getSourceStyleSources, configuredSourceEntries, debug) {
1805
1860
  let sourceFile = resolveSourceStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug);
1806
1861
  let rawSource = sourceFile ? getSourceStyleSource?.(sourceFile) : void 0;
1807
- if (!rawSource || !hasTailwindGenerationSourceForFile(sourceFile, rawSource)) {
1862
+ if (!sourceFile || !rawSource || !hasTailwindGenerationSourceForFile(sourceFile, rawSource)) {
1808
1863
  const scoredSources = [...getSourceStyleSources?.() ?? [], ...configuredSourceEntries ?? []].filter(([file, source]) => CSS_SOURCE_OUTPUT_EXT_RE.test(file) && hasTailwindGenerationSourceForFile(file, source)).map(([file, source]) => ({
1809
1864
  file,
1810
1865
  source,
@@ -1879,7 +1934,7 @@ function collectMiniProgramSubpackageSourceEntries(snapshot, subpackageRoots, so
1879
1934
  if (entry.output.type !== "chunk" || !isSubpackageOutputFile(entry.file, subpackageRoots)) continue;
1880
1935
  const matchedSubpackageRoot = [...subpackageRoots].find((root) => isSubpackageOutputFile(entry.file, new Set([root])));
1881
1936
  if (!matchedSubpackageRoot) continue;
1882
- for (const moduleId of collectChunkModuleIds$1(entry.output)) {
1937
+ for (const moduleId of collectChunkModuleIds$2(entry.output)) {
1883
1938
  if (!path.isAbsolute(moduleId.replace(/[?#].*$/, ""))) continue;
1884
1939
  const sourceRoot = resolveSubpackageSourceRootFromModuleId(moduleId, matchedSubpackageRoot);
1885
1940
  if (sourceRoot) sourceRoots.add(sourceRoot);
@@ -1913,7 +1968,7 @@ function readAssetSource$2(asset) {
1913
1968
  function clearAssetSource(asset) {
1914
1969
  asset.source = "";
1915
1970
  }
1916
- function appendCss(baseCss, css) {
1971
+ function appendCss$1(baseCss, css) {
1917
1972
  if (baseCss.length === 0) return css;
1918
1973
  if (css.length === 0) return baseCss;
1919
1974
  return `${baseCss}\n${css}`;
@@ -2063,6 +2118,7 @@ function resolvePreservedImportShellInjectionTarget(opts, bundle, file, css) {
2063
2118
  const importedStyleFiles = collectImportedStyleFiles(css, file);
2064
2119
  if (importedStyleFiles.size !== 1) return;
2065
2120
  const [importedFile] = importedStyleFiles;
2121
+ if (!importedFile) return;
2066
2122
  if (!isRootStyleOutputFile(importedFile)) return;
2067
2123
  for (const [bundleFile, output] of Object.entries(bundle)) {
2068
2124
  if (output.type !== "asset") continue;
@@ -2245,13 +2301,13 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
2245
2301
  let css = stripBundlerGeneratedCssMarkers(record.css).trim();
2246
2302
  css = removeCssCoveredByImportedViteResults(css, importedCssSources).trim();
2247
2303
  if (css.length === 0) continue;
2248
- if (containsCssAfterMinify(nextCss, css) || filterExistingCssRules(nextCss, css).length === 0) continue;
2249
2304
  const mergedLayerCss = mergeMarkedUserLayerComponentsCss(nextCss, css);
2250
2305
  if (mergedLayerCss.merged) {
2251
2306
  nextCss = mergedLayerCss.css;
2252
2307
  css = extractMarkedUserLayerComponentsCss(css).rest.trim();
2253
2308
  if (css.length === 0) continue;
2254
2309
  }
2310
+ if (containsCssAfterMinify(nextCss, css) || filterExistingCssRules(nextCss, css).length === 0) continue;
2255
2311
  if (containsCssAfterMinify(nextCss, css)) continue;
2256
2312
  const mergedPreflightDeclarations = mergeMiniProgramPreflightRuleDeclarations(nextCss, css);
2257
2313
  if (mergedPreflightDeclarations.changed) {
@@ -2273,7 +2329,7 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
2273
2329
  }
2274
2330
  const missingCss = filterExistingCssRules(nextCss, css);
2275
2331
  if (missingCss.length === 0 || containsCssAfterMinify(nextCss, missingCss)) continue;
2276
- nextCss = appendCss(nextCss, missingCss);
2332
+ nextCss = appendCss$1(nextCss, missingCss);
2277
2333
  }
2278
2334
  if (nextCss === originalSource) continue;
2279
2335
  output.source = nextCss;
@@ -2346,9 +2402,9 @@ async function finalizeMiniProgramCssAssets(bundle, options) {
2346
2402
  cssOptions: {
2347
2403
  ...cssHandlerOptions.cssOptions ?? {},
2348
2404
  autoprefixer: false,
2349
- cssPresetEnv: false
2405
+ cssPresetEnv: {}
2350
2406
  },
2351
- cssPresetEnv: false
2407
+ cssPresetEnv: {}
2352
2408
  });
2353
2409
  const outputCss = stripMiniProgramCssSpecificityPlaceholders(css);
2354
2410
  if (outputCss === rawSource) continue;
@@ -2450,6 +2506,27 @@ function formatMs(value) {
2450
2506
  }
2451
2507
  //#endregion
2452
2508
  //#region src/bundlers/vite/generate-bundle/uni-app-x-postprocess.ts
2509
+ function appendCss(baseCss, css) {
2510
+ if (baseCss.length === 0) return css;
2511
+ if (css.length === 0) return baseCss;
2512
+ return `${baseCss}\n${css}`;
2513
+ }
2514
+ function injectHarmonyCssIntoMainAsset(bundle, cssSources, onUpdate, debug) {
2515
+ const output = bundle["main.css"];
2516
+ if (output?.type !== "asset" || cssSources.length === 0) return false;
2517
+ const currentSource = String(output.source);
2518
+ let nextSource = currentSource;
2519
+ for (const css of cssSources) {
2520
+ const trimmedCss = css.trim();
2521
+ if (trimmedCss.length === 0 || nextSource.includes(trimmedCss)) continue;
2522
+ nextSource = appendCss(nextSource, trimmedCss);
2523
+ }
2524
+ if (nextSource === currentSource) return false;
2525
+ output.source = nextSource;
2526
+ onUpdate("main.css", currentSource, nextSource);
2527
+ debug("uni-app-x harmony main css inject");
2528
+ return true;
2529
+ }
2453
2530
  async function handleUniAppXPostCssTasks(options) {
2454
2531
  const { bundle, debug, generatorRuntime, getCssHandlerOptions, getSourceCandidateSourcesForEntries, getSourceCandidatesForEntries, getViteProcessedCssAssetResults, isHarmonyAppStyleTarget, isNativeAppStyleTarget, onUpdate, opts, runtimeState, styleHandler } = options;
2455
2532
  const applyStyleSources = collectUniAppXHarmonyApplyStyleSources(bundle);
@@ -2482,6 +2559,7 @@ async function handleUniAppXPostCssTasks(options) {
2482
2559
  }));
2483
2560
  }
2484
2561
  if (isHarmonyAppStyleTarget && injectUniAppXHarmonyBundleStyles(bundle, { cssSources: viteProcessedCssSources })) debug("uni-app-x harmony bundle styles inject");
2562
+ if (isHarmonyAppStyleTarget) injectHarmonyCssIntoMainAsset(bundle, viteProcessedCssSources, onUpdate, debug);
2485
2563
  for (const [file, item] of Object.entries(bundle)) {
2486
2564
  if (item.type !== "asset" || !file.endsWith(".uvue.ts")) continue;
2487
2565
  const currentSource = String(item.source);
@@ -2547,11 +2625,11 @@ function readAssetSource(asset) {
2547
2625
  function getAssetFile(bundleFile, asset) {
2548
2626
  return asset.fileName || bundleFile;
2549
2627
  }
2550
- function isRootMiniProgramStyleOutputFile$1(file) {
2628
+ function isRootMiniProgramStyleOutputFile(file) {
2551
2629
  const normalized = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
2552
2630
  return !normalized.includes("/") && /\.(?:wxss|acss|ttss|qss|jxss|tyss)$/i.test(normalized);
2553
2631
  }
2554
- function createRelativeCssImportRequest$1(targetFile, importedFile) {
2632
+ function createRelativeCssImportRequest(targetFile, importedFile) {
2555
2633
  const normalizedTargetFile = normalizeOutputPathKey(targetFile.replace(/[?#].*$/, ""));
2556
2634
  const normalizedImportedFile = normalizeOutputPathKey(importedFile.replace(/[?#].*$/, ""));
2557
2635
  const targetDir = path.posix.dirname(normalizedTargetFile);
@@ -2559,12 +2637,12 @@ function createRelativeCssImportRequest$1(targetFile, importedFile) {
2559
2637
  const relative = path.posix.relative(baseDir, normalizedImportedFile);
2560
2638
  return relative.startsWith(".") ? relative : `./${relative}`;
2561
2639
  }
2562
- function createCssImportShell$1(targetFile, importedFile) {
2563
- return `@import "${createRelativeCssImportRequest$1(targetFile, importedFile)}";\n`;
2640
+ function createCssImportShell(targetFile, importedFile) {
2641
+ return `@import "${createRelativeCssImportRequest(targetFile, importedFile)}";\n`;
2564
2642
  }
2565
2643
  function resolveRootMiniProgramOriginStyleFile(file) {
2566
2644
  const normalized = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
2567
- if (!isRootMiniProgramStyleOutputFile$1(normalized)) return;
2645
+ if (!isRootMiniProgramStyleOutputFile(normalized)) return;
2568
2646
  if (/(?:^|\/)[^/]+-origin\.[^.]+$/i.test(normalized)) return;
2569
2647
  return normalized.replace(/(\.[^.]+)$/, "-origin$1");
2570
2648
  }
@@ -2589,7 +2667,7 @@ function normalizeTaroRootImportShellAssets(bundle, options) {
2589
2667
  for (const [rootBundleFile, rootOutput] of Object.entries(bundle)) {
2590
2668
  if (rootOutput.type !== "asset") continue;
2591
2669
  const rootFile = getAssetFile(rootBundleFile, rootOutput);
2592
- if (!isRootMiniProgramStyleOutputFile$1(rootFile) || !options.cssMatcher(rootFile)) continue;
2670
+ if (!isRootMiniProgramStyleOutputFile(rootFile) || !options.cssMatcher(rootFile)) continue;
2593
2671
  const originFile = resolveRootMiniProgramOriginStyleFile(rootFile);
2594
2672
  if (!originFile || !options.cssMatcher(originFile)) continue;
2595
2673
  const originOutput = Object.entries(bundle).find(([bundleFile, output]) => output.type === "asset" && normalizeOutputPathKey(getAssetFile(bundleFile, output)) === normalizeOutputPathKey(originFile))?.[1];
@@ -2601,7 +2679,7 @@ function normalizeTaroRootImportShellAssets(bundle, options) {
2601
2679
  const importedFile = resolveSingleCssImportOutputFile(originFile, originSource);
2602
2680
  if (importedFile && normalizeOutputPathKey(importedFile) !== normalizeOutputPathKey(rootFile)) continue;
2603
2681
  } else if (originSource.trim().length > 0 && originSource.trim() !== rootSource.trim()) continue;
2604
- const nextRootSource = createCssImportShell$1(rootFile, originFile);
2682
+ const nextRootSource = createCssImportShell(rootFile, originFile);
2605
2683
  if (rootSource === nextRootSource) continue;
2606
2684
  rootOutput.source = nextRootSource;
2607
2685
  originOutput.source = rootSource;
@@ -2615,12 +2693,14 @@ function normalizeTaroRootImportShellAssets(bundle, options) {
2615
2693
  return updated;
2616
2694
  }
2617
2695
  async function finalizeGenerateBundle(options) {
2618
- 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;
2696
+ const { activeProcessCacheKeys, activeProcessHashKeys, activeViteCssCacheFiles, bundle, bundleFiles, cache, cssTaskFactories, debug, defaultStyleOutputExtension, formatIteration, generatorCandidateSignature, generatorRuntime, getCssHandlerOptions, getSourceCandidateSourcesForEntries, getSourceCandidatesForEntries, getViteCssCacheStats, getViteProcessedCssAssetResults, hmrTimingRecorder, hmrTimingStartedAt, isHarmonyAppStyleTarget, isNativeAppStyleTarget, isViteProcessedCssAsset, isWebGeneratorTarget, jsAfterCss, jsTaskFactories, 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;
2697
+ const tasksStart = performance.now();
2619
2698
  if (cssTaskFactories.length > 0) {
2620
- const cssConcurrency = resolveViteCssTaskConcurrency(useIncrementalMode, runtimeState.tailwindRuntime.majorVersion);
2621
- tasks.push(runWithConcurrency(cssTaskFactories, cssConcurrency).then(() => void 0));
2699
+ const cssTask = runWithConcurrency(cssTaskFactories, resolveViteCssTaskConcurrency(useIncrementalMode, runtimeState.tailwindRuntime.majorVersion)).then(() => void 0);
2700
+ if (jsAfterCss) await cssTask;
2701
+ else tasks.push(cssTask);
2622
2702
  }
2623
- const tasksStart = performance.now();
2703
+ if (jsTaskFactories.length > 0) tasks.push(runWithConcurrency(jsTaskFactories).then(() => void 0));
2624
2704
  await Promise.all(tasks);
2625
2705
  recordTimingDetail("tasks", tasksStart);
2626
2706
  for (const apply of pendingLinkedUpdates) apply();
@@ -2740,6 +2820,120 @@ async function finalizeGenerateBundle(options) {
2740
2820
  debug("end");
2741
2821
  }
2742
2822
  //#endregion
2823
+ //#region src/bundlers/vite/generate-bundle/candidates.ts
2824
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
2825
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
2826
+ const CLASS_ATTRIBUTE_RE = /\bclass\s*=\s*/g;
2827
+ const MUSTACHE_OPEN = "{{";
2828
+ const MUSTACHE_CLOSE = "}}";
2829
+ function isUrlLikeCandidate(candidate) {
2830
+ return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
2831
+ }
2832
+ function isArbitraryValueCandidate(candidate) {
2833
+ return candidate.includes("[") && candidate.includes("]") && !isUrlLikeCandidate(candidate.trim());
2834
+ }
2835
+ function collectClassAttributeValues(source) {
2836
+ const values = [];
2837
+ CLASS_ATTRIBUTE_RE.lastIndex = 0;
2838
+ let matched = CLASS_ATTRIBUTE_RE.exec(source);
2839
+ while (matched !== null) {
2840
+ const quoteIndex = CLASS_ATTRIBUTE_RE.lastIndex;
2841
+ const quote = source[quoteIndex];
2842
+ if (quote !== "\"" && quote !== "'") {
2843
+ matched = CLASS_ATTRIBUTE_RE.exec(source);
2844
+ continue;
2845
+ }
2846
+ let expressionDepth = 0;
2847
+ for (let index = quoteIndex + 1; index < source.length; index++) {
2848
+ if (source.startsWith(MUSTACHE_OPEN, index)) {
2849
+ expressionDepth++;
2850
+ index += 1;
2851
+ continue;
2852
+ }
2853
+ if (expressionDepth > 0 && source.startsWith(MUSTACHE_CLOSE, index)) {
2854
+ expressionDepth--;
2855
+ index += 1;
2856
+ continue;
2857
+ }
2858
+ if (expressionDepth === 0 && source[index] === quote) {
2859
+ values.push(source.slice(quoteIndex + 1, index));
2860
+ CLASS_ATTRIBUTE_RE.lastIndex = index + 1;
2861
+ break;
2862
+ }
2863
+ }
2864
+ matched = CLASS_ATTRIBUTE_RE.exec(source);
2865
+ }
2866
+ return values;
2867
+ }
2868
+ function collectUnescapedDynamicCandidates(source, allowedCandidates) {
2869
+ const matches = /* @__PURE__ */ new Set();
2870
+ const shouldFilterByAllowedCandidates = allowedCandidates !== void 0 && allowedCandidates.size > 0;
2871
+ for (const classValue of collectClassAttributeValues(source)) for (const expression of classValue.match(MUSTACHE_EXPRESSION_RE) ?? []) {
2872
+ QUOTED_LITERAL_RE.lastIndex = 0;
2873
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
2874
+ while (quoted !== null) {
2875
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
2876
+ for (const candidate of splitCandidateTokens(literal)) {
2877
+ const normalized = candidate.trim();
2878
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
2879
+ if (shouldFilterByAllowedCandidates && !allowedCandidates.has(normalized)) continue;
2880
+ matches.add(normalized);
2881
+ }
2882
+ quoted = QUOTED_LITERAL_RE.exec(expression);
2883
+ }
2884
+ }
2885
+ return [...matches];
2886
+ }
2887
+ //#endregion
2888
+ //#region src/bundlers/vite/generate-bundle/html-processing.ts
2889
+ function processHtmlBundleEntry(options) {
2890
+ const { cache, context, debug, dynamicRetryCandidates, file, metrics, onUpdate, originalEntrySource, originalSource, rememberProcessCacheKey, resolveCurrentSourceCandidateSource, tasks, templateHandler, timeTask, transformRuntime, transformRuntimeSignature } = options;
2891
+ const rawSource = resolveCurrentSourceCandidateSource(file) ?? originalEntrySource;
2892
+ const currentRawDynamicCandidates = collectUnescapedDynamicCandidates(rawSource);
2893
+ const templateRuntime = currentRawDynamicCandidates.length > 0 ? new Set([...transformRuntime, ...currentRawDynamicCandidates]) : transformRuntime;
2894
+ const templateRuntimeSignature = templateRuntime === transformRuntime ? transformRuntimeSignature : createCandidateSignature(templateRuntime);
2895
+ const htmlProcessHash = `${cache.computeHash(rawSource)}:${cache.computeHash(createRuntimeAffectingSourceSignature(rawSource, "html"))}:${templateRuntimeSignature}`;
2896
+ const cacheKey = `${file}:html:${htmlProcessHash}`;
2897
+ const hashKey = cacheKey;
2898
+ rememberProcessCacheKey(cacheKey, hashKey);
2899
+ tasks.push(timeTask("html", () => processCachedTask({
2900
+ cache,
2901
+ cacheKey,
2902
+ hashKey,
2903
+ hash: htmlProcessHash,
2904
+ applyResult(source) {
2905
+ originalSource.source = source;
2906
+ },
2907
+ onCacheHit() {
2908
+ metrics.html.cacheHits++;
2909
+ debug("html cache hit: %s", file);
2910
+ },
2911
+ async transform() {
2912
+ const start = performance.now();
2913
+ let transformed = await templateHandler(rawSource, { runtimeSet: templateRuntime });
2914
+ let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
2915
+ let retryRuntimeSet;
2916
+ if (unresolvedDynamicCandidates.length > 0) {
2917
+ const fullRuntimeSet = await context.ensureRuntimeClassSet(true);
2918
+ const allowedRetryCandidates = fullRuntimeSet.size === 0 ? unresolvedDynamicCandidates : unresolvedDynamicCandidates.filter((candidate) => dynamicRetryCandidates.has(candidate) || fullRuntimeSet.has(candidate));
2919
+ retryRuntimeSet = new Set([...fullRuntimeSet, ...allowedRetryCandidates]);
2920
+ unresolvedDynamicCandidates = unresolvedDynamicCandidates.filter((candidate) => retryRuntimeSet?.has(candidate) === true);
2921
+ }
2922
+ if (retryRuntimeSet && unresolvedDynamicCandidates.length > 0) {
2923
+ logger.warn("检测到已提取 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
2924
+ transformed = await templateHandler(rawSource, { runtimeSet: retryRuntimeSet });
2925
+ unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed, retryRuntimeSet);
2926
+ if (unresolvedDynamicCandidates.length > 0) logger.warn("已提取 WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
2927
+ }
2928
+ metrics.html.elapsed += measureElapsed(start);
2929
+ metrics.html.transformed++;
2930
+ onUpdate(file, rawSource, transformed);
2931
+ debug("html handle: %s", file);
2932
+ return { result: transformed };
2933
+ }
2934
+ })));
2935
+ }
2936
+ //#endregion
2743
2937
  //#region src/bundlers/vite/generate-bundle/js-entries.ts
2744
2938
  function createJsEntryResolver(jsEntries) {
2745
2939
  const normalizedJsEntries = /* @__PURE__ */ new Map();
@@ -2796,7 +2990,7 @@ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
2796
2990
  //#endregion
2797
2991
  //#region src/bundlers/vite/generate-bundle/js-processing.ts
2798
2992
  function processJsBundleEntry(options) {
2799
- const { applyLinkedUpdates, bundle, cache, createHandlerOptions, debug, disableJsPrecheck, entry, getJsEntry, jsHandler, jsTaskFactories, linkedByEntry, metrics, onUpdate, outDir, processFiles, rememberProcessCacheKey, runtimeSignature, snapshot, timeTask, transformRuntime, uniAppX, useIncrementalMode } = options;
2993
+ const { applyLinkedUpdates, bundle, cache, createHandlerOptions, debug, disableJsPrecheck, entry, getJsEntry, jsHandler, jsTaskFactories, linkedByEntry, metrics, onUpdate, outDir, processFiles, rememberProcessCacheKey, runtimeSignature, snapshot, shouldSkipAstTransform, slowJsAstWarnMs, timeTask, transformRuntime, transformRuntimeSignature, transformFilterSignature, uniAppX, useIncrementalMode } = options;
2800
2994
  const { file, output: originalSource, source: originalEntrySource } = entry;
2801
2995
  metrics.js.total++;
2802
2996
  const shouldTransformJs = !useIncrementalMode || processFiles.js.has(file);
@@ -2806,7 +3000,8 @@ function processJsBundleEntry(options) {
2806
3000
  const initialRawSource = originalEntrySource;
2807
3001
  const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
2808
3002
  if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
2809
- const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
3003
+ const linkedImpactSignature = useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0;
3004
+ const hashSalt = createJsHashSalt(`${transformRuntimeSignature}:transform-filter:${transformFilterSignature}`, linkedImpactSignature);
2810
3005
  const hashKey = `${file}:js`;
2811
3006
  const processHash = `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`;
2812
3007
  rememberProcessCacheKey(file, hashKey);
@@ -2837,15 +3032,24 @@ function processJsBundleEntry(options) {
2837
3032
  const start = performance.now();
2838
3033
  const rawSource = originalSource.code;
2839
3034
  if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
3035
+ if (shouldSkipAstTransform?.(originalSource)) {
3036
+ metrics.js.elapsed += measureElapsed(start);
3037
+ metrics.js.transformed++;
3038
+ debug("js skip ast transform (filtered): %s", file);
3039
+ return { result: rawSource };
3040
+ }
2840
3041
  const handlerOptions = createHandlerOptions(absoluteFile);
2841
3042
  if (!disableJsPrecheck && shouldSkipJsTransform(rawSource, handlerOptions)) {
2842
3043
  metrics.js.elapsed += measureElapsed(start);
2843
3044
  metrics.js.transformed++;
2844
3045
  return { result: rawSource };
2845
3046
  }
3047
+ const handlerStart = performance.now();
2846
3048
  const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
3049
+ const handlerElapsed = measureElapsed(handlerStart);
2847
3050
  metrics.js.elapsed += measureElapsed(start);
2848
3051
  metrics.js.transformed++;
3052
+ if (handlerElapsed >= slowJsAstWarnMs) logger$1.warn("JS AST 转译耗时较长: %s 用时 %sms,源码约 %d bytes。若这是大型生成 TS/JS chunk,请配置 weapp-tailwindcss 的 transform.exclude 排除 generated/openapi 等目录。", file, handlerElapsed.toFixed(1), rawSource.length);
2849
3053
  onUpdate(file, rawSource, code);
2850
3054
  debug("js handle: %s", file);
2851
3055
  collectLinkedFileNames(linked, getJsEntry, linkedSet);
@@ -2972,7 +3176,8 @@ function mergeRememberedCssSources(sources, outputFile) {
2972
3176
  function collectRememberedCssReplayGroups(sources, opts, rootDir, isWebGeneratorTarget, preserveCssExtension, sourceRoot, styleOutputExtension, styleOutputFiles) {
2973
3177
  const groups = /* @__PURE__ */ new Map();
2974
3178
  for (const [key, remembered] of sources ?? []) {
2975
- const outputKey = normalizeOutputPathKey(resolveViteCssPipelineOutputFile(remembered.outputFile, opts, rootDir, isWebGeneratorTarget, preserveCssExtension, sourceRoot, styleOutputExtension, styleOutputFiles));
3179
+ const cleanSourceFile = remembered.sourceFile.replace(/[?#].*$/, "");
3180
+ const outputKey = normalizeOutputPathKey(CSS_SOURCE_OUTPUT_EXT_RE.test(cleanSourceFile) ? resolveViteCssPipelineOutputFileFromSourceFile(remembered.sourceFile, opts, rootDir, isWebGeneratorTarget, preserveCssExtension, sourceRoot, styleOutputExtension, styleOutputFiles) : resolveViteCssPipelineOutputFileFromSourceFile(remembered.outputFile, opts, rootDir, isWebGeneratorTarget, preserveCssExtension, sourceRoot, styleOutputExtension, styleOutputFiles));
2976
3181
  const group = groups.get(outputKey) ?? [];
2977
3182
  group.push({
2978
3183
  key,
@@ -3055,7 +3260,7 @@ async function processRememberedCssReplay(options) {
3055
3260
  }
3056
3261
  if (shouldEmitRememberedReplayCssAsset) {
3057
3262
  const replayAsset = emitOrReplayCssAsset(outputFile, css);
3058
- markCssAssetProcessed?.(replayAsset, outputFile);
3263
+ if (replayAsset) markCssAssetProcessed?.(replayAsset, outputFile);
3059
3264
  }
3060
3265
  metrics.css.elapsed += measureElapsed(start);
3061
3266
  metrics.css.transformed++;
@@ -3110,6 +3315,26 @@ function collectJsImportedCssFiles(snapshot) {
3110
3315
  return files;
3111
3316
  }
3112
3317
  //#endregion
3318
+ //#region src/bundlers/vite/generate-bundle/runtime-linked-source-memory.ts
3319
+ function rememberRuntimeLinkedCssSources(options) {
3320
+ const { bundleFiles, defaultStyleOutputExtension, debug, getConfiguredTailwindV4CssSourceEntries, getSourceCandidateSource, getSourceCandidateSources, isWebGeneratorTarget, jsImportedCssFiles, opts, outDir, rememberCssSource, rootDir, runtimeLinkedCssFiles, shouldPreserveAppCssExtension, snapshot, sourceRoot } = options;
3321
+ for (const file of runtimeLinkedCssFiles) {
3322
+ if (snapshot.sourceHashByFile.has(file)) {
3323
+ snapshot.processFiles.css.add(file);
3324
+ continue;
3325
+ }
3326
+ const outputFile = resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension, sourceRoot, defaultStyleOutputExtension, bundleFiles);
3327
+ const inferredSourceStyle = resolveSourceStyleSourceFromOutputFile(outputFile, snapshot, outDir, sourceRoot, getSourceCandidateSource, jsImportedCssFiles.has(file) ? getSourceCandidateSources : void 0, getConfiguredTailwindV4CssSourceEntries().map((entry) => [entry.file, entry.source]), debug);
3328
+ const rawSource = inferredSourceStyle?.rawSource ?? getSourceCandidateSource?.(path.resolve(outDir, file)) ?? getSourceCandidateSource?.(file);
3329
+ if (rawSource === void 0 || !hasTailwindGenerationSource(rawSource)) continue;
3330
+ rememberCssSource?.({
3331
+ outputFile,
3332
+ rawSource,
3333
+ sourceFile: inferredSourceStyle?.sourceFile ?? path.resolve(outDir, file)
3334
+ });
3335
+ }
3336
+ }
3337
+ //#endregion
3113
3338
  //#region src/bundlers/vite/generate-bundle/source-candidate-scope.ts
3114
3339
  function intersectCandidateSets(left, right) {
3115
3340
  if (left.size === 0 || right.size === 0) return /* @__PURE__ */ new Set();
@@ -3235,6 +3460,111 @@ function createSubpackageSourceCandidateScope(options) {
3235
3460
  };
3236
3461
  }
3237
3462
  //#endregion
3463
+ //#region src/bundlers/vite/generate-bundle/source-candidate-source.ts
3464
+ function normalizeSourceCandidatePathKey(file) {
3465
+ return normalizeOutputPathKey(path.resolve(file));
3466
+ }
3467
+ function resolveCurrentSourceCandidateSource(options) {
3468
+ const { file, getSourceCandidateSource, getSourceCandidateSources, outDir, rootDir, sourceRoot } = options;
3469
+ const cleanedFile = file.replace(/[?#].*$/, "");
3470
+ const normalizedFile = normalizeOutputPathKey(cleanedFile);
3471
+ const absoluteFile = path.isAbsolute(cleanedFile) ? cleanedFile : path.resolve(rootDir, cleanedFile);
3472
+ const relativeFromOutDir = normalizeOutputPathKey(path.relative(outDir, absoluteFile));
3473
+ const sourceCandidates = [
3474
+ sourceRoot ? path.resolve(sourceRoot, file) : void 0,
3475
+ path.resolve(rootDir, file),
3476
+ path.resolve(path.dirname(outDir), file),
3477
+ path.resolve(outDir, file),
3478
+ !path.isAbsolute(relativeFromOutDir) && !relativeFromOutDir.startsWith("../") ? path.resolve(rootDir, relativeFromOutDir) : void 0,
3479
+ !path.isAbsolute(relativeFromOutDir) && !relativeFromOutDir.startsWith("../") ? path.resolve(path.dirname(outDir), relativeFromOutDir) : void 0,
3480
+ file
3481
+ ];
3482
+ const explicitSource = sourceCandidates.reduce((source, candidate) => {
3483
+ if (source || !candidate) return source;
3484
+ return getSourceCandidateSource?.(candidate);
3485
+ }, void 0);
3486
+ if (explicitSource) return explicitSource;
3487
+ const normalizedSourceCandidates = sourceCandidates.filter((candidate) => Boolean(candidate)).map((candidate) => ({
3488
+ absolute: path.isAbsolute(candidate),
3489
+ key: normalizeSourceCandidatePathKey(candidate)
3490
+ }));
3491
+ let bestSource;
3492
+ for (const [sourceFile, source] of getSourceCandidateSources?.() ?? []) {
3493
+ const normalizedSourceFile = normalizeSourceCandidatePathKey(sourceFile);
3494
+ let score = 0;
3495
+ for (const candidate of normalizedSourceCandidates) if (normalizedSourceFile === candidate.key) {
3496
+ score = Math.max(score, candidate.absolute ? 100 : 80);
3497
+ continue;
3498
+ }
3499
+ if (normalizedSourceFile.endsWith(`/${normalizedFile}`)) score = Math.max(score, 20);
3500
+ if (score > (bestSource?.score ?? 0)) bestSource = {
3501
+ score,
3502
+ source
3503
+ };
3504
+ }
3505
+ return bestSource?.source;
3506
+ }
3507
+ //#endregion
3508
+ //#region src/bundlers/vite/generate-bundle/tailwind-v4-css-source.ts
3509
+ function collectTailwindV4SourceFingerprint(source) {
3510
+ const tokens = /* @__PURE__ */ new Set();
3511
+ const add = (prefix, value) => {
3512
+ tokens.add(`${prefix}:${value.trim()}`);
3513
+ };
3514
+ for (const match of source.matchAll(/@config\s+(["'])(.+?)\1\s*;?/g)) {
3515
+ const configRequest = match[2];
3516
+ add("config", path.basename(configRequest));
3517
+ add("config-request", configRequest.replace(/\\/g, "/"));
3518
+ }
3519
+ for (const match of source.matchAll(/@source\s+(not\s+)?(["'])(.+?)\2\s*;?/g)) add(match[1] ? "source:not" : "source", match[3]);
3520
+ for (const match of source.matchAll(/@custom-variant\s+([^{\s]+)/g)) add("custom-variant", match[1]);
3521
+ for (const match of source.matchAll(/@(?:theme|utility|variant|layer)\s+([^{;\s]+)/g)) add("directive", match[1]);
3522
+ for (const match of source.matchAll(/--[\w-]+(?=\s*:)/g)) add("theme-token", match[0]);
3523
+ for (const match of source.matchAll(/\.([_a-z][\w-]*)\s*[{,]/gi)) add("selector", match[1]);
3524
+ return tokens;
3525
+ }
3526
+ function scoreConfiguredTailwindV4SourceForRawSource(rawSource, entrySource) {
3527
+ if (!rawSource) return 0;
3528
+ const rawTokens = collectTailwindV4SourceFingerprint(rawSource);
3529
+ if (rawTokens.size === 0) return 0;
3530
+ const entryTokens = collectTailwindV4SourceFingerprint(entrySource);
3531
+ let score = 0;
3532
+ for (const token of entryTokens) if (rawTokens.has(token)) score += token.startsWith("config:") ? 100 : 1;
3533
+ return score;
3534
+ }
3535
+ function resolveSubpackageRootForFile(file, subpackageRoots) {
3536
+ if (!file || !subpackageRoots) return;
3537
+ return [...subpackageRoots].find((root) => isSubpackageOutputFile(file, new Set([root])));
3538
+ }
3539
+ function isSameSubpackageScope(outputFile, sourceFile, subpackageRoots) {
3540
+ return resolveSubpackageRootForFile(outputFile, subpackageRoots) === resolveSubpackageRootForFile(sourceFile, subpackageRoots);
3541
+ }
3542
+ function selectTailwindV4GenerationCssSourceForOutput(outputFile, entries, rawSource, subpackageRoots) {
3543
+ const generationSources = entries.filter((entry) => hasTailwindGenerationSource(entry.source));
3544
+ if (generationSources.length <= 1) return generationSources[0];
3545
+ const selectByRawSourceFingerprint = (candidates) => {
3546
+ const scoredSources = candidates.map((entry) => ({
3547
+ entry,
3548
+ score: scoreConfiguredTailwindV4SourceForRawSource(rawSource, entry.source)
3549
+ })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
3550
+ const bestScore = scoredSources[0]?.score;
3551
+ const bestSources = bestScore ? scoredSources.filter((item) => item.score === bestScore) : [];
3552
+ return bestSources.length === 1 ? bestSources[0]?.entry : void 0;
3553
+ };
3554
+ const rawSourceMatched = selectByRawSourceFingerprint(generationSources);
3555
+ if (rawSourceMatched) return rawSourceMatched;
3556
+ const scopedSources = subpackageRoots ? generationSources.filter((entry) => {
3557
+ const outputMatchesSubpackage = isSubpackageOutputFile(outputFile, subpackageRoots);
3558
+ const sourceMatchesSubpackage = isSubpackageOutputFile(entry.file, subpackageRoots);
3559
+ if (!outputMatchesSubpackage) return !sourceMatchesSubpackage;
3560
+ return sourceMatchesSubpackage && [...subpackageRoots].some((root) => isSubpackageOutputFile(outputFile, new Set([root])) && isSubpackageOutputFile(entry.file, new Set([root])));
3561
+ }) : generationSources;
3562
+ const explicitSources = scopedSources.filter((entry) => /@(?:config|source|plugin|custom-variant|theme|utility|variant|apply)\b/.test(entry.source));
3563
+ const candidates = explicitSources.length === 1 ? explicitSources : scopedSources;
3564
+ if (candidates.length === 1) return candidates[0];
3565
+ return selectByRawSourceFingerprint(candidates);
3566
+ }
3567
+ //#endregion
3238
3568
  //#region src/bundlers/vite/generate-bundle/timing.ts
3239
3569
  function createBundleTaskTimer(recordTimingDetail) {
3240
3570
  return async (name, task) => {
@@ -3247,6 +3577,102 @@ function createBundleTaskTimer(recordTimingDetail) {
3247
3577
  };
3248
3578
  }
3249
3579
  //#endregion
3580
+ //#region src/bundlers/vite/generate-bundle/transform-filter.ts
3581
+ function toArray(value) {
3582
+ return Array.isArray(value) ? value : value === void 0 ? [] : [value];
3583
+ }
3584
+ function normalizeSourceId(id) {
3585
+ const file = cleanUrl(id);
3586
+ return path.isAbsolute(file) ? path.resolve(file) : void 0;
3587
+ }
3588
+ function collectChunkModuleIds$1(chunk) {
3589
+ const ids = /* @__PURE__ */ new Set();
3590
+ for (const id of chunk.moduleIds ?? []) {
3591
+ const normalized = normalizeSourceId(id);
3592
+ if (normalized) ids.add(normalized);
3593
+ }
3594
+ for (const id of Object.keys(chunk.modules ?? {})) {
3595
+ const normalized = normalizeSourceId(id);
3596
+ if (normalized) ids.add(normalized);
3597
+ }
3598
+ return ids;
3599
+ }
3600
+ function collectAssetSourceIds(asset, fallbackFile, rootDir) {
3601
+ const ids = /* @__PURE__ */ new Set();
3602
+ const sourceCandidates = [asset.originalFileName, ...asset.originalFileNames ?? []].filter((candidate) => typeof candidate === "string" && candidate.length > 0);
3603
+ const candidates = sourceCandidates.length > 0 ? sourceCandidates : [fallbackFile];
3604
+ for (const candidate of candidates) {
3605
+ if (typeof candidate !== "string" || candidate.length === 0) continue;
3606
+ const cleanCandidate = cleanUrl(candidate);
3607
+ const resolved = path.isAbsolute(cleanCandidate) ? path.resolve(cleanCandidate) : path.resolve(rootDir, cleanCandidate);
3608
+ ids.add(resolved);
3609
+ }
3610
+ return ids;
3611
+ }
3612
+ function isStringRuleMatched(rule, id, rootDir) {
3613
+ const normalizedId = slash(id);
3614
+ const normalizedRule = slash(rule);
3615
+ if (path.isAbsolute(rule)) return micromatch.isMatch(normalizedId, normalizedRule);
3616
+ const relative = slash(path.relative(rootDir, id));
3617
+ return relative.length > 0 && !relative.startsWith("../") && !path.isAbsolute(relative) && micromatch.isMatch(relative, normalizedRule);
3618
+ }
3619
+ function isRuleMatched(rule, id, rootDir) {
3620
+ if (typeof rule === "string") return isStringRuleMatched(rule, id, rootDir);
3621
+ if (rule instanceof RegExp) {
3622
+ rule.lastIndex = 0;
3623
+ return rule.test(slash(id));
3624
+ }
3625
+ return rule(id) === true;
3626
+ }
3627
+ function createTransformMatcher(rules, rootDir) {
3628
+ const normalizedRules = toArray(rules);
3629
+ if (normalizedRules.length === 0) return;
3630
+ return (id) => normalizedRules.some((rule) => isRuleMatched(rule, id, rootDir));
3631
+ }
3632
+ function shouldSkipSourceIds(sourceIds, filter) {
3633
+ if (sourceIds.size === 0) return false;
3634
+ if (filter.exclude) {
3635
+ let excluded = true;
3636
+ for (const id of sourceIds) if (!filter.exclude(id)) {
3637
+ excluded = false;
3638
+ break;
3639
+ }
3640
+ if (excluded) return true;
3641
+ }
3642
+ if (filter.include) {
3643
+ for (const id of sourceIds) if (filter.include(id)) return false;
3644
+ return true;
3645
+ }
3646
+ return false;
3647
+ }
3648
+ function createTransformFilter(options, rootDir) {
3649
+ const include = createTransformMatcher(options?.include, rootDir);
3650
+ const exclude = createTransformMatcher(options?.exclude, rootDir);
3651
+ if (!include && !exclude) return;
3652
+ return {
3653
+ include,
3654
+ exclude
3655
+ };
3656
+ }
3657
+ function shouldSkipViteJsChunkTransform(chunk, filter) {
3658
+ if (!filter) return false;
3659
+ return shouldSkipSourceIds(collectChunkModuleIds$1(chunk), filter);
3660
+ }
3661
+ function shouldSkipViteAssetTransform(asset, file, rootDir, filter) {
3662
+ if (!filter) return false;
3663
+ return shouldSkipSourceIds(collectAssetSourceIds(asset, file, rootDir), filter);
3664
+ }
3665
+ function createRuleSignature(rules) {
3666
+ return toArray(rules).map((rule) => {
3667
+ if (typeof rule === "string") return `s:${rule}`;
3668
+ if (rule instanceof RegExp) return `r:${rule.source}/${rule.flags}`;
3669
+ return "f";
3670
+ }).join("|") || "none";
3671
+ }
3672
+ function createTransformFilterSignature(options) {
3673
+ return [`include:${createRuleSignature(options?.include)}`, `exclude:${createRuleSignature(options?.exclude)}`].join(";");
3674
+ }
3675
+ //#endregion
3250
3676
  //#region src/bundlers/vite/uni-app-x-css-options.ts
3251
3677
  function resolveUniAppXNativeCssHandlerOptions(opts) {
3252
3678
  const uniUtsPlatform = resolveUniUtsPlatform();
@@ -3279,7 +3705,7 @@ function resolveWeappViteSourceRoot(config, _appType) {
3279
3705
  const root = typeof viteConfig?.root === "string" && viteConfig.root.length > 0 ? path.resolve(viteConfig.root) : process$1.cwd();
3280
3706
  const configuredSrcRoot = resolveSourceRootCandidate(root, viteConfig?.weapp?.srcRoot);
3281
3707
  if (configuredSrcRoot) return configuredSrcRoot;
3282
- 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);
3708
+ 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"]);
3283
3709
  if (envSrcRoot) return envSrcRoot;
3284
3710
  }
3285
3711
  function stripFileExtension(file) {
@@ -3323,32 +3749,6 @@ function resolveSourceRootFromBundleGraph(config, bundle) {
3323
3749
  }
3324
3750
  //#endregion
3325
3751
  //#region src/bundlers/vite/generate-bundle.ts
3326
- function isRootMiniProgramStyleOutputFile(file) {
3327
- const normalized = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
3328
- return !normalized.includes("/") && /\.(?:wxss|acss|ttss|qss|jxss|tyss)$/i.test(normalized);
3329
- }
3330
- function createRelativeCssImportRequest(targetFile, importedFile) {
3331
- const normalizedTargetFile = normalizeOutputPathKey(targetFile.replace(/[?#].*$/, ""));
3332
- const normalizedImportedFile = normalizeOutputPathKey(importedFile.replace(/[?#].*$/, ""));
3333
- const targetDir = path.posix.dirname(normalizedTargetFile);
3334
- const baseDir = targetDir === "." ? "" : targetDir;
3335
- const relative = path.posix.relative(baseDir, normalizedImportedFile);
3336
- return relative.startsWith(".") ? relative : `./${relative}`;
3337
- }
3338
- function createCssImportShell(targetFile, importedFile) {
3339
- return `@import "${createRelativeCssImportRequest(targetFile, importedFile)}";\n`;
3340
- }
3341
- function createRootMiniProgramOriginStyleOutputFile(file) {
3342
- const normalized = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
3343
- if (/(?:^|\/)[^/]+-origin\.[^.]+$/i.test(normalized)) return normalized;
3344
- return normalized.replace(/(\.[^.]+)$/, "-origin$1");
3345
- }
3346
- function shouldKeepRootMiniProgramStyleAsImportShell(appType) {
3347
- return appType === "uni-app-vite" || appType === "uni-app-x" || appType === "taro";
3348
- }
3349
- function shouldMoveRootMiniProgramStyleToImportShellOrigin(appType) {
3350
- return appType === "taro";
3351
- }
3352
3752
  function createGenerateBundleHook(context) {
3353
3753
  const state = createBundleBuildState();
3354
3754
  const lastCssResultByFile = /* @__PURE__ */ new Map();
@@ -3438,119 +3838,17 @@ function createGenerateBundleHook(context) {
3438
3838
  }
3439
3839
  }
3440
3840
  }, opts.tailwindcssBasedir ?? rootDir);
3441
- const collectTailwindV4SourceFingerprint = (source) => {
3442
- const tokens = /* @__PURE__ */ new Set();
3443
- const add = (prefix, value) => {
3444
- const normalized = value?.trim();
3445
- if (normalized) tokens.add(`${prefix}:${normalized}`);
3446
- };
3447
- for (const match of source.matchAll(/@config\s+(["'])(.+?)\1\s*;?/g)) {
3448
- const configRequest = match[2] ?? "";
3449
- add("config", path.basename(configRequest));
3450
- add("config-request", configRequest.replace(/\\/g, "/"));
3451
- }
3452
- for (const match of source.matchAll(/@source\s+(not\s+)?(["'])(.+?)\2\s*;?/g)) add(match[1] ? "source:not" : "source", match[3]);
3453
- for (const match of source.matchAll(/@custom-variant\s+([^{\s]+)/g)) add("custom-variant", match[1]);
3454
- for (const match of source.matchAll(/@(?:theme|utility|variant|layer)\s+([^{;\s]+)/g)) add("directive", match[1]);
3455
- for (const match of source.matchAll(/--[\w-]+(?=\s*:)/g)) add("theme-token", match[0]);
3456
- for (const match of source.matchAll(/\.([_a-z][\w-]*)\s*[{,]/gi)) add("selector", match[1]);
3457
- return tokens;
3458
- };
3459
- const scoreConfiguredTailwindV4SourceForRawSource = (rawSource, entrySource) => {
3460
- if (!rawSource) return 0;
3461
- const rawTokens = collectTailwindV4SourceFingerprint(rawSource);
3462
- if (rawTokens.size === 0) return 0;
3463
- const entryTokens = collectTailwindV4SourceFingerprint(entrySource);
3464
- let score = 0;
3465
- for (const token of entryTokens) if (rawTokens.has(token)) score += token.startsWith("config:") ? 100 : 1;
3466
- return score;
3467
- };
3468
- const selectTailwindV4GenerationCssSourceForOutput = (outputFile, entries, rawSource) => {
3469
- const generationSources = entries.filter((entry) => hasTailwindGenerationSource(entry.source));
3470
- if (generationSources.length <= 1) return generationSources[0];
3471
- const selectByRawSourceFingerprint = (candidates) => {
3472
- const scoredSources = candidates.map((entry) => ({
3473
- entry,
3474
- score: scoreConfiguredTailwindV4SourceForRawSource(rawSource, entry.source)
3475
- })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
3476
- const bestScore = scoredSources[0]?.score;
3477
- const bestSources = bestScore ? scoredSources.filter((item) => item.score === bestScore) : [];
3478
- return bestSources.length === 1 ? bestSources[0]?.entry : void 0;
3479
- };
3480
- const rawSourceMatched = selectByRawSourceFingerprint(generationSources);
3481
- if (rawSourceMatched) return rawSourceMatched;
3482
- const scopedSources = currentSubpackageRoots ? generationSources.filter((entry) => {
3483
- const outputMatchesSubpackage = isSubpackageOutputFile(outputFile, currentSubpackageRoots);
3484
- const sourceMatchesSubpackage = isSubpackageOutputFile(entry.file, currentSubpackageRoots);
3485
- if (!outputMatchesSubpackage) return !sourceMatchesSubpackage;
3486
- return sourceMatchesSubpackage && [...currentSubpackageRoots].some((root) => isSubpackageOutputFile(outputFile, new Set([root])) && isSubpackageOutputFile(entry.file, new Set([root])));
3487
- }) : generationSources;
3488
- const explicitSources = scopedSources.filter((entry) => /@(?:config|source|plugin|custom-variant|theme|utility|variant|apply)\b/.test(entry.source));
3489
- const candidates = explicitSources.length === 1 ? explicitSources : scopedSources;
3490
- if (candidates.length === 1) return candidates[0];
3491
- return selectByRawSourceFingerprint(candidates);
3492
- };
3493
- const resolveSubpackageRootForFile = (file) => {
3494
- if (!file || !currentSubpackageRoots) return;
3495
- return [...currentSubpackageRoots].find((root) => isSubpackageOutputFile(file, new Set([root])));
3496
- };
3497
- const isSameSubpackageScope = (outputFile, sourceFile) => {
3498
- return resolveSubpackageRootForFile(outputFile) === resolveSubpackageRootForFile(sourceFile);
3499
- };
3500
3841
  const normalizeGeneratorUserRawSource = (source, sourceFile, fallbackFile) => normalizeRelativeCssConfigDirectives(source, sourceFile || fallbackFile, outDir, opts);
3501
- const normalizeSourceCandidatePathKey = (file) => normalizeOutputPathKey(path.resolve(file));
3502
- const resolveCurrentSourceCandidateSource = (file) => {
3503
- const cleanedFile = file.replace(/[?#].*$/, "");
3504
- const normalizedFile = normalizeOutputPathKey(cleanedFile);
3505
- const absoluteFile = path.isAbsolute(cleanedFile) ? cleanedFile : path.resolve(rootDir, cleanedFile);
3506
- const relativeFromOutDir = normalizeOutputPathKey(path.relative(outDir, absoluteFile));
3507
- const sourceCandidates = [
3508
- sourceRoot ? path.resolve(sourceRoot, file) : void 0,
3509
- path.resolve(rootDir, file),
3510
- path.resolve(path.dirname(outDir), file),
3511
- path.resolve(outDir, file),
3512
- !path.isAbsolute(relativeFromOutDir) && !relativeFromOutDir.startsWith("../") ? path.resolve(rootDir, relativeFromOutDir) : void 0,
3513
- !path.isAbsolute(relativeFromOutDir) && !relativeFromOutDir.startsWith("../") ? path.resolve(path.dirname(outDir), relativeFromOutDir) : void 0,
3514
- file
3515
- ];
3516
- const explicitSource = sourceCandidates.reduce((source, candidate) => {
3517
- if (source || !candidate) return source;
3518
- return getSourceCandidateSource?.(candidate);
3519
- }, void 0);
3520
- if (explicitSource) return explicitSource;
3521
- const normalizedSourceCandidates = sourceCandidates.filter((candidate) => Boolean(candidate)).map((candidate) => ({
3522
- absolute: path.isAbsolute(candidate),
3523
- key: normalizeSourceCandidatePathKey(candidate)
3524
- }));
3525
- let bestSource;
3526
- for (const [sourceFile, source] of getSourceCandidateSources?.() ?? []) {
3527
- const normalizedSourceFile = normalizeSourceCandidatePathKey(sourceFile);
3528
- let score = 0;
3529
- for (const candidate of normalizedSourceCandidates) {
3530
- if (normalizedSourceFile === candidate.key) {
3531
- score = Math.max(score, candidate.absolute ? 100 : 80);
3532
- continue;
3533
- }
3534
- if (normalizedSourceFile.endsWith(`/${candidate.key}`)) score = Math.max(score, candidate.absolute ? 60 : 40);
3535
- }
3536
- if (normalizedSourceFile.endsWith(`/${normalizedFile}`)) score = Math.max(score, 20);
3537
- if (score > (bestSource?.score ?? 0)) bestSource = {
3538
- score,
3539
- source
3540
- };
3541
- }
3542
- return bestSource?.source;
3543
- };
3544
- const resolveOutputFileFromMatchedCssSource = (sourceFile) => {
3545
- if (!sourceFile) return;
3546
- const outputFile = resolveViteCssPipelineOutputFileFromSourceFile(sourceFile, opts, rootDir, isWebGeneratorTarget, false, sourceRoot, defaultStyleOutputExtension, bundleFiles);
3547
- return opts.cssMatcher(outputFile) ? outputFile : void 0;
3548
- };
3549
- const hasViteProcessedCssResultForSource = (sourceFile) => {
3550
- const sourceKey = normalizeOutputPathKey(sourceFile);
3551
- for (const [file] of getViteProcessedCssAssetResults?.() ?? []) if (normalizeOutputPathKey(file) === sourceKey) return true;
3552
- return false;
3553
- };
3842
+ const resolveMatchedCssSourceOutputFile = (sourceFile) => resolveOutputFileFromMatchedCssSource({
3843
+ bundleFiles,
3844
+ defaultStyleOutputExtension,
3845
+ isWebGeneratorTarget,
3846
+ opts,
3847
+ rootDir,
3848
+ shouldPreserveAppCssExtension: false,
3849
+ sourceFile,
3850
+ sourceRoot
3851
+ });
3554
3852
  const usedConfiguredTailwindV4CssSourceFiles = /* @__PURE__ */ new Set();
3555
3853
  const buildCommand = resolvedConfig?.command === "build";
3556
3854
  const hasPreviousBundleState = state.iteration > 0 || state.sourceHashByFile.size > 0;
@@ -3600,33 +3898,47 @@ function createGenerateBundleHook(context) {
3600
3898
  });
3601
3899
  const jsEntries = snapshot.jsEntries;
3602
3900
  const getJsEntry = createJsEntryResolver(jsEntries);
3901
+ const transformFilter = createTransformFilter(opts.transform, rootDir);
3902
+ const transformFilterSignature = createTransformFilterSignature(opts.transform);
3603
3903
  const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
3604
3904
  const hasRuntimeAffectingChanges = hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
3605
3905
  const runtimeStart = performance.now();
3606
3906
  const forceV4RuntimeRefreshBySource = forceRuntimeRefreshBySource;
3607
- const runtime = isWebGeneratorTarget && !shouldGenerateWebCssByGenerator ? /* @__PURE__ */ new Set() : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, envFlags.forceRuntimeRefreshByEnv || forceV4RuntimeRefreshBySource, { allowBaselineOnlyInitialSync: buildCommand }) : await context.ensureRuntimeClassSet(envFlags.forceRuntimeRefreshByEnv);
3907
+ const runtime = isWebGeneratorTarget ? /* @__PURE__ */ new Set() : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, envFlags.forceRuntimeRefreshByEnv, {
3908
+ allowBaselineOnlyInitialSync: buildCommand,
3909
+ refreshBySource: forceV4RuntimeRefreshBySource
3910
+ }) : await context.ensureRuntimeClassSet(envFlags.forceRuntimeRefreshByEnv);
3608
3911
  const shouldFilterTailwindV4MiniProgramCandidates = shouldUseMiniProgramCssBranch(generatorBranch);
3609
3912
  const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
3610
3913
  const filteredGeneratorCandidates = shouldFilterTailwindV4MiniProgramCandidates ? filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
3611
- const transformRuntime = runtime;
3914
+ const filteredSourceCandidates = shouldFilterTailwindV4MiniProgramCandidates ? filterUnsupportedMiniProgramTailwindV4Candidates(sourceCandidates) : sourceCandidates;
3915
+ const transformRuntime = shouldFilterTailwindV4MiniProgramCandidates ? new Set(runtime) : new Set(filteredGeneratorCandidates);
3612
3916
  const generatorRuntime = filteredGeneratorCandidates;
3613
3917
  const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
3614
- if (sourceCandidates.size > 0 && jsEntries.size > 0) {
3918
+ const hasMultipleConfiguredCssEntries = (opts.cssEntries?.length ?? 0) > 1;
3919
+ if (sourceCandidates.size > 0 && !hasMultipleConfiguredCssEntries) {
3615
3920
  const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
3616
3921
  if (mainCssEntry) {
3617
- const validatedSourceRuntime = await validateCandidatesByGenerator({
3618
- opts,
3619
- runtimeState,
3620
- candidates: filteredGeneratorCandidates,
3621
- rawSource: mainCssEntry.source,
3622
- file: mainCssEntry.file,
3623
- cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
3624
- cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
3625
- styleHandler,
3626
- debug,
3627
- skipGenerateFallback: true
3628
- });
3629
- if (validatedSourceRuntime.size > 0) for (const candidate of validatedSourceRuntime) transformRuntime.add(candidate);
3922
+ const mainCssRawSource = typeof mainCssEntry.output.source === "string" ? mainCssEntry.output.source : Buffer.from(mainCssEntry.output.source).toString();
3923
+ if (!hasTailwindApplyDirective(mainCssRawSource)) {
3924
+ const generatedCssSources = /* @__PURE__ */ new Set();
3925
+ for (const [, record] of getViteProcessedCssAssetResults?.() ?? []) if (typeof record === "string") generatedCssSources.add(record);
3926
+ else if (typeof record?.css === "string") generatedCssSources.add(record.css);
3927
+ const validatedSourceRuntime = await validateCandidatesByGenerator({
3928
+ opts,
3929
+ runtimeState,
3930
+ candidates: filteredSourceCandidates,
3931
+ rawSource: mainCssRawSource,
3932
+ generatedCssSources,
3933
+ file: mainCssEntry.file,
3934
+ cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
3935
+ cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
3936
+ styleHandler,
3937
+ debug,
3938
+ skipGenerateFallback: false
3939
+ });
3940
+ if (validatedSourceRuntime.size > 0) for (const candidate of validatedSourceRuntime) transformRuntime.add(candidate);
3941
+ }
3630
3942
  }
3631
3943
  }
3632
3944
  const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
@@ -3634,21 +3946,24 @@ function createGenerateBundleHook(context) {
3634
3946
  const cssExtensionByStem = collectCssExtensionByStem(bundleFiles, opts.cssMatcher);
3635
3947
  const jsImportedCssFiles = collectJsImportedCssFiles(snapshot);
3636
3948
  const runtimeLinkedCssFiles = new Set([...collectRuntimeLinkedCssFiles(snapshot, cssExtensionByStem, defaultStyleOutputExtension), ...jsImportedCssFiles]);
3637
- for (const file of runtimeLinkedCssFiles) {
3638
- if (snapshot.sourceHashByFile.has(file)) {
3639
- processFiles.css.add(file);
3640
- continue;
3641
- }
3642
- const outputFile = resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension, sourceRoot, defaultStyleOutputExtension, bundleFiles);
3643
- const inferredSourceStyle = resolveSourceStyleSourceFromOutputFile(outputFile, snapshot, outDir, sourceRoot, getSourceCandidateSource, jsImportedCssFiles.has(file) ? getSourceCandidateSources : void 0, getConfiguredTailwindV4CssSourceEntries().map((entry) => [entry.file, entry.source]), debug);
3644
- const rawSource = inferredSourceStyle?.rawSource ?? getSourceCandidateSource?.(path.resolve(outDir, file)) ?? getSourceCandidateSource?.(file);
3645
- if (rawSource === void 0 || !hasTailwindGenerationSource(rawSource)) continue;
3646
- rememberCssSource?.({
3647
- outputFile,
3648
- rawSource,
3649
- sourceFile: inferredSourceStyle?.sourceFile ?? path.resolve(outDir, file)
3650
- });
3651
- }
3949
+ rememberRuntimeLinkedCssSources({
3950
+ bundleFiles,
3951
+ debug,
3952
+ defaultStyleOutputExtension,
3953
+ getConfiguredTailwindV4CssSourceEntries,
3954
+ getSourceCandidateSource,
3955
+ getSourceCandidateSources,
3956
+ isWebGeneratorTarget,
3957
+ jsImportedCssFiles,
3958
+ opts,
3959
+ outDir,
3960
+ rememberCssSource,
3961
+ rootDir,
3962
+ runtimeLinkedCssFiles,
3963
+ shouldPreserveAppCssExtension,
3964
+ snapshot,
3965
+ sourceRoot
3966
+ });
3652
3967
  recordGeneratorCandidates?.(generatorRuntime);
3653
3968
  const dynamicRetryCandidates = new Set([
3654
3969
  ...sourceCandidates,
@@ -3690,90 +4005,86 @@ function createGenerateBundleHook(context) {
3690
4005
  debug("html skip web target: %s", file);
3691
4006
  continue;
3692
4007
  }
4008
+ if (shouldSkipViteAssetTransform(originalSource, file, rootDir, transformFilter)) {
4009
+ metrics.html.transformed++;
4010
+ debug("html skip transform (filtered): %s", file);
4011
+ continue;
4012
+ }
3693
4013
  if (!processFiles.html.has(file)) continue;
3694
- const rawSource = resolveCurrentSourceCandidateSource(file) ?? originalEntrySource;
3695
- const currentRawDynamicCandidates = collectUnescapedDynamicCandidates(rawSource);
3696
- const templateRuntime = currentRawDynamicCandidates.length > 0 ? new Set([...transformRuntime, ...currentRawDynamicCandidates]) : transformRuntime;
3697
- const templateRuntimeSignature = templateRuntime === transformRuntime ? transformRuntimeSignature : createCandidateSignature(templateRuntime);
3698
- const htmlProcessHash = `${cache.computeHash(rawSource)}:${cache.computeHash(createRuntimeAffectingSourceSignature(rawSource, "html"))}:${templateRuntimeSignature}`;
3699
- const cacheKey = `${file}:html:${htmlProcessHash}`;
3700
- const hashKey = cacheKey;
3701
- rememberProcessCacheKey(cacheKey, hashKey);
3702
- tasks.push(timeTask("html", () => processCachedTask({
4014
+ processHtmlBundleEntry({
3703
4015
  cache,
3704
- cacheKey,
3705
- hashKey,
3706
- hash: htmlProcessHash,
3707
- applyResult(source) {
3708
- originalSource.source = source;
3709
- },
3710
- onCacheHit() {
3711
- metrics.html.cacheHits++;
3712
- debug("html cache hit: %s", file);
3713
- },
3714
- async transform() {
3715
- const start = performance.now();
3716
- let transformed = await templateHandler(rawSource, { runtimeSet: templateRuntime });
3717
- let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
3718
- let retryRuntimeSet;
3719
- if (unresolvedDynamicCandidates.length > 0) {
3720
- const fullRuntimeSet = await context.ensureRuntimeClassSet(true);
3721
- const allowedRetryCandidates = fullRuntimeSet.size === 0 ? unresolvedDynamicCandidates : unresolvedDynamicCandidates.filter((candidate) => dynamicRetryCandidates.has(candidate) || fullRuntimeSet.has(candidate));
3722
- retryRuntimeSet = new Set([...fullRuntimeSet, ...allowedRetryCandidates]);
3723
- unresolvedDynamicCandidates = unresolvedDynamicCandidates.filter((candidate) => retryRuntimeSet?.has(candidate) === true);
3724
- }
3725
- if (retryRuntimeSet && unresolvedDynamicCandidates.length > 0) {
3726
- logger.warn("检测到已提取 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
3727
- transformed = await templateHandler(rawSource, { runtimeSet: retryRuntimeSet });
3728
- unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed, retryRuntimeSet);
3729
- if (unresolvedDynamicCandidates.length > 0) logger.warn("已提取 WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
3730
- }
3731
- metrics.html.elapsed += measureElapsed(start);
3732
- metrics.html.transformed++;
3733
- onUpdate(file, rawSource, transformed);
3734
- debug("html handle: %s", file);
3735
- return { result: transformed };
3736
- }
3737
- })));
4016
+ context,
4017
+ debug,
4018
+ dynamicRetryCandidates,
4019
+ file,
4020
+ metrics,
4021
+ onUpdate,
4022
+ originalEntrySource,
4023
+ originalSource,
4024
+ rememberProcessCacheKey,
4025
+ resolveCurrentSourceCandidateSource: (file) => resolveCurrentSourceCandidateSource({
4026
+ file,
4027
+ getSourceCandidateSource,
4028
+ getSourceCandidateSources,
4029
+ outDir,
4030
+ rootDir,
4031
+ sourceRoot
4032
+ }),
4033
+ tasks,
4034
+ templateHandler,
4035
+ timeTask,
4036
+ transformRuntime,
4037
+ transformRuntimeSignature
4038
+ });
3738
4039
  continue;
3739
4040
  }
3740
4041
  if (type === "css" && originalSource.type === "asset") {
3741
4042
  metrics.css.total++;
3742
4043
  const assetSourceFile = resolveAssetSourceFile(originalSource, file);
3743
4044
  const rawSource = normalizeRelativeCssConfigDirectives(originalEntrySource, assetSourceFile, outDir, opts);
3744
- let outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, shouldPreserveAppCssExtension, defaultStyleOutputExtension, bundleFiles);
3745
- if (outputFile !== file && (originalSource.originalFileNames?.length ?? 0) > 0 && opts.cssMatcher(file)) outputFile = file;
3746
- if (outputFile === file && isRootMiniProgramStyleOutputFile(file) && shouldMoveRootMiniProgramStyleToImportShellOrigin(opts.appType)) outputFile = createRootMiniProgramOriginStyleOutputFile(file);
3747
- const resolveMatchedOutputFileForCurrentAsset = (sourceFile) => {
3748
- if (!sourceFile) return;
3749
- if (normalizeOutputPathKey(assetSourceFile.replace(/[?#].*$/, "")) === normalizeOutputPathKey(sourceFile.replace(/[?#].*$/, "")) || originalSource.originalFileNames?.some((originalFile) => normalizeOutputPathKey(originalFile.replace(/[?#].*$/, "")) === normalizeOutputPathKey(sourceFile.replace(/[?#].*$/, "")))) return file;
3750
- return resolveOutputFileFromMatchedCssSource(sourceFile);
3751
- };
4045
+ let outputFile = resolveCssBundleOutputFile({
4046
+ bundleFiles,
4047
+ defaultStyleOutputExtension,
4048
+ file,
4049
+ isWebGeneratorTarget,
4050
+ opts,
4051
+ shouldPreserveAppCssExtension
4052
+ });
4053
+ const resolveMatchedOutputFileForCurrentAsset = createMatchedCssSourceOutputResolver({
4054
+ assetSourceFile,
4055
+ file,
4056
+ originalFileNames: originalSource.originalFileNames,
4057
+ resolveOutputFileFromMatchedCssSource: resolveMatchedCssSourceOutputFile
4058
+ });
3752
4059
  activeViteCssCacheFiles.add(normalizeViteCssCacheKey(outputFile));
3753
- if (outputFile !== file && !canProcessViteSourceStyleAsCss(rawSource, file)) {
4060
+ if (shouldSkipRawSourceStyleAsset(outputFile, file, rawSource)) {
3754
4061
  delete bundle[file];
3755
4062
  debug("css skip raw source style asset: %s -> %s", file, outputFile);
3756
4063
  continue;
3757
4064
  }
4065
+ const hasViteProcessedCssRecord = getViteProcessedCssAssetResult?.(file) != null;
4066
+ const viteProcessedCssAsset = isViteProcessedCssAsset?.(originalSource, file) === true || hasViteProcessedCssRecord;
3758
4067
  const applyCssResult = (source) => {
3759
- if (outputFile !== file) {
3760
- const importShellSource = isRootMiniProgramStyleOutputFile(file) && isRootMiniProgramStyleOutputFile(outputFile) && shouldKeepRootMiniProgramStyleAsImportShell(opts.appType) ? createCssImportShell(file, outputFile) : void 0;
3761
- if (bundle[file] === originalSource && originalSource.originalFileNames?.includes(assetSourceFile)) {
3762
- const existingOutput = bundle[outputFile];
3763
- if (existingOutput?.type === "asset") existingOutput.source = source;
3764
- else emitOrReplayCssAsset(outputFile, source);
3765
- originalSource.source = importShellSource ?? source;
3766
- return;
3767
- }
3768
- const existingOutput = bundle[outputFile];
3769
- if (existingOutput?.type === "asset") existingOutput.source = source;
3770
- else emitOrReplayCssAsset(outputFile, source);
3771
- if (!viteProcessedCssAsset && SOURCE_STYLE_OUTPUT_EXT_RE.test(file)) delete bundle[file];
3772
- else originalSource.source = importShellSource ?? "";
3773
- return;
3774
- }
3775
- originalSource.source = source;
4068
+ applyCssResultToBundle({
4069
+ appType: opts.appType,
4070
+ assetSourceFile,
4071
+ bundle,
4072
+ emitOrReplayCssAsset,
4073
+ file,
4074
+ originalSource,
4075
+ outputFile,
4076
+ source,
4077
+ viteProcessedCssAsset
4078
+ });
3776
4079
  };
4080
+ if (shouldSkipViteAssetTransform(originalSource, file, rootDir, transformFilter)) {
4081
+ applyCssResult(rawSource);
4082
+ markCssAssetProcessed?.(originalSource, outputFile);
4083
+ onUpdate(outputFile, rawSource, rawSource);
4084
+ metrics.css.transformed++;
4085
+ debug("css skip transform (filtered): %s", outputFile);
4086
+ continue;
4087
+ }
3777
4088
  if (isWebGeneratorTarget && !shouldGenerateWebCssByGenerator) {
3778
4089
  applyCssResult(rawSource);
3779
4090
  markCssAssetProcessed?.(originalSource, outputFile);
@@ -3781,12 +4092,12 @@ function createGenerateBundleHook(context) {
3781
4092
  debug("css skip web target: %s", outputFile);
3782
4093
  continue;
3783
4094
  }
3784
- const hasViteProcessedCssRecord = getViteProcessedCssAssetResult?.(file) != null;
3785
- const viteProcessedCssAsset = isViteProcessedCssAsset?.(originalSource, file) === true || hasViteProcessedCssRecord;
3786
4095
  const cssAssetProcessed = isCssAssetProcessed?.(originalSource, file) === true;
3787
4096
  const alreadyProcessedCssAsset = viteProcessedCssAsset || cssAssetProcessed;
3788
4097
  let rememberedCssSources = findRememberedCssSources(getRememberedCssSources?.(), outputFile, file, originalSource, outDir, opts.tailwindcssBasedir);
3789
- if (rememberedCssSources.length > 0) rememberedCssSources = await Promise.all(rememberedCssSources.map(async (remembered) => await refreshRememberedCssSource?.(remembered) ?? remembered));
4098
+ if (rememberedCssSources.length > 0) rememberedCssSources = await Promise.all(rememberedCssSources.map(async (remembered) => {
4099
+ return await refreshRememberedCssSource?.(remembered) ?? remembered;
4100
+ }));
3790
4101
  let hasUsableRememberedTailwindSource = rememberedCssSources.some((remembered) => hasTailwindGenerationSource(remembered.rawSource) && normalizeOutputPathKey(remembered.sourceFile.replace(/[?#].*$/, "")) !== normalizeOutputPathKey(file));
3791
4102
  const inferredSfcStyleSource = await resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outDir, opts.tailwindcssBasedir, opts.cssMatcher, getSfcSource, debug);
3792
4103
  if (inferredSfcStyleSource) {
@@ -3795,7 +4106,7 @@ function createGenerateBundleHook(context) {
3795
4106
  if (!hasUsableRememberedTailwindSource || rememberedSourcesBelongToInferredSfc) rememberedCssSources = [inferredSfcStyleSource];
3796
4107
  }
3797
4108
  let outputCssHandlerOptions = getCssHandlerOptions(outputFile);
3798
- if (currentSubpackageRoots && rememberedCssSources.length > 0 && rememberedCssSources.some((remembered) => configuredTailwindV4CssSourceFileKeysForScope.has(normalizeOutputPathKey(remembered.sourceFile.replace(/[?#].*$/, ""))) && !isSameSubpackageScope(outputFile, remembered.sourceFile))) {
4109
+ if (currentSubpackageRoots && rememberedCssSources.length > 0 && rememberedCssSources.some((remembered) => configuredTailwindV4CssSourceFileKeysForScope.has(normalizeOutputPathKey(remembered.sourceFile.replace(/[?#].*$/, ""))) && !isSameSubpackageScope(outputFile, remembered.sourceFile, currentSubpackageRoots))) {
3799
4110
  rememberedCssSources = [];
3800
4111
  hasUsableRememberedTailwindSource = false;
3801
4112
  }
@@ -3812,8 +4123,8 @@ function createGenerateBundleHook(context) {
3812
4123
  }];
3813
4124
  } else if (hasTailwindGenerationSource(rawSource) && (originalSource.originalFileNames?.length ?? 0) === 0) {
3814
4125
  const availableConfiguredTailwindV4CssSourceEntries = configuredTailwindV4CssSourceEntries.filter((entry) => !usedConfiguredTailwindV4CssSourceFiles.has(normalizeOutputPathKey(entry.file)));
3815
- const configuredGenerationSource = selectTailwindV4GenerationCssSourceForOutput(outputFile, availableConfiguredTailwindV4CssSourceEntries, rawSource);
3816
- if (configuredGenerationSource && !hasViteProcessedCssResultForSource(configuredGenerationSource.file)) {
4126
+ const configuredGenerationSource = selectTailwindV4GenerationCssSourceForOutput(outputFile, availableConfiguredTailwindV4CssSourceEntries, rawSource, currentSubpackageRoots);
4127
+ if (configuredGenerationSource && !hasViteProcessedCssResultForSource(configuredGenerationSource.file, getViteProcessedCssAssetResults)) {
3817
4128
  outputFile = resolveMatchedOutputFileForCurrentAsset(configuredGenerationSource.file) ?? outputFile;
3818
4129
  activeViteCssCacheFiles.add(normalizeViteCssCacheKey(outputFile));
3819
4130
  outputCssHandlerOptions = getCssHandlerOptions(outputFile);
@@ -3893,8 +4204,10 @@ function createGenerateBundleHook(context) {
3893
4204
  const shouldInjectVitePipelineCssIntoMain = vitePipelineCssAsset && outputCssHandlerOptions.isMainChunk !== true && shouldInjectCssIntoMainFromOutput(outputFile, generatorSourceFile, outputCssHandlerOptions);
3894
4205
  const shouldTrackGeneratorRuntime = hasStaleViteProcessedCssSource || shouldRegenerateMainPackageCssWithScopedCandidates || hasCurrentTailwindGenerationDirective || hasSameOutputRememberedTailwindGenerationSource || shouldProcessTailwindGeneration && (!useIncrementalMode || cssHandlerOptions.isMainChunk || processFiles.css.has(file) || runtimeLinkedCssFiles.has(file) || runtimeLinkedCssFiles.has(outputFile) || shouldRegenerateCollectedViteCss || hasRuntimeAffectingChanges && (alreadyProcessedCssAsset || vitePipelineCssAsset));
3895
4206
  const shouldPreserveCollectedViteCssAsset = !shouldRegenerateCollectedViteCss && (state.generatorCandidateSignature === void 0 || !generatorCandidatesChanged) && (collectedBundlerGeneratedCssFiles.has(file) || hasBundlerGeneratedCssMarker(rawSource));
3896
- if (alreadyProcessedCssAsset && !shouldRefreshViteProcessedCssByCandidates && !hasStaleViteProcessedCssSource && !hasRememberedApplySource && !shouldRegenerateMainPackageCssWithScopedCandidates && (!shouldTrackGeneratorRuntime || shouldPreserveCollectedViteCssAsset)) {
3897
- const nextCss = stripBundlerGeneratedCssMarkers(rawSource);
4207
+ const strippedViteProcessedCss = stripBundlerGeneratedCssMarkers(rawSource);
4208
+ const shouldPreserveStaleGeneratedCssAsset = hasStaleViteProcessedCssSource && shouldPreserveCollectedViteCssAsset && strippedViteProcessedCss.trim().length > 0 && !strippedViteProcessedCss.includes("weapp-tailwindcss generator-placeholder") && !strippedViteProcessedCss.includes("vite-placeholder") && !hasTailwindGenerationSource(strippedViteProcessedCss) && !hasTailwindApplyDirective(strippedViteProcessedCss);
4209
+ if (alreadyProcessedCssAsset && !shouldRefreshViteProcessedCssByCandidates && (!hasStaleViteProcessedCssSource || shouldPreserveStaleGeneratedCssAsset) && !hasRememberedApplySource && !shouldRegenerateMainPackageCssWithScopedCandidates && (!shouldTrackGeneratorRuntime || shouldPreserveCollectedViteCssAsset)) {
4210
+ const nextCss = strippedViteProcessedCss;
3898
4211
  applyCssResult(nextCss);
3899
4212
  markCssAssetProcessed?.(originalSource, outputFile);
3900
4213
  recordCssAssetResult?.(outputFile, nextCss);
@@ -3913,9 +4226,9 @@ function createGenerateBundleHook(context) {
3913
4226
  }) : trackedGeneratorCandidateSignature;
3914
4227
  const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, scopedGeneratorCandidateSignature);
3915
4228
  const rememberedCssRuntimeSignature = createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash);
3916
- const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.tailwindRuntime.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}:${scopedGeneratorCandidateSignature}:${sourceTraceSignature}`;
3917
- const cssCacheKey = file;
3918
- const cssHashKey = `${file}:css:${cssRuntimeSignature}:${runtimeState.tailwindRuntime.majorVersion ?? "unknown"}`;
4229
+ const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.tailwindRuntime.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingHash}:${scopedGeneratorCandidateSignature}:${sourceTraceSignature}`;
4230
+ const cssCacheKey = outputFile;
4231
+ const cssHashKey = `${outputFile}:css:${cssRuntimeSignature}:${runtimeState.tailwindRuntime.majorVersion ?? "unknown"}`;
3919
4232
  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(":") : "";
3920
4233
  if (!shouldTrackGeneratorRuntime && !runtimeLinkedCssFiles.has(file) && !runtimeLinkedCssFiles.has(outputFile)) {
3921
4234
  const lastCss = getLastCssResult(lastCssResultByFile, outputFile, file);
@@ -3984,6 +4297,7 @@ function createGenerateBundleHook(context) {
3984
4297
  registerGeneratorDependencies$1({ addWatchFile }, generated.dependencies);
3985
4298
  if (envFlags.debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, tracedCss));
3986
4299
  debug("css generated result: %s bytes=%d", file, tracedCss.length);
4300
+ for (const candidate of generated.classSet ?? []) transformRuntime.add(candidate);
3987
4301
  recordCssAssetResult?.(outputFile, tracedCss);
3988
4302
  recordViteProcessedCssAssetResult?.(outputFile, tracedCss, {
3989
4303
  injectIntoMain: outputCssHandlerOptions.isMainChunk ? false : shouldInjectVitePipelineCssIntoMain,
@@ -4045,8 +4359,12 @@ function createGenerateBundleHook(context) {
4045
4359
  rememberProcessCacheKey,
4046
4360
  runtimeSignature,
4047
4361
  snapshot,
4362
+ transformFilterSignature,
4363
+ shouldSkipAstTransform: transformFilter ? (chunk) => shouldSkipViteJsChunkTransform(chunk, transformFilter) : void 0,
4364
+ slowJsAstWarnMs: envFlags.slowJsAstWarnMs,
4048
4365
  timeTask,
4049
4366
  transformRuntime,
4367
+ transformRuntimeSignature,
4050
4368
  uniAppX,
4051
4369
  useIncrementalMode
4052
4370
  });
@@ -4057,10 +4375,10 @@ function createGenerateBundleHook(context) {
4057
4375
  bundle,
4058
4376
  bundleFiles,
4059
4377
  cache,
4378
+ cssTaskFactories,
4060
4379
  createScopedGeneratorRuntime: createScopedGeneratorRuntime$1,
4061
4380
  createScopedSourceCandidateGetter,
4062
4381
  createScopedSourceCandidateSourceGetter,
4063
- cssTaskFactories,
4064
4382
  debug,
4065
4383
  defaultStyleOutputExtension,
4066
4384
  emitOrReplayCssAsset,
@@ -4091,7 +4409,6 @@ function createGenerateBundleHook(context) {
4091
4409
  timeTask,
4092
4410
  useIncrementalMode
4093
4411
  });
4094
- pushConcurrentTaskFactories(tasks, jsTaskFactories);
4095
4412
  await finalizeGenerateBundle({
4096
4413
  activeProcessCacheKeys,
4097
4414
  activeProcessHashKeys,
@@ -4116,6 +4433,8 @@ function createGenerateBundleHook(context) {
4116
4433
  isNativeAppStyleTarget,
4117
4434
  isViteProcessedCssAsset,
4118
4435
  isWebGeneratorTarget,
4436
+ jsAfterCss: shouldFilterTailwindV4MiniProgramCandidates && cssTaskFactories.length > 0,
4437
+ jsTaskFactories,
4119
4438
  lastCssResultByFile,
4120
4439
  lastCssSourceHashByFile,
4121
4440
  linkedByEntry,
@@ -4169,7 +4488,7 @@ function createCssHandlerOptions(opts, majorVersion, file) {
4169
4488
  ...resolveUniAppXNativeCssHandlerOptions(opts),
4170
4489
  isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
4171
4490
  postcssOptions: { options: { from: file } },
4172
- ...majorVersion === void 0 ? {} : { majorVersion }
4491
+ ...normalizeStyleHandlerMajorVersion(majorVersion) === void 0 ? {} : { majorVersion: 4 }
4173
4492
  };
4174
4493
  }
4175
4494
  function shouldGenerateCssByGenerator(opts, majorVersion, file, rawSource, processed) {
@@ -4454,6 +4773,7 @@ function shouldCollectTransformedSourceCandidates(id) {
4454
4773
  function createViteCssMemory(options) {
4455
4774
  const rememberedCssSources = /* @__PURE__ */ new Map();
4456
4775
  const rememberedCssSignatureByFile = /* @__PURE__ */ new Map();
4776
+ const knownCssSources = /* @__PURE__ */ new Map();
4457
4777
  const knownSfcSources = /* @__PURE__ */ new Map();
4458
4778
  const rememberKnownSfcSource = (id, code) => {
4459
4779
  if (id.search(/[?#]/) >= 0) return;
@@ -4505,6 +4825,7 @@ function createViteCssMemory(options) {
4505
4825
  return nextRemembered;
4506
4826
  };
4507
4827
  const refreshRememberedCssSourceBySourceFile = (sourceFile, rawSource) => {
4828
+ touchMapEntry(knownCssSources, normalizeCssSourceIdentity(sourceFile), rawSource);
4508
4829
  const normalizedSourceFile = normalizeCssSourceIdentity(sourceFile);
4509
4830
  const relatedRememberedEntries = [...rememberedCssSources].filter(([, remembered]) => normalizeCssSourceIdentity(remembered.sourceFile) === normalizedSourceFile);
4510
4831
  for (const [rememberedKey, remembered] of relatedRememberedEntries) refreshRememberedCssSourceEntry(rememberedKey, remembered, sourceFile, rawSource);
@@ -4518,6 +4839,10 @@ function createViteCssMemory(options) {
4518
4839
  const cached = resolveCachedStyleSource(sourceFile);
4519
4840
  if (cached != null) return cached;
4520
4841
  const file = cleanUrl(stripRequestQuery(sourceFile));
4842
+ const knownSource = knownCssSources.get(normalizeCssSourceIdentity(sourceFile));
4843
+ if (knownSource != null) return knownSource;
4844
+ const candidateSource = options.getSourceCandidateSource(file);
4845
+ if (candidateSource != null) return candidateSource;
4521
4846
  if (!isSourceStyleRequest(file)) return;
4522
4847
  try {
4523
4848
  return await readFile(file, "utf8");
@@ -4579,6 +4904,7 @@ function createViteCssMemory(options) {
4579
4904
  pruneMapToMaxSize(rememberedCssSources, VITE_REMEMBERED_CSS_CACHE_MAX, (rememberedKey) => {
4580
4905
  rememberedCssSignatureByFile.delete(String(rememberedKey));
4581
4906
  });
4907
+ pruneMapToMaxSize(knownCssSources, VITE_REMEMBERED_CSS_CACHE_MAX);
4582
4908
  pruneMapToMaxSize(knownSfcSources, VITE_KNOWN_SFC_SOURCE_CACHE_MAX);
4583
4909
  };
4584
4910
  return {
@@ -4590,6 +4916,8 @@ function createViteCssMemory(options) {
4590
4916
  rememberedCssSources: rememberedCssSources.size,
4591
4917
  rememberedCssSourcesRaw: summarizeRememberedCssSources(rememberedCssSources),
4592
4918
  rememberedCssSignatureByFile: rememberedCssSignatureByFile.size,
4919
+ knownCssSources: knownCssSources.size,
4920
+ knownCssSourcesRaw: summarizeStringMapCache(knownCssSources),
4593
4921
  knownSfcSources: knownSfcSources.size,
4594
4922
  knownSfcSourcesRaw: summarizeStringMapCache(knownSfcSources)
4595
4923
  }),
@@ -4716,6 +5044,35 @@ function disableAndRemoveTailwindVitePlugins(plugins) {
4716
5044
  return removed;
4717
5045
  }
4718
5046
  //#endregion
5047
+ //#region src/bundlers/vite/plugin-cache.ts
5048
+ function isMissingInternalCssSource(file, packageDir) {
5049
+ return !existsSync(file) && path.resolve(file).startsWith(`${packageDir}${path.sep}`);
5050
+ }
5051
+ function normalizeVitePersistentCacheKey(file) {
5052
+ return normalizeOutputPathKey(file);
5053
+ }
5054
+ function toMb(bytes) {
5055
+ return Math.round(bytes / 1024 / 1024);
5056
+ }
5057
+ function summarizeStringCache(map) {
5058
+ let bytes = 0;
5059
+ for (const value of map.values()) bytes += value.length;
5060
+ return {
5061
+ bytes,
5062
+ mb: toMb(bytes),
5063
+ size: map.size
5064
+ };
5065
+ }
5066
+ function summarizeViteProcessedCssResults(map) {
5067
+ let bytes = 0;
5068
+ for (const record of map.values()) bytes += record.css.length;
5069
+ return {
5070
+ bytes,
5071
+ mb: toMb(bytes),
5072
+ size: map.size
5073
+ };
5074
+ }
5075
+ //#endregion
4719
5076
  //#region src/bundlers/shared/css-imports.ts
4720
5077
  const tailwindcssImportRE = /^(?:tailwindcss|weapp-tailwindcss)(?:\/.*)?$/;
4721
5078
  const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])((?:tailwindcss|weapp-tailwindcss)(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
@@ -4887,7 +5244,7 @@ function createViteRuntimeClassSet(options) {
4887
5244
  if (runtimeSetPromise === task) runtimeSetPromise = void 0;
4888
5245
  }
4889
5246
  }
4890
- async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false, _options = {}) {
5247
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false, options = {}) {
4891
5248
  const forceRuntimeRefresh = forceRefresh || process$1.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
4892
5249
  const invalidation = resolveRuntimeRefreshOptions();
4893
5250
  const shouldRefreshRuntime = forceRuntimeRefresh || invalidation.changed;
@@ -4901,7 +5258,14 @@ function createViteRuntimeClassSet(options) {
4901
5258
  await transformRuntimeClassSetManager.reset();
4902
5259
  }
4903
5260
  if (!forceRuntimeRefresh) try {
4904
- const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.tailwindRuntime, snapshot);
5261
+ const baseClassSet = options.baseClassSet ?? runtimeSet ?? await collectRuntimeClassSet(runtimeState.tailwindRuntime, {
5262
+ force: invalidation.changed,
5263
+ clearCache: invalidation.changed
5264
+ });
5265
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.tailwindRuntime, snapshot, {
5266
+ baseClassSet,
5267
+ skipInitialFullScanWithBase: options.allowBaselineOnlyInitialSync
5268
+ });
4905
5269
  runtimeSet = nextRuntimeSet;
4906
5270
  return nextRuntimeSet;
4907
5271
  } catch (error) {
@@ -5033,33 +5397,6 @@ const weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
5033
5397
  const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
5034
5398
  const SOURCE_CANDIDATE_SCAN_CACHE_MAX = 8;
5035
5399
  const sourceCandidateScanSnapshotCache = new LRUCache({ max: SOURCE_CANDIDATE_SCAN_CACHE_MAX });
5036
- function isMissingInternalCssSource(file) {
5037
- return !existsSync(file) && path.resolve(file).startsWith(`${weappTailwindcssPackageDir}${path.sep}`);
5038
- }
5039
- function normalizeVitePersistentCacheKey(file) {
5040
- return normalizeOutputPathKey(file);
5041
- }
5042
- function toMb(bytes) {
5043
- return Math.round(bytes / 1024 / 1024);
5044
- }
5045
- function summarizeStringCache(map) {
5046
- let bytes = 0;
5047
- for (const value of map.values()) bytes += value.length;
5048
- return {
5049
- bytes,
5050
- mb: toMb(bytes),
5051
- size: map.size
5052
- };
5053
- }
5054
- function summarizeViteProcessedCssResults(map) {
5055
- let bytes = 0;
5056
- for (const record of map.values()) bytes += record.css.length;
5057
- return {
5058
- bytes,
5059
- mb: toMb(bytes),
5060
- size: map.size
5061
- };
5062
- }
5063
5400
  /**
5064
5401
  * @name WeappTailwindcss
5065
5402
  * @description uni-app vite / uni-app-x 版本插件
@@ -5112,7 +5449,7 @@ function WeappTailwindcss(options = {}) {
5112
5449
  let autoCssSourcesRefresh;
5113
5450
  let autoCssSourcesDiscovered = false;
5114
5451
  const syncTailwindCssSourceCandidates = async (id, css) => {
5115
- if (tailwindcssMajorVersion === 4 && isMissingInternalCssSource(cleanUrl(id))) return;
5452
+ if (tailwindcssMajorVersion === 4 && isMissingInternalCssSource(cleanUrl(id), weappTailwindcssPackageDir)) return;
5116
5453
  await sourceCandidateCollector.syncCss(id, css);
5117
5454
  cacheCurrentSourceCandidateScan();
5118
5455
  };
@@ -5121,7 +5458,7 @@ function WeappTailwindcss(options = {}) {
5121
5458
  const file = cleanUrl(id);
5122
5459
  if (!path.isAbsolute(file)) return;
5123
5460
  if (!isTailwindV4CssEntry(file)) return;
5124
- if (isMissingInternalCssSource(file)) return;
5461
+ if (isMissingInternalCssSource(file, weappTailwindcssPackageDir)) return;
5125
5462
  const sourceFile = path.normalize(file);
5126
5463
  const sourceBase = path.dirname(sourceFile);
5127
5464
  const sourceCss = normalizeTailwindSourceForGenerator(normalizeTailwindConfigDirectives(css, sourceBase), { importFallback: true });
@@ -5232,7 +5569,7 @@ function WeappTailwindcss(options = {}) {
5232
5569
  recordedGeneratorCandidates = void 0;
5233
5570
  };
5234
5571
  const getSourceCandidates = () => sourceCandidateCollector.values();
5235
- const getSourceCandidatesForEntries = (entries) => sourceCandidateCollector.valuesForEntries(entries);
5572
+ const getSourceCandidatesForEntries = (entries, options) => sourceCandidateCollector.valuesForEntries(entries, options);
5236
5573
  const getSourceCandidateSourcesForEntries = (entries, options) => sourceCandidateCollector.sourcesForEntries(entries, options);
5237
5574
  const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
5238
5575
  const isWatchLikeBuild = () => isWatchBuild() || resolvedConfig?.command === "serve" || process$1.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || process$1.env["WEAPP_TW_HMR_TIMING"] === "1";