weapp-tailwindcss 5.0.13 → 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 (200) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/auto-Ba6hDrse.mjs +13 -0
  4. package/dist/auto-DtU6f3X6.js +18 -0
  5. package/dist/bundlers/shared/css-cleanup.d.ts +1 -1
  6. package/dist/bundlers/shared/generator-css/class-selectors.d.ts +2 -0
  7. package/dist/bundlers/shared/generator-css/directives.d.ts +2 -1
  8. package/dist/bundlers/shared/generator-css/generation-helpers.d.ts +10 -6
  9. package/dist/bundlers/shared/generator-css/local-imports.d.ts +3 -0
  10. package/dist/bundlers/shared/generator-css/source-resolver/apply-reference.d.ts +3 -0
  11. package/dist/bundlers/shared/generator-css/source-resolver/matching.d.ts +0 -1
  12. package/dist/bundlers/shared/generator-css/source-resolver/metadata.d.ts +1 -1
  13. package/dist/bundlers/shared/generator-css/source-resolver/types.d.ts +3 -3
  14. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +2 -2
  15. package/dist/bundlers/shared/generator-css/types.d.ts +13 -1
  16. package/dist/bundlers/shared/generator-css/user-css.d.ts +5 -1
  17. package/dist/bundlers/shared/generator-css/validate.d.ts +1 -0
  18. package/dist/bundlers/shared/run-tasks.d.ts +1 -0
  19. package/dist/bundlers/shared/v4-generation-core.d.ts +11 -0
  20. package/dist/bundlers/vite/css-finalizer.d.ts +1 -1
  21. package/dist/bundlers/vite/css-memory.d.ts +16 -0
  22. package/dist/bundlers/vite/generate-bundle/candidates.d.ts +0 -1
  23. package/dist/bundlers/vite/generate-bundle/configured-css-sources.d.ts +1 -1
  24. package/dist/bundlers/vite/generate-bundle/css-assets.d.ts +1 -1
  25. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +1 -1
  26. package/dist/bundlers/vite/generate-bundle/css-output-helpers.d.ts +39 -0
  27. package/dist/bundlers/vite/generate-bundle/css-output.d.ts +1 -0
  28. package/dist/bundlers/vite/generate-bundle/env-flags.d.ts +1 -1
  29. package/dist/bundlers/vite/generate-bundle/final-css-assets.d.ts +13 -0
  30. package/dist/bundlers/vite/generate-bundle/finalize.d.ts +7 -0
  31. package/dist/bundlers/vite/generate-bundle/html-processing.d.ts +26 -0
  32. package/dist/bundlers/vite/generate-bundle/js-processing.d.ts +4 -0
  33. package/dist/bundlers/vite/generate-bundle/memory-debug.d.ts +21 -18
  34. package/dist/bundlers/vite/generate-bundle/remembered-css-replay.d.ts +1 -1
  35. package/dist/bundlers/vite/generate-bundle/remembered-css.d.ts +1 -1
  36. package/dist/bundlers/vite/generate-bundle/root-style-output.d.ts +6 -0
  37. package/dist/bundlers/vite/generate-bundle/runtime-linked-source-memory.d.ts +25 -0
  38. package/dist/bundlers/vite/generate-bundle/sfc-style-source.d.ts +3 -1
  39. package/dist/bundlers/vite/generate-bundle/source-candidate-scope.d.ts +1 -0
  40. package/dist/bundlers/vite/generate-bundle/source-candidate-source.d.ts +9 -0
  41. package/dist/bundlers/vite/generate-bundle/tailwind-v4-css-source.d.ts +9 -0
  42. package/dist/bundlers/vite/generate-bundle/transform-filter.d.ts +15 -0
  43. package/dist/bundlers/vite/generate-bundle/types.d.ts +2 -1
  44. package/dist/bundlers/vite/generate-bundle/vite-css-cache.d.ts +1 -1
  45. package/dist/bundlers/vite/generate-bundle.d.ts +2 -1
  46. package/dist/bundlers/vite/incremental-runtime-class-set/escaped-candidates.d.ts +1 -0
  47. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +3 -3
  48. package/dist/bundlers/vite/plugin-cache.d.ts +15 -0
  49. package/dist/bundlers/vite/rewrite-css-imports.d.ts +1 -0
  50. package/dist/bundlers/vite/runtime-class-set.d.ts +5 -4
  51. package/dist/bundlers/vite/source-candidates/script.d.ts +1 -7
  52. package/dist/bundlers/vite/source-candidates.d.ts +9 -2
  53. package/dist/bundlers/vite/source-scan/css-entries.d.ts +2 -6
  54. package/dist/bundlers/vite/source-scan.d.ts +2 -2
  55. package/dist/bundlers/vite/uni-app-x-css-options.d.ts +1 -1
  56. package/dist/bundlers/vite/utils.d.ts +1 -0
  57. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +26 -2
  58. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/css-source-resolvers.d.ts +34 -0
  59. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/helpers.d.ts +48 -11
  60. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/js-module-graph.d.ts +37 -0
  61. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/pipeline-helpers.d.ts +199 -0
  62. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/source-candidate-cache.d.ts +28 -0
  63. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/source-candidate-refresh.d.ts +11 -0
  64. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +1 -0
  65. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +4 -2
  66. package/dist/bundlers/webpack/loaders/runtime-registry.d.ts +10 -1
  67. package/dist/bundlers/webpack/shared/css-loader-runtime.d.ts +1 -0
  68. package/dist/cache/index.d.ts +1 -0
  69. package/dist/cli/mount-options.d.ts +2 -2
  70. package/dist/cli.js +138 -444
  71. package/dist/cli.mjs +134 -440
  72. package/dist/context/index.d.ts +3 -3
  73. package/dist/context/style-options.d.ts +5 -1
  74. package/dist/context/tailwindcss.d.ts +1 -1
  75. package/dist/{precheck-B0Z8yW7E.js → context-B6hVF7dr.js} +405 -156
  76. package/dist/{precheck-CRI90iL1.mjs → context-DlpKD7aN.mjs} +377 -141
  77. package/dist/core.js +15 -12
  78. package/dist/core.mjs +10 -7
  79. package/dist/css-macro/index.d.ts +3 -7
  80. package/dist/css-macro.js +1 -1
  81. package/dist/css-macro.mjs +1 -1
  82. package/dist/{defaults-Bqx18S1f.mjs → defaults-BhE26nSw.mjs} +12 -13
  83. package/dist/{defaults-C_J_kBpw.js → defaults-CmFBmxsr.js} +11 -18
  84. package/dist/defaults.d.ts +2 -8
  85. package/dist/defaults.js +1 -2
  86. package/dist/defaults.mjs +2 -2
  87. package/dist/generator/index.d.ts +6 -7
  88. package/dist/generator/options.d.ts +3 -3
  89. package/dist/generator/types.d.ts +9 -10
  90. package/dist/generator-6oMJtTDO.js +170 -0
  91. package/dist/generator-CjzBK7h-.mjs +123 -0
  92. package/dist/generator.js +10 -16
  93. package/dist/generator.mjs +3 -3
  94. package/dist/{gulp-XT8Jc7lH.js → gulp-BtGq6LP9.js} +49 -87
  95. package/dist/{gulp-DfOQERcV.mjs → gulp-DNU10Vtc.mjs} +42 -80
  96. package/dist/gulp.js +1 -1
  97. package/dist/gulp.mjs +1 -1
  98. package/dist/{hmr-timing-DQIP_8qP.mjs → hmr-timing-B0KuWDjV.mjs} +1197 -858
  99. package/dist/{hmr-timing-BMftW7Us.js → hmr-timing-CegXR9O4.js} +1356 -927
  100. package/dist/index.js +4 -4
  101. package/dist/index.mjs +4 -4
  102. package/dist/js/fast-path/oxc.d.ts +4 -0
  103. package/dist/js/precheck.d.ts +1 -0
  104. package/dist/postcss.js +3 -4
  105. package/dist/postcss.mjs +2 -3
  106. package/dist/presets.js +9 -19
  107. package/dist/presets.mjs +8 -18
  108. package/dist/runtime-branch/create-branch.d.ts +2 -0
  109. package/dist/runtime-branch/generator-target-env.d.ts +4 -0
  110. package/dist/runtime-branch/index.d.ts +6 -0
  111. package/dist/runtime-branch/mini-program.d.ts +2 -0
  112. package/dist/runtime-branch/native-app.d.ts +2 -0
  113. package/dist/runtime-branch/platform.d.ts +6 -0
  114. package/dist/runtime-branch/tailwind-version.d.ts +2 -0
  115. package/dist/runtime-branch/types.d.ts +37 -0
  116. package/dist/runtime-branch/web.d.ts +2 -0
  117. package/dist/runtime-branch.d.ts +1 -0
  118. package/dist/{bundle-state-zQ2MrDdi.mjs → source-candidate-scan-signature-B5af2Ahe.mjs} +187 -17
  119. package/dist/{bundle-state-CKWeTEhv.js → source-candidate-scan-signature-BKYb9jxa.js} +261 -19
  120. package/dist/tailwindcss/candidates.d.ts +7 -0
  121. package/dist/tailwindcss/index.d.ts +2 -2
  122. package/dist/tailwindcss/runtime/cache.d.ts +6 -6
  123. package/dist/tailwindcss/runtime-factory.d.ts +12 -0
  124. package/dist/tailwindcss/runtime-options.d.ts +8 -0
  125. package/dist/tailwindcss/runtime-types.d.ts +87 -0
  126. package/dist/tailwindcss/runtime.d.ts +6 -6
  127. package/dist/tailwindcss/source-scan.d.ts +1 -1
  128. package/dist/tailwindcss/targets.d.ts +2 -2
  129. package/dist/tailwindcss/v4/config.d.ts +3 -3
  130. package/dist/tailwindcss/v4/css-entries.d.ts +1 -0
  131. package/dist/tailwindcss/v4/css-sources.d.ts +4 -2
  132. package/dist/tailwindcss/v4/index.d.ts +1 -1
  133. package/dist/tailwindcss/v4/multi-runtime.d.ts +2 -0
  134. package/dist/tailwindcss/v4/runtime-factory.d.ts +15 -0
  135. package/dist/tailwindcss/v4/runtime-options.d.ts +2 -0
  136. package/dist/tailwindcss/v4-engine/design-system.d.ts +1 -1
  137. package/dist/tailwindcss/v4-engine/generator/css-compat.d.ts +1 -1
  138. package/dist/tailwindcss/v4-engine/generator/rpx-candidates.d.ts +3 -3
  139. package/dist/tailwindcss/v4-engine/generator/scan-sources.d.ts +1 -1
  140. package/dist/tailwindcss/v4-engine/generator.d.ts +10 -3
  141. package/dist/tailwindcss/v4-engine/index.d.ts +1 -1
  142. package/dist/tailwindcss/v4-engine/miniprogram.d.ts +7 -1
  143. package/dist/tailwindcss/v4-engine/source.d.ts +15 -7
  144. package/dist/tailwindcss/v4-engine/types.d.ts +17 -10
  145. package/dist/tailwindcss/version.d.ts +1 -1
  146. package/dist/tailwindcss-B5mRo0-M.mjs +1423 -0
  147. package/dist/tailwindcss-dbrbY4cd.js +1528 -0
  148. package/dist/{transform-DfcEjsZF.mjs → transform-fRBeuuK-.mjs} +2 -2
  149. package/dist/{transform-YmrmxuF3.js → transform-vLwZpiTE.js} +17 -17
  150. package/dist/typedoc.export.d.ts +1 -1
  151. package/dist/types/index.d.ts +16 -17
  152. package/dist/types/shared.d.ts +1 -1
  153. package/dist/types/{typedoc-tailwindcss-patch.d.ts → typedoc-tailwindcss-runtime.d.ts} +4 -10
  154. package/dist/types/user-defined-options/general.d.ts +5 -3
  155. package/dist/types/user-defined-options/important.d.ts +2 -2
  156. package/dist/types/user-defined-options/matcher.d.ts +7 -0
  157. package/dist/uni-app-x/style-asset.d.ts +1 -0
  158. package/dist/v4-engine-C3qSwQ-e.mjs +2376 -0
  159. package/dist/v4-engine-ON_oSLfO.js +2752 -0
  160. package/dist/{vite-DjI09vVN.mjs → vite-CWRooooa.mjs} +1417 -540
  161. package/dist/{vite-CXHVsHmX.js → vite-w-RkgaTY.js} +1575 -698
  162. package/dist/vite.js +1 -1
  163. package/dist/vite.mjs +1 -1
  164. package/dist/weapp-tw-css-import-rewrite-loader.js +5665 -4443
  165. package/dist/weapp-tw-runtime-classset-loader.js +15 -4
  166. package/dist/webpack-8PaV1gG3.mjs +2334 -0
  167. package/dist/webpack-CGgBOx9l.js +2346 -0
  168. package/dist/webpack.js +1 -1
  169. package/dist/webpack.mjs +1 -1
  170. package/package.json +6 -7
  171. package/dist/auto-CTp6wE5a.js +0 -33
  172. package/dist/auto-Cl8_hsG6.mjs +0 -22
  173. package/dist/bundlers/vite/incremental-runtime-class-set/v3-candidates.d.ts +0 -13
  174. package/dist/bundlers/vite/source-candidates/tailwind-v3-default-extractor.d.ts +0 -1
  175. package/dist/context/tailwindcss/rax.d.ts +0 -2
  176. package/dist/generator-CzpArpCL.js +0 -92
  177. package/dist/generator-ITLd7PTl.mjs +0 -67
  178. package/dist/tailwindcss/patcher-options.d.ts +0 -8
  179. package/dist/tailwindcss/patcher.d.ts +0 -12
  180. package/dist/tailwindcss/runtime-patch.d.ts +0 -5
  181. package/dist/tailwindcss/v3-engine/generator/cache-key.d.ts +0 -3
  182. package/dist/tailwindcss/v3-engine/generator/content.d.ts +0 -10
  183. package/dist/tailwindcss/v3-engine/generator/runtime-ready.d.ts +0 -2
  184. package/dist/tailwindcss/v3-engine/generator.d.ts +0 -19
  185. package/dist/tailwindcss/v3-engine/index.d.ts +0 -4
  186. package/dist/tailwindcss/v3-engine/miniprogram.d.ts +0 -4
  187. package/dist/tailwindcss/v3-engine/source.d.ts +0 -5
  188. package/dist/tailwindcss/v3-engine/types.d.ts +0 -61
  189. package/dist/tailwindcss/v4/multi-patcher.d.ts +0 -2
  190. package/dist/tailwindcss/v4/patcher-options.d.ts +0 -2
  191. package/dist/tailwindcss/v4/patcher.d.ts +0 -15
  192. package/dist/tailwindcss/v4-engine/tailwind-v3-compatibility.d.ts +0 -1
  193. package/dist/tailwindcss/v4-engine/tailwind-v3-default-colors.d.ts +0 -1
  194. package/dist/tailwindcss-DTq3uYBK.mjs +0 -556
  195. package/dist/tailwindcss-DZEwT3C_.js +0 -613
  196. package/dist/v3-engine-2rrgylhn.js +0 -4686
  197. package/dist/v3-engine-C6eJ0YzK.mjs +0 -4272
  198. package/dist/webpack-BcPpnT90.mjs +0 -1184
  199. package/dist/webpack-CfkUkMXG.js +0 -1196
  200. /package/dist/tailwindcss/{patcher-resolve.d.ts → runtime-resolve.d.ts} +0 -0
@@ -1,14 +1,13 @@
1
- import { $ as loadTailwindV4DesignSystem, A as normalizeTailwindSourceDirectives, B as splitGeneratorPlaceholderCssBySourceOrder, C as resolveTailwindV4SourceFromPatcher, D as hasTailwindRootDirectives, E as hasTailwindApplyDirective, F as resolveCssEntrySource, G as stripTailwindBanners, H as splitTailwindV4GeneratedCssBySourceOrder, I as VITE_MARKER_RE, K as normalizeConfigDirective, L as createCssAppend, M as normalizeTailwindV3CssEntrySource, N as parseImportRequest, O as hasTailwindSourceDirectives, P as removeTailwindSourceDirectives, Q as filterUnsupportedMiniProgramTailwindV4Candidates, R as hasTailwindGeneratedCss, U as stripGeneratorPlaceholderMarkers, V as splitTailwindGeneratedCssByBanner, W as stripTailwindBanner, _ as resolveTailwindConfigEntriesFromCssCached, at as toPosixPath$1, et as FULL_SOURCE_SCAN_EXTENSION_RE, gt as omitUndefined, it as resolveTailwindV4CssSourceBase, n as resolveTailwindV3SourceFromPatcher, nt as normalizeLegacyContentEntries, ot as createDebug, q as prependConfigDirective, r as resolveTailwindV3SourceOptionsFromPatcher, rt as resolveSourceScanPath, t as resolveTailwindV3Source, tt as isFileMatchedByTailwindSourceEntries, u as getRuntimeClassSetSignature, v as resolveTailwindV4EntriesFromCss, w as resolveTailwindV4SourceOptionsFromPatcher, x as resolveTailwindV4Source$1, z as hasTailwindGeneratedCssMarkers } from "./v3-engine-C6eJ0YzK.mjs";
2
- import { i as normalizeWeappTailwindcssGeneratorOptions, t as createWeappTailwindcssGenerator } from "./generator-ITLd7PTl.mjs";
3
- import { h as traverse, m as babelParse, p as replaceWxml, r as resolveStyleOptionsFromContext, x as md5Hash } from "./precheck-CRI90iL1.mjs";
4
- import { r as isUniAppXEnabled } from "./tailwindcss-DTq3uYBK.mjs";
5
- import { createRequire } from "node:module";
1
+ import { A as resolveCssEntrySource, B as stripTailwindBanner, C as hasTailwindRootDirectives, E as normalizeTailwindSourceDirectives, F as hasTailwindGeneratedCssMarkers, H as normalizeConfigDirective, I as splitGeneratorPlaceholderCssBySourceOrder, J as FULL_SOURCE_SCAN_EXTENSION_RE, L as splitTailwindGeneratedCssByBanner, M as VITE_MARKER_RE, N as createCssAppend, O as parseImportRequest, P as hasTailwindGeneratedCss, Q as isFileMatchedByTailwindSourceEntries, R as splitTailwindV4GeneratedCssBySourceOrder, U as prependConfigDirective, V as stripTailwindBanners, i as resolveTailwindV4SourceOptionsFromRuntime, it as toPosixPath$1, j as GENERATOR_PLACEHOLDER_MARKER_RE, k as removeTailwindSourceDirectives, lt as loadTailwindV4DesignSystem, n as resolveTailwindV4SourceFromRuntime, nt as resolveSourceScanPath, ot as filterUnsupportedMiniProgramTailwindV4Candidates, rt as resolveTailwindV4CssSourceBase, st as omitUndefined, t as resolveTailwindV4Source$1, w as hasTailwindSourceDirectives, x as hasTailwindApplyDirective, z as stripGeneratorPlaceholderMarkers } from "./v4-engine-C3qSwQ-e.mjs";
2
+ import { a as resolveGeneratorRuntimeBranch, i as normalizeWeappTailwindcssGeneratorOptions, s as shouldUseMiniProgramCssBranch, t as createWeappTailwindcssGenerator } from "./generator-CjzBK7h-.mjs";
3
+ import { C as md5Hash, S as createDebug, g as traverse, h as babelParse, m as replaceWxml, r as resolveStyleOptionsFromContext } from "./context-DlpKD7aN.mjs";
4
+ import { h as resolveTailwindV4EntriesFromCss, l as getRuntimeClassSetSignature, r as isUniAppXEnabled } from "./tailwindcss-B5mRo0-M.mjs";
6
5
  import { existsSync, readFileSync } from "node:fs";
7
6
  import path from "node:path";
8
7
  import process from "node:process";
9
- import { finalizeMiniProgramCss, postcss, pruneMiniProgramGeneratedCss, removeUnsupportedCascadeLayers, removeUnsupportedMiniProgramAtRules } from "@weapp-tailwindcss/postcss";
8
+ import { extractRawCandidatesWithPositions, extractSourceCandidates, extractValidCandidates, resolveProjectSourceFiles, resolveValidTailwindV4Candidates, splitCandidateTokens } from "@tailwindcss-mangle/engine";
9
+ import { filterExistingCssRules, finalizeMiniProgramCss, hasMiniProgramCssSpecificityPlaceholders, postcss, pruneMiniProgramGeneratedCss, removeUnsupportedCascadeLayers, removeUnsupportedMiniProgramAtRules, stripMiniProgramCssSpecificityPlaceholders } from "@weapp-tailwindcss/postcss";
10
10
  import { LRUCache } from "lru-cache";
11
- import { extractRawCandidatesWithPositions, extractSourceCandidates, extractValidCandidates, resolveProjectSourceFiles, resolveValidTailwindV4Candidates, splitCandidateTokens } from "tailwindcss-patch";
12
11
  import { readFile } from "node:fs/promises";
13
12
  import { MappingChars2String, unescape } from "@weapp-core/escape";
14
13
  //#region src/bundlers/shared/cache.ts
@@ -129,13 +128,39 @@ function annotateCssSourceTrace(css, options) {
129
128
  }
130
129
  }
131
130
  //#endregion
131
+ //#region src/bundlers/shared/generator-css/class-selectors.ts
132
+ function normalizeCssClassSelector(value) {
133
+ return value.replace(/\\([^\da-f\r\n])/gi, "$1").replace(/\\([\da-f]{1,6})\s?/gi, (_, code) => String.fromCodePoint(Number.parseInt(code, 16)));
134
+ }
135
+ function collectRawSourceClassSelectors(rawSource) {
136
+ const selectors = /* @__PURE__ */ new Set();
137
+ try {
138
+ postcss.parse(rawSource).walkRules((rule) => {
139
+ for (const selector of rule.selectors ?? [rule.selector]) for (const match of selector.matchAll(/\.((?:\\.|[_a-z\u00A0-\uFFFF-])(?:\\.|[\w\u00A0-\uFFFF-])*)/gi)) selectors.add(normalizeCssClassSelector(match[1]));
140
+ });
141
+ } catch {}
142
+ return selectors;
143
+ }
144
+ function collectGeneratedRawSourceCandidates(candidates, rawSource, escapeMap) {
145
+ const selectors = collectRawSourceClassSelectors(rawSource);
146
+ if (selectors.size === 0) return /* @__PURE__ */ new Set();
147
+ const matched = /* @__PURE__ */ new Set();
148
+ for (const candidate of candidates) {
149
+ const escaped = normalizeCssClassSelector(replaceWxml(candidate, { escapeMap }));
150
+ if (selectors.has(candidate) || selectors.has(escaped)) matched.add(candidate);
151
+ }
152
+ return matched;
153
+ }
154
+ //#endregion
132
155
  //#region src/bundlers/shared/generator-css/generation-helpers.ts
133
- function finalizeMiniProgramGeneratorCss(css, target, majorVersion, cssPreflight, options = {}) {
156
+ function hasMiniProgramTailwindV4PreflightReset(css) {
157
+ return /(?:^|[},])\s*view\s*,\s*text\s*,\s*::after\s*,\s*::before\s*\{[^}]*\bborder\s*:\s*0\s+solid\b/.test(css);
158
+ }
159
+ function finalizeMiniProgramGeneratorCss(css, target, _majorVersion, cssPreflight, options = {}) {
134
160
  if (target !== "weapp") return css;
135
161
  return finalizeMiniProgramCss(css, {
136
- cssPreflight: majorVersion === 4 && options.injectPreflight !== false ? cssPreflight : void 0,
137
- isTailwindcssV4: majorVersion === 4,
138
- preservePseudoContentInit: majorVersion === 3,
162
+ cssPreflight: options.injectPreflight !== false && !hasMiniProgramTailwindV4PreflightReset(css) ? cssPreflight : void 0,
163
+ isTailwindcssV4: true,
139
164
  tailwindcssV4GradientFallback: options.styleOptions?.cssOptions?.tailwindcssV4GradientFallback ?? options.styleOptions?.tailwindcssV4GradientFallback
140
165
  });
141
166
  }
@@ -145,11 +170,6 @@ function shouldInjectMiniProgramPreflightForGeneratorCss(opts, options) {
145
170
  return isUniAppXEnabled(opts.uniAppX) && Boolean(options.localImports?.trim());
146
171
  }
147
172
  function mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtime, options) {
148
- if (options.majorVersion === 3 && !options.isolateCssSource) return new Set([
149
- ...scopedRuntime,
150
- ...runtime,
151
- ...options.currentCssCandidates ?? []
152
- ]);
153
173
  if (options.isolateCssSource) {
154
174
  if (options.matchedCssSourceFile) return new Set([...scopedRuntime, ...options.currentCssCandidates ?? []]);
155
175
  return new Set([...scopedRuntime, ...options.currentCssCandidates ?? []]);
@@ -157,24 +177,24 @@ function mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtime, options) {
157
177
  if (runtime.size === 0 || !options.cssHandlerOptions.isMainChunk) return scopedRuntime;
158
178
  return new Set([...scopedRuntime, ...runtime]);
159
179
  }
160
- function shouldIsolateScopedCssSource(majorVersion, source, sourceEntries, options) {
180
+ function shouldIsolateScopedCssSource(_majorVersion, source, sourceEntries, options) {
161
181
  if (options.target !== "weapp") return false;
162
182
  if (source.__weappTailwindcssMeta?.isolateCssSource) return true;
163
183
  if (source.__weappTailwindcssMeta?.matchedCssSourceFile && (sourceEntries?.length ?? 0) > 0) return true;
164
184
  if (sourceEntries?.length === 0) return false;
165
- return (majorVersion === 3 || majorVersion === 4) && sourceEntries !== void 0 && options.cssHandlerOptions?.isMainChunk !== true;
185
+ return sourceEntries !== void 0 && options.cssHandlerOptions?.isMainChunk !== true;
166
186
  }
167
- function shouldIsolateCurrentTailwindV4CssCandidates(majorVersion, cssHandlerOptions, options) {
168
- return majorVersion === 4 && !cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(options.rawSource) && !hasTailwindRootDirectives(options.rawSource) && !options.hasGeneratedCss && !options.hasGeneratedMarkers;
187
+ function shouldIsolateCurrentTailwindV4CssCandidates(_majorVersion, cssHandlerOptions, options) {
188
+ return !cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(options.rawSource) && !hasTailwindRootDirectives(options.rawSource) && !options.hasGeneratedCss && !options.hasGeneratedMarkers;
169
189
  }
170
190
  function shouldScanTailwindV4Sources(majorVersion, target, generatorRuntime, isolateCssSource) {
171
- if (majorVersion !== 4) return false;
191
+ if (majorVersion !== 4) throw new Error("weapp-tailwindcss 生成管线仅支持 Tailwind CSS v4。");
172
192
  if (target === "web") return true;
173
193
  if (isolateCssSource) return false;
174
194
  return generatorRuntime.size === 0;
175
195
  }
176
- function shouldAppendWebBundleCssFallback(target, options) {
177
- return target === "web" && !options.hasMatchedCssSourceFile && !options.hasSourceDirectives;
196
+ function shouldAppendWebBundleCssFallback(target, _options) {
197
+ return target === "web";
178
198
  }
179
199
  function isEmptyCssSourceOrderParts(parts) {
180
200
  return parts.before.trim().length === 0 && parts.after.trim().length === 0;
@@ -212,7 +232,9 @@ function splitRawSourceByGeneratedCssOrder(rawSource, rawTailwindCss) {
212
232
  }
213
233
  function shouldUseGeneratorForCurrentCss(_majorVersion, cssHandlerOptions, options) {
214
234
  const hasApplyDirectives = hasTailwindApplyDirective(options.rawSource);
215
- return options.hasGeneratedCss || options.hasGeneratedMarkers || options.hasSourceDirectives || hasApplyDirectives || cssHandlerOptions.isMainChunk;
235
+ const sourceCss = cssHandlerOptions.sourceOptions?.sourceCss;
236
+ const hasSourceCssDirectives = typeof sourceCss === "string" && (hasTailwindRootDirectives(sourceCss, { importFallback: true }) || hasTailwindSourceDirectives(sourceCss, { importFallback: true }) || hasTailwindApplyDirective(sourceCss));
237
+ return options.forceGenerator === true || options.hasGeneratedCss || options.hasGeneratedMarkers || options.hasSourceDirectives || hasApplyDirectives || hasSourceCssDirectives || cssHandlerOptions.isMainChunk && (options.configuredCssSourceCount ?? 0) > 0 || cssHandlerOptions.isMainChunk && options.rawSource.includes("weapp-tailwindcss") || options.target === "web" && cssHandlerOptions.isMainChunk && (options.runtimeCandidateCount ?? 0) > 0;
216
238
  }
217
239
  function createRuntimeWithCurrentCssCandidates(runtime, currentCssCandidates, isolateCurrentCssCandidates) {
218
240
  return isolateCurrentCssCandidates ? new Set(currentCssCandidates) : currentCssCandidates.length > 0 ? new Set([...runtime, ...currentCssCandidates]) : runtime;
@@ -234,10 +256,6 @@ function mergeGeneratorResults(generatedResults) {
234
256
  sources: generatedResults.flatMap((item) => item.sources)
235
257
  };
236
258
  }
237
- const SUPPORTED_GENERATOR_MAJOR_VERSIONS$1 = new Set([3, 4]);
238
- function isSupportedGeneratorMajorVersion(majorVersion) {
239
- return SUPPORTED_GENERATOR_MAJOR_VERSIONS$1.has(majorVersion ?? 0);
240
- }
241
259
  //#endregion
242
260
  //#region src/bundlers/shared/generator-css/legacy-selectors.ts
243
261
  const CLASS_SELECTOR_RE = /(?:^|[^\w-])\.[_a-z\u00A0-\uFFFF\\-]/i;
@@ -387,6 +405,21 @@ function collectGeneratedDeclarationPropsBySelector(generatedCss, selectors) {
387
405
  }
388
406
  return propsBySelector;
389
407
  }
408
+ function isRuleCoveredByGeneratedProps(rule, generatedDeclarationPropsBySelector) {
409
+ const nodeSelectors = getRuleCompatSelectorKeys(rule);
410
+ if (nodeSelectors.length === 0) return false;
411
+ const props = /* @__PURE__ */ new Set();
412
+ rule.walkDecls((decl) => {
413
+ props.add(decl.prop);
414
+ });
415
+ if (props.size === 0) return false;
416
+ for (const selector of nodeSelectors) {
417
+ const generatedProps = generatedDeclarationPropsBySelector.get(selector);
418
+ if (!generatedProps) continue;
419
+ if ([...props].every((prop) => generatedProps.has(prop))) return true;
420
+ }
421
+ return false;
422
+ }
390
423
  function removeGeneratedSelectorCompatCss(css, generatedCss) {
391
424
  const generatedSelectors = collectGeneratedSelectors(generatedCss);
392
425
  if (generatedSelectors.size === 0) return css;
@@ -427,6 +460,7 @@ function collectDedupedPostTransformCompatCss(css, generatedCss) {
427
460
  preservedNodes.push(node.clone());
428
461
  return;
429
462
  }
463
+ if (isRuleCoveredByGeneratedProps(node, generatedDeclarationPropsBySelector)) return;
430
464
  if (isCustomPropertyOnlyRule(node) && !isPseudoContentInitRule(node) && !hasUtilityClassSelector(node.selector)) {
431
465
  const declarationProps = /* @__PURE__ */ new Set();
432
466
  node.walkDecls((decl) => {
@@ -463,6 +497,16 @@ function removeDuplicatedViteMarkers(css, baseCss) {
463
497
  //#endregion
464
498
  //#region src/bundlers/shared/generator-css/source-files.ts
465
499
  const SFC_STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
500
+ const STYLE_IMPORT_EXTENSIONS = [
501
+ ".css",
502
+ ".scss",
503
+ ".sass",
504
+ ".less",
505
+ ".styl",
506
+ ".stylus",
507
+ ".pcss",
508
+ ".postcss"
509
+ ];
466
510
  function stripStyleExtension(file) {
467
511
  const normalized = file.replace(/[?#].*$/, "");
468
512
  const ext = path.extname(normalized);
@@ -570,15 +614,71 @@ function extractStyleDirectiveSources(source) {
570
614
  if (styleSources.length > 0) return styleSources;
571
615
  return hasTailwindSourceDirectives(source, { importFallback: true }) ? [source] : [];
572
616
  }
617
+ function extractSfcStyleSources(source) {
618
+ const styleSources = [];
619
+ SFC_STYLE_BLOCK_RE.lastIndex = 0;
620
+ let match = SFC_STYLE_BLOCK_RE.exec(source);
621
+ while (match !== null) {
622
+ styleSources.push(match[1] ?? "");
623
+ match = SFC_STYLE_BLOCK_RE.exec(source);
624
+ }
625
+ return styleSources;
626
+ }
627
+ function isLocalStyleImportRequest(request) {
628
+ return typeof request === "string" && request.length > 0 && (request.startsWith(".") || request.startsWith("/"));
629
+ }
630
+ function resolveLocalStyleImportFile(request, base) {
631
+ const normalized = (path.isAbsolute(request) ? request : path.resolve(base, request)).replace(/[?#].*$/, "");
632
+ if (existsSync(normalized)) return normalized;
633
+ if (path.extname(normalized)) return;
634
+ for (const extension of STYLE_IMPORT_EXTENSIONS) {
635
+ const candidate = `${normalized}${extension}`;
636
+ if (existsSync(candidate)) return candidate;
637
+ }
638
+ }
639
+ function collectLocalStyleImportFiles(source, base) {
640
+ const files = [];
641
+ const sources = extractSfcStyleSources(source);
642
+ if (sources.length === 0) sources.push(source);
643
+ for (const styleSource of sources) try {
644
+ postcss.parse(styleSource).walkAtRules("import", (rule) => {
645
+ const request = parseImportRequest(rule.params);
646
+ if (!isLocalStyleImportRequest(request)) return;
647
+ const file = request ? resolveLocalStyleImportFile(request, base) : void 0;
648
+ if (file) files.push(file);
649
+ });
650
+ } catch {}
651
+ return files;
652
+ }
653
+ function extractStyleDirectiveSourcesDeep(source, sourceFile, seen) {
654
+ const ownSources = extractStyleDirectiveSources(source);
655
+ if (ownSources.length > 0) return ownSources.map((styleSource) => ({
656
+ source: styleSource,
657
+ file: sourceFile
658
+ }));
659
+ const sources = [];
660
+ const base = path.dirname(sourceFile);
661
+ for (const importedFile of collectLocalStyleImportFiles(source, base)) {
662
+ const normalizedImportedFile = path.resolve(importedFile);
663
+ if (seen.has(normalizedImportedFile)) continue;
664
+ seen.add(normalizedImportedFile);
665
+ try {
666
+ const importedSource = readFileSync(normalizedImportedFile, "utf8");
667
+ sources.push(...extractStyleDirectiveSourcesDeep(importedSource, normalizedImportedFile, seen));
668
+ } catch {}
669
+ }
670
+ return sources;
671
+ }
573
672
  function resolveSourceSideCssEntrySource(file, sourceOptions, resolveOptions = {}) {
574
673
  for (const sourceFile of createSourceStylePathCandidates(file, sourceOptions)) try {
575
674
  const source = sourceOptions.sourceFile && path.resolve(sourceOptions.sourceFile) === path.resolve(sourceFile) && typeof sourceOptions.sourceCss === "string" ? sourceOptions.sourceCss : existsSync(sourceFile) ? readFileSync(sourceFile, "utf8") : void 0;
576
675
  if (source === void 0) continue;
577
- for (const styleSource of extractStyleDirectiveSources(source)) {
578
- const cssEntrySource = resolveCssEntrySource(styleSource, path.dirname(sourceFile), resolveOptions);
676
+ const directiveSources = extractStyleDirectiveSourcesDeep(source, sourceFile, new Set([path.resolve(sourceFile)]));
677
+ for (const styleSource of directiveSources) {
678
+ const cssEntrySource = resolveCssEntrySource(styleSource.source, path.dirname(styleSource.file), resolveOptions);
579
679
  if (cssEntrySource) return {
580
680
  ...cssEntrySource,
581
- file: sourceFile
681
+ file: styleSource.file
582
682
  };
583
683
  }
584
684
  } catch {
@@ -588,14 +688,40 @@ function resolveSourceSideCssEntrySource(file, sourceOptions, resolveOptions = {
588
688
  //#endregion
589
689
  //#region src/bundlers/shared/generator-css/source-resolver/apply-reference.ts
590
690
  function createTailwindV4ApplyReferenceSource(css, sourceOptions) {
591
- if (!hasTailwindApplyDirective(css) || hasTailwindRootDirectives(css)) return css;
592
- const utilities = collectTailwindApplyUtilities(css);
691
+ return createTailwindV4SourceReferenceSource(css, sourceOptions);
692
+ }
693
+ function createTailwindV4SourceReferenceSource(css, sourceOptions) {
694
+ if (hasTailwindV4RootImport(css, sourceOptions)) return css;
695
+ const hasApplyDirective = hasTailwindApplyDirective(css);
696
+ if (!hasApplyDirective && !hasTailwindSourceDirectives(css, { importFallback: true })) return css;
697
+ const utilities = hasApplyDirective ? collectTailwindApplyUtilities(css) : [];
593
698
  return [
594
699
  `@import "${sourceOptions.packageName ?? "tailwindcss"}" source(none);`,
595
700
  utilities.length > 0 ? `@source inline(${JSON.stringify(utilities.join(" "))});` : void 0,
596
701
  css
597
702
  ].filter(Boolean).join("\n");
598
703
  }
704
+ function hasTailwindV4RootImport(css, sourceOptions) {
705
+ try {
706
+ const root = postcss.parse(css);
707
+ let found = false;
708
+ root.walkAtRules((rule) => {
709
+ if (rule.name === "tailwind") {
710
+ found = true;
711
+ return false;
712
+ }
713
+ if (rule.name !== "import" && rule.name !== "use" && rule.name !== "forward") return;
714
+ const request = parseImportRequest(rule.params);
715
+ if (request === (sourceOptions.packageName ?? "tailwindcss") || request === "tailwindcss" || request === "tailwindcss4" || request?.startsWith("tailwindcss/") || request?.startsWith("tailwindcss4/")) {
716
+ found = true;
717
+ return false;
718
+ }
719
+ });
720
+ return found;
721
+ } catch {
722
+ return /@(?:import|use|forward|tailwind)(?:[\s"'(;]|$)/.test(css) && (css.includes("tailwindcss") || css.includes("tailwindcss4") || css.includes("weapp-tailwindcss"));
723
+ }
724
+ }
599
725
  function collectTailwindApplyUtilities(css) {
600
726
  let root;
601
727
  try {
@@ -642,10 +768,6 @@ function resolveExistingConfigPath(config, configRequest, file, sourceOptions) {
642
768
  function normalizeCssSourceForCompare(css) {
643
769
  return stripGeneratorPlaceholderMarkers(stripTailwindBanners(css)).trim();
644
770
  }
645
- function getOutputFileStem(file) {
646
- const normalized = file.replace(/[?#].*$/, "");
647
- return path.basename(normalized, path.extname(normalized));
648
- }
649
771
  function getOutputFileWithoutExtension(file) {
650
772
  const normalized = file.replace(/[?#].*$/, "");
651
773
  const ext = path.extname(normalized);
@@ -654,6 +776,12 @@ function getOutputFileWithoutExtension(file) {
654
776
  function normalizeMatchPath(file) {
655
777
  return file.split(path.sep).join("/");
656
778
  }
779
+ function stripBundlerContentHash(name) {
780
+ return name.replace(/[._-]?[a-f0-9]{6,32}$/i, "");
781
+ }
782
+ function getMatchBasename(file) {
783
+ return stripBundlerContentHash(path.basename(getOutputFileWithoutExtension(file.replace(/[?#].*$/, ""))));
784
+ }
657
785
  function isPathWithinRoot(file, root) {
658
786
  const relative = path.relative(root, file);
659
787
  return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
@@ -663,11 +791,7 @@ function collectCssSourceMatchBases(file, roots) {
663
791
  const bases = /* @__PURE__ */ new Set();
664
792
  const addBase = (candidate) => {
665
793
  const base = normalizeMatchPath(getOutputFileWithoutExtension(candidate));
666
- if (base.length > 0) {
667
- bases.add(base);
668
- const withoutWorkspaceSegment = base.replace(/^(?:src|dist)\//, "");
669
- if (withoutWorkspaceSegment !== base && withoutWorkspaceSegment.length > 0) bases.add(withoutWorkspaceSegment);
670
- }
794
+ if (base.length > 0) bases.add(base);
671
795
  };
672
796
  addBase(normalizedFile);
673
797
  const resolvedRoots = roots.filter((root) => typeof root === "string" && root.length > 0).map((root) => path.resolve(root));
@@ -683,10 +807,13 @@ function scoreTailwindV4CssSourceFileMatch(file, cssSourceFile, sourceOptions) {
683
807
  sourceOptions.cwd
684
808
  ]);
685
809
  const sourceBases = collectCssSourceMatchBases(cssSourceFile, [sourceOptions.projectRoot, sourceOptions.cwd]);
810
+ const outputBasename = getMatchBasename(file);
811
+ const sourceBasename = getMatchBasename(cssSourceFile);
686
812
  let bestScore = 0;
687
813
  for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
688
814
  else if (outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
689
815
  else if (sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
816
+ if (outputBasename && outputBasename === sourceBasename) bestScore = Math.max(bestScore, 100 + outputBasename.length);
690
817
  return bestScore;
691
818
  }
692
819
  //#endregion
@@ -730,12 +857,16 @@ function createCssEntrySources(cssEntries) {
730
857
  }
731
858
  function mergeCssSources(cssSources, cssEntrySources) {
732
859
  const merged = [];
733
- const seenFiles = /* @__PURE__ */ new Set();
860
+ const fileIndex = /* @__PURE__ */ new Map();
734
861
  const addSource = (cssSource) => {
735
862
  const file = typeof cssSource.file === "string" && cssSource.file.length > 0 ? path.resolve(cssSource.file) : void 0;
736
863
  if (file) {
737
- if (seenFiles.has(file)) return;
738
- seenFiles.add(file);
864
+ const previousIndex = fileIndex.get(file);
865
+ if (previousIndex !== void 0) {
866
+ if (typeof merged[previousIndex]?.css !== "string" && typeof cssSource.css === "string") merged[previousIndex] = cssSource;
867
+ return;
868
+ }
869
+ fileIndex.set(file, merged.length);
739
870
  }
740
871
  merged.push(cssSource);
741
872
  };
@@ -784,17 +915,13 @@ function canResolveSourceSideCssEntry(file, cssHandlerOptions, sourceOptions) {
784
915
  function shouldResolveSourceSideCssEntry(rawSource) {
785
916
  return rawSource.includes("@apply") || hasTailwindRootDirectives(rawSource, { importFallback: true }) || hasTailwindSourceDirectives(rawSource, { importFallback: true }) || hasTailwindGeneratedCss(rawSource) || hasTailwindGeneratedCssMarkers(rawSource);
786
917
  }
787
- function shouldPreferTailwindV3SourceSideEntry(rawSource, sourceSideEntrySource) {
788
- return Boolean(sourceSideEntrySource) && !hasTailwindSourceDirectives(rawSource, { importFallback: true });
789
- }
790
- function shouldPreferResolvedSourceSideEntry(cssEntrySource, sourceSideEntrySource) {
791
- return Boolean(sourceSideEntrySource?.config) && (Boolean(cssEntrySource?.configRequest) || !cssEntrySource?.config) && (!cssEntrySource?.config || !existsSync(cssEntrySource.config));
792
- }
793
918
  function resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) {
794
919
  const cssEntries = sourceOptions.cssEntries;
795
920
  if (!cssEntries?.length) return;
921
+ const normalizedFile = path.resolve(file.replace(/[?#].*$/, ""));
922
+ const pathMatchedEntries = cssEntries.filter((cssEntry) => path.resolve(cssEntry.replace(/[?#].*$/, "")) === normalizedFile);
923
+ if (pathMatchedEntries.length === 1) return resolveTailwindV4CssEntrySource(pathMatchedEntries[0], sourceOptions);
796
924
  const normalizedRawSource = normalizeCssSourceForCompare(rawSource);
797
- const outputStem = getOutputFileStem(file);
798
925
  const matches = cssEntries.map((cssEntry) => {
799
926
  if (!existsSync(cssEntry)) return;
800
927
  try {
@@ -804,14 +931,6 @@ function resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) {
804
931
  cssEntry,
805
932
  score: 1e6 + pathScore
806
933
  };
807
- if (pathScore > 0) return {
808
- cssEntry,
809
- score: pathScore
810
- };
811
- if (cssEntries.length === 1 && outputStem.length > 0 && getOutputFileStem(cssEntry) === outputStem) return {
812
- cssEntry,
813
- score: 1
814
- };
815
934
  return;
816
935
  } catch {
817
936
  return;
@@ -831,6 +950,18 @@ function normalizeTailwindV4CssSourceConfig(cssSource, sourceBase) {
831
950
  css: normalizeConfigDirective(cssSource.css, entrySource.config)
832
951
  };
833
952
  }
953
+ function normalizeResolvedTailwindV4SourceConfig(source, file, sourceOptions) {
954
+ if (!("css" in source) || typeof source.css !== "string" || !source.css.includes("@config")) return source;
955
+ const sourceFile = typeof file === "string" && file.length > 0 ? file : source.__weappTailwindcssMeta?.matchedCssSourceFile;
956
+ if (!sourceFile) return source;
957
+ const entrySource = resolveCssEntrySource(source.css, path.dirname(path.resolve(sourceFile)), { removeConfig: false });
958
+ const config = resolveExistingConfigPath(entrySource?.config, entrySource?.configRequest, sourceFile, sourceOptions ?? {});
959
+ const normalizedCss = normalizeConfigDirective(source.css, config);
960
+ return normalizedCss === source.css ? source : {
961
+ ...source,
962
+ css: normalizedCss
963
+ };
964
+ }
834
965
  function hydrateTailwindV4CssSource(cssSource) {
835
966
  if (typeof cssSource.css === "string" && cssSource.css.length > 0) return cssSource;
836
967
  if (typeof cssSource.file !== "string" || !existsSync(cssSource.file)) return cssSource;
@@ -870,18 +1001,10 @@ async function resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOpt
870
1001
  index,
871
1002
  score: 1e6
872
1003
  };
873
- if (typeof cssSource.file === "string") {
874
- const pathScore = scoreTailwindV4CssSourceFileMatch(file, cssSource.file, sourceOptions);
875
- if (pathScore > 0) return {
876
- cssSource,
877
- index,
878
- score: pathScore
879
- };
880
- }
881
1004
  if (normalizeCssSourceForCompare(cssSource.css) === normalizedRawSource) return {
882
1005
  cssSource,
883
1006
  index,
884
- score: 1
1007
+ score: 1 + (typeof cssSource.file === "string" ? scoreTailwindV4CssSourceFileMatch(file, cssSource.file, sourceOptions) : 0)
885
1008
  };
886
1009
  }).filter((match) => Boolean(match)).sort((a, b) => b.score - a.score || a.index - b.index);
887
1010
  const bestScore = matches[0]?.score;
@@ -891,7 +1014,7 @@ async function resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOpt
891
1014
  }
892
1015
  function tryResolveTailwindV4SourceOptions(runtimeState) {
893
1016
  try {
894
- return resolveTailwindV4SourceOptionsFromPatcher(runtimeState.twPatcher);
1017
+ return resolveTailwindV4SourceOptionsFromRuntime(runtimeState.tailwindRuntime);
895
1018
  } catch {
896
1019
  return;
897
1020
  }
@@ -902,10 +1025,10 @@ function hasConfiguredTailwindV4CssSource(sourceOptions) {
902
1025
  async function resolveSingleTailwindV4CssSource(cssSource, sourceOptions, options = {}) {
903
1026
  const sourceBase = resolveTailwindV4CssSourceBase(cssSource, sourceOptions.base ?? sourceOptions.projectRoot ?? process.cwd());
904
1027
  const normalizedCssSource = normalizeTailwindV4CssSourceConfig(cssSource, sourceBase);
905
- return withGeneratorSourceMetadata(await resolveTailwindV4Source$1({
906
- ...omitUndefined(sourceOptions),
907
- cssSources: [normalizedCssSource]
908
- }), {
1028
+ return withGeneratorSourceMetadata(await resolveTailwindV4Source$1(createSingleTailwindV4SourceOptions(sourceOptions, {
1029
+ base: sourceBase,
1030
+ css: normalizedCssSource.css
1031
+ })), {
909
1032
  matchedCssSourceFile: options.matched && typeof normalizedCssSource.file === "string" ? normalizedCssSource.file : void 0,
910
1033
  sourceBase,
911
1034
  sourceCss: normalizedCssSource.css
@@ -961,62 +1084,22 @@ async function resolveTailwindV4SourceSideEntrySource(resolvedEntrySource, sourc
961
1084
  ...resolvedSourceOptions,
962
1085
  sourceFile: resolvedEntrySource.file
963
1086
  });
964
- const css = createTailwindV4ApplyReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), resolvedSourceOptions);
1087
+ const css = createTailwindV4SourceReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), resolvedSourceOptions);
965
1088
  return withMatchedSourceSideMetadata(await resolveTailwindV4Source$1(createSingleTailwindV4SourceOptions(resolvedSourceOptions, {
966
1089
  base: resolvedEntrySource.base,
967
1090
  css
968
1091
  })), resolvedEntrySource);
969
1092
  }
970
- function resolveTailwindV3SourceEntries(source) {
971
- if (!("version" in source) || source.version !== 3) return;
972
- const entries = normalizeLegacyContentEntries(source.configObject?.content, source.cwd, { relativeBase: source.config ? path.dirname(source.config) : source.cwd });
973
- return entries.length > 0 ? entries : void 0;
974
- }
975
- function withTailwindV3SourceMetadata(source) {
976
- const sourceEntries = resolveTailwindV3SourceEntries(source);
977
- return sourceEntries ? withGeneratorSourceMetadata(source, { sourceEntries }) : source;
978
- }
979
- async function resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions) {
1093
+ async function resolveGeneratorSource(_majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions) {
980
1094
  const base = resolveCssSourceBase(file, cssHandlerOptions);
981
1095
  const cssEntrySource = resolveCssEntrySource(rawSource, base, {
982
1096
  importFallback: generatorOptions?.importFallback ?? false,
983
- removeConfig: majorVersion === 3
1097
+ removeConfig: false
984
1098
  });
985
1099
  const applyEntrySource = hasTailwindApplyDirective(rawSource) ? {
986
1100
  base,
987
1101
  css: rawSource
988
1102
  } : void 0;
989
- if (majorVersion === 3) {
990
- const sourceOptions = resolveTailwindV3SourceOptionsFromPatcher(runtimeState.twPatcher);
991
- const mergedSourceOptions = omitUndefined({
992
- ...sourceOptions,
993
- config: generatorOptions?.config ?? sourceOptions.config,
994
- sourceFile: resolvePostcssSourceFile(cssHandlerOptions),
995
- ...resolveCssHandlerSourceOptions(cssHandlerOptions),
996
- cssEntries: selectionOptions?.cssEntries,
997
- cssSources: createCssEntrySources(selectionOptions?.cssEntries)
998
- });
999
- const sourceSideEntrySource = canResolveSourceSideCssEntry(file, cssHandlerOptions, mergedSourceOptions) ? resolveSourceSideCssEntrySource(file, mergedSourceOptions, { removeConfig: true }) : void 0;
1000
- const shouldPreferSourceSideEntry = shouldPreferResolvedSourceSideEntry(cssEntrySource, sourceSideEntrySource);
1001
- const resolvedEntrySource = shouldResolveSourceSideCssEntry(rawSource) ? shouldPreferSourceSideEntry ? sourceSideEntrySource ?? cssEntrySource ?? applyEntrySource : cssEntrySource ?? applyEntrySource ?? sourceSideEntrySource : shouldPreferTailwindV3SourceSideEntry(rawSource, sourceSideEntrySource) || shouldPreferSourceSideEntry ? sourceSideEntrySource ?? cssEntrySource ?? applyEntrySource : cssEntrySource ?? applyEntrySource ?? sourceSideEntrySource;
1002
- if (!resolvedEntrySource) return withTailwindV3SourceMetadata(await (generatorOptions?.config ? resolveTailwindV3Source(mergedSourceOptions) : resolveTailwindV3SourceFromPatcher(runtimeState.twPatcher)));
1003
- if (cssEntrySource && !sourceSideEntrySource && !applyEntrySource && !hasTailwindRootDirectives(rawSource, { importFallback: true })) return withTailwindV3SourceMetadata(await (generatorOptions?.config ? resolveTailwindV3Source(mergedSourceOptions) : resolveTailwindV3SourceFromPatcher(runtimeState.twPatcher)));
1004
- const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, omitUndefined(mergedSourceOptions));
1005
- const sourceWithMetadata = withTailwindV3SourceMetadata(await resolveTailwindV3Source({
1006
- ...mergedSourceOptions,
1007
- base: resolvedEntrySource.base,
1008
- css: normalizeTailwindV3CssEntrySource(resolvedEntrySource.css),
1009
- ...config ? { config } : {}
1010
- }));
1011
- const cssEntrySourceEntries = await resolveTailwindConfigEntriesFromCssCached(rawSource, resolvedEntrySource.base);
1012
- const sourceMetadata = sourceWithMetadata.__weappTailwindcssMeta;
1013
- const matchedSourceFile = resolvedEntrySource.file ?? sourceSideEntrySource?.file;
1014
- return withGeneratorSourceMetadata(sourceWithMetadata, {
1015
- ...sourceMetadata,
1016
- matchedCssSourceFile: matchedSourceFile,
1017
- sourceEntries: cssEntrySourceEntries?.entries ?? sourceMetadata?.sourceEntries
1018
- });
1019
- }
1020
1103
  const sourceOptions = tryResolveTailwindV4SourceOptions(runtimeState);
1021
1104
  const resolvedSourceOptions = sourceOptions ? omitUndefined({
1022
1105
  ...sourceOptions,
@@ -1052,16 +1135,19 @@ async function resolveGeneratorSource(majorVersion, runtimeState, rawSource, fil
1052
1135
  } : preferredCssEntrySource;
1053
1136
  const resolvedEntrySource = sourceSideEntrySource ?? cssEntrySource ?? applyEntrySource;
1054
1137
  if (!resolvedEntrySource) {
1055
- const source = await resolveTailwindV4SourceFromPatcher(runtimeState.twPatcher);
1138
+ const source = await resolveTailwindV4SourceFromRuntime(runtimeState.tailwindRuntime);
1056
1139
  return generatorOptions?.config ? {
1057
1140
  ...source,
1058
1141
  css: prependConfigDirective(source.css, generatorOptions.config)
1059
1142
  } : source;
1060
1143
  }
1061
1144
  if (sourceSideEntrySource && normalizedSourceOptions) return resolveTailwindV4SourceSideEntrySource(sourceSideEntrySource, normalizedSourceOptions, generatorOptions, file);
1062
- const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, resolvedSourceOptions ?? {});
1145
+ const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, omitUndefined({
1146
+ ...resolvedSourceOptions ?? {},
1147
+ sourceFile: resolvedEntrySource.file ?? resolvedSourceOptions?.sourceFile ?? resolvePostcssSourceFile(cssHandlerOptions)
1148
+ }));
1063
1149
  const sourceBase = resolvedEntrySource === cssEntrySource && config ? path.dirname(config) : resolvedEntrySource.base;
1064
- const css = createTailwindV4ApplyReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), normalizedSourceOptions ?? {});
1150
+ const css = createTailwindV4SourceReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), normalizedSourceOptions ?? {});
1065
1151
  return resolveTailwindV4Source$1(createSingleTailwindV4SourceOptions(normalizedSourceOptions ?? {}, {
1066
1152
  base: sourceBase,
1067
1153
  css
@@ -1070,47 +1156,48 @@ async function resolveGeneratorSource(majorVersion, runtimeState, rawSource, fil
1070
1156
  async function resolveGeneratorSources(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions) {
1071
1157
  const cssEntrySource = resolveCssEntrySource(rawSource, resolveCssSourceBase(file, cssHandlerOptions), {
1072
1158
  importFallback: generatorOptions?.importFallback ?? false,
1073
- removeConfig: majorVersion === 3
1159
+ removeConfig: false
1074
1160
  });
1075
- if (majorVersion !== 4 || cssEntrySource && !cssHandlerOptions.isMainChunk || !cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(rawSource) && !hasTailwindRootDirectives(rawSource, { importFallback: generatorOptions?.importFallback ?? false })) {
1161
+ if (cssEntrySource && !cssHandlerOptions.isMainChunk || !cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(rawSource) && !hasTailwindRootDirectives(rawSource, { importFallback: generatorOptions?.importFallback ?? false })) {
1076
1162
  const resolved = await resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions);
1077
1163
  return resolved ? [resolved] : [];
1078
1164
  }
1079
1165
  let sourceOptions;
1080
1166
  try {
1081
- const sourceOptionsFromPatcher = resolveTailwindV4SourceOptionsFromPatcher(runtimeState.twPatcher);
1082
- const cssEntries = selectionOptions?.cssEntries ?? sourceOptionsFromPatcher.cssEntries;
1167
+ const sourceOptionsFromRuntime = resolveTailwindV4SourceOptionsFromRuntime(runtimeState.tailwindRuntime);
1168
+ const cssEntries = selectionOptions?.cssEntries ?? sourceOptionsFromRuntime.cssEntries;
1169
+ const runtimeCssSources = selectionOptions?.cssEntries ? void 0 : sourceOptionsFromRuntime.cssSources;
1083
1170
  sourceOptions = omitUndefined({
1084
- ...sourceOptionsFromPatcher,
1171
+ ...sourceOptionsFromRuntime,
1085
1172
  sourceFile: resolvePostcssSourceFile(cssHandlerOptions),
1086
1173
  ...resolveCssHandlerSourceOptions(cssHandlerOptions),
1087
1174
  cssEntries,
1088
- cssSources: mergeCssSources(mergeCssSources(sourceOptionsFromPatcher.cssSources, selectionOptions?.cssSources), sourceOptionsFromPatcher.cssSources?.length || selectionOptions?.cssSources?.length ? void 0 : createCssEntrySources(cssEntries))
1175
+ cssSources: mergeCssSources(mergeCssSources(runtimeCssSources, selectionOptions?.cssSources), void 0)
1089
1176
  });
1090
1177
  } catch {
1091
1178
  const resolved = await resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions);
1092
1179
  return resolved ? [resolved] : [];
1093
1180
  }
1094
1181
  const matchedCssEntrySource = sourceOptions ? await resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) : void 0;
1095
- if (matchedCssEntrySource) return [generatorOptions?.config ? {
1182
+ if (matchedCssEntrySource) return [normalizeResolvedTailwindV4SourceConfig(generatorOptions?.config ? {
1096
1183
  ...matchedCssEntrySource,
1097
1184
  css: prependConfigDirective(matchedCssEntrySource.css, generatorOptions.config)
1098
- } : matchedCssEntrySource];
1185
+ } : matchedCssEntrySource, matchedCssEntrySource.__weappTailwindcssMeta?.matchedCssSourceFile, sourceOptions)];
1099
1186
  const sourceSideCssSource = await resolveTailwindV4SourceSideEntrySource(canResolveSourceSideCssEntry(file, cssHandlerOptions, sourceOptions) ? resolveSourceSideCssEntrySource(file, sourceOptions, { removeConfig: false }) : void 0, sourceOptions, generatorOptions, file);
1100
1187
  if (sourceSideCssSource) return [sourceSideCssSource];
1101
1188
  const matchedCssSource = await resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, sourceOptions);
1102
1189
  const candidateMatchedCssSource = await resolveCandidateMatchedTailwindV4CssSource(rawSource, cssHandlerOptions, sourceOptions, selectionOptions);
1103
1190
  const preferredCssEntrySource = matchedCssEntrySource ?? matchedCssSource ?? candidateMatchedCssSource;
1104
- if (preferredCssEntrySource) return [generatorOptions?.config ? {
1191
+ if (preferredCssEntrySource) return [normalizeResolvedTailwindV4SourceConfig(generatorOptions?.config ? {
1105
1192
  ...preferredCssEntrySource,
1106
1193
  css: prependConfigDirective(preferredCssEntrySource.css, generatorOptions.config)
1107
- } : preferredCssEntrySource];
1194
+ } : preferredCssEntrySource, preferredCssEntrySource.__weappTailwindcssMeta?.matchedCssSourceFile, sourceOptions)];
1108
1195
  if (!sourceOptions.cssEntries || sourceOptions.cssEntries.length <= 1) {
1109
1196
  if (cssHandlerOptions.isMainChunk && sourceOptions.cssEntries?.length === 1) return [await resolveTailwindV4CssEntrySource(sourceOptions.cssEntries[0], normalizeTailwindV4CssSourceConfigs(sourceOptions)).then((source) => generatorOptions?.config ? {
1110
1197
  ...source,
1111
1198
  css: prependConfigDirective(source.css, generatorOptions.config)
1112
1199
  } : source)];
1113
- if (sourceOptions.cssSources?.length === 1) return [await createTailwindV4CssSourceResolver(sourceOptions, generatorOptions)(sourceOptions.cssSources[0])];
1200
+ if (sourceOptions.cssSources?.length === 1) return [normalizeResolvedTailwindV4SourceConfig(await createTailwindV4CssSourceResolver(sourceOptions, generatorOptions)(sourceOptions.cssSources[0]), sourceOptions.cssSources[0]?.file, sourceOptions)];
1114
1201
  const resolved = await resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions);
1115
1202
  return resolved ? [resolved] : [];
1116
1203
  }
@@ -1153,132 +1240,627 @@ async function resolveGeneratorSourceEntries(source, runtimeState) {
1153
1240
  return resolved?.entries;
1154
1241
  }
1155
1242
  //#endregion
1156
- //#region src/bundlers/shared/generator-css/legacy-compat.ts
1157
- const LEGACY_CONTAINER_COMPAT_CSS = [
1158
- ".container {",
1159
- " width: 100%;",
1160
- "}",
1161
- "@media (min-width: 40rem) {",
1162
- " .container {",
1163
- " max-width: 40rem;",
1164
- " }",
1165
- "}",
1166
- "@media (min-width: 48rem) {",
1167
- " .container {",
1168
- " max-width: 48rem;",
1169
- " }",
1170
- "}",
1171
- "@media (min-width: 64rem) {",
1172
- " .container {",
1173
- " max-width: 64rem;",
1174
- " }",
1175
- "}",
1176
- "@media (min-width: 80rem) {",
1177
- " .container {",
1178
- " max-width: 80rem;",
1179
- " }",
1180
- "}",
1181
- "@media (min-width: 96rem) {",
1182
- " .container {",
1183
- " max-width: 96rem;",
1184
- " }",
1185
- "}"
1186
- ].join("\n");
1187
- const LEGACY_COMPAT_CACHE_LIMIT = 128;
1188
- const legacyCompatSourceCache = /* @__PURE__ */ new Map();
1189
- const legacyCompatTransformCache = /* @__PURE__ */ new Map();
1190
- function setLimitedCacheValue(cache, key, value) {
1191
- if (cache.size >= LEGACY_COMPAT_CACHE_LIMIT) {
1192
- const firstKey = cache.keys().next().value;
1193
- if (firstKey !== void 0) cache.delete(firstKey);
1243
+ //#region src/bundlers/shared/generator-css/user-css.ts
1244
+ const TAILWIND_V4_GENERATOR_AT_RULES = new Set([
1245
+ "config",
1246
+ "custom-variant",
1247
+ "plugin",
1248
+ "source",
1249
+ "theme",
1250
+ "utility",
1251
+ "variant"
1252
+ ]);
1253
+ function removeBalancedAtRuleBlock(source, atRuleStart) {
1254
+ const blockStart = source.indexOf("{", atRuleStart);
1255
+ if (blockStart === -1) {
1256
+ const semicolon = source.indexOf(";", atRuleStart);
1257
+ return semicolon === -1 ? source.slice(0, atRuleStart) : `${source.slice(0, atRuleStart)}${source.slice(semicolon + 1)}`;
1194
1258
  }
1195
- cache.set(key, value);
1259
+ let depth = 0;
1260
+ for (let index = blockStart; index < source.length; index++) {
1261
+ const char = source[index];
1262
+ if (char === "{") {
1263
+ depth++;
1264
+ continue;
1265
+ }
1266
+ if (char !== "}") continue;
1267
+ depth--;
1268
+ if (depth === 0) return `${source.slice(0, atRuleStart)}${source.slice(index + 1)}`;
1269
+ }
1270
+ return source.slice(0, atRuleStart);
1196
1271
  }
1197
- function createStableJson(value) {
1198
- if (value === void 0) return "undefined";
1199
- if (value === null || typeof value !== "object") return JSON.stringify(value);
1200
- if (Array.isArray(value)) return `[${value.map((item) => createStableJson(item)).join(",")}]`;
1201
- return `{${Object.keys(value).sort().map((key) => {
1202
- const record = value;
1203
- return `${JSON.stringify(key)}:${createStableJson(record[key])}`;
1204
- }).join(",")}}`;
1272
+ function removeTailwindV4GeneratorAtRulesFallback(source) {
1273
+ let next = source;
1274
+ let changed = false;
1275
+ const sourceMediaRE = /@media\s+source\([^)]*\)\s*\{/g;
1276
+ for (;;) {
1277
+ sourceMediaRE.lastIndex = 0;
1278
+ const match = sourceMediaRE.exec(next);
1279
+ if (!match) break;
1280
+ next = removeBalancedAtRuleBlock(next, match.index);
1281
+ changed = true;
1282
+ }
1283
+ const atRuleRE = /@(?:config|custom-variant|plugin|source|theme|utility|variant)\b/g;
1284
+ for (;;) {
1285
+ atRuleRE.lastIndex = 0;
1286
+ const match = atRuleRE.exec(next);
1287
+ if (!match) break;
1288
+ next = removeBalancedAtRuleBlock(next, match.index);
1289
+ changed = true;
1290
+ }
1291
+ return changed ? next : source;
1292
+ }
1293
+ function isTailwindGeneratedPreflightComment(text) {
1294
+ return text.includes("cssremedy") || text.includes("Use the user's configured") || text.includes("tailwindlabs/tailwindcss") || text.includes("Prevent padding and border from affecting element width") || text.includes("Remove default margins and padding") || text.includes("Deprecated") || text.includes("Reset all borders") || text.includes("Add the correct text decoration") || text.includes("Make elements with the HTML hidden attribute stay hidden") || text.includes("Inherit font styles in all browsers") || text.includes("Add the correct height in Firefox") || text.includes("Remove the default font size and weight for headings") || text.includes("Reset links to optimize for opt-in styling") || text.includes("Add the correct font weight in Edge and Safari") || text.includes("Use the user's configured `mono` font-family") || text.includes("Add the correct font size in all browsers") || text.includes("Prevent `sub` and `sup` elements from affecting the line height") || text.includes("Remove text indentation from table contents") || text.includes("Use the modern Firefox focus style") || text.includes("Add the correct vertical alignment") || text.includes("Add the correct display") || text.includes("Make lists unstyled by default") || text.includes("Make replaced elements `display: block` by default") || text.includes("Constrain images and videos to the parent width") || text.includes("Restore default font weight") || text.includes("Restore indentation") || text.includes("Restore space after button") || text.includes("Prevent resizing textareas horizontally") || text.includes("Remove the inner padding in Chrome and Safari") || text.includes("Ensure date/time inputs have the same height") || text.includes("Prevent height from changing on date/time inputs") || text.includes("Remove excess padding from pseudo-elements") || text.includes("Center dropdown marker shown on inputs") || text.includes("Remove the additional `:invalid` styles") || text.includes("Correct the inability to style the border radius") || text.includes("Correct the cursor style of increment and decrement buttons");
1295
+ }
1296
+ function isTailwindGeneratedThemeRule(selector, node) {
1297
+ if (!/(?:^|,)\s*(?::host|page|\.tw-root|wx-root-portal-content)\b/.test(selector)) return false;
1298
+ return node.nodes?.some((child) => child.type === "decl" && /^--(?:color|spacing|text|font|default|radius|tw-)/.test(child.prop)) ?? false;
1299
+ }
1300
+ function isTailwindGeneratedPreflightRule(selector, node) {
1301
+ if (selector === "view,text,::after,::before" || selector === "view, text, ::after, ::before" || selector === "*" || selector === "::after" || selector === "::before" || selector === "::backdrop" || selector === ":host" || selector === "[hidden]:not([hidden=\"until-found\"])" || selector === "[hidden]:not([hidden='until-found'])" || selector === "button,input[type=\"button\"],input[type=\"reset\"],input[type=\"submit\"]" || selector === "button, input[type=\"button\"], input[type=\"reset\"], input[type=\"submit\"]" || selector === "button,input[type='button'],input[type='reset'],input[type='submit']" || selector === "button, input[type='button'], input[type='reset'], input[type='submit']") return true;
1302
+ if (selector === "abbr[title]") return node.nodes?.some((child) => child.type === "decl" && child.prop === "text-decoration") ?? false;
1303
+ if (selector === ":host") return node.nodes?.some((child) => child.type === "decl" && child.value?.includes("--theme(")) ?? false;
1304
+ return false;
1205
1305
  }
1206
- function createLegacyCompatTransformCacheKey(source, options) {
1207
- return `${createStableJson(options)}\0${source}`;
1306
+ function removeTailwindV4GeneratedUserCssArtifacts(source) {
1307
+ try {
1308
+ const root = postcss.parse(source);
1309
+ let changed = false;
1310
+ root.walkComments((comment) => {
1311
+ if (!isTailwindGeneratedPreflightComment(comment.text)) return;
1312
+ comment.remove();
1313
+ changed = true;
1314
+ });
1315
+ root.walkRules((rule) => {
1316
+ const selector = rule.selector.replace(/\s+/g, " ").trim();
1317
+ if (isTailwindGeneratedThemeRule(selector, rule) || isTailwindGeneratedPreflightRule(selector, rule)) {
1318
+ rule.remove();
1319
+ changed = true;
1320
+ }
1321
+ });
1322
+ root.walkAtRules((rule) => {
1323
+ if (rule.nodes !== void 0 && rule.nodes.length === 0) {
1324
+ rule.remove();
1325
+ changed = true;
1326
+ }
1327
+ });
1328
+ return changed ? root.toString() : source;
1329
+ } catch {
1330
+ return source;
1331
+ }
1208
1332
  }
1209
- function countUnclosedBlocks(source) {
1210
- let depth = 0;
1211
- let quote;
1212
- let inComment = false;
1213
- let escaped = false;
1214
- for (let index = 0; index < source.length; index += 1) {
1215
- const char = source[index];
1216
- const next = source[index + 1];
1217
- if (inComment) {
1218
- if (char === "*" && next === "/") {
1219
- inComment = false;
1220
- index += 1;
1333
+ function removeTailwindSourceMediaBlocks(source) {
1334
+ let next = source;
1335
+ let changed = false;
1336
+ const sourceMediaRE = /@media\s+source\([^)]*\)\s*\{/g;
1337
+ for (;;) {
1338
+ sourceMediaRE.lastIndex = 0;
1339
+ const match = sourceMediaRE.exec(next);
1340
+ if (!match) break;
1341
+ const blockStart = next.indexOf("{", match.index);
1342
+ if (blockStart === -1) break;
1343
+ let depth = 0;
1344
+ let blockEnd = -1;
1345
+ for (let index = blockStart; index < next.length; index++) {
1346
+ const char = next[index];
1347
+ if (char === "{") {
1348
+ depth++;
1349
+ continue;
1350
+ }
1351
+ if (char !== "}") continue;
1352
+ depth--;
1353
+ if (depth === 0) {
1354
+ blockEnd = index;
1355
+ break;
1221
1356
  }
1357
+ }
1358
+ if (blockEnd === -1) break;
1359
+ next = `${next.slice(0, match.index)}${next.slice(blockEnd + 1)}`;
1360
+ changed = true;
1361
+ }
1362
+ for (;;) {
1363
+ const atRuleStart = findTailwindSourceWrapperBlockStart(next);
1364
+ if (atRuleStart === -1) break;
1365
+ next = removeBalancedAtRuleBlock(next, atRuleStart);
1366
+ changed = true;
1367
+ }
1368
+ return changed ? next : source;
1369
+ }
1370
+ function terminateTailwindSourceAtRulesBeforeNextDirective(source) {
1371
+ if (!source.includes("@source")) return source;
1372
+ let next = "";
1373
+ let searchIndex = 0;
1374
+ for (;;) {
1375
+ const atRuleStart = source.indexOf("@source", searchIndex);
1376
+ if (atRuleStart === -1) {
1377
+ next += source.slice(searchIndex);
1378
+ break;
1379
+ }
1380
+ const nextChar = source[atRuleStart + 7];
1381
+ if (nextChar && /[\w-]/.test(nextChar)) {
1382
+ next += source.slice(searchIndex, atRuleStart + 7);
1383
+ searchIndex = atRuleStart + 7;
1222
1384
  continue;
1223
1385
  }
1224
- if (quote) {
1225
- if (escaped) {
1226
- escaped = false;
1386
+ next += source.slice(searchIndex, atRuleStart);
1387
+ let quote;
1388
+ let parenDepth = 0;
1389
+ let terminated = false;
1390
+ let index = atRuleStart + 7;
1391
+ for (; index < source.length; index++) {
1392
+ const char = source[index];
1393
+ if (quote) {
1394
+ if (char === "\\") {
1395
+ index++;
1396
+ continue;
1397
+ }
1398
+ if (char === quote) quote = void 0;
1227
1399
  continue;
1228
1400
  }
1229
- if (char === "\\") {
1230
- escaped = true;
1401
+ if (char === "\"" || char === "'") {
1402
+ quote = char;
1231
1403
  continue;
1232
1404
  }
1233
- if (char === quote) quote = void 0;
1234
- continue;
1405
+ if (char === "(") {
1406
+ parenDepth++;
1407
+ continue;
1408
+ }
1409
+ if (char === ")" && parenDepth > 0) {
1410
+ parenDepth--;
1411
+ continue;
1412
+ }
1413
+ if (parenDepth > 0) continue;
1414
+ if (char === ";" || char === "{") {
1415
+ terminated = true;
1416
+ index++;
1417
+ break;
1418
+ }
1419
+ if (char === "@" && /^(?:config|custom-variant|plugin|source|theme|utility|variant)\b/.test(source.slice(index + 1))) break;
1235
1420
  }
1236
- if (char === "/" && next === "*") {
1237
- inComment = true;
1238
- index += 1;
1421
+ const segment = source.slice(atRuleStart, index);
1422
+ const trimmedSegment = segment.trimEnd();
1423
+ next += terminated || trimmedSegment.endsWith(";") || trimmedSegment.endsWith("{") ? segment : `${trimmedSegment};${segment.slice(trimmedSegment.length)}`;
1424
+ searchIndex = index;
1425
+ }
1426
+ return next;
1427
+ }
1428
+ function findTailwindSourceWrapperBlockStart(source) {
1429
+ let searchIndex = 0;
1430
+ for (;;) {
1431
+ const atRuleStart = source.indexOf("@source", searchIndex);
1432
+ if (atRuleStart === -1) return -1;
1433
+ const nextChar = source[atRuleStart + 7];
1434
+ if (nextChar && /[\w-]/.test(nextChar)) {
1435
+ searchIndex = atRuleStart + 7;
1239
1436
  continue;
1240
1437
  }
1241
- if (char === "\"" || char === "'") {
1242
- quote = char;
1243
- continue;
1438
+ let quote;
1439
+ let parenDepth = 0;
1440
+ for (let index = atRuleStart + 7; index < source.length; index++) {
1441
+ const char = source[index];
1442
+ if (quote) {
1443
+ if (char === "\\") {
1444
+ index++;
1445
+ continue;
1446
+ }
1447
+ if (char === quote) quote = void 0;
1448
+ continue;
1449
+ }
1450
+ if (char === "\"" || char === "'") {
1451
+ quote = char;
1452
+ continue;
1453
+ }
1454
+ if (char === "(") {
1455
+ parenDepth++;
1456
+ continue;
1457
+ }
1458
+ if (char === ")" && parenDepth > 0) {
1459
+ parenDepth--;
1460
+ continue;
1461
+ }
1462
+ if (parenDepth > 0) continue;
1463
+ if (char === ";") {
1464
+ searchIndex = index + 1;
1465
+ break;
1466
+ }
1467
+ if (char === "{") return atRuleStart;
1244
1468
  }
1245
- if (char === "{") depth += 1;
1246
- else if (char === "}" && depth > 0) depth -= 1;
1469
+ if (searchIndex <= atRuleStart) return -1;
1247
1470
  }
1248
- return depth;
1249
1471
  }
1250
- function closeTrailingUnclosedBlocks(source) {
1472
+ function removeTailwindApplyAtRules(source) {
1473
+ if (!source.includes("@apply")) return source;
1251
1474
  try {
1252
- postcss.parse(source);
1475
+ const root = postcss.parse(source);
1476
+ let changed = false;
1477
+ root.walkAtRules("apply", (rule) => {
1478
+ rule.remove();
1479
+ changed = true;
1480
+ });
1481
+ root.walk((node) => {
1482
+ if ("nodes" in node && node.nodes?.length === 0) node.remove();
1483
+ });
1484
+ return changed ? root.toString() : source;
1485
+ } catch {
1253
1486
  return source;
1254
- } catch (error) {
1255
- if (error.reason !== "Unclosed block") return source;
1256
- const unclosedBlocks = countUnclosedBlocks(source);
1257
- return unclosedBlocks > 0 ? `${source}${"}".repeat(unclosedBlocks)}` : source;
1258
1487
  }
1259
1488
  }
1260
- function removeTailwindApplyRules(rawSource) {
1489
+ function removeTailwindV4GeneratorAtRules(source) {
1261
1490
  try {
1262
- const root = postcss.parse(rawSource);
1263
- let removed = false;
1264
- root.walkAtRules("apply", (rule) => {
1265
- const parent = rule.parent;
1266
- if (parent?.type === "rule") parent.remove();
1267
- else rule.remove();
1268
- removed = true;
1269
- });
1491
+ const root = postcss.parse(source);
1492
+ let changed = false;
1270
1493
  root.walkAtRules((rule) => {
1271
- if (rule.nodes && rule.nodes.length === 0) rule.remove();
1494
+ if (rule.name === "media" && /^source\(/.test(rule.params.trim())) {
1495
+ rule.remove();
1496
+ changed = true;
1497
+ return;
1498
+ }
1499
+ if (!TAILWIND_V4_GENERATOR_AT_RULES.has(rule.name)) return;
1500
+ rule.remove();
1501
+ changed = true;
1272
1502
  });
1273
- return removed ? root.toString() : rawSource;
1503
+ return changed ? root.toString() : source;
1274
1504
  } catch {
1275
- return rawSource;
1505
+ return removeTailwindV4GeneratorAtRulesFallback(source);
1276
1506
  }
1277
1507
  }
1278
- function resolveLegacyCompatCssSource(rawSource) {
1279
- const cached = legacyCompatSourceCache.get(rawSource);
1508
+ function isCommentOnlyCss(source) {
1509
+ try {
1510
+ const root = postcss.parse(source);
1511
+ return root.nodes.length > 0 && root.nodes.every((node) => node.type === "comment");
1512
+ } catch {
1513
+ return false;
1514
+ }
1515
+ }
1516
+ function removeMiniProgramHoverSelectors(source, enabled = true) {
1517
+ if (!enabled || !source.includes(":hover")) return source;
1518
+ try {
1519
+ const root = postcss.parse(source);
1520
+ let changed = false;
1521
+ root.walkRules((rule) => {
1522
+ const selectors = rule.selectors ?? [rule.selector];
1523
+ const keptSelectors = selectors.filter((selector) => !selector.includes(":hover"));
1524
+ if (keptSelectors.length === selectors.length) return;
1525
+ changed = true;
1526
+ if (keptSelectors.length === 0) {
1527
+ rule.remove();
1528
+ return;
1529
+ }
1530
+ rule.selectors = keptSelectors;
1531
+ });
1532
+ root.walk((node) => {
1533
+ if ("nodes" in node && node.nodes?.length === 0) {
1534
+ node.remove();
1535
+ changed = true;
1536
+ }
1537
+ });
1538
+ return changed ? root.toString() : source;
1539
+ } catch {
1540
+ return source;
1541
+ }
1542
+ }
1543
+ function removeProcessedMiniProgramUnsupportedCss(source, options) {
1544
+ return removeMiniProgramHoverSelectors(removeUnsupportedMiniProgramAtRules(source), options.cssRemoveHoverPseudoClass);
1545
+ }
1546
+ function unwrapMiniProgramCascadeLayers(source) {
1547
+ if (!source.includes("@layer")) return source;
1548
+ try {
1549
+ const root = postcss.parse(source);
1550
+ removeUnsupportedCascadeLayers(root);
1551
+ return root.toString();
1552
+ } catch {
1553
+ return source;
1554
+ }
1555
+ }
1556
+ function stripTailwindSourceMediaFragments(source) {
1557
+ let removedSourceMediaStart = false;
1558
+ return terminateTailwindSourceAtRulesBeforeNextDirective(removeTailwindSourceMediaBlocks(source)).split(/\r?\n/).filter((line) => {
1559
+ if (/^\s*@media\s+source\([^)]*\)\s*\{\s*$/.test(line)) {
1560
+ removedSourceMediaStart = true;
1561
+ return false;
1562
+ }
1563
+ if (/^\s*\}\s*\/\*\s*source\([^)]*\)\s*\*\/\s*$/.test(line)) return false;
1564
+ if (removedSourceMediaStart && /^\s*\}\s*$/.test(line)) {
1565
+ removedSourceMediaStart = false;
1566
+ return false;
1567
+ }
1568
+ return true;
1569
+ }).join("\n");
1570
+ }
1571
+ function stripLeadingTailwindSourceMediaCloseFragment(source) {
1572
+ return source.replace(/^\s*\}\s*(?:\n|$)/, "");
1573
+ }
1574
+ function stripUnmatchedTailwindSourceMediaCloseFragments(source) {
1575
+ try {
1576
+ postcss.parse(source);
1577
+ return source;
1578
+ } catch {
1579
+ return stripLeadingTailwindSourceMediaCloseFragment(source).replace(/\s*\}\s*$/, "");
1580
+ }
1581
+ }
1582
+ function splitUserCssLayerBlocks(source) {
1583
+ if (!source.includes("@layer")) return {
1584
+ layer: "",
1585
+ rest: source
1586
+ };
1587
+ try {
1588
+ const root = postcss.parse(source);
1589
+ const layerRoot = postcss.root();
1590
+ const restRoot = postcss.root();
1591
+ for (const node of root.nodes) (node.type === "atrule" && node.name === "layer" && node.nodes?.length ? layerRoot : restRoot).append(node.clone());
1592
+ return {
1593
+ layer: layerRoot.toString(),
1594
+ rest: restRoot.toString()
1595
+ };
1596
+ } catch {
1597
+ return {
1598
+ layer: source,
1599
+ rest: ""
1600
+ };
1601
+ }
1602
+ }
1603
+ function hasUserCssLayerBlocks(source) {
1604
+ if (!source.includes("@layer")) return false;
1605
+ try {
1606
+ let hasLayerBlock = false;
1607
+ postcss.parse(source).walkAtRules("layer", (node) => {
1608
+ if (node.nodes?.length) hasLayerBlock = true;
1609
+ });
1610
+ return hasLayerBlock;
1611
+ } catch {
1612
+ return true;
1613
+ }
1614
+ }
1615
+ function collectUserLayerSelectors(source) {
1616
+ const selectors = /* @__PURE__ */ new Set();
1617
+ try {
1618
+ postcss.parse(source).walkRules((rule) => {
1619
+ for (const selector of rule.selectors ?? [rule.selector]) {
1620
+ const normalized = selector.trim();
1621
+ if (normalized) selectors.add(normalized);
1622
+ }
1623
+ });
1624
+ } catch {}
1625
+ return selectors;
1626
+ }
1627
+ function matchesUserLayerSelector(selector, userLayerSelector) {
1628
+ if (selector === userLayerSelector) return true;
1629
+ if (!selector.startsWith(userLayerSelector)) return false;
1630
+ const next = selector[userLayerSelector.length];
1631
+ return next === ":" || next === "[";
1632
+ }
1633
+ function extractGeneratedCssForUserLayerSelectors(css, userLayerSource) {
1634
+ const selectors = collectUserLayerSelectors(userLayerSource);
1635
+ if (selectors.size === 0) return {
1636
+ layer: "",
1637
+ rest: css
1638
+ };
1639
+ try {
1640
+ const root = postcss.parse(css);
1641
+ const layerRoot = postcss.root();
1642
+ const selectorList = [...selectors];
1643
+ root.walkRules((rule) => {
1644
+ if ((rule.selectors ?? [rule.selector]).some((selector) => selectorList.some((userSelector) => matchesUserLayerSelector(selector.trim(), userSelector)))) {
1645
+ layerRoot.append(rule.clone());
1646
+ rule.remove();
1647
+ }
1648
+ });
1649
+ return {
1650
+ layer: layerRoot.toString(),
1651
+ rest: root.toString()
1652
+ };
1653
+ } catch {
1654
+ return {
1655
+ layer: "",
1656
+ rest: css
1657
+ };
1658
+ }
1659
+ }
1660
+ function normalizeGeneratedSelector(selector) {
1661
+ return selector.replace(/:not\(#\\#\)/g, "").trim();
1662
+ }
1663
+ function collectApplyOnlySourceSelectors(source) {
1664
+ const selectors = /* @__PURE__ */ new Set();
1665
+ try {
1666
+ postcss.parse(source).walkRules((rule) => {
1667
+ if (!rule.nodes?.some((node) => node.type === "atrule" && node.name === "apply")) return;
1668
+ for (const selector of rule.selectors ?? [rule.selector]) {
1669
+ const normalized = normalizeGeneratedSelector(selector);
1670
+ if (normalized) selectors.add(normalized);
1671
+ }
1672
+ });
1673
+ } catch {}
1674
+ return selectors;
1675
+ }
1676
+ function hasOnlyApplyBackedSourceRules(source) {
1677
+ let hasApplyRule = false;
1678
+ let hasNonApplyRule = false;
1679
+ try {
1680
+ postcss.parse(source).walkRules((rule) => {
1681
+ if (rule.nodes?.some((node) => node.type === "atrule" && node.name === "apply")) hasApplyRule = true;
1682
+ else hasNonApplyRule = true;
1683
+ });
1684
+ } catch {
1685
+ return false;
1686
+ }
1687
+ return hasApplyRule && !hasNonApplyRule;
1688
+ }
1689
+ function filterApplyOnlyGeneratedCss(css, source) {
1690
+ const selectors = collectApplyOnlySourceSelectors(source);
1691
+ if (selectors.size === 0) return css;
1692
+ const selectorList = [...selectors];
1693
+ try {
1694
+ const root = postcss.parse(css);
1695
+ root.walkRules((rule) => {
1696
+ const isApplySelector = (rule.selectors ?? [rule.selector]).some((selector) => {
1697
+ const normalized = normalizeGeneratedSelector(selector);
1698
+ return selectorList.some((sourceSelector) => {
1699
+ if (normalized === sourceSelector) return true;
1700
+ if (!normalized.startsWith(sourceSelector)) return false;
1701
+ const next = normalized[sourceSelector.length];
1702
+ return next === ":" || next === "[" || next === ".";
1703
+ });
1704
+ });
1705
+ const isVariableRule = rule.nodes?.some((node) => node.type === "decl" && node.prop.startsWith("--"));
1706
+ if (!isApplySelector && !isVariableRule) rule.remove();
1707
+ });
1708
+ root.walkAtRules((rule) => {
1709
+ if (rule.nodes !== void 0 && rule.nodes.length === 0) rule.remove();
1710
+ });
1711
+ return root.toString();
1712
+ } catch {
1713
+ return css;
1714
+ }
1715
+ }
1716
+ function shouldFilterApplyOnlyGeneratedCss(_majorVersion, target, source, options) {
1717
+ return target === "weapp" && hasTailwindApplyDirective(source) && !hasTailwindRootDirectives(source) && !options.hasGeneratedCss && !options.hasGeneratedMarkers && collectApplyOnlySourceSelectors(source).size > 0 && hasOnlyApplyBackedSourceRules(source);
1718
+ }
1719
+ async function transformGeneratorUserCss(source, options) {
1720
+ if (source.trim().length === 0) return "";
1721
+ if (options.processed) return stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(removeTailwindV4GeneratorAtRules(options.generatorTarget === "weapp" ? removeTailwindV4GeneratedUserCssArtifacts(removeProcessedMiniProgramUnsupportedCss(source, {
1722
+ ...options.generatorStyleOptions,
1723
+ ...options.cssUserHandlerOptions
1724
+ })) : source)));
1725
+ const cleanedSource = removeTailwindSourceDirectives(removeTailwindV4GeneratorAtRules(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(source))), { importFallback: options.importFallback });
1726
+ if (cleanedSource.trim().length === 0) return "";
1727
+ const userSource = stripUnmatchedTailwindSourceMediaCloseFragments(removeTailwindApplyAtRules(removeTailwindSourceDirectives(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(options.generatorTarget === "weapp" ? removeTailwindV4GeneratedUserCssArtifacts(removeUnsupportedMiniProgramAtRules(unwrapMiniProgramCascadeLayers(cleanedSource))) : cleanedSource)), { importFallback: options.importFallback })));
1728
+ if (userSource.trim().length === 0) return "";
1729
+ if (isCommentOnlyCss(userSource)) return userSource;
1730
+ if (options.generatorTarget !== "weapp") return userSource;
1731
+ const { css } = await options.styleHandler(userSource, {
1732
+ ...options.generatorStyleOptions,
1733
+ ...options.cssUserHandlerOptions
1734
+ });
1735
+ return removeTailwindV4GeneratedUserCssArtifacts(removeUnsupportedMiniProgramAtRules(css));
1736
+ }
1737
+ //#endregion
1738
+ //#region src/bundlers/shared/generator-css/legacy-compat.ts
1739
+ const LEGACY_CONTAINER_COMPAT_CSS = [
1740
+ ".container {",
1741
+ " width: 100%;",
1742
+ "}",
1743
+ "@media (min-width: 40rem) {",
1744
+ " .container {",
1745
+ " max-width: 40rem;",
1746
+ " }",
1747
+ "}",
1748
+ "@media (min-width: 48rem) {",
1749
+ " .container {",
1750
+ " max-width: 48rem;",
1751
+ " }",
1752
+ "}",
1753
+ "@media (min-width: 64rem) {",
1754
+ " .container {",
1755
+ " max-width: 64rem;",
1756
+ " }",
1757
+ "}",
1758
+ "@media (min-width: 80rem) {",
1759
+ " .container {",
1760
+ " max-width: 80rem;",
1761
+ " }",
1762
+ "}",
1763
+ "@media (min-width: 96rem) {",
1764
+ " .container {",
1765
+ " max-width: 96rem;",
1766
+ " }",
1767
+ "}"
1768
+ ].join("\n");
1769
+ const LEGACY_COMPAT_CACHE_LIMIT = 128;
1770
+ const legacyCompatSourceCache = /* @__PURE__ */ new Map();
1771
+ const legacyCompatTransformCache = /* @__PURE__ */ new Map();
1772
+ function setLimitedCacheValue(cache, key, value) {
1773
+ if (cache.size >= LEGACY_COMPAT_CACHE_LIMIT) {
1774
+ const firstKey = cache.keys().next().value;
1775
+ if (firstKey !== void 0) cache.delete(firstKey);
1776
+ }
1777
+ cache.set(key, value);
1778
+ }
1779
+ function createStableJson(value) {
1780
+ if (value === void 0) return "undefined";
1781
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1782
+ if (Array.isArray(value)) return `[${value.map((item) => createStableJson(item)).join(",")}]`;
1783
+ return `{${Object.keys(value).sort().map((key) => {
1784
+ const record = value;
1785
+ return `${JSON.stringify(key)}:${createStableJson(record[key])}`;
1786
+ }).join(",")}}`;
1787
+ }
1788
+ function createLegacyCompatTransformCacheKey(source, options) {
1789
+ return `${createStableJson(options)}\0${source}`;
1790
+ }
1791
+ function countUnclosedBlocks(source) {
1792
+ let depth = 0;
1793
+ let quote;
1794
+ let inComment = false;
1795
+ let escaped = false;
1796
+ for (let index = 0; index < source.length; index += 1) {
1797
+ const char = source[index];
1798
+ const next = source[index + 1];
1799
+ if (inComment) {
1800
+ if (char === "*" && next === "/") {
1801
+ inComment = false;
1802
+ index += 1;
1803
+ }
1804
+ continue;
1805
+ }
1806
+ if (quote) {
1807
+ if (escaped) {
1808
+ escaped = false;
1809
+ continue;
1810
+ }
1811
+ if (char === "\\") {
1812
+ escaped = true;
1813
+ continue;
1814
+ }
1815
+ if (char === quote) quote = void 0;
1816
+ continue;
1817
+ }
1818
+ if (char === "/" && next === "*") {
1819
+ inComment = true;
1820
+ index += 1;
1821
+ continue;
1822
+ }
1823
+ if (char === "\"" || char === "'") {
1824
+ quote = char;
1825
+ continue;
1826
+ }
1827
+ if (char === "{") depth += 1;
1828
+ else if (char === "}" && depth > 0) depth -= 1;
1829
+ }
1830
+ return depth;
1831
+ }
1832
+ function closeTrailingUnclosedBlocks(source) {
1833
+ try {
1834
+ postcss.parse(source);
1835
+ return source;
1836
+ } catch (error) {
1837
+ if (error.reason !== "Unclosed block") return source;
1838
+ const unclosedBlocks = countUnclosedBlocks(source);
1839
+ return unclosedBlocks > 0 ? `${source}${"}".repeat(unclosedBlocks)}` : source;
1840
+ }
1841
+ }
1842
+ function removeTailwindApplyRules(rawSource) {
1843
+ try {
1844
+ const root = postcss.parse(rawSource);
1845
+ let removed = false;
1846
+ root.walkAtRules("apply", (rule) => {
1847
+ const parent = rule.parent;
1848
+ if (parent?.type === "rule") parent.remove();
1849
+ else rule.remove();
1850
+ removed = true;
1851
+ });
1852
+ root.walkAtRules((rule) => {
1853
+ if (rule.nodes && rule.nodes.length === 0) rule.remove();
1854
+ });
1855
+ return removed ? root.toString() : rawSource;
1856
+ } catch {
1857
+ return rawSource;
1858
+ }
1859
+ }
1860
+ function resolveLegacyCompatCssSource(rawSource) {
1861
+ const cached = legacyCompatSourceCache.get(rawSource);
1280
1862
  if (cached !== void 0) return cached;
1281
- const resolved = closeTrailingUnclosedBlocks(removeUnsupportedMiniProgramAtRules(removeTailwindApplyRules(removeTailwindSourceDirectives(closeTrailingUnclosedBlocks(stripTailwindBanners(rawSource))))));
1863
+ const resolved = closeTrailingUnclosedBlocks(removeTailwindV4GeneratedUserCssArtifacts(removeUnsupportedMiniProgramAtRules(removeTailwindApplyRules(removeTailwindSourceDirectives(closeTrailingUnclosedBlocks(stripTailwindBanners(rawSource)))))));
1282
1864
  setLimitedCacheValue(legacyCompatSourceCache, rawSource, resolved);
1283
1865
  return resolved;
1284
1866
  }
@@ -1317,12 +1899,13 @@ function hasConfiguredContainerCompat(rawSource, file, cssHandlerOptions) {
1317
1899
  }
1318
1900
  }
1319
1901
  function hasConfiguredContainerCompatSource(source) {
1902
+ if (typeof source.css !== "string") return false;
1320
1903
  if (hasContainerConfigToken(source.css)) return true;
1321
1904
  const cssEntrySource = resolveCssEntrySource(source.css, source.base);
1322
1905
  if (cssEntrySource?.config) try {
1323
1906
  if (/\bcontainer\b/.test(readFileSync(cssEntrySource.config, "utf8"))) return true;
1324
1907
  } catch {}
1325
- if ("config" in source && source.config) try {
1908
+ if ("config" in source && typeof source.config === "string") try {
1326
1909
  if (/\bcontainer\b/.test(readFileSync(source.config, "utf8"))) return true;
1327
1910
  } catch {}
1328
1911
  return false;
@@ -1345,7 +1928,7 @@ async function appendLegacyCompatCss(css, rawSource, generatorTarget, styleHandl
1345
1928
  compatCss = (await styleHandler(compatSource, styleOptions)).css;
1346
1929
  setLimitedCacheValue(legacyCompatTransformCache, compatCssCacheKey, compatCss);
1347
1930
  }
1348
- const cleanedCompatCss = collectDedupedPostTransformCompatCss(removeDuplicatedViteMarkers(removeUnsupportedMiniProgramAtRules(compatCss), css), css);
1931
+ const cleanedCompatCss = collectDedupedPostTransformCompatCss(removeTailwindV4GeneratedUserCssArtifacts(removeDuplicatedViteMarkers(removeUnsupportedMiniProgramAtRules(compatCss), css)), css);
1349
1932
  if (cleanedCompatCss.trim().length === 0) return css;
1350
1933
  return createCssAppend(css, cleanedCompatCss);
1351
1934
  }
@@ -1415,6 +1998,8 @@ function inheritLegacyUnitConvertedDeclarations(css, legacyCss) {
1415
1998
  //#endregion
1416
1999
  //#region src/bundlers/shared/generator-css/local-imports.ts
1417
2000
  const REMOTE_IMPORT_RE = /^(?:https?:)?\/\//i;
2001
+ const CSS_STYLE_EXTENSION_RE = /\.(?:css|wxss|acss|ttss|qss|jxss|tyss|scss|sass|less|styl|stylus|pcss|postcss)(?:$|[?#])/i;
2002
+ const SOURCE_STYLE_EXTENSION_RE = /\.(?:css|scss|sass|less|styl|stylus|pcss|postcss)(?:$|[?#])/i;
1418
2003
  function createCssSourceOrderAppend(base, extra) {
1419
2004
  if (!base) return extra;
1420
2005
  if (!extra) return base;
@@ -1485,266 +2070,58 @@ function splitLocalCssImports(source) {
1485
2070
  if (node.type !== "atrule" || node.name !== "import") continue;
1486
2071
  const request = parseImportRequest(node.params);
1487
2072
  if (!request || !isLocalImportRequest(request)) continue;
1488
- importRoot.append(node.clone());
1489
- node.remove();
1490
- changed = true;
1491
- }
1492
- const imports = importRoot.nodes.filter((node) => node.type === "atrule" && node.name === "import").map((node) => `@import ${node.params};`).join("\n");
1493
- return changed ? {
1494
- imports,
1495
- source: root.toString()
1496
- } : void 0;
1497
- } catch {
1498
- return;
1499
- }
1500
- }
1501
- function restoreLocalCssImports(css, imports) {
1502
- if (!imports?.trim()) return css;
1503
- return createCssSourceOrderAppend(imports, css);
1504
- }
1505
- //#endregion
1506
- //#region src/bundlers/shared/generator-css/user-css.ts
1507
- const TAILWIND_V4_GENERATOR_AT_RULES = new Set([
1508
- "config",
1509
- "custom-variant",
1510
- "plugin",
1511
- "source",
1512
- "theme",
1513
- "utility",
1514
- "variant"
1515
- ]);
1516
- function removeTailwindApplyAtRules(source) {
1517
- if (!source.includes("@apply")) return source;
1518
- try {
1519
- const root = postcss.parse(source);
1520
- let changed = false;
1521
- root.walkAtRules("apply", (rule) => {
1522
- rule.remove();
1523
- changed = true;
1524
- });
1525
- root.walk((node) => {
1526
- if ("nodes" in node && node.nodes?.length === 0) node.remove();
1527
- });
1528
- return changed ? root.toString() : source;
1529
- } catch {
1530
- return source;
1531
- }
1532
- }
1533
- function removeTailwindV4GeneratorAtRules(source) {
1534
- try {
1535
- const root = postcss.parse(source);
1536
- let changed = false;
1537
- root.walkAtRules((rule) => {
1538
- if (!TAILWIND_V4_GENERATOR_AT_RULES.has(rule.name)) return;
1539
- rule.remove();
1540
- changed = true;
1541
- });
1542
- root.walk((node) => {
1543
- if ("nodes" in node && node.nodes?.length === 0) {
1544
- node.remove();
1545
- changed = true;
1546
- }
1547
- });
1548
- return changed ? root.toString() : source;
1549
- } catch {
1550
- return source;
1551
- }
1552
- }
1553
- function isCommentOnlyCss(source) {
1554
- try {
1555
- const root = postcss.parse(source);
1556
- return root.nodes.length > 0 && root.nodes.every((node) => node.type === "comment");
1557
- } catch {
1558
- return false;
1559
- }
1560
- }
1561
- function unwrapMiniProgramCascadeLayers(source) {
1562
- if (!source.includes("@layer")) return source;
1563
- try {
1564
- const root = postcss.parse(source);
1565
- removeUnsupportedCascadeLayers(root);
1566
- return root.toString();
1567
- } catch {
1568
- return source;
1569
- }
1570
- }
1571
- function stripTailwindSourceMediaFragments(source) {
1572
- let removedSourceMediaStart = false;
1573
- return source.split(/\r?\n/).filter((line) => {
1574
- if (/^\s*@media\s+source\([^)]*\)\s*\{\s*$/.test(line)) {
1575
- removedSourceMediaStart = true;
1576
- return false;
1577
- }
1578
- if (/^\s*\}\s*\/\*\s*source\([^)]*\)\s*\*\/\s*$/.test(line)) return false;
1579
- if (removedSourceMediaStart && /^\s*\}\s*$/.test(line)) {
1580
- removedSourceMediaStart = false;
1581
- return false;
1582
- }
1583
- return true;
1584
- }).join("\n").replace(/\}[^\S\r\n]*(?=@(?:config|source)\b)/g, "");
1585
- }
1586
- function stripLeadingTailwindSourceMediaCloseFragment(source) {
1587
- return source.replace(/^\s*\}\s*(?:\n|$)/, "");
1588
- }
1589
- function stripUnmatchedTailwindSourceMediaCloseFragments(source) {
1590
- try {
1591
- postcss.parse(source);
1592
- return source;
1593
- } catch {
1594
- return stripLeadingTailwindSourceMediaCloseFragment(source).replace(/\s*\}\s*$/, "");
1595
- }
1596
- }
1597
- function splitUserCssLayerBlocks(source) {
1598
- if (!source.includes("@layer")) return {
1599
- layer: "",
1600
- rest: source
1601
- };
1602
- try {
1603
- const root = postcss.parse(source);
1604
- const layerRoot = postcss.root();
1605
- const restRoot = postcss.root();
1606
- for (const node of root.nodes) (node.type === "atrule" && node.name === "layer" && node.nodes?.length ? layerRoot : restRoot).append(node.clone());
1607
- return {
1608
- layer: layerRoot.toString(),
1609
- rest: restRoot.toString()
1610
- };
1611
- } catch {
1612
- return {
1613
- layer: source,
1614
- rest: ""
1615
- };
1616
- }
1617
- }
1618
- function hasUserCssLayerBlocks(source) {
1619
- if (!source.includes("@layer")) return false;
1620
- try {
1621
- let hasLayerBlock = false;
1622
- postcss.parse(source).walkAtRules("layer", (node) => {
1623
- if (node.nodes?.length) hasLayerBlock = true;
1624
- });
1625
- return hasLayerBlock;
1626
- } catch {
1627
- return true;
1628
- }
1629
- }
1630
- function collectUserLayerSelectors(source) {
1631
- const selectors = /* @__PURE__ */ new Set();
1632
- try {
1633
- postcss.parse(source).walkRules((rule) => {
1634
- for (const selector of rule.selectors ?? [rule.selector]) {
1635
- const normalized = selector.trim();
1636
- if (normalized) selectors.add(normalized);
1637
- }
1638
- });
1639
- } catch {}
1640
- return selectors;
1641
- }
1642
- function matchesUserLayerSelector(selector, userLayerSelector) {
1643
- if (selector === userLayerSelector) return true;
1644
- if (!selector.startsWith(userLayerSelector)) return false;
1645
- const next = selector[userLayerSelector.length];
1646
- return next === ":" || next === "[";
1647
- }
1648
- function extractGeneratedCssForUserLayerSelectors(css, userLayerSource) {
1649
- const selectors = collectUserLayerSelectors(userLayerSource);
1650
- if (selectors.size === 0) return {
1651
- layer: "",
1652
- rest: css
1653
- };
1654
- try {
1655
- const root = postcss.parse(css);
1656
- const layerRoot = postcss.root();
1657
- const selectorList = [...selectors];
1658
- root.walkRules((rule) => {
1659
- if ((rule.selectors ?? [rule.selector]).some((selector) => selectorList.some((userSelector) => matchesUserLayerSelector(selector.trim(), userSelector)))) {
1660
- layerRoot.append(rule.clone());
1661
- rule.remove();
1662
- }
1663
- });
1664
- return {
1665
- layer: layerRoot.toString(),
1666
- rest: root.toString()
1667
- };
1668
- } catch {
1669
- return {
1670
- layer: "",
1671
- rest: css
1672
- };
1673
- }
1674
- }
1675
- function normalizeGeneratedSelector(selector) {
1676
- return selector.replace(/:not\(#\\#\)/g, "").trim();
1677
- }
1678
- function collectApplyOnlySourceSelectors(source) {
1679
- const selectors = /* @__PURE__ */ new Set();
1680
- try {
1681
- postcss.parse(source).walkRules((rule) => {
1682
- if (!rule.nodes?.some((node) => node.type === "atrule" && node.name === "apply")) return;
1683
- for (const selector of rule.selectors ?? [rule.selector]) {
1684
- const normalized = normalizeGeneratedSelector(selector);
1685
- if (normalized) selectors.add(normalized);
1686
- }
1687
- });
1688
- } catch {}
1689
- return selectors;
1690
- }
1691
- function hasOnlyApplyBackedSourceRules(source) {
1692
- let hasApplyRule = false;
1693
- let hasNonApplyRule = false;
1694
- try {
1695
- postcss.parse(source).walkRules((rule) => {
1696
- if (rule.nodes?.some((node) => node.type === "atrule" && node.name === "apply")) hasApplyRule = true;
1697
- else hasNonApplyRule = true;
1698
- });
2073
+ importRoot.append(node.clone());
2074
+ node.remove();
2075
+ changed = true;
2076
+ }
2077
+ const imports = importRoot.nodes.filter((node) => node.type === "atrule" && node.name === "import").map((node) => `@import ${node.params};`).join("\n");
2078
+ return changed ? {
2079
+ imports,
2080
+ source: root.toString()
2081
+ } : void 0;
1699
2082
  } catch {
1700
- return false;
2083
+ return;
1701
2084
  }
1702
- return hasApplyRule && !hasNonApplyRule;
1703
2085
  }
1704
- function filterApplyOnlyGeneratedCss(css, source) {
1705
- const selectors = collectApplyOnlySourceSelectors(source);
1706
- if (selectors.size === 0) return css;
1707
- const selectorList = [...selectors];
2086
+ function restoreLocalCssImports(css, imports) {
2087
+ if (!imports?.trim()) return css;
2088
+ return createCssSourceOrderAppend(imports, css);
2089
+ }
2090
+ function splitRequestSuffix(request) {
2091
+ const suffixIndexCandidates = [request.indexOf("?"), request.indexOf("#")].filter((index) => index >= 0);
2092
+ const suffixIndex = suffixIndexCandidates.length > 0 ? Math.min(...suffixIndexCandidates) : -1;
2093
+ if (suffixIndex < 0) return {
2094
+ clean: request,
2095
+ suffix: ""
2096
+ };
2097
+ return {
2098
+ clean: request.slice(0, suffixIndex),
2099
+ suffix: request.slice(suffixIndex)
2100
+ };
2101
+ }
2102
+ function normalizeOutputImportRequest(request, styleOutputExtension) {
2103
+ const normalizedStyleOutputExtension = styleOutputExtension?.startsWith(".") ? styleOutputExtension : styleOutputExtension ? `.${styleOutputExtension}` : void 0;
2104
+ const { clean, suffix } = splitRequestSuffix(request.replace(/\\/g, "/"));
2105
+ return `${clean.replace(/^(?:\.\/)?src\//, "./").replace(SOURCE_STYLE_EXTENSION_RE, normalizedStyleOutputExtension ?? ".css")}${suffix}`;
2106
+ }
2107
+ function rewriteLocalCssImportRequestsForOutput(css, options = {}) {
2108
+ if (!css.includes("@import")) return css;
1708
2109
  try {
1709
2110
  const root = postcss.parse(css);
1710
- root.walkRules((rule) => {
1711
- const isApplySelector = (rule.selectors ?? [rule.selector]).some((selector) => {
1712
- const normalized = normalizeGeneratedSelector(selector);
1713
- return selectorList.some((sourceSelector) => {
1714
- if (normalized === sourceSelector) return true;
1715
- if (!normalized.startsWith(sourceSelector)) return false;
1716
- const next = normalized[sourceSelector.length];
1717
- return next === ":" || next === "[" || next === ".";
1718
- });
1719
- });
1720
- const isVariableRule = rule.nodes?.some((node) => node.type === "decl" && node.prop.startsWith("--"));
1721
- if (!isApplySelector && !isVariableRule) rule.remove();
1722
- });
1723
- root.walkAtRules((rule) => {
1724
- if (rule.nodes !== void 0 && rule.nodes.length === 0) rule.remove();
2111
+ let changed = false;
2112
+ root.walkAtRules("import", (atRule) => {
2113
+ const request = parseImportRequest(atRule.params);
2114
+ if (!request || !isLocalImportRequest(request) || !CSS_STYLE_EXTENSION_RE.test(request)) return;
2115
+ const rewritten = normalizeOutputImportRequest(request, options.styleOutputExtension);
2116
+ if (rewritten === request) return;
2117
+ atRule.params = atRule.params.replace(request, rewritten);
2118
+ changed = true;
1725
2119
  });
1726
- return root.toString();
2120
+ return changed ? root.toString() : css;
1727
2121
  } catch {
1728
2122
  return css;
1729
2123
  }
1730
2124
  }
1731
- function shouldFilterApplyOnlyGeneratedCss(majorVersion, target, source, options) {
1732
- return majorVersion === 4 && target === "weapp" && hasTailwindApplyDirective(source) && !hasTailwindRootDirectives(source) && !options.hasGeneratedCss && !options.hasGeneratedMarkers && collectApplyOnlySourceSelectors(source).size > 0 && hasOnlyApplyBackedSourceRules(source);
1733
- }
1734
- async function transformGeneratorUserCss(source, options) {
1735
- if (source.trim().length === 0) return "";
1736
- const cleanedSource = removeTailwindSourceDirectives(removeTailwindV4GeneratorAtRules(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(source))), { importFallback: options.importFallback });
1737
- if (cleanedSource.trim().length === 0) return "";
1738
- const userSource = stripUnmatchedTailwindSourceMediaCloseFragments(removeTailwindApplyAtRules(removeTailwindSourceDirectives(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(options.generatorTarget === "weapp" ? removeUnsupportedMiniProgramAtRules(unwrapMiniProgramCascadeLayers(cleanedSource)) : cleanedSource)), { importFallback: options.importFallback })));
1739
- if (userSource.trim().length === 0) return "";
1740
- if (isCommentOnlyCss(userSource)) return userSource;
1741
- if (options.generatorTarget !== "weapp") return userSource;
1742
- const { css } = await options.styleHandler(userSource, {
1743
- ...options.generatorStyleOptions,
1744
- ...options.cssUserHandlerOptions
1745
- });
1746
- return removeUnsupportedMiniProgramAtRules(css);
1747
- }
1748
2125
  //#endregion
1749
2126
  //#region src/bundlers/shared/generator-css/user-layer-order.ts
1750
2127
  const USER_LAYER_COMPONENTS_START = "/*! weapp-tailwindcss layer components start */";
@@ -1892,38 +2269,40 @@ async function runWithConcurrency(factories, limit = Math.min(4, Math.max(1, fac
1892
2269
  await Promise.all(executing);
1893
2270
  return results;
1894
2271
  }
2272
+ function resolveTaskConcurrency(defaultLimit = 1) {
2273
+ const configured = Number.parseInt(process.env["WEAPP_TW_TASK_CONCURRENCY"] ?? "", 10);
2274
+ if (Number.isFinite(configured) && configured > 0) return configured;
2275
+ return defaultLimit;
2276
+ }
1895
2277
  function pushConcurrentTaskFactories(queue, factories, limit) {
1896
2278
  if (factories.length === 0) return;
1897
2279
  queue.push(runWithConcurrency(factories, limit).then(() => void 0));
1898
2280
  }
1899
2281
  //#endregion
1900
2282
  //#region src/bundlers/shared/generator-css/validate.ts
1901
- const SUPPORTED_GENERATOR_MAJOR_VERSIONS = new Set([3, 4]);
1902
2283
  async function validateCandidatesByGenerator(options) {
1903
- const { candidates, cssHandlerOptions, debug, file, opts, rawSource, runtimeState, skipGenerateFallback } = options;
1904
- const majorVersion = runtimeState.twPatcher.majorVersion;
1905
- if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || candidates.size === 0) return /* @__PURE__ */ new Set();
1906
- const generatorOptions = {
1907
- ...normalizeWeappTailwindcssGeneratorOptions(opts.generator),
1908
- bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues
1909
- };
1910
- const sources = await resolveGeneratorSources(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, {
1911
- cssEntries: opts.cssEntries,
1912
- runtime: candidates
1913
- });
1914
- const classSets = await Promise.all(sources.map(async (source) => {
1915
- const generator = createWeappTailwindcssGenerator(source);
1916
- if (generatorOptions.bareArbitraryValues === void 0 || generatorOptions.bareArbitraryValues === false) {
1917
- if (typeof generator.validateCandidates === "function") return generator.validateCandidates(candidates);
1918
- }
1919
- if (skipGenerateFallback) return /* @__PURE__ */ new Set();
1920
- return (await generator.generate({
1921
- bareArbitraryValues: generatorOptions.bareArbitraryValues,
1922
- candidates,
1923
- target: "tailwind"
1924
- })).classSet;
1925
- }));
1926
- const classSet = new Set(classSets.flatMap((item) => [...item]));
2284
+ const { candidates, cssHandlerOptions, debug, file, opts, rawSource, runtimeState } = options;
2285
+ const majorVersion = runtimeState.tailwindRuntime.majorVersion;
2286
+ if (majorVersion !== 4 || candidates.size === 0) return /* @__PURE__ */ new Set();
2287
+ const classSet = /* @__PURE__ */ new Set();
2288
+ try {
2289
+ const sources = await resolveGeneratorSources(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, {
2290
+ ...normalizeWeappTailwindcssGeneratorOptions(opts.generator),
2291
+ bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues
2292
+ }, {
2293
+ cssEntries: opts.cssEntries,
2294
+ runtime: candidates
2295
+ });
2296
+ const classSets = await Promise.all(sources.map(async (source) => {
2297
+ const generator = createWeappTailwindcssGenerator(source);
2298
+ if (typeof generator.validateCandidates !== "function") return /* @__PURE__ */ new Set();
2299
+ return generator.validateCandidates(candidates);
2300
+ }));
2301
+ for (const candidate of classSets.flatMap((item) => [...item])) classSet.add(candidate);
2302
+ } catch {}
2303
+ const rawSourceCandidates = collectGeneratedRawSourceCandidates(candidates, rawSource, opts.escapeMap);
2304
+ for (const candidate of rawSourceCandidates) classSet.add(candidate);
2305
+ for (const generatedCss of options.generatedCssSources ?? []) for (const candidate of collectGeneratedRawSourceCandidates(candidates, generatedCss, opts.escapeMap)) classSet.add(candidate);
1927
2306
  debug("tailwind generator validated candidates: %s candidates=%d classSet=%d", file, candidates.size, classSet.size);
1928
2307
  return classSet;
1929
2308
  }
@@ -1934,38 +2313,97 @@ function resolveGeneratorSourceConcurrency() {
1934
2313
  if (Number.isFinite(configured) && configured > 0) return configured;
1935
2314
  return 1;
1936
2315
  }
2316
+ function intersectCandidateSets(left, right) {
2317
+ if (left.size === 0 || right.size === 0) return /* @__PURE__ */ new Set();
2318
+ const [small, large] = left.size <= right.size ? [left, right] : [right, left];
2319
+ const matched = /* @__PURE__ */ new Set();
2320
+ for (const candidate of small) if (large.has(candidate)) matched.add(candidate);
2321
+ return matched;
2322
+ }
2323
+ function collectCssRuleIdentityMarkers(source) {
2324
+ const markers = /* @__PURE__ */ new Set();
2325
+ try {
2326
+ const root = postcss.parse(source);
2327
+ root.walkRules((rule) => {
2328
+ for (const selector of rule.selectors ?? [rule.selector]) for (const match of selector.matchAll(/\.((?:\\.|[_a-z\u00A0-\uFFFF-])(?:\\.|[\w\u00A0-\uFFFF-])*)/gi)) markers.add(`class:${match[1]}`);
2329
+ });
2330
+ root.walkAtRules("keyframes", (rule) => {
2331
+ if (rule.params) markers.add(`keyframes:${rule.params}`);
2332
+ });
2333
+ } catch {}
2334
+ return markers;
2335
+ }
2336
+ function isCssAlreadyRepresentedByMarkers(css, source) {
2337
+ const sourceMarkers = collectCssRuleIdentityMarkers(source);
2338
+ if (sourceMarkers.size === 0) return false;
2339
+ const cssMarkers = collectCssRuleIdentityMarkers(css);
2340
+ for (const marker of sourceMarkers) if (!cssMarkers.has(marker)) return false;
2341
+ return true;
2342
+ }
2343
+ function mergeGeneratedCssClassSet(classSet, candidates, css, escapeMap) {
2344
+ const merged = new Set(classSet);
2345
+ for (const candidate of collectGeneratedRawSourceCandidates(candidates, css, escapeMap)) merged.add(candidate);
2346
+ return merged;
2347
+ }
1937
2348
  async function generateCssByGenerator(options) {
1938
- const { opts, runtimeState, runtime, rawSource, file, cssHandlerOptions, cssUserHandlerOptions, getSourceCandidatesForEntries, styleHandler, debug } = options;
2349
+ const { opts, runtimeState, runtime, rawSource, file, cssHandlerOptions, cssUserHandlerOptions, getSourceCandidatesForEntries, styleHandler, userRawSource, userRawSourceProcessed, debug } = options;
1939
2350
  const generatorOptions = {
1940
- ...normalizeWeappTailwindcssGeneratorOptions(opts.generator),
2351
+ ...normalizeWeappTailwindcssGeneratorOptions(opts.generator, {
2352
+ appType: opts.appType,
2353
+ platform: opts.cssOptions?.platform ?? opts.platform,
2354
+ tailwindcssMajorVersion: runtimeState.tailwindRuntime.majorVersion,
2355
+ uniAppX: opts.uniAppX
2356
+ }),
1941
2357
  bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues
1942
2358
  };
1943
- const majorVersion = runtimeState.twPatcher.majorVersion;
2359
+ const generatorBranch = resolveGeneratorRuntimeBranch(generatorOptions, {
2360
+ appType: opts.appType,
2361
+ platform: opts.cssOptions?.platform ?? opts.platform,
2362
+ tailwindcssMajorVersion: runtimeState.tailwindRuntime.majorVersion,
2363
+ uniAppX: opts.uniAppX
2364
+ });
2365
+ const majorVersion = runtimeState.tailwindRuntime.majorVersion;
2366
+ if (majorVersion !== 4) throw new Error("weapp-tailwindcss 生成管线仅支持 Tailwind CSS v4。");
1944
2367
  const effectiveRawSource = stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(normalizeTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })));
1945
2368
  const localImportParts = splitLocalCssImports(effectiveRawSource);
2369
+ const localImports = options.restoreLocalCssImports === false ? void 0 : localImportParts?.imports;
1946
2370
  const generatorRawSource = localImportParts?.source ?? effectiveRawSource;
1947
- const userCssRawSource = majorVersion === 4 ? removeTailwindV4GeneratorAtRules(generatorRawSource) : generatorRawSource;
2371
+ const rawUserSource = userRawSource === void 0 ? generatorRawSource : userRawSourceProcessed ? userRawSource : stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(normalizeTailwindSourceDirectives(userRawSource, { importFallback: generatorOptions.importFallback })));
2372
+ const userSource = splitLocalCssImports(rawUserSource)?.source ?? rawUserSource;
2373
+ const userCssRawSource = removeTailwindV4GeneratorAtRules(userSource);
2374
+ const generatedUserCssOrderSource = hasTailwindGeneratedCss(userSource) ? splitTailwindV4GeneratedCssBySourceOrder(userSource, generatorRawSource) : void 0;
2375
+ const generatedUserCssRawSource = generatedUserCssOrderSource ? createCssAppend(generatedUserCssOrderSource.before, generatedUserCssOrderSource.after) : hasTailwindGeneratedCss(userSource) ? "" : userCssRawSource;
2376
+ const userCssOrderSource = GENERATOR_PLACEHOLDER_MARKER_RE.test(userSource) ? userSource : hasTailwindGeneratedCss(userSource) ? userSource : generatedUserCssRawSource;
2377
+ const hasDistinctUserRawSource = typeof userRawSource === "string" && normalizeCssSourceForCompare(generatedUserCssRawSource) !== normalizeCssSourceForCompare(generatorRawSource);
1948
2378
  const cleanedLocalImportWrapper = cleanLocalCssImportWrapperTailwindDirectives(effectiveRawSource);
1949
2379
  if (cleanedLocalImportWrapper !== void 0) return {
1950
- css: generatorOptions.target === "weapp" ? removeUnsupportedMiniProgramAtRules(cleanedLocalImportWrapper) : cleanedLocalImportWrapper,
2380
+ css: shouldUseMiniProgramCssBranch(generatorBranch) ? removeUnsupportedMiniProgramAtRules(cleanedLocalImportWrapper) : cleanedLocalImportWrapper,
2381
+ classSet: /* @__PURE__ */ new Set(),
1951
2382
  target: generatorOptions.target,
1952
2383
  source: "generator",
1953
- dependencies: []
2384
+ dependencies: [],
2385
+ metadata: {
2386
+ file,
2387
+ majorVersion
2388
+ }
1954
2389
  };
1955
2390
  if (isPureLocalCssImportWrapper(effectiveRawSource)) return;
1956
2391
  const hasGeneratedCss = hasTailwindGeneratedCss(generatorRawSource);
1957
2392
  const hasSourceDirectives = hasTailwindSourceDirectives(generatorRawSource, { importFallback: generatorOptions.importFallback });
1958
2393
  const hasGeneratedMarkers = hasTailwindGeneratedCssMarkers(generatorRawSource);
1959
- const shouldGenerateCurrentCss = shouldUseGeneratorForCurrentCss(majorVersion, cssHandlerOptions, {
2394
+ if (!shouldUseGeneratorForCurrentCss(majorVersion, cssHandlerOptions, {
2395
+ forceGenerator: options.forceGenerator,
1960
2396
  hasGeneratedCss,
1961
2397
  hasGeneratedMarkers,
1962
2398
  hasSourceDirectives,
1963
- rawSource: generatorRawSource
1964
- });
1965
- if (!isSupportedGeneratorMajorVersion(majorVersion) || !shouldGenerateCurrentCss || majorVersion === 3 && !hasSourceDirectives && !hasGeneratedCss && !hasGeneratedMarkers) return;
2399
+ rawSource: generatorRawSource,
2400
+ runtimeCandidateCount: runtime.size,
2401
+ target: generatorOptions.target,
2402
+ configuredCssSourceCount: options.cssSources?.length
2403
+ })) return;
1966
2404
  try {
1967
2405
  await runtimeState.readyPromise;
1968
- const currentCssCandidates = majorVersion === 4 ? await extractSourceCandidates(generatorRawSource, "css", { ...generatorOptions.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: generatorOptions.bareArbitraryValues } }) : [];
2406
+ const currentCssCandidates = await extractSourceCandidates(generatorRawSource, "css", { ...generatorOptions.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: generatorOptions.bareArbitraryValues } });
1969
2407
  const isolateCurrentCssCandidates = shouldIsolateCurrentTailwindV4CssCandidates(majorVersion, cssHandlerOptions, {
1970
2408
  hasGeneratedCss,
1971
2409
  hasGeneratedMarkers,
@@ -1983,8 +2421,9 @@ async function generateCssByGenerator(options) {
1983
2421
  const sourceConcurrency = resolveGeneratorSourceConcurrency();
1984
2422
  const generated = mergeGeneratorResults((await runWithConcurrency(sources.map((source) => async () => {
1985
2423
  const generator = createWeappTailwindcssGenerator(source);
1986
- const sourceEntries = getSourceCandidatesForEntries && (majorVersion === 3 || majorVersion === 4) ? await resolveGeneratorSourceEntries(source, runtimeState) : void 0;
1987
- const scopedRuntime = sourceEntries && sourceEntries.length > 0 ? getSourceCandidatesForEntries?.(sourceEntries) : void 0;
2424
+ const sourceEntries = getSourceCandidatesForEntries ? await resolveGeneratorSourceEntries(source, runtimeState) : void 0;
2425
+ const sourceScopedRuntime = sourceEntries && sourceEntries.length > 0 ? getSourceCandidatesForEntries?.(sourceEntries) : void 0;
2426
+ const scopedRuntime = options.sourceCandidates && sourceScopedRuntime ? intersectCandidateSets(options.sourceCandidates, sourceScopedRuntime) : options.sourceCandidates ?? sourceScopedRuntime;
1988
2427
  const isolateCssSource = shouldIsolateScopedCssSource(majorVersion, source, sourceEntries, {
1989
2428
  cssHandlerOptions,
1990
2429
  target: generatorOptions.target
@@ -2002,15 +2441,13 @@ async function generateCssByGenerator(options) {
2002
2441
  majorVersion,
2003
2442
  matchedCssSourceFile
2004
2443
  }) : runtimeWithCurrentCss;
2005
- const generatorRuntime = majorVersion === 4 && generatorOptions.target === "weapp" ? filterUnsupportedMiniProgramTailwindV4Candidates(sourceRuntime) : sourceRuntime;
2006
- const useIncrementalCache = (majorVersion === 3 || majorVersion === 4) && !(majorVersion === 3 && isolateCssSource);
2444
+ const generatorRuntime = shouldUseMiniProgramCssBranch(generatorBranch) ? filterUnsupportedMiniProgramTailwindV4Candidates(sourceRuntime) : sourceRuntime;
2007
2445
  return generator.generate({
2008
2446
  bareArbitraryValues: generatorOptions.bareArbitraryValues,
2009
2447
  candidates: generatorRuntime,
2010
- incrementalCache: useIncrementalCache,
2448
+ incrementalCache: true,
2011
2449
  scanSources: shouldScanTailwindV4Sources(majorVersion, generatorOptions.target, generatorRuntime, isolateCssSource),
2012
2450
  styleOptions: generatorStyleOptions,
2013
- tailwindcssV3Compatibility: generatorOptions.tailwindcssV3Compatibility,
2014
2451
  target: generatorOptions.target
2015
2452
  });
2016
2453
  }), sourceConcurrency)).filter((item) => Boolean(item)));
@@ -2018,24 +2455,32 @@ async function generateCssByGenerator(options) {
2018
2455
  debug("tailwind generator result: %s rawBytes=%d cssBytes=%d candidates=%d", file, generated.rawCss.length, generated.css.length, generated.classSet.size);
2019
2456
  if ((generated.target !== "weapp" || !hasUserCssLayerBlocks(generatorRawSource)) && typeof options.previousCss === "string" && typeof generated.incrementalCss === "string") {
2020
2457
  const incrementalCss = stripTailwindBanner(generated.incrementalCss);
2458
+ const finalCss = restoreLocalCssImports(incrementalCss.trim().length > 0 ? createCssAppend(options.previousCss, finalizeMiniProgramGeneratorCss(incrementalCss, generated.target, majorVersion, opts.cssPreflight, {
2459
+ injectPreflight: false,
2460
+ styleOptions: generatorStyleOptions
2461
+ })) : options.previousCss, localImports);
2021
2462
  return {
2022
- css: restoreLocalCssImports(incrementalCss.trim().length > 0 ? createCssAppend(options.previousCss, finalizeMiniProgramGeneratorCss(incrementalCss, generated.target, majorVersion, opts.cssPreflight, {
2023
- injectPreflight: false,
2024
- styleOptions: generatorStyleOptions
2025
- })) : options.previousCss, localImportParts?.imports),
2463
+ css: finalCss,
2464
+ classSet: mergeGeneratedCssClassSet(generated.classSet, runtimeWithCurrentCss, finalCss, opts.escapeMap),
2026
2465
  target: generated.target,
2027
2466
  source: "generator",
2028
2467
  dependencies: generated.dependencies,
2029
- incremental: true
2468
+ incremental: true,
2469
+ metadata: {
2470
+ file,
2471
+ majorVersion,
2472
+ rawCss: generated.rawCss
2473
+ }
2030
2474
  };
2031
2475
  }
2032
2476
  const shouldFilterApplyOnlyCss = shouldFilterApplyOnlyGeneratedCss(majorVersion, generated.target, generatorRawSource, {
2033
2477
  hasGeneratedCss,
2034
2478
  hasGeneratedMarkers
2035
2479
  });
2036
- const generatedCss = shouldFilterApplyOnlyCss ? filterApplyOnlyGeneratedCss(stripTailwindBanner(generated.css), generatorRawSource) : stripTailwindBanner(generated.css);
2480
+ const generatedCssSource = generated.target === "web" ? generated.css : stripTailwindBanner(generated.css);
2481
+ const generatedCss = shouldFilterApplyOnlyCss ? filterApplyOnlyGeneratedCss(generatedCssSource, generatorRawSource) : generatedCssSource;
2037
2482
  const hasMatchedCssSourceFile = sources.some((source) => source.__weappTailwindcssMeta?.matchedCssSourceFile);
2038
- const orderedExtraCss = hasMatchedCssSourceFile ? splitTailwindV4GeneratedCssBySourceOrder(userCssRawSource, generated.rawCss) : splitRawSourceByGeneratedCssOrder(userCssRawSource, generated.rawCss);
2483
+ const orderedExtraCss = splitGeneratorPlaceholderCssBySourceOrder(userCssOrderSource, generated.rawCss) ?? (hasMatchedCssSourceFile ? splitTailwindV4GeneratedCssBySourceOrder(userCssOrderSource, generated.rawCss) : splitRawSourceByGeneratedCssOrder(userCssOrderSource, generated.rawCss));
2039
2484
  const shouldAppendMatchedCssSourceCompat = !hasMatchedCssSourceFile || orderedExtraCss !== void 0;
2040
2485
  if (orderedExtraCss) {
2041
2486
  let css = generatedCss;
@@ -2045,7 +2490,8 @@ async function generateCssByGenerator(options) {
2045
2490
  generatorStyleOptions,
2046
2491
  cssUserHandlerOptions,
2047
2492
  styleHandler,
2048
- importFallback: generatorOptions.importFallback
2493
+ importFallback: generatorOptions.importFallback,
2494
+ processed: userRawSourceProcessed
2049
2495
  };
2050
2496
  const afterLayerParts = generated.target === "weapp" ? splitUserCssLayerBlocks(orderedExtraCss.after) : {
2051
2497
  layer: "",
@@ -2063,29 +2509,54 @@ async function generateCssByGenerator(options) {
2063
2509
  const userCss = await transformGeneratorUserCss(userCssRawSource, userCssOptions);
2064
2510
  css = createCssSourceOrderAppend$1(css, userCss);
2065
2511
  }
2512
+ if (generated.target === "web") {
2513
+ const userCss = await transformGeneratorUserCss(userCssRawSource, userCssOptions);
2514
+ const missingUserCss = isCommentOnlyCss(userCss) ? "" : filterExistingCssRules(css, userCss);
2515
+ css = createCssSourceOrderAppend$1(css, missingUserCss);
2516
+ }
2517
+ if (generated.target === "weapp" && isEmptyCssSourceOrderParts(orderedExtraCss) && hasDistinctUserRawSource && !hasGeneratedCss && !hasGeneratedMarkers && !hasTailwindApplyDirective(generatedUserCssRawSource)) {
2518
+ const userCss = await transformGeneratorUserCss(generatedUserCssRawSource, userCssOptions);
2519
+ const missingUserCss = isCssAlreadyRepresentedByMarkers(css, generatedUserCssRawSource) ? filterExistingCssRules(css, userCss) : userCss;
2520
+ css = createCssSourceOrderAppend$1(css, missingUserCss);
2521
+ }
2066
2522
  if (generated.target === "weapp" && shouldAppendMatchedCssSourceCompat) {
2067
2523
  if (shouldFinalizeMarkedUserLayerComponentsCss(file)) css = reorderMarkedUserLayerComponentsCss(css);
2068
- if (!shouldFilterApplyOnlyCss) {
2069
- css = await appendLegacyCompatCss(css, userCssRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2070
- if (!isolateCurrentCssCandidates) css = await appendLegacyContainerCompatCss(css, userCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2524
+ if (!shouldFilterApplyOnlyCss && !userRawSourceProcessed && !hasGeneratedCss && !hasGeneratedMarkers) {
2525
+ css = await appendLegacyCompatCss(css, generatedUserCssRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2526
+ if (!isolateCurrentCssCandidates) css = await appendLegacyContainerCompatCss(css, generatedUserCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2071
2527
  }
2072
2528
  } else if (generated.target === "weapp" && shouldFinalizeMarkedUserLayerComponentsCss(file)) css = reorderMarkedUserLayerComponentsCss(css);
2529
+ const finalCss = restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, {
2530
+ injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
2531
+ cssHandlerOptions,
2532
+ isolateCurrentCssCandidates,
2533
+ localImports
2534
+ }),
2535
+ styleOptions: generatorStyleOptions
2536
+ }), localImports);
2073
2537
  return {
2074
- css: restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, {
2075
- injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
2076
- cssHandlerOptions,
2077
- isolateCurrentCssCandidates,
2078
- localImports: localImportParts?.imports
2079
- }),
2080
- styleOptions: generatorStyleOptions
2081
- }), localImportParts?.imports),
2538
+ css: finalCss,
2539
+ classSet: mergeGeneratedCssClassSet(generated.classSet, runtimeWithCurrentCss, finalCss, opts.escapeMap),
2082
2540
  target: generated.target,
2083
2541
  source: "generator",
2084
- dependencies: generated.dependencies
2542
+ dependencies: generated.dependencies,
2543
+ metadata: {
2544
+ file,
2545
+ majorVersion,
2546
+ rawCss: generated.rawCss
2547
+ }
2085
2548
  };
2086
2549
  }
2087
2550
  debug("tailwind direct css generation prefix mismatch, append transformed bundle css %s", file);
2088
2551
  let css = generatedCss;
2552
+ if (generated.target === "weapp" && generatorRawSource.includes("weapp-tailwindcss generator-placeholder") && !hasUserCssLayerBlocks(generatorRawSource)) css = createCssSourceOrderAppend$1(await transformGeneratorUserCss(generatedUserCssRawSource, {
2553
+ generatorTarget: generated.target,
2554
+ generatorStyleOptions,
2555
+ cssUserHandlerOptions,
2556
+ styleHandler,
2557
+ importFallback: generatorOptions.importFallback,
2558
+ processed: userRawSourceProcessed
2559
+ }), css);
2089
2560
  if (generated.target === "weapp") {
2090
2561
  css = inheritLegacyUnitConvertedDeclarations(css, generatorRawSource);
2091
2562
  if (hasUserCssLayerBlocks(generatorRawSource)) {
@@ -2095,7 +2566,8 @@ async function generateCssByGenerator(options) {
2095
2566
  generatorStyleOptions,
2096
2567
  cssUserHandlerOptions,
2097
2568
  styleHandler,
2098
- importFallback: generatorOptions.importFallback
2569
+ importFallback: generatorOptions.importFallback,
2570
+ processed: userRawSourceProcessed
2099
2571
  });
2100
2572
  const layerCss = layerUserCss.trim().length > 0 && !hasTailwindApplyDirective(layerUserCss) ? {
2101
2573
  layer: layerUserCss,
@@ -2108,22 +2580,36 @@ async function generateCssByGenerator(options) {
2108
2580
  }
2109
2581
  }
2110
2582
  if (hasMatchedCssSourceFile || generated.target === "web") {
2111
- if (hasMatchedCssSourceFile && generated.target === "weapp" && !hasGeneratedCss && !hasGeneratedMarkers) {
2112
- const userCss = await transformGeneratorUserCss(userCssRawSource, {
2583
+ if (generated.target === "weapp" && !hasGeneratedCss && !hasGeneratedMarkers) {
2584
+ const userCss = await transformGeneratorUserCss(generatedUserCssRawSource, {
2113
2585
  generatorTarget: generated.target,
2114
2586
  generatorStyleOptions,
2115
2587
  cssUserHandlerOptions,
2116
2588
  styleHandler,
2117
- importFallback: generatorOptions.importFallback
2589
+ importFallback: generatorOptions.importFallback,
2590
+ processed: userRawSourceProcessed
2118
2591
  });
2119
- css = createCssSourceOrderAppend$1(css, userCss);
2120
- } else if (hasMatchedCssSourceFile && generated.target === "weapp" && hasUserCssLayerBlocks(userCssRawSource)) {
2121
- const layerUserCss = await transformGeneratorUserCss(splitUserCssLayerBlocks(userCssRawSource).layer, {
2592
+ const missingUserCss = isCssAlreadyRepresentedByMarkers(css, generatedUserCssRawSource) ? filterExistingCssRules(css, userCss) : userCss;
2593
+ css = createCssSourceOrderAppend$1(css, missingUserCss);
2594
+ } else if (hasMatchedCssSourceFile && generated.target === "weapp" && hasGeneratedMarkers && !hasGeneratedCss) {
2595
+ const userCss = await transformGeneratorUserCss(removeTailwindV4GeneratedUserCssArtifacts(userCssRawSource), {
2596
+ generatorTarget: generated.target,
2597
+ generatorStyleOptions,
2598
+ cssUserHandlerOptions,
2599
+ styleHandler,
2600
+ importFallback: generatorOptions.importFallback,
2601
+ processed: userRawSourceProcessed
2602
+ });
2603
+ const missingUserCss = filterExistingCssRules(css, userCss);
2604
+ css = createCssSourceOrderAppend$1(css, missingUserCss);
2605
+ } else if (hasMatchedCssSourceFile && generated.target === "weapp" && hasUserCssLayerBlocks(generatedUserCssRawSource)) {
2606
+ const layerUserCss = await transformGeneratorUserCss(splitUserCssLayerBlocks(generatedUserCssRawSource).layer, {
2122
2607
  generatorTarget: generated.target,
2123
2608
  generatorStyleOptions,
2124
2609
  cssUserHandlerOptions,
2125
2610
  styleHandler,
2126
- importFallback: generatorOptions.importFallback
2611
+ importFallback: generatorOptions.importFallback,
2612
+ processed: userRawSourceProcessed
2127
2613
  });
2128
2614
  if (layerUserCss.trim().length > 0) {
2129
2615
  css = createCssSourceOrderAppend$1(css, wrapUserLayerComponentsCss(layerUserCss));
@@ -2131,51 +2617,79 @@ async function generateCssByGenerator(options) {
2131
2617
  }
2132
2618
  }
2133
2619
  if (hasMatchedCssSourceFile && generated.target === "weapp") {
2134
- if (!isolateCurrentCssCandidates && !shouldFilterApplyOnlyCss) css = await appendLegacyContainerCompatCss(css, userCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2620
+ if (!isolateCurrentCssCandidates && !shouldFilterApplyOnlyCss && !userRawSourceProcessed && !hasGeneratedCss && !hasGeneratedMarkers) css = await appendLegacyContainerCompatCss(css, generatedUserCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2135
2621
  }
2136
2622
  if (shouldAppendWebBundleCssFallback(generated.target, {
2137
2623
  hasSourceDirectives,
2138
2624
  hasMatchedCssSourceFile
2139
2625
  })) {
2140
- const userCss = await transformGeneratorUserCss(userCssRawSource, {
2626
+ const userCss = await transformGeneratorUserCss(generatedUserCssRawSource, {
2141
2627
  generatorTarget: generated.target,
2142
2628
  generatorStyleOptions,
2143
2629
  cssUserHandlerOptions,
2144
2630
  styleHandler,
2145
- importFallback: generatorOptions.importFallback
2631
+ importFallback: generatorOptions.importFallback,
2632
+ processed: userRawSourceProcessed
2146
2633
  });
2147
- css = createCssSourceOrderAppend$1(css, userCss);
2634
+ const missingUserCss = isCommentOnlyCss(userCss) ? "" : filterExistingCssRules(css, userCss);
2635
+ css = createCssSourceOrderAppend$1(css, missingUserCss);
2148
2636
  }
2637
+ const finalCss = restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, {
2638
+ injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
2639
+ cssHandlerOptions,
2640
+ isolateCurrentCssCandidates,
2641
+ localImports
2642
+ }),
2643
+ styleOptions: generatorStyleOptions
2644
+ }), localImports);
2149
2645
  return {
2150
- css: restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, {
2151
- injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
2152
- cssHandlerOptions,
2153
- isolateCurrentCssCandidates,
2154
- localImports: localImportParts?.imports
2155
- }),
2156
- styleOptions: generatorStyleOptions
2157
- }), localImportParts?.imports),
2646
+ css: finalCss,
2647
+ classSet: mergeGeneratedCssClassSet(generated.classSet, runtimeWithCurrentCss, finalCss, opts.escapeMap),
2158
2648
  target: generated.target,
2159
2649
  source: "generator",
2160
- dependencies: generated.dependencies
2650
+ dependencies: generated.dependencies,
2651
+ metadata: {
2652
+ file,
2653
+ majorVersion,
2654
+ rawCss: generated.rawCss
2655
+ }
2161
2656
  };
2162
2657
  }
2163
- if (!shouldFilterApplyOnlyCss) {
2164
- css = await appendLegacyCompatCss(css, userCssRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2165
- css = await appendLegacyContainerCompatCss(css, userCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2658
+ if (!shouldFilterApplyOnlyCss && !userRawSourceProcessed && !hasGeneratedCss && !hasGeneratedMarkers) {
2659
+ css = await appendLegacyCompatCss(css, generatedUserCssRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2660
+ css = await appendLegacyContainerCompatCss(css, generatedUserCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2661
+ }
2662
+ if (generated.target === "weapp" && hasDistinctUserRawSource && !hasGeneratedCss && !hasGeneratedMarkers && !hasTailwindApplyDirective(generatedUserCssRawSource)) {
2663
+ const userCss = await transformGeneratorUserCss(generatedUserCssRawSource, {
2664
+ generatorTarget: generated.target,
2665
+ generatorStyleOptions,
2666
+ cssUserHandlerOptions,
2667
+ styleHandler,
2668
+ importFallback: generatorOptions.importFallback,
2669
+ processed: userRawSourceProcessed
2670
+ });
2671
+ const missingUserCss = isCssAlreadyRepresentedByMarkers(css, generatedUserCssRawSource) ? filterExistingCssRules(css, userCss) : userCss;
2672
+ css = createCssSourceOrderAppend$1(css, missingUserCss);
2166
2673
  }
2674
+ const finalCss = restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, {
2675
+ injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
2676
+ cssHandlerOptions,
2677
+ isolateCurrentCssCandidates,
2678
+ localImports
2679
+ }),
2680
+ styleOptions: generatorStyleOptions
2681
+ }), localImports);
2167
2682
  return {
2168
- css: restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, {
2169
- injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
2170
- cssHandlerOptions,
2171
- isolateCurrentCssCandidates,
2172
- localImports: localImportParts?.imports
2173
- }),
2174
- styleOptions: generatorStyleOptions
2175
- }), localImportParts?.imports),
2683
+ css: finalCss,
2684
+ classSet: mergeGeneratedCssClassSet(generated.classSet, runtimeWithCurrentCss, finalCss, opts.escapeMap),
2176
2685
  target: generated.target,
2177
2686
  source: "generator",
2178
- dependencies: generated.dependencies
2687
+ dependencies: generated.dependencies,
2688
+ metadata: {
2689
+ file,
2690
+ majorVersion,
2691
+ rawCss: generated.rawCss
2692
+ }
2179
2693
  };
2180
2694
  } catch (error) {
2181
2695
  debug("tailwind direct css generation failed: %s %O", file, error);
@@ -2276,182 +2790,19 @@ function collectEscapedRuntimeCandidates(source, escapeMap, escapeFragments) {
2276
2790
  }
2277
2791
  return candidates;
2278
2792
  }
2279
- //#endregion
2280
- //#region src/bundlers/vite/incremental-runtime-class-set/v3-candidates.ts
2281
- const TAILWIND_V3_ARBITRARY_UTILITY_PREFIXES = new Set([
2282
- "accent",
2283
- "animate",
2284
- "basis",
2285
- "bg",
2286
- "blur",
2287
- "border",
2288
- "bottom",
2289
- "brightness",
2290
- "caret",
2291
- "col",
2292
- "columns",
2293
- "content",
2294
- "contrast",
2295
- "decoration",
2296
- "delay",
2297
- "divide",
2298
- "drop-shadow",
2299
- "duration",
2300
- "ease",
2301
- "fill",
2302
- "font",
2303
- "gap",
2304
- "gradient",
2305
- "grid",
2306
- "grayscale",
2307
- "grow",
2308
- "h",
2309
- "hue-rotate",
2310
- "indent",
2311
- "inset",
2312
- "invert",
2313
- "leading",
2314
- "left",
2315
- "list",
2316
- "m",
2317
- "max",
2318
- "mb",
2319
- "min",
2320
- "ml",
2321
- "mr",
2322
- "mt",
2323
- "mx",
2324
- "my",
2325
- "object",
2326
- "opacity",
2327
- "order",
2328
- "outline",
2329
- "overflow",
2330
- "p",
2331
- "pb",
2332
- "pl",
2333
- "pr",
2334
- "pt",
2335
- "px",
2336
- "py",
2337
- "right",
2338
- "ring",
2339
- "rotate",
2340
- "rounded",
2341
- "row",
2342
- "saturate",
2343
- "scale",
2344
- "scroll",
2345
- "sepia",
2346
- "shadow",
2347
- "shrink",
2348
- "skew",
2349
- "space",
2350
- "stroke",
2351
- "text",
2352
- "top",
2353
- "tracking",
2354
- "translate",
2355
- "underline",
2356
- "w",
2357
- "z"
2358
- ]);
2359
- function isUrlLikeCandidate(candidate) {
2360
- return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
2361
- }
2362
- function getBaseUtilityCandidate(candidate) {
2363
- let bracketDepth = 0;
2364
- let lastVariantSeparator = -1;
2365
- for (let index = 0; index < candidate.length; index++) {
2366
- const char = candidate[index];
2367
- if (char === "[") bracketDepth += 1;
2368
- else if (char === "]") bracketDepth = Math.max(0, bracketDepth - 1);
2369
- else if (char === ":" && bracketDepth === 0) lastVariantSeparator = index;
2370
- }
2371
- let utility = lastVariantSeparator >= 0 ? candidate.slice(lastVariantSeparator + 1) : candidate;
2372
- if (utility.startsWith("!")) utility = utility.slice(1);
2373
- if (utility.startsWith("-")) utility = utility.slice(1);
2374
- return utility;
2375
- }
2376
- function getArbitraryUtilityPrefix(utility) {
2377
- const bracketIndex = utility.indexOf("[");
2378
- if (bracketIndex <= 0 || !utility.endsWith("]")) return;
2379
- const prefix = utility.slice(0, bracketIndex).replace(/-$/, "");
2380
- const firstDash = prefix.indexOf("-");
2381
- return firstDash >= 0 ? prefix.slice(0, firstDash) : prefix;
2382
- }
2383
- function isLikelyTailwindV3ArbitraryUtility(candidate) {
2384
- const utility = getBaseUtilityCandidate(candidate);
2385
- if (utility.startsWith("[") && utility.endsWith("]") && utility.includes(":")) return true;
2386
- const prefix = getArbitraryUtilityPrefix(utility);
2387
- return Boolean(prefix && TAILWIND_V3_ARBITRARY_UTILITY_PREFIXES.has(prefix));
2388
- }
2389
- function isLikelyTailwindV3VariantUtility(candidate) {
2390
- if (!candidate.includes(":") || isUrlLikeCandidate(candidate)) return false;
2391
- const utility = getBaseUtilityCandidate(candidate);
2392
- return /^[!-]?[a-z@[]/.test(utility);
2393
- }
2394
- function isLikelyTailwindV3OpacityModifier(candidate) {
2395
- if (!candidate.includes("/") || isUrlLikeCandidate(candidate)) return false;
2396
- const utility = getBaseUtilityCandidate(candidate);
2397
- return /^[!-]?[a-z][\w-]*-\w[\w-]*\/(?:\d+|\[[^\]]+\])$/.test(utility);
2398
- }
2399
- function isHighConfidenceV3Candidate(candidate) {
2400
- return isLikelyTailwindV3ArbitraryUtility(candidate) || isLikelyTailwindV3VariantUtility(candidate) || isLikelyTailwindV3OpacityModifier(candidate);
2401
- }
2402
- function isRawCandidateInClassContext(source, start, extension) {
2403
- if (typeof start !== "number" || start <= 0) return false;
2404
- const before = source.slice(Math.max(0, start - 200), start);
2405
- if (extension === "html") return /\bclass\s*=\s*["'][^"']*$/i.test(before);
2406
- return /\bclass(?:Name)?\s*[:=]\s*["'][^"']*$/i.test(before) || /\.classList\.(?:add|remove|toggle|contains)\([^)]*$/i.test(before);
2407
- }
2408
- function resolveQuotedLiteralRange(source, start) {
2409
- if (typeof start !== "number" || start <= 0) return;
2410
- let quote;
2411
- let literalStart = -1;
2412
- for (let index = start - 1; index >= 0; index--) {
2413
- const char = source[index];
2414
- if (char !== "\"" && char !== "'" && char !== "`") continue;
2415
- quote = char;
2416
- literalStart = index;
2417
- break;
2418
- }
2419
- if (!quote) return;
2420
- let escaped = false;
2421
- for (let index = literalStart + 1; index < source.length; index++) {
2422
- const char = source[index];
2423
- if (escaped) {
2424
- escaped = false;
2425
- continue;
2426
- }
2427
- if (char === "\\") {
2428
- escaped = true;
2429
- continue;
2430
- }
2431
- if (char === quote) {
2432
- if (start < index) return {
2433
- start: literalStart,
2434
- end: index
2435
- };
2436
- return;
2793
+ function collectStrictEscapedRuntimeCandidates(source, escapeMap, escapeFragments) {
2794
+ const candidates = /* @__PURE__ */ new Set();
2795
+ ESCAPED_CLASS_TOKEN_RE.lastIndex = 0;
2796
+ let match = ESCAPED_CLASS_TOKEN_RE.exec(source);
2797
+ while (match) {
2798
+ const token = match[0];
2799
+ if (hasEscapeFragment(token, escapeFragments)) {
2800
+ const restored = unescape(token, { map: escapeMap });
2801
+ if (restored !== token && TAILWIND_RESTORED_CANDIDATE_SIGNAL_RE.test(restored) && !/\s/.test(restored)) candidates.add(restored);
2437
2802
  }
2803
+ match = ESCAPED_CLASS_TOKEN_RE.exec(source);
2438
2804
  }
2439
- }
2440
- function createHighConfidenceLiteralRanges(source, matches) {
2441
- const ranges = [];
2442
- for (const match of matches) {
2443
- const candidate = match?.rawCandidate;
2444
- if (typeof candidate !== "string" || !isHighConfidenceV3Candidate(candidate)) continue;
2445
- const range = resolveQuotedLiteralRange(source, match?.start ?? source.indexOf(candidate));
2446
- if (range) ranges.push(range);
2447
- }
2448
- return ranges;
2449
- }
2450
- function isRawCandidateInRanges(start, ranges) {
2451
- return typeof start === "number" && ranges.some((range) => start > range.start && start < range.end);
2452
- }
2453
- function isRawCandidateAllowedForV3(source, candidate, start, extension, knownSourceCandidates, highConfidenceLiteralRanges = []) {
2454
- return isHighConfidenceV3Candidate(candidate) || knownSourceCandidates?.has(candidate) === true || isRawCandidateInClassContext(source, start, extension) || isRawCandidateInRanges(start, highConfidenceLiteralRanges);
2805
+ return candidates;
2455
2806
  }
2456
2807
  //#endregion
2457
2808
  //#region src/bundlers/vite/incremental-runtime-class-set.ts
@@ -2517,8 +2868,8 @@ function createBundleRuntimeClassSetManager(options = {}) {
2517
2868
  validationContext = void 0;
2518
2869
  designSystemPromise = void 0;
2519
2870
  }
2520
- async function resolveValidationContextCached(patcher) {
2521
- if (!validationContext) validationContext = await resolveTailwindV4SourceFromPatcher(patcher);
2871
+ async function resolveValidationContextCached(runtime) {
2872
+ if (!validationContext) validationContext = await resolveTailwindV4SourceFromRuntime(runtime);
2522
2873
  return validationContext;
2523
2874
  }
2524
2875
  async function loadDesignSystem(context) {
@@ -2529,13 +2880,9 @@ function createBundleRuntimeClassSetManager(options = {}) {
2529
2880
  const validCandidates = resolveValidTailwindV4Candidates(designSystem, unknownCandidates, { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } });
2530
2881
  for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
2531
2882
  }
2532
- async function validateUnknownCandidates(patcher, unknownCandidates) {
2883
+ async function validateUnknownCandidates(runtime, unknownCandidates) {
2533
2884
  if (unknownCandidates.size === 0) return;
2534
- if (patcher.majorVersion === 3 && !customExtractCandidates) {
2535
- for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, true);
2536
- return;
2537
- }
2538
- const context = await resolveValidationContextCached(patcher);
2885
+ const context = await resolveValidationContextCached(runtime);
2539
2886
  if (!customExtractCandidates) try {
2540
2887
  populateCandidateValidityCacheFromDesignSystem(await loadDesignSystem(context), unknownCandidates);
2541
2888
  return;
@@ -2548,23 +2895,19 @@ function createBundleRuntimeClassSetManager(options = {}) {
2548
2895
  const validCandidates = new Set(await extractCandidates(createExtractOptions(context, source, options.bareArbitraryValues)));
2549
2896
  for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
2550
2897
  }
2551
- async function extractEntryRawCandidates(entry, patcher, knownSourceCandidates) {
2898
+ async function extractEntryRawCandidates(entry, _runtime, _knownSourceCandidates) {
2552
2899
  const extension = resolveEntryExtension(entry);
2553
2900
  const matches = options.bareArbitraryValues === void 0 || options.bareArbitraryValues === false ? await extractRawCandidates(entry.source, extension) : await extractRawCandidates(entry.source, extension, { bareArbitraryValues: options.bareArbitraryValues });
2554
- const highConfidenceLiteralRanges = patcher.majorVersion === 3 && !customExtractCandidates ? createHighConfidenceLiteralRanges(entry.source, matches) : [];
2555
2901
  const candidates = /* @__PURE__ */ new Set();
2556
2902
  for (const match of matches) {
2557
2903
  const candidate = match?.rawCandidate;
2558
- if (typeof candidate === "string" && candidate.length > 0) {
2559
- if (patcher.majorVersion === 3 && !customExtractCandidates && !isRawCandidateAllowedForV3(entry.source, candidate, match.start, extension, knownSourceCandidates, highConfidenceLiteralRanges)) continue;
2560
- candidates.add(candidate);
2561
- }
2904
+ if (typeof candidate === "string" && candidate.length > 0) candidates.add(candidate);
2562
2905
  }
2563
- if (patcher.majorVersion === 4) for (const candidate of collectEscapedRuntimeCandidates(entry.source, escapeMap, escapeFragments)) candidates.add(candidate);
2906
+ for (const candidate of collectEscapedRuntimeCandidates(entry.source, escapeMap, escapeFragments)) candidates.add(candidate);
2564
2907
  return candidates;
2565
2908
  }
2566
- async function sync(patcher, snapshot, options = {}) {
2567
- const nextSignature = getRuntimeClassSetSignature(patcher) ?? "runtime:missing";
2909
+ async function sync(runtime, snapshot, options = {}) {
2910
+ const nextSignature = getRuntimeClassSetSignature(runtime) ?? "runtime:missing";
2568
2911
  const runtimeEntries = createRuntimeEntries(snapshot);
2569
2912
  const runtimeEntriesByFile = new Map(runtimeEntries.map((entry) => [entry.file, entry]));
2570
2913
  const currentRuntimeFiles = new Set(runtimeEntriesByFile.keys());
@@ -2589,14 +2932,14 @@ function createBundleRuntimeClassSetManager(options = {}) {
2589
2932
  }
2590
2933
  const rawCandidatesByFile = /* @__PURE__ */ new Map();
2591
2934
  const unknownCandidates = /* @__PURE__ */ new Set();
2592
- await Promise.all(changedRuntimeFiles.map(async (file) => {
2935
+ for (const file of changedRuntimeFiles) {
2593
2936
  const entry = runtimeEntriesByFile.get(file);
2594
- if (!entry) return;
2595
- const candidates = await extractEntryRawCandidates(entry, patcher, nextBaseClassSet);
2937
+ if (!entry) continue;
2938
+ const candidates = await extractEntryRawCandidates(entry, runtime, nextBaseClassSet);
2596
2939
  rawCandidatesByFile.set(file, candidates);
2597
2940
  for (const candidate of candidates) if (!candidateValidityCache.has(candidate)) unknownCandidates.add(candidate);
2598
- }));
2599
- await validateUnknownCandidates(patcher, unknownCandidates);
2941
+ }
2942
+ await validateUnknownCandidates(runtime, unknownCandidates);
2600
2943
  let rawCandidateCount = 0;
2601
2944
  for (const file of changedRuntimeFiles) {
2602
2945
  const nextRawCandidates = rawCandidatesByFile.get(file);
@@ -2626,6 +2969,52 @@ function createBundleRuntimeClassSetManager(options = {}) {
2626
2969
  };
2627
2970
  }
2628
2971
  //#endregion
2972
+ //#region src/tailwindcss/candidates.ts
2973
+ const SCRIPT_SOURCE_CANDIDATE_EXTENSIONS = new Set([
2974
+ "js",
2975
+ "jsx",
2976
+ "mjs",
2977
+ "cjs",
2978
+ "ts",
2979
+ "tsx",
2980
+ "mts",
2981
+ "cts"
2982
+ ]);
2983
+ async function extractCandidatesFromSource(source, extension, options = {}) {
2984
+ const candidates = options.extractor ? new Set(await options.extractor(source, extension)) : new Set(await extractSourceCandidates(source, extension, { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } }));
2985
+ const scriptCandidates = await extractScriptStringCandidates(source, extension, options);
2986
+ for (const candidate of scriptCandidates) candidates.add(candidate);
2987
+ return candidates;
2988
+ }
2989
+ async function extractScriptStringCandidates(source, extension, options) {
2990
+ if (!SCRIPT_SOURCE_CANDIDATE_EXTENSIONS.has(extension)) return [];
2991
+ const values = /* @__PURE__ */ new Set();
2992
+ try {
2993
+ traverse(babelParse(source, {
2994
+ cache: true,
2995
+ cacheKey: `source-candidates:${extension}`,
2996
+ plugins: ["jsx", "typescript"],
2997
+ sourceType: "unambiguous"
2998
+ }), {
2999
+ noScope: true,
3000
+ StringLiteral(path) {
3001
+ values.add(path.node.value);
3002
+ },
3003
+ TemplateElement(path) {
3004
+ values.add(path.node.value.raw);
3005
+ }
3006
+ });
3007
+ } catch {
3008
+ return [];
3009
+ }
3010
+ const candidates = /* @__PURE__ */ new Set();
3011
+ for (const value of values) {
3012
+ const extractedCandidates = options.extractor ? await options.extractor(value, "html") : await extractSourceCandidates(value, "html", { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } });
3013
+ for (const candidate of extractedCandidates) candidates.add(candidate);
3014
+ }
3015
+ return candidates;
3016
+ }
3017
+ //#endregion
2629
3018
  //#region src/bundlers/vite/source-candidates/scan-root.ts
2630
3019
  const TAILWIND_V4_IGNORED_CONTENT_DIRS = [
2631
3020
  ".git",
@@ -2733,76 +3122,6 @@ function resolveSourceCandidateScanFiles(options) {
2733
3122
  });
2734
3123
  }
2735
3124
  //#endregion
2736
- //#region src/bundlers/vite/source-candidates/script.ts
2737
- const SCRIPT_SOURCE_CANDIDATE_EXTENSIONS = new Set([
2738
- "js",
2739
- "jsx",
2740
- "mjs",
2741
- "cjs",
2742
- "ts",
2743
- "tsx",
2744
- "mts",
2745
- "cts"
2746
- ]);
2747
- async function extractScriptStringCandidates(source, extension, options) {
2748
- if (!SCRIPT_SOURCE_CANDIDATE_EXTENSIONS.has(extension)) return [];
2749
- const values = /* @__PURE__ */ new Set();
2750
- try {
2751
- traverse(babelParse(source, {
2752
- cache: true,
2753
- cacheKey: `vite-source-candidates:${extension}`,
2754
- plugins: ["jsx", "typescript"],
2755
- sourceType: "unambiguous"
2756
- }), {
2757
- noScope: true,
2758
- StringLiteral(path) {
2759
- values.add(path.node.value);
2760
- },
2761
- TemplateElement(path) {
2762
- values.add(path.node.value.raw);
2763
- }
2764
- });
2765
- } catch {
2766
- return [];
2767
- }
2768
- const candidates = /* @__PURE__ */ new Set();
2769
- for (const value of values) {
2770
- const extractedCandidates = options.extractor ? await options.extractor(value, "html") : await extractSourceCandidates(value, "html", { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } });
2771
- for (const candidate of extractedCandidates) candidates.add(candidate);
2772
- }
2773
- return candidates;
2774
- }
2775
- //#endregion
2776
- //#region src/bundlers/vite/source-candidates/tailwind-v3-default-extractor.ts
2777
- const require = createRequire(import.meta.url);
2778
- const TAILWIND_V3_HTML_TOKEN_CANDIDATES = new Set([
2779
- "/block",
2780
- "/div",
2781
- "/span",
2782
- "/template",
2783
- "/text",
2784
- "/view",
2785
- "class",
2786
- "className",
2787
- "div",
2788
- "hover-class",
2789
- "span",
2790
- "template",
2791
- "text",
2792
- "view"
2793
- ]);
2794
- function createTailwindV3DefaultExtractor() {
2795
- try {
2796
- const defaultExtractorModule = require("tailwindcss/lib/lib/defaultExtractor");
2797
- const resolveConfigModule = require("tailwindcss/resolveConfig");
2798
- const resolveConfig = resolveConfigModule.default ?? resolveConfigModule;
2799
- const extractor = (defaultExtractorModule.defaultExtractor ?? defaultExtractorModule.default ?? defaultExtractorModule)({ tailwindConfig: resolveConfig({ content: [] }) });
2800
- return (source) => new Set(extractor(source).filter((candidate) => !TAILWIND_V3_HTML_TOKEN_CANDIDATES.has(candidate)));
2801
- } catch {
2802
- return;
2803
- }
2804
- }
2805
- //#endregion
2806
3125
  //#region src/bundlers/vite/source-candidates.ts
2807
3126
  const CLEAN_URL_RE = /[?#].*$/;
2808
3127
  const sourceCandidateContentCache = new LRUCache({ max: 128 });
@@ -2817,10 +3136,7 @@ function createSourceCandidateContentCacheKey(extension, source, bareArbitraryVa
2817
3136
  return `${extension}\0${JSON.stringify(bareArbitraryValues ?? false)}\0${extractor ? "custom" : "default"}\0${md5Hash(source)}`;
2818
3137
  }
2819
3138
  async function extractCandidates(source, extension, options) {
2820
- const candidates = options.extractor ? new Set(await options.extractor(source, extension)) : new Set(await extractSourceCandidates(source, extension, { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } }));
2821
- const scriptCandidates = await extractScriptStringCandidates(source, extension, options);
2822
- for (const candidate of scriptCandidates) candidates.add(candidate);
2823
- return candidates;
3139
+ return extractCandidatesFromSource(source, extension, options);
2824
3140
  }
2825
3141
  function isSourceCandidateRequest(id) {
2826
3142
  return FULL_SOURCE_SCAN_EXTENSION_RE.test(cleanUrl(id));
@@ -2839,18 +3155,20 @@ function removeCandidateSet(candidateCount, candidates) {
2839
3155
  function addCandidateSet(candidateCount, candidates) {
2840
3156
  for (const candidate of candidates) candidateCount.set(candidate, (candidateCount.get(candidate) ?? 0) + 1);
2841
3157
  }
2842
- function createSourceCandidateCollector(options = {}) {
3158
+ function createSourceCandidateStore(options = {}) {
2843
3159
  const candidatesById = /* @__PURE__ */ new Map();
2844
3160
  const scanCandidatesById = /* @__PURE__ */ new Map();
2845
3161
  const transformCandidatesById = /* @__PURE__ */ new Map();
2846
3162
  const cssCandidatesById = /* @__PURE__ */ new Map();
2847
- const sourceById = /* @__PURE__ */ new Map();
3163
+ const scanSourceById = /* @__PURE__ */ new Map();
3164
+ const transformSourceById = /* @__PURE__ */ new Map();
3165
+ const cssSourceById = /* @__PURE__ */ new Map();
2848
3166
  const candidateCount = /* @__PURE__ */ new Map();
2849
3167
  let inlineIncludedCandidates = /* @__PURE__ */ new Set();
2850
3168
  let inlineExcludedCandidates = /* @__PURE__ */ new Set();
2851
3169
  async function sync(id, source) {
2852
3170
  const normalizedId = cleanUrl(id);
2853
- sourceById.set(normalizedId, source);
3171
+ scanSourceById.set(normalizedId, source);
2854
3172
  const extension = resolveSourceCandidateExtension(normalizedId);
2855
3173
  const contentCacheKey = createSourceCandidateContentCacheKey(extension, source, options.bareArbitraryValues, options.extractor);
2856
3174
  const cachedCandidates = sourceCandidateContentCache.get(contentCacheKey);
@@ -2864,7 +3182,7 @@ function createSourceCandidateCollector(options = {}) {
2864
3182
  }
2865
3183
  async function syncCss(id, source) {
2866
3184
  const normalizedId = cleanUrl(id);
2867
- sourceById.set(normalizedId, source);
3185
+ cssSourceById.set(normalizedId, source);
2868
3186
  const contentCacheKey = createSourceCandidateContentCacheKey("css", source, options.bareArbitraryValues, options.extractor);
2869
3187
  const cachedCandidates = sourceCandidateContentCache.get(contentCacheKey);
2870
3188
  if (cachedCandidates) {
@@ -2877,7 +3195,7 @@ function createSourceCandidateCollector(options = {}) {
2877
3195
  }
2878
3196
  async function merge(id, source) {
2879
3197
  const normalizedId = cleanUrl(id);
2880
- sourceById.set(normalizedId, source);
3198
+ transformSourceById.set(normalizedId, source);
2881
3199
  const extension = resolveSourceCandidateExtension(normalizedId);
2882
3200
  const contentCacheKey = createSourceCandidateContentCacheKey(extension, source, options.bareArbitraryValues, options.extractor);
2883
3201
  const cachedCandidates = sourceCandidateContentCache.get(contentCacheKey);
@@ -2959,17 +3277,20 @@ function createSourceCandidateCollector(options = {}) {
2959
3277
  scanCandidatesById.delete(normalizedId);
2960
3278
  transformCandidatesById.delete(normalizedId);
2961
3279
  cssCandidatesById.delete(normalizedId);
2962
- sourceById.delete(normalizedId);
3280
+ scanSourceById.delete(normalizedId);
3281
+ transformSourceById.delete(normalizedId);
3282
+ cssSourceById.delete(normalizedId);
2963
3283
  const previousCandidates = candidatesById.get(normalizedId);
2964
3284
  if (!previousCandidates) return;
2965
3285
  removeCandidateSet(candidateCount, previousCandidates);
2966
3286
  candidatesById.delete(normalizedId);
2967
3287
  }
2968
3288
  function source(id) {
2969
- return sourceById.get(cleanUrl(id));
3289
+ const normalizedId = cleanUrl(id);
3290
+ return scanSourceById.get(normalizedId) ?? cssSourceById.get(normalizedId) ?? transformSourceById.get(normalizedId);
2970
3291
  }
2971
3292
  function sources() {
2972
- return sourceById.entries();
3293
+ return mergeSourcesByPriority().entries();
2973
3294
  }
2974
3295
  function values() {
2975
3296
  const values = new Set([...candidateCount.keys(), ...inlineIncludedCandidates]);
@@ -3020,7 +3341,9 @@ function createSourceCandidateCollector(options = {}) {
3020
3341
  scanCandidatesById.clear();
3021
3342
  transformCandidatesById.clear();
3022
3343
  cssCandidatesById.clear();
3023
- sourceById.clear();
3344
+ scanSourceById.clear();
3345
+ transformSourceById.clear();
3346
+ cssSourceById.clear();
3024
3347
  candidateCount.clear();
3025
3348
  inlineIncludedCandidates.clear();
3026
3349
  inlineExcludedCandidates.clear();
@@ -3041,9 +3364,12 @@ function createSourceCandidateCollector(options = {}) {
3041
3364
  return {
3042
3365
  candidatesById: [...candidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
3043
3366
  cssCandidatesById: [...cssCandidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
3367
+ cssSourceById: [...cssSourceById.entries()],
3044
3368
  scanCandidatesById: [...scanCandidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
3045
- sourceById: [...sourceById.entries()],
3369
+ scanSourceById: [...scanSourceById.entries()],
3370
+ sourceById: [...mergeSourcesByPriority().entries()],
3046
3371
  transformCandidatesById: [...transformCandidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
3372
+ transformSourceById: [...transformSourceById.entries()],
3047
3373
  inlineExcludedCandidates: [...inlineExcludedCandidates],
3048
3374
  inlineIncludedCandidates: [...inlineIncludedCandidates]
3049
3375
  };
@@ -3068,7 +3394,9 @@ function createSourceCandidateCollector(options = {}) {
3068
3394
  if (candidateSet.size === 0) continue;
3069
3395
  cssCandidatesById.set(id, candidateSet);
3070
3396
  }
3071
- for (const [id, source] of snapshot.sourceById ?? []) sourceById.set(id, source);
3397
+ for (const [id, source] of snapshot.scanSourceById ?? snapshot.sourceById ?? []) scanSourceById.set(id, source);
3398
+ for (const [id, source] of snapshot.transformSourceById ?? []) transformSourceById.set(id, source);
3399
+ for (const [id, source] of snapshot.cssSourceById ?? []) cssSourceById.set(id, source);
3072
3400
  const ids = new Set([
3073
3401
  ...scanCandidatesById.keys(),
3074
3402
  ...transformCandidatesById.keys(),
@@ -3077,6 +3405,7 @@ function createSourceCandidateCollector(options = {}) {
3077
3405
  for (const id of ids) recompute(id);
3078
3406
  }
3079
3407
  return {
3408
+ syncSource: sync,
3080
3409
  sync,
3081
3410
  syncCss,
3082
3411
  merge,
@@ -3096,6 +3425,16 @@ function createSourceCandidateCollector(options = {}) {
3096
3425
  resetScan,
3097
3426
  clear
3098
3427
  };
3428
+ function mergeSourcesByPriority() {
3429
+ const sources = /* @__PURE__ */ new Map();
3430
+ for (const [id, source] of transformSourceById) sources.set(id, source);
3431
+ for (const [id, source] of cssSourceById) sources.set(id, source);
3432
+ for (const [id, source] of scanSourceById) sources.set(id, source);
3433
+ return sources;
3434
+ }
3435
+ }
3436
+ function createSourceCandidateCollector(options = {}) {
3437
+ return createSourceCandidateStore(options);
3099
3438
  }
3100
3439
  //#endregion
3101
3440
  //#region src/bundlers/shared/hmr-timing.ts
@@ -3176,4 +3515,4 @@ function createHmrTimingRecorder(bundler) {
3176
3515
  };
3177
3516
  }
3178
3517
  //#endregion
3179
- export { createCssSourceTraceCacheSignature as _, createTailwindV3DefaultExtractor as a, processCachedTask as b, validateCandidatesByGenerator as c, extractMarkedUserLayerComponentsCss as d, mergeMarkedUserLayerComponentsCss as f, annotateCssSourceTrace as g, pruneMiniProgramGeneratedCss as h, isSourceCandidateRequest as i, pushConcurrentTaskFactories as l, finalizeMiniProgramCss as m, emitHmrTiming as n, createBundleRuntimeClassSetManager as o, isPureLocalCssImportWrapper as p, createSourceCandidateCollector as r, generateCssByGenerator as s, createHmrTimingRecorder as t, runWithConcurrency as u, createCssTokenSourceMap as v, isCssSourceTraceEnabled as y };
3518
+ export { hasMiniProgramCssSpecificityPlaceholders as A, stripTailwindSourceMediaFragments as C, createCssSourceOrderAppend$1 as D, removeGeneratedSelectorCompatCss as E, createCssTokenSourceMap as F, isCssSourceTraceEnabled as I, processCachedTask as L, stripMiniProgramCssSpecificityPlaceholders as M, annotateCssSourceTrace as N, hasMiniProgramTailwindV4PreflightReset as O, createCssSourceTraceCacheSignature as P, removeTailwindV4GeneratorAtRules as S, scoreTailwindV4CssSourceFileMatch as T, isPureLocalCssImportWrapper as _, isSourceCandidateRequest as a, removeMiniProgramHoverSelectors as b, collectStrictEscapedRuntimeCandidates as c, validateCandidatesByGenerator as d, pushConcurrentTaskFactories as f, mergeMarkedUserLayerComponentsCss as g, extractMarkedUserLayerComponentsCss as h, createSourceCandidateStore as i, pruneMiniProgramGeneratedCss as j, finalizeMiniProgramCss as k, createEscapeFragments as l, runWithConcurrency as m, emitHmrTiming as n, resolveSourceCandidateScanFiles as o, resolveTaskConcurrency as p, createSourceCandidateCollector as r, createBundleRuntimeClassSetManager as s, createHmrTimingRecorder as t, generateCssByGenerator as u, rewriteLocalCssImportRequestsForOutput as v, stripUnmatchedTailwindSourceMediaCloseFragments as w, removeTailwindV4GeneratedUserCssArtifacts as x, splitLocalCssImports as y };