weapp-tailwindcss 4.12.0 → 5.0.0-next.10

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 (324) hide show
  1. package/README.md +4 -5
  2. package/bin/weapp-tailwindcss.js +1 -21
  3. package/dist/babel/index.d.ts +3 -0
  4. package/dist/bundle-state-BWqi5ZyX.mjs +343 -0
  5. package/dist/bundle-state-EUbcdKqo.js +410 -0
  6. package/dist/bundlers/gulp/index.d.ts +7 -0
  7. package/dist/bundlers/shared/cache.d.ts +16 -0
  8. package/dist/bundlers/shared/css-cleanup/at-rules.d.ts +2 -0
  9. package/dist/bundlers/shared/css-cleanup/color-gamut.d.ts +3 -0
  10. package/dist/bundlers/shared/css-cleanup/root-cleanups.d.ts +4 -0
  11. package/dist/bundlers/shared/css-cleanup/selectors.d.ts +8 -0
  12. package/dist/bundlers/shared/css-cleanup.d.ts +3 -0
  13. package/dist/bundlers/shared/css-imports.d.ts +8 -0
  14. package/dist/bundlers/shared/generator-css/config-directive.d.ts +2 -0
  15. package/dist/bundlers/shared/generator-css/directives.d.ts +13 -0
  16. package/dist/bundlers/shared/generator-css/legacy-compat.d.ts +7 -0
  17. package/dist/bundlers/shared/generator-css/legacy-selectors.d.ts +5 -0
  18. package/dist/bundlers/shared/generator-css/legacy-units.d.ts +1 -0
  19. package/dist/bundlers/shared/generator-css/markers.d.ts +16 -0
  20. package/dist/bundlers/shared/generator-css/source-files.d.ts +11 -0
  21. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +10 -0
  22. package/dist/bundlers/shared/generator-css.d.ts +33 -0
  23. package/dist/bundlers/shared/module-graph.d.ts +5 -0
  24. package/dist/bundlers/shared/run-tasks.d.ts +2 -0
  25. package/dist/bundlers/vite/bundle-entries.d.ts +14 -0
  26. package/dist/bundlers/vite/bundle-state.d.ts +43 -0
  27. package/dist/bundlers/vite/css-finalizer.d.ts +22 -0
  28. package/dist/bundlers/vite/generate-bundle/candidates.d.ts +2 -0
  29. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +20 -0
  30. package/dist/bundlers/vite/generate-bundle/css-share-scope.d.ts +3 -0
  31. package/dist/bundlers/vite/generate-bundle/dirty-state.d.ts +1 -0
  32. package/dist/bundlers/vite/generate-bundle/js-entries.d.ts +2 -0
  33. package/dist/bundlers/vite/generate-bundle/js-handler-options.d.ts +8 -0
  34. package/dist/bundlers/vite/generate-bundle/js-linking.d.ts +13 -0
  35. package/dist/bundlers/vite/generate-bundle/metrics.d.ts +17 -0
  36. package/dist/bundlers/vite/generate-bundle/process-plan.d.ts +9 -0
  37. package/dist/bundlers/vite/generate-bundle/rollup-assets.d.ts +7 -0
  38. package/dist/bundlers/vite/generate-bundle/signatures.d.ts +8 -0
  39. package/dist/bundlers/vite/generate-bundle.d.ts +34 -0
  40. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +21 -0
  41. package/dist/bundlers/vite/index.d.ts +3 -0
  42. package/dist/bundlers/vite/js-precheck.d.ts +1 -0
  43. package/dist/bundlers/vite/official-tailwind-plugins.d.ts +5 -0
  44. package/dist/bundlers/vite/postcss-config.d.ts +6 -0
  45. package/dist/bundlers/vite/query.d.ts +15 -0
  46. package/dist/bundlers/vite/resolve-app-type.d.ts +2 -0
  47. package/dist/bundlers/vite/rewrite-css-imports.d.ts +13 -0
  48. package/dist/bundlers/vite/runtime-affecting-signature.d.ts +2 -0
  49. package/dist/bundlers/vite/runtime-class-set.d.ts +22 -0
  50. package/dist/bundlers/vite/source-candidates.d.ts +18 -0
  51. package/dist/bundlers/vite/source-scan.d.ts +8 -0
  52. package/dist/bundlers/vite/tailwind-basedir.d.ts +1 -0
  53. package/dist/bundlers/vite/utils.d.ts +9 -0
  54. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +21 -0
  55. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +20 -0
  56. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +20 -0
  57. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +10 -0
  58. package/dist/bundlers/webpack/index.d.ts +1 -0
  59. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +14 -0
  60. package/dist/bundlers/webpack/loaders/weapp-tw-runtime-classset-loader.d.ts +11 -0
  61. package/dist/bundlers/webpack/shared/loader-anchors.d.ts +8 -0
  62. package/dist/cache/index.d.ts +38 -0
  63. package/dist/cache/md5.d.ts +1 -0
  64. package/dist/cache-BVAiJV3J.js +502 -0
  65. package/dist/cache-CHs4DXui.mjs +434 -0
  66. package/dist/chunk-8l464Juk.js +28 -0
  67. package/dist/cli/context.d.ts +13 -0
  68. package/dist/cli/doctor/constants.d.ts +7 -0
  69. package/dist/cli/doctor/types.d.ts +31 -0
  70. package/dist/cli/doctor.d.ts +4 -0
  71. package/dist/cli/helpers/options/format.d.ts +2 -0
  72. package/dist/cli/helpers/options/parse.d.ts +3 -0
  73. package/dist/cli/helpers/options/resolve.d.ts +1 -0
  74. package/dist/cli/helpers/options.d.ts +3 -0
  75. package/dist/cli/helpers.d.ts +4 -0
  76. package/dist/cli/mount-options.d.ts +4 -0
  77. package/dist/cli/types.d.ts +15 -0
  78. package/dist/cli/vscode-entry.d.ts +14 -0
  79. package/dist/cli.d.ts +1 -2
  80. package/dist/cli.js +1985 -3574
  81. package/dist/cli.mjs +1962 -3554
  82. package/dist/constants-BG12WAKw.mjs +44 -0
  83. package/dist/constants-BeeyfJ9k.js +73 -0
  84. package/dist/constants.d.ts +12 -0
  85. package/dist/context/compiler-context-cache.d.ts +3 -0
  86. package/dist/context/custom-attributes.d.ts +2 -0
  87. package/dist/context/handlers.d.ts +6 -0
  88. package/dist/context/index.d.ts +7 -0
  89. package/dist/context/logger.d.ts +4 -0
  90. package/dist/context/tailwindcss/basedir.d.ts +1 -0
  91. package/dist/context/tailwindcss/rax.d.ts +2 -0
  92. package/dist/context/tailwindcss.d.ts +4 -0
  93. package/dist/context/workspace.d.ts +3 -0
  94. package/dist/core.d.ts +5 -21
  95. package/dist/core.js +131 -180
  96. package/dist/core.mjs +129 -180
  97. package/dist/css-macro/constants.d.ts +14 -0
  98. package/dist/css-macro/index.d.ts +15 -0
  99. package/dist/css-macro/postcss.d.ts +3 -7
  100. package/dist/css-macro/postcss.js +44 -58
  101. package/dist/css-macro/postcss.mjs +44 -56
  102. package/dist/css-macro.d.ts +2 -20
  103. package/dist/css-macro.js +37 -50
  104. package/dist/css-macro.mjs +33 -47
  105. package/dist/debug/index.d.ts +5 -0
  106. package/dist/defaults.d.ts +16 -11
  107. package/dist/defaults.js +151 -8
  108. package/dist/defaults.mjs +143 -7
  109. package/dist/escape.js +31 -54
  110. package/dist/escape.mjs +18 -25
  111. package/dist/generator/index.d.ts +11 -0
  112. package/dist/generator/options.d.ts +16 -0
  113. package/dist/generator/types.d.ts +20 -0
  114. package/dist/generator-DKkhJbOg.js +1531 -0
  115. package/dist/generator-UBmfduYg.mjs +1432 -0
  116. package/dist/generator.d.ts +1 -0
  117. package/dist/generator.js +19 -0
  118. package/dist/generator.mjs +2 -0
  119. package/dist/gulp.d.ts +4 -24
  120. package/dist/gulp.js +370 -13
  121. package/dist/gulp.mjs +362 -13
  122. package/dist/incremental-runtime-class-set-BYmzQ-_f.js +1555 -0
  123. package/dist/incremental-runtime-class-set-BgMW6wf2.mjs +1510 -0
  124. package/dist/index.d.ts +8 -15
  125. package/dist/index.js +12 -24
  126. package/dist/index.mjs +6 -24
  127. package/dist/js/JsTokenUpdater.d.ts +14 -0
  128. package/dist/js/ModuleGraph.d.ts +18 -0
  129. package/dist/js/NodePathWalker.d.ts +33 -0
  130. package/dist/js/babel/parse.d.ts +9 -0
  131. package/dist/js/babel/process.d.ts +4 -0
  132. package/dist/js/babel.d.ts +13 -0
  133. package/dist/js/class-context.d.ts +3 -0
  134. package/dist/js/evalTransforms.d.ts +7 -0
  135. package/dist/js/handlers.d.ts +5 -0
  136. package/dist/js/index.d.ts +5 -0
  137. package/dist/js/literal-transform.d.ts +2 -0
  138. package/dist/js/module-graph/ignored-exports.d.ts +18 -0
  139. package/dist/js/module-graph/types.d.ts +17 -0
  140. package/dist/js/node-path-walker/export-handlers.d.ts +12 -0
  141. package/dist/js/node-path-walker/import-tokens.d.ts +24 -0
  142. package/dist/js/precheck.d.ts +2 -0
  143. package/dist/js/sourceAnalysis.d.ts +17 -0
  144. package/dist/js/taggedTemplateIgnore.d.ts +13 -0
  145. package/dist/js/types.d.ts +11 -0
  146. package/dist/lightningcss/index.d.ts +8 -0
  147. package/dist/lightningcss/style-handler/options.d.ts +3 -0
  148. package/dist/lightningcss/style-handler/selector-transform.d.ts +10 -0
  149. package/dist/lightningcss/style-handler/selector-utils.d.ts +10 -0
  150. package/dist/lightningcss/style-handler.d.ts +17 -0
  151. package/dist/logger/index.d.ts +2 -0
  152. package/dist/logger-CZUxvJJD.mjs +2 -0
  153. package/dist/logger-EVNB9z7i.js +1 -0
  154. package/dist/postcss/config-directive.d.ts +1 -0
  155. package/dist/postcss/context.d.ts +9 -0
  156. package/dist/postcss/source-files.d.ts +8 -0
  157. package/dist/postcss/tailwind-version.d.ts +3 -0
  158. package/dist/postcss-C7efq3hr.mjs +231 -0
  159. package/dist/postcss-Dg-_lyHS.js +240 -0
  160. package/dist/postcss-html-transform.d.ts +3 -3
  161. package/dist/postcss-html-transform.js +7 -10
  162. package/dist/postcss-html-transform.mjs +3 -6
  163. package/dist/postcss.d.ts +15 -0
  164. package/dist/postcss.js +7 -0
  165. package/dist/postcss.mjs +2 -0
  166. package/dist/precheck-B32p-gLI.js +2736 -0
  167. package/dist/precheck-B4RH6ZNN.mjs +2622 -0
  168. package/dist/presets/hbuilderx.d.ts +4 -0
  169. package/dist/presets/index.d.ts +3 -0
  170. package/dist/presets/shared.d.ts +10 -0
  171. package/dist/presets/taro.d.ts +4 -0
  172. package/dist/presets/uni-app-x.d.ts +16 -0
  173. package/dist/presets/uni-app.d.ts +4 -0
  174. package/dist/presets.d.ts +1 -76
  175. package/dist/presets.js +117 -163
  176. package/dist/presets.mjs +109 -163
  177. package/dist/reset/index.d.ts +2 -0
  178. package/dist/reset.d.ts +2 -4
  179. package/dist/reset.js +19 -8
  180. package/dist/reset.mjs +2 -8
  181. package/dist/runtime-patch-CwN5ya72.mjs +71 -0
  182. package/dist/runtime-patch-D6mBo_KB.js +85 -0
  183. package/dist/shared/classname-transform.d.ts +14 -0
  184. package/dist/shared/mpx.d.ts +7 -0
  185. package/dist/shared/tailwindcss-css-redirect.d.ts +1 -0
  186. package/dist/source-scan-BaYvNx-k.js +293 -0
  187. package/dist/source-scan-cGZxoJqP.mjs +254 -0
  188. package/dist/tailwindcss/index.d.ts +11 -0
  189. package/dist/tailwindcss/miniprogram.d.ts +5 -0
  190. package/dist/tailwindcss/patcher-options.d.ts +8 -0
  191. package/dist/tailwindcss/patcher-resolve.d.ts +4 -0
  192. package/dist/tailwindcss/patcher.d.ts +12 -0
  193. package/dist/tailwindcss/remove-unsupported-css.d.ts +2 -0
  194. package/dist/tailwindcss/runtime/cache.d.ts +11 -0
  195. package/dist/tailwindcss/runtime-logs.d.ts +3 -0
  196. package/dist/tailwindcss/runtime-patch.d.ts +5 -0
  197. package/dist/tailwindcss/runtime.d.ts +28 -0
  198. package/dist/tailwindcss/source-scan.d.ts +25 -0
  199. package/dist/tailwindcss/targets.d.ts +2 -0
  200. package/dist/tailwindcss/v3-engine/generator.d.ts +2 -0
  201. package/dist/tailwindcss/v3-engine/index.d.ts +4 -0
  202. package/dist/tailwindcss/v3-engine/miniprogram.d.ts +4 -0
  203. package/dist/tailwindcss/v3-engine/source.d.ts +5 -0
  204. package/dist/tailwindcss/v3-engine/types.d.ts +55 -0
  205. package/dist/tailwindcss/v4/config.d.ts +5 -0
  206. package/dist/tailwindcss/v4/css-entries.d.ts +7 -0
  207. package/dist/tailwindcss/v4/css-sources.d.ts +5 -0
  208. package/dist/tailwindcss/v4/index.d.ts +2 -0
  209. package/dist/tailwindcss/v4/multi-patcher.d.ts +2 -0
  210. package/dist/tailwindcss/v4/patcher-options.d.ts +2 -0
  211. package/dist/tailwindcss/v4/patcher.d.ts +15 -0
  212. package/dist/tailwindcss/v4-engine/candidates.d.ts +2 -0
  213. package/dist/tailwindcss/v4-engine/design-system.d.ts +1 -0
  214. package/dist/tailwindcss/v4-engine/generator.d.ts +2 -0
  215. package/dist/tailwindcss/v4-engine/index.d.ts +5 -0
  216. package/dist/tailwindcss/v4-engine/miniprogram.d.ts +5 -0
  217. package/dist/tailwindcss/v4-engine/source.d.ts +7 -0
  218. package/dist/tailwindcss/v4-engine/tailwind-v3-compatibility.d.ts +1 -0
  219. package/dist/tailwindcss/v4-engine/tailwind-v3-default-colors.d.ts +1 -0
  220. package/dist/tailwindcss/v4-engine/tailwind-v4-default-colors.d.ts +1 -0
  221. package/dist/tailwindcss/v4-engine/types.d.ts +19 -0
  222. package/dist/tailwindcss/version.d.ts +4 -0
  223. package/dist/tailwindcss-Bu-RWIHx.js +630 -0
  224. package/dist/tailwindcss-C5IgPlQ0.mjs +579 -0
  225. package/dist/typedoc.export.d.ts +3 -0
  226. package/dist/types/base.d.ts +1 -0
  227. package/dist/types/index.d.ts +97 -0
  228. package/dist/types/shared.d.ts +10 -0
  229. package/dist/types/user-defined-options/general.d.ts +29 -0
  230. package/dist/types/user-defined-options/important.d.ts +37 -0
  231. package/dist/types/user-defined-options/index.d.ts +11 -0
  232. package/dist/types/user-defined-options/lifecycle.d.ts +6 -0
  233. package/dist/types/user-defined-options/matcher.d.ts +9 -0
  234. package/dist/types.d.ts +1 -150
  235. package/dist/types.js +0 -1
  236. package/dist/types.mjs +1 -1
  237. package/dist/uni-app-x/component-local-style.d.ts +19 -0
  238. package/dist/uni-app-x/index.d.ts +2 -0
  239. package/dist/uni-app-x/options.d.ts +12 -0
  240. package/dist/uni-app-x/style-isolation.d.ts +2 -0
  241. package/dist/uni-app-x/transform.d.ts +9 -0
  242. package/dist/uni-app-x/vite.d.ts +36 -0
  243. package/dist/utils/decode.d.ts +2 -0
  244. package/dist/utils/disabled.d.ts +5 -0
  245. package/dist/utils/hbuilderx.d.ts +5 -0
  246. package/dist/utils/index.d.ts +7 -0
  247. package/dist/utils/nameMatcher.d.ts +4 -0
  248. package/dist/utils/resolve-package.d.ts +1 -0
  249. package/dist/utils/uni-platform.d.ts +11 -0
  250. package/dist/utils-BiShvil9.js +61 -0
  251. package/dist/utils-Btw1iOVV.mjs +48 -0
  252. package/dist/vite-BU74SkOi.mjs +2246 -0
  253. package/dist/vite-CKjx_5c3.js +2261 -0
  254. package/dist/vite.d.ts +3 -17
  255. package/dist/vite.js +4 -14
  256. package/dist/vite.mjs +2 -14
  257. package/dist/weapp-tw-css-import-rewrite-loader.js +68 -92
  258. package/dist/weapp-tw-runtime-classset-loader.js +31 -50
  259. package/dist/webpack-CAk_ITq7.mjs +713 -0
  260. package/dist/webpack-damWiYqY.js +723 -0
  261. package/dist/webpack.d.ts +4 -25
  262. package/dist/webpack.js +6 -17
  263. package/dist/webpack.mjs +2 -17
  264. package/dist/wxml/Tokenizer.d.ts +15 -0
  265. package/dist/wxml/custom-attributes.d.ts +4 -0
  266. package/dist/wxml/index.d.ts +2 -0
  267. package/dist/wxml/shared.d.ts +2 -0
  268. package/dist/wxml/tokenizer/types.d.ts +18 -0
  269. package/dist/wxml/utils/codegen/legacy-rewriter.d.ts +2 -0
  270. package/dist/wxml/utils/codegen/legacy-visitor.d.ts +8 -0
  271. package/dist/wxml/utils/codegen.d.ts +2 -0
  272. package/dist/wxml/utils/custom-template.d.ts +3 -0
  273. package/dist/wxml/utils/fragment-helpers.d.ts +6 -0
  274. package/dist/wxml/utils/fragment-updater.d.ts +4 -0
  275. package/dist/wxml/utils/template-fragments.d.ts +3 -0
  276. package/dist/wxml/utils.d.ts +8 -0
  277. package/dist/wxml/whitespace.d.ts +2 -0
  278. package/generator-placeholder.css +1 -0
  279. package/package.json +39 -38
  280. package/dist/chunk-24AGZQVR.js +0 -183
  281. package/dist/chunk-3VQKDHGP.mjs +0 -179
  282. package/dist/chunk-4AFQP74Z.js +0 -24
  283. package/dist/chunk-57SOQCAU.mjs +0 -582
  284. package/dist/chunk-5ZYHNDEK.mjs +0 -2439
  285. package/dist/chunk-76S2EME4.mjs +0 -34
  286. package/dist/chunk-A5PB4KZT.js +0 -138
  287. package/dist/chunk-DUHYLR2R.js +0 -276
  288. package/dist/chunk-DYLQ6UOI.js +0 -71
  289. package/dist/chunk-E7I5TW5K.js +0 -52
  290. package/dist/chunk-FS2NOOEB.js +0 -292
  291. package/dist/chunk-HVNGIKLS.js +0 -3930
  292. package/dist/chunk-JZQBZHN5.js +0 -579
  293. package/dist/chunk-KGTVD4EP.mjs +0 -3930
  294. package/dist/chunk-NNOQDMUP.mjs +0 -10
  295. package/dist/chunk-OF6MFURR.js +0 -34
  296. package/dist/chunk-OFB2KBRP.js +0 -2442
  297. package/dist/chunk-OOHJLO5M.mjs +0 -71
  298. package/dist/chunk-PCDYXXSK.mjs +0 -1515
  299. package/dist/chunk-RKISS72P.js +0 -7
  300. package/dist/chunk-RRQZL7FQ.mjs +0 -292
  301. package/dist/chunk-XAKAD2CR.mjs +0 -138
  302. package/dist/chunk-XZP3MREK.mjs +0 -276
  303. package/dist/chunk-ZAA5ZG3D.js +0 -1518
  304. package/dist/chunk-ZCH4YINE.mjs +0 -52
  305. package/dist/cli.d.mts +0 -2
  306. package/dist/core.d.mts +0 -26
  307. package/dist/css-macro/postcss.d.mts +0 -7
  308. package/dist/css-macro.d.mts +0 -18
  309. package/dist/defaults.d.mts +0 -11
  310. package/dist/gulp.d.mts +0 -24
  311. package/dist/index-BXrmQelt.d.mts +0 -672
  312. package/dist/index-BXrmQelt.d.ts +0 -672
  313. package/dist/index.d.mts +0 -15
  314. package/dist/postcss-html-transform.d.mts +0 -2
  315. package/dist/presets.d.mts +0 -76
  316. package/dist/reset.d.mts +0 -1
  317. package/dist/types.d.mts +0 -150
  318. package/dist/vite.d.mts +0 -17
  319. package/dist/webpack.d.mts +0 -25
  320. package/dist/webpack4.d.mts +0 -26
  321. package/dist/webpack4.d.ts +0 -26
  322. package/dist/webpack4.js +0 -493
  323. package/dist/webpack4.mjs +0 -495
  324. package/scripts/postinstall.mjs +0 -59
@@ -0,0 +1,2246 @@
1
+ import { c as resolveTailwindcssOptions, l as findNearestPackageRoot, n as getRuntimeClassSetSignature, s as findTailwindConfig } from "./cache-CHs4DXui.mjs";
2
+ import { n as createDebug } from "./runtime-patch-CwN5ya72.mjs";
3
+ import { c as resolveTailwindV4SourceOptionsFromPatcher, d as filterUnsupportedMiniProgramTailwindV4Candidates, i as normalizeWeappTailwindcssGeneratorOptions, m as resolveTailwindV3SourceFromPatcher, s as resolveTailwindV4SourceFromPatcher } from "./generator-UBmfduYg.mjs";
4
+ import { a as hasTailwindRootDirectives, i as processCachedTask, n as generateCssByGenerator, o as hasTailwindSourceDirectives, r as validateCandidatesByGenerator, s as hasTailwindGeneratedCssMarkers, t as createBundleRuntimeClassSetManager } from "./incremental-runtime-class-set-BgMW6wf2.mjs";
5
+ import { a as analyzeSource, c as isClassContextLiteralPath, g as createTailwindRuntimeReadyPromise, h as collectRuntimeClassSet, i as createAttributeMatcher, l as replaceWxml, m as toCustomAttributesEntities, n as getCompilerContext, o as JsTokenUpdater, p as vitePluginName, r as generateCode, s as _defineProperty, t as shouldSkipJsTransform, u as babelParse, v as refreshTailwindRuntimeState } from "./precheck-B4RH6ZNN.mjs";
6
+ import { o as resolveUniUtsPlatform } from "./utils-Btw1iOVV.mjs";
7
+ import { c as upsertTailwindV4CssSource, i as resolveUniAppXOptions, r as isUniAppXEnabled, s as hasConfiguredTailwindV4CssRoots } from "./tailwindcss-C5IgPlQ0.mjs";
8
+ import { i as normalizeLegacyContentEntries, n as createSourceScanPattern, o as resolveCssSourceEntries, r as expandTailwindSourceEntries, t as collectCssInlineSourceCandidates } from "./source-scan-cGZxoJqP.mjs";
9
+ import { a as createBundleModuleGraphOptions, c as resolvePluginDisabledState, d as toAbsoluteOutputPath, i as applyLinkedResults, l as normalizeOutputPathKey, n as createBundleBuildState, o as pushConcurrentTaskFactories, r as updateBundleBuildState, s as resolvePackageDir, t as buildBundleSnapshot } from "./bundle-state-BWqi5ZyX.mjs";
10
+ import { t as logger$1 } from "./logger-CZUxvJJD.mjs";
11
+ import postcss from "postcss";
12
+ import path from "node:path";
13
+ import process from "node:process";
14
+ import { logger } from "@weapp-tailwindcss/logger";
15
+ import { cleanUrl as cleanUrl$1, ensurePosix } from "@weapp-tailwindcss/shared";
16
+ import { extractRawCandidatesWithPositions } from "tailwindcss-patch";
17
+ import fs, { existsSync, readFileSync } from "node:fs";
18
+ import { readFile } from "node:fs/promises";
19
+ import MagicString from "magic-string";
20
+ import { splitCode } from "@weapp-tailwindcss/shared/extractors";
21
+ import fg from "fast-glob";
22
+ import micromatch from "micromatch";
23
+ import postcssHtmlTransform from "@weapp-tailwindcss/postcss/html-transform";
24
+ import { NodeTypes } from "@vue/compiler-dom";
25
+ import { parse } from "@vue/compiler-sfc";
26
+ import { parse as parse$1 } from "comment-json";
27
+ import postcssrc from "postcss-load-config";
28
+ //#region src/uni-app-x/component-local-style.ts
29
+ const EXPRESSION_WRAPPER_PREFIX = "(\n";
30
+ const EXPRESSION_WRAPPER_SUFFIX = "\n)";
31
+ const COMPONENT_RE = /(?:^|[/\\])components(?:[/\\].+)?\.(?:uvue|nvue)$/;
32
+ function createStableHash(input) {
33
+ let hash = 2166136261;
34
+ for (let i = 0; i < input.length; i++) {
35
+ hash ^= input.charCodeAt(i);
36
+ hash = Math.imul(hash, 16777619);
37
+ }
38
+ return (hash >>> 0).toString(36);
39
+ }
40
+ function extractLiteralValue(path) {
41
+ const allowDoubleQuotes = path.isTemplateElement();
42
+ if (path.isStringLiteral()) return {
43
+ allowDoubleQuotes,
44
+ literal: path.node.value,
45
+ offset: 1
46
+ };
47
+ return {
48
+ allowDoubleQuotes,
49
+ literal: typeof path.node.value === "string" ? path.node.value : path.node.value.raw,
50
+ offset: 0
51
+ };
52
+ }
53
+ function createAlias(fileId, utility, index) {
54
+ return `wtu-${createStableHash(`${fileId}:${utility}`)}-${index.toString(36)}`;
55
+ }
56
+ function isRuntimeCandidate(candidate, runtimeSet) {
57
+ if (!runtimeSet || runtimeSet.size === 0) return false;
58
+ return runtimeSet.has(candidate) || runtimeSet.has(replaceWxml(candidate));
59
+ }
60
+ function shouldEnableComponentLocalStyle(id) {
61
+ return COMPONENT_RE.test(id);
62
+ }
63
+ var UniAppXComponentLocalStyleCollector = class {
64
+ constructor(fileId, runtimeSet) {
65
+ this.fileId = fileId;
66
+ this.runtimeSet = runtimeSet;
67
+ _defineProperty(this, "aliasByUtility", /* @__PURE__ */ new Map());
68
+ _defineProperty(this, "aliasByLookup", /* @__PURE__ */ new Map());
69
+ }
70
+ ensureAlias(utility) {
71
+ const cached = this.aliasByUtility.get(utility);
72
+ if (cached) return cached;
73
+ const alias = createAlias(this.fileId, utility, this.aliasByUtility.size);
74
+ this.aliasByUtility.set(utility, alias);
75
+ this.aliasByLookup.set(utility, alias);
76
+ this.aliasByLookup.set(replaceWxml(utility), alias);
77
+ return alias;
78
+ }
79
+ rewriteLiteral(literal, shouldInclude) {
80
+ const candidates = splitCode(literal);
81
+ if (candidates.length === 0) return literal;
82
+ let rewritten = literal;
83
+ for (const candidate of candidates) {
84
+ if (!shouldInclude(candidate)) continue;
85
+ rewritten = rewritten.replace(candidate, this.ensureAlias(candidate));
86
+ }
87
+ return rewritten;
88
+ }
89
+ collectAndRewriteStaticClass(literal) {
90
+ return this.rewriteLiteral(literal, (candidate) => isRuntimeCandidate(candidate, this.runtimeSet));
91
+ }
92
+ collectRuntimeClasses(rawSource, options = {}) {
93
+ const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
94
+ try {
95
+ const analysis = analyzeSource(babelParse(wrapped, {
96
+ plugins: ["typescript"],
97
+ sourceType: options.wrapExpression ? "module" : "unambiguous"
98
+ }), {}, void 0, false);
99
+ for (const path of analysis.targetPaths) {
100
+ const { literal, allowDoubleQuotes } = extractLiteralValue(path);
101
+ const candidates = splitCode(literal, allowDoubleQuotes);
102
+ const classContext = options.wrapExpression || isClassContextLiteralPath(path);
103
+ for (const candidate of candidates) {
104
+ if (!candidate || !classContext && !isRuntimeCandidate(candidate, this.runtimeSet)) continue;
105
+ if (isRuntimeCandidate(candidate, this.runtimeSet)) this.ensureAlias(candidate);
106
+ }
107
+ }
108
+ } catch {}
109
+ }
110
+ rewriteTransformedCode(rawSource, options = {}) {
111
+ if (this.aliasByLookup.size === 0) return rawSource;
112
+ const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
113
+ try {
114
+ const analysis = analyzeSource(babelParse(wrapped, {
115
+ plugins: ["typescript"],
116
+ sourceType: options.wrapExpression ? "module" : "unambiguous"
117
+ }), {}, void 0, false);
118
+ if (analysis.targetPaths.length === 0) return rawSource;
119
+ const updater = new JsTokenUpdater();
120
+ for (const path of analysis.targetPaths) {
121
+ const { literal, allowDoubleQuotes, offset } = extractLiteralValue(path);
122
+ const candidates = splitCode(literal, allowDoubleQuotes);
123
+ if (candidates.length === 0) continue;
124
+ let rewritten = literal;
125
+ let mutated = false;
126
+ for (const candidate of candidates) {
127
+ const alias = this.aliasByLookup.get(candidate);
128
+ if (!alias) continue;
129
+ const replaced = rewritten.replace(candidate, alias);
130
+ if (replaced !== rewritten) {
131
+ rewritten = replaced;
132
+ mutated = true;
133
+ }
134
+ }
135
+ if (!mutated || typeof path.node.start !== "number" || typeof path.node.end !== "number") continue;
136
+ updater.addToken({
137
+ start: path.node.start + offset,
138
+ end: path.node.end - offset,
139
+ value: rewritten,
140
+ path
141
+ });
142
+ }
143
+ if (updater.length === 0) return rawSource;
144
+ const ms = new MagicString(wrapped);
145
+ updater.updateMagicString(ms);
146
+ if (options.wrapExpression) {
147
+ ms.remove(0, 2);
148
+ ms.remove(wrapped.length - 2, wrapped.length);
149
+ }
150
+ return ms.toString();
151
+ } catch {
152
+ return rawSource;
153
+ }
154
+ }
155
+ hasStyles() {
156
+ return this.aliasByUtility.size > 0;
157
+ }
158
+ toStyleBlock() {
159
+ if (!this.hasStyles()) return "";
160
+ const lines = ["<style scoped>"];
161
+ for (const [utility, alias] of this.aliasByUtility) {
162
+ lines.push(`.${alias} {`);
163
+ lines.push(` @apply ${utility};`);
164
+ lines.push("}");
165
+ }
166
+ lines.push("</style>");
167
+ return `${lines.join("\n")}\n`;
168
+ }
169
+ };
170
+ //#endregion
171
+ //#region src/uni-app-x/transform.ts
172
+ function traverse(node, visitor) {
173
+ visitor(node);
174
+ if (Array.isArray(node.children)) {
175
+ for (const child of node.children) if (child && typeof child === "object" && "type" in child) traverse(child, visitor);
176
+ }
177
+ }
178
+ function updateStaticAttribute(ms, prop, content = prop.value?.content) {
179
+ if (!prop.value) return;
180
+ const start = prop.value.loc.start.offset + 1;
181
+ const end = prop.value.loc.end.offset - 1;
182
+ if (start < end) ms.update(start, end, replaceWxml(content ?? ""));
183
+ }
184
+ function updateStaticAttributeWithLocalStyle(ms, prop, collector, content = prop.value?.content) {
185
+ if (!prop.value) return;
186
+ const start = prop.value.loc.start.offset + 1;
187
+ const end = prop.value.loc.end.offset - 1;
188
+ if (start < end) ms.update(start, end, collector.collectAndRewriteStaticClass(content ?? ""));
189
+ }
190
+ function updateDirectiveExpression(ms, prop, jsHandler, runtimeSet) {
191
+ if (prop.exp?.type !== NodeTypes.SIMPLE_EXPRESSION) return;
192
+ const expression = prop.exp.content;
193
+ const start = prop.exp.loc.start.offset;
194
+ const end = prop.exp.loc.end.offset;
195
+ if (start >= end) return;
196
+ const generated = generateCode(expression, {
197
+ jsHandler,
198
+ runtimeSet,
199
+ wrapExpression: true
200
+ });
201
+ ms.update(start, end, generated);
202
+ }
203
+ function updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, collector, runtimeSet) {
204
+ if (prop.exp?.type !== NodeTypes.SIMPLE_EXPRESSION) return;
205
+ const expression = prop.exp.content;
206
+ const start = prop.exp.loc.start.offset;
207
+ const end = prop.exp.loc.end.offset;
208
+ if (start >= end) return;
209
+ collector.collectRuntimeClasses(expression, { wrapExpression: true });
210
+ const generated = generateCode(expression, {
211
+ jsHandler,
212
+ runtimeSet,
213
+ wrapExpression: true
214
+ });
215
+ ms.update(start, end, collector.rewriteTransformedCode(generated, { wrapExpression: true }));
216
+ }
217
+ function shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute) {
218
+ const lowerName = attrName.toLowerCase();
219
+ const shouldHandleDefault = !disabledDefaultTemplateHandler && lowerName === "class";
220
+ const shouldHandleCustom = matchCustomAttribute?.(tag, attrName) ?? false;
221
+ return {
222
+ shouldHandleDefault,
223
+ shouldHandleCustom,
224
+ shouldHandle: shouldHandleDefault || shouldHandleCustom
225
+ };
226
+ }
227
+ const defaultCreateJsHandlerOptions = { babelParserOptions: { plugins: ["typescript"] } };
228
+ const UVUE_NVUE_RE$1 = /\.(?:uvue|nvue)(?:\?.*)?$/;
229
+ function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
230
+ if (!UVUE_NVUE_RE$1.test(id)) return;
231
+ const { customAttributesEntities, disabledDefaultTemplateHandler = false } = options;
232
+ const matchCustomAttribute = createAttributeMatcher(customAttributesEntities);
233
+ const ms = new MagicString(code);
234
+ const { descriptor, errors } = parse(code);
235
+ const localStyleCollector = options.enableComponentLocalStyle && shouldEnableComponentLocalStyle(id) ? new UniAppXComponentLocalStyleCollector(id, runtimeSet) : void 0;
236
+ if (errors.length === 0) {
237
+ if (descriptor.template?.ast) traverse(descriptor.template.ast, (node) => {
238
+ if (node.type !== NodeTypes.ELEMENT) return;
239
+ const tag = node.tag;
240
+ for (const prop of node.props) if (prop.type === NodeTypes.ATTRIBUTE) {
241
+ const { shouldHandle, shouldHandleDefault } = shouldHandleAttribute(tag, prop.name, disabledDefaultTemplateHandler, matchCustomAttribute);
242
+ if (!shouldHandle) continue;
243
+ if (shouldHandleDefault && localStyleCollector) updateStaticAttributeWithLocalStyle(ms, prop, localStyleCollector);
244
+ else updateStaticAttribute(ms, prop);
245
+ if (shouldHandleDefault) continue;
246
+ } else if (prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.isStatic) {
247
+ const attrName = prop.arg.content;
248
+ const { shouldHandle } = shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute);
249
+ if (!shouldHandle) continue;
250
+ if (attrName.toLowerCase() === "class" && localStyleCollector) updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, localStyleCollector, runtimeSet);
251
+ else updateDirectiveExpression(ms, prop, jsHandler, runtimeSet);
252
+ }
253
+ });
254
+ if (descriptor.script) {
255
+ localStyleCollector?.collectRuntimeClasses(descriptor.script.content);
256
+ const { code } = jsHandler(descriptor.script.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
257
+ ms.update(descriptor.script.loc.start.offset, descriptor.script.loc.end.offset, localStyleCollector ? localStyleCollector.rewriteTransformedCode(code) : code);
258
+ }
259
+ if (descriptor.scriptSetup) {
260
+ localStyleCollector?.collectRuntimeClasses(descriptor.scriptSetup.content);
261
+ const { code } = jsHandler(descriptor.scriptSetup.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
262
+ ms.update(descriptor.scriptSetup.loc.start.offset, descriptor.scriptSetup.loc.end.offset, localStyleCollector ? localStyleCollector.rewriteTransformedCode(code) : code);
263
+ }
264
+ if (localStyleCollector?.hasStyles()) ms.append(`\n${localStyleCollector.toStyleBlock()}`);
265
+ }
266
+ const result = {
267
+ code: ms.toString(),
268
+ map: null
269
+ };
270
+ Object.defineProperty(result, "map", {
271
+ configurable: true,
272
+ enumerable: true,
273
+ get() {
274
+ return ms.generateMap();
275
+ }
276
+ });
277
+ return result;
278
+ }
279
+ //#endregion
280
+ //#region src/bundlers/vite/query.ts
281
+ function parseVueRequest(id) {
282
+ const [filename, rawQuery] = id.split(`?`, 2);
283
+ const searchParams = new URLSearchParams(rawQuery);
284
+ const query = Object.fromEntries(searchParams);
285
+ if (query.vue != null) query.vue = true;
286
+ if (query.index != null) query.index = Number(query.index);
287
+ if (query.raw != null) query.raw = true;
288
+ if (query.url != null) query.url = true;
289
+ if (query.scoped != null) query.scoped = true;
290
+ const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
291
+ const langType = query.lang || (langTypeMatch ? langTypeMatch.slice(5) : void 0);
292
+ if (langType) query.lang = langType;
293
+ return {
294
+ filename,
295
+ query
296
+ };
297
+ }
298
+ //#endregion
299
+ //#region src/bundlers/vite/utils.ts
300
+ function slash(p) {
301
+ return ensurePosix(p);
302
+ }
303
+ const isWindows = process.platform === "win32";
304
+ const cssLangRE = new RegExp(`\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`);
305
+ function isCSSRequest(request) {
306
+ return cssLangRE.test(request);
307
+ }
308
+ function normalizePath(id) {
309
+ return path.posix.normalize(isWindows ? ensurePosix(id) : id);
310
+ }
311
+ async function formatPostcssSourceMap(rawMap, file) {
312
+ const inputFileDir = path.dirname(file);
313
+ const sources = rawMap.sources.map((source) => {
314
+ const cleanSource = cleanUrl$1(decodeURIComponent(source));
315
+ if (cleanSource[0] === "<" && cleanSource.endsWith(">")) return `\0${cleanSource}`;
316
+ return normalizePath(path.resolve(inputFileDir, cleanSource));
317
+ });
318
+ return {
319
+ file,
320
+ mappings: rawMap.mappings,
321
+ names: rawMap.names,
322
+ sources,
323
+ sourcesContent: rawMap.sourcesContent,
324
+ version: rawMap.version
325
+ };
326
+ }
327
+ //#endregion
328
+ //#region src/uni-app-x/style-isolation.ts
329
+ const manifestCache = /* @__PURE__ */ new Map();
330
+ function resolveUniAppXStyleIsolationEnabled(root) {
331
+ if (!root) return false;
332
+ const normalizedRoot = path.resolve(root);
333
+ const cached = manifestCache.get(normalizedRoot);
334
+ if (cached !== void 0) return cached;
335
+ const manifestPath = path.join(normalizedRoot, "manifest.json");
336
+ let enabled = false;
337
+ try {
338
+ enabled = `${parse$1(fs.readFileSync(manifestPath, "utf8"))["uni-app-x"]?.styleIsolationVersion ?? ""}` === "2";
339
+ } catch {
340
+ enabled = false;
341
+ }
342
+ manifestCache.set(normalizedRoot, enabled);
343
+ return enabled;
344
+ }
345
+ //#endregion
346
+ //#region src/uni-app-x/vite.ts
347
+ const preprocessorLangs = new Set([
348
+ "scss",
349
+ "sass",
350
+ "less",
351
+ "styl",
352
+ "stylus"
353
+ ]);
354
+ const INLINE_LANG_RE = /lang\.([a-z]+)/i;
355
+ const PREPROCESSOR_EXT_RE = /\.(?:scss|sass|less|styl|stylus)(?:\?|$)/i;
356
+ const UVUE_NVUE_QUERY_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
357
+ const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
358
+ function isPreprocessorRequest(id, lang) {
359
+ const normalizedLang = lang?.toLowerCase();
360
+ if (normalizedLang && preprocessorLangs.has(normalizedLang)) return true;
361
+ const inlineLangMatch = id.match(INLINE_LANG_RE);
362
+ if (inlineLangMatch && preprocessorLangs.has(inlineLangMatch[1].toLowerCase())) return true;
363
+ return PREPROCESSOR_EXT_RE.test(id);
364
+ }
365
+ function resolveUniAppXCssTarget(id) {
366
+ return UVUE_NVUE_RE.test(cleanUrl$1(id)) ? "uvue" : void 0;
367
+ }
368
+ function resolveUniAppXJsTransformEnabled$1(uniAppX) {
369
+ return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
370
+ }
371
+ function createUniAppXPlugins(options) {
372
+ const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, jsHandler, ensureRuntimeClassSet, getResolvedConfig, uniAppX } = options;
373
+ const resolvedUniAppXOptions = resolveUniAppXOptions(uniAppX);
374
+ const isIosPlatform = providedIosPlatform ?? resolveUniUtsPlatform().isAppIos;
375
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
376
+ let componentLocalStyleEnabled;
377
+ function shouldEnableComponentLocalStyle() {
378
+ if (!resolvedUniAppXOptions.componentLocalStyles.enabled) {
379
+ componentLocalStyleEnabled = false;
380
+ return false;
381
+ }
382
+ if (!resolvedUniAppXOptions.componentLocalStyles.onlyWhenStyleIsolationVersion2) {
383
+ componentLocalStyleEnabled = true;
384
+ return true;
385
+ }
386
+ if (componentLocalStyleEnabled !== void 0) return componentLocalStyleEnabled;
387
+ const root = getResolvedConfig()?.root;
388
+ componentLocalStyleEnabled = resolveUniAppXStyleIsolationEnabled(root);
389
+ return componentLocalStyleEnabled;
390
+ }
391
+ async function transformStyle(code, id, query) {
392
+ const parsed = query ?? parseVueRequest(id).query;
393
+ if (isCSSRequest(id) || parsed.vue && parsed.type === "style") {
394
+ const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
395
+ let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
396
+ if (!styleHandlerOptions) {
397
+ styleHandlerOptions = {
398
+ isMainChunk: mainCssChunkMatcher(id, appType),
399
+ uniAppXCssTarget: resolveUniAppXCssTarget(id),
400
+ uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
401
+ postcssOptions: { options: {
402
+ from: id,
403
+ map: {
404
+ inline: false,
405
+ annotation: false,
406
+ sourcesContent: true
407
+ }
408
+ } }
409
+ };
410
+ cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
411
+ }
412
+ const postcssResult = await styleHandler(code, styleHandlerOptions);
413
+ const warnings = typeof postcssResult.warnings === "function" ? postcssResult.warnings() : [];
414
+ for (const warning of warnings) logger$1.warn(warning.toString());
415
+ const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), cleanUrl$1(id));
416
+ return {
417
+ code: postcssResult.css,
418
+ map: postcssMap
419
+ };
420
+ }
421
+ }
422
+ const cssPlugins = [{
423
+ name: "weapp-tailwindcss:uni-app-x:css",
424
+ async transform(code, id) {
425
+ await runtimeState.readyPromise;
426
+ return transformStyle(code, id);
427
+ }
428
+ }, {
429
+ name: "weapp-tailwindcss:uni-app-x:css:pre",
430
+ enforce: "pre",
431
+ async transform(code, id) {
432
+ await runtimeState.readyPromise;
433
+ const { query } = parseVueRequest(id);
434
+ const lang = query.lang;
435
+ if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
436
+ return transformStyle(code, id, query);
437
+ }
438
+ }];
439
+ const nvuePlugin = {
440
+ name: "weapp-tailwindcss:uni-app-x:nvue",
441
+ enforce: "pre",
442
+ async buildStart() {
443
+ await ensureRuntimeClassSet(true);
444
+ },
445
+ async transform(code, id) {
446
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
447
+ const resolvedConfig = getResolvedConfig();
448
+ const isServeCommand = resolvedConfig?.command === "serve";
449
+ const isWatchBuild = resolvedConfig?.command === "build" && !!resolvedConfig.build?.watch;
450
+ const isNonWatchBuild = resolvedConfig?.command === "build" && !resolvedConfig.build?.watch;
451
+ const currentRuntimeSet = isServeCommand || isWatchBuild || isNonWatchBuild ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
452
+ const extraOptions = customAttributesEntities.length > 0 || disabledDefaultTemplateHandler ? {
453
+ customAttributesEntities,
454
+ disabledDefaultTemplateHandler,
455
+ enableComponentLocalStyle: shouldEnableComponentLocalStyle()
456
+ } : void 0;
457
+ if (extraOptions) return transformUVue(code, id, jsHandler, currentRuntimeSet, extraOptions);
458
+ if (shouldEnableComponentLocalStyle()) return transformUVue(code, id, jsHandler, currentRuntimeSet, { enableComponentLocalStyle: true });
459
+ return transformUVue(code, id, jsHandler, currentRuntimeSet);
460
+ },
461
+ async handleHotUpdate(ctx) {
462
+ if (getResolvedConfig()?.command !== "serve") return;
463
+ if (!UVUE_NVUE_RE.test(ctx.file)) return;
464
+ await ensureRuntimeClassSet(true);
465
+ },
466
+ async watchChange(id) {
467
+ const resolvedConfig = getResolvedConfig();
468
+ if (resolvedConfig?.command !== "build" || !resolvedConfig.build?.watch) return;
469
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
470
+ await ensureRuntimeClassSet(true);
471
+ }
472
+ };
473
+ return [...cssPlugins, nvuePlugin];
474
+ }
475
+ function createUniAppXAssetTask(file, originalSource, outDir, options) {
476
+ return async () => {
477
+ const { cache, hashKey, createHandlerOptions, debug, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
478
+ const absoluteFile = toAbsoluteOutputPath(file, outDir);
479
+ const rawSource = originalSource.source.toString();
480
+ await processCachedTask({
481
+ cache,
482
+ cacheKey: file,
483
+ hashKey,
484
+ rawSource: options.hashSalt ? `${rawSource}\n/*${options.hashSalt}*/` : rawSource,
485
+ applyResult(source) {
486
+ originalSource.source = source;
487
+ },
488
+ onCacheHit() {
489
+ debug("js cache hit: %s", file);
490
+ },
491
+ async transform() {
492
+ const currentSource = originalSource.source.toString();
493
+ const { code, linked } = await jsHandler(currentSource, runtimeSet, createHandlerOptions(absoluteFile, {
494
+ uniAppX: resolveUniAppXJsTransformEnabled$1(options.uniAppX),
495
+ babelParserOptions: {
496
+ plugins: ["typescript"],
497
+ sourceType: "unambiguous"
498
+ }
499
+ }));
500
+ onUpdate(file, currentSource, code);
501
+ debug("js handle: %s", file);
502
+ applyLinkedResults(linked);
503
+ return { result: code };
504
+ }
505
+ });
506
+ };
507
+ }
508
+ //#endregion
509
+ //#region src/bundlers/vite/css-finalizer.ts
510
+ function isAddWatchFileInvalidRollupPhaseError$1(error) {
511
+ const candidate = error;
512
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
513
+ }
514
+ function registerGeneratorDependencies$1(ctx, dependencies) {
515
+ if (typeof ctx.addWatchFile !== "function") return;
516
+ for (const dependency of dependencies ?? []) try {
517
+ ctx.addWatchFile(dependency);
518
+ } catch (error) {
519
+ if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
520
+ logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
521
+ continue;
522
+ }
523
+ throw error;
524
+ }
525
+ }
526
+ function createCssHandlerOptions(opts, majorVersion, file) {
527
+ return {
528
+ isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
529
+ postcssOptions: { options: { from: file } },
530
+ majorVersion
531
+ };
532
+ }
533
+ function shouldGenerateCssByGenerator(opts, file, rawSource, processed) {
534
+ if (hasTailwindGeneratedCssMarkers(rawSource) || hasTailwindSourceDirectives(rawSource)) return true;
535
+ return processed && shouldFinalizeProcessedCssAsset(opts, file);
536
+ }
537
+ function shouldFinalizeProcessedCssAsset(opts, file) {
538
+ return opts.mainCssChunkMatcher(file, opts.appType);
539
+ }
540
+ function createViteCssFinalizerOutputPlugin(context) {
541
+ return {
542
+ name: "weapp-tailwindcss:adaptor:css-finalizer",
543
+ generateBundle: {
544
+ order: "post",
545
+ async handler(_options, bundle) {
546
+ const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, getRecordedGeneratorCandidates, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource } = context;
547
+ if (getResolvedConfig()?.command !== "build") return;
548
+ const entries = Object.entries(bundle).filter(([, output]) => output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName)));
549
+ if (entries.length === 0) return;
550
+ await runtimeState.readyPromise;
551
+ await waitForSourceCandidateSyncs?.();
552
+ const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
553
+ const runtime = getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet();
554
+ const collectedGeneratorCandidates = new Set([...runtime, ...getSourceCandidates?.() ?? []]);
555
+ const generatorRuntime = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp" ? filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
556
+ await Promise.all(entries.map(async ([bundleFile, output]) => {
557
+ const file = output.fileName || bundleFile;
558
+ const rawSource = output.source.toString();
559
+ const cssHandlerOptions = createCssHandlerOptions(opts, runtimeState.twPatcher.majorVersion, file);
560
+ const cssUserHandlerOptions = {
561
+ ...cssHandlerOptions,
562
+ isMainChunk: false
563
+ };
564
+ const generated = shouldGenerateCssByGenerator(opts, file, rawSource, isCssAssetProcessed(output, file)) ? await generateCssByGenerator({
565
+ opts,
566
+ runtimeState,
567
+ runtime: generatorRuntime,
568
+ rawSource,
569
+ file,
570
+ cssHandlerOptions,
571
+ cssUserHandlerOptions,
572
+ styleHandler: opts.styleHandler,
573
+ debug
574
+ }) : void 0;
575
+ const nextCss = generated?.css ?? (await opts.styleHandler(rawSource, cssHandlerOptions)).css;
576
+ if (generated) {
577
+ registerGeneratorDependencies$1(this, generated.dependencies);
578
+ debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
579
+ recordCssAssetResult?.(file, nextCss);
580
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, rawSource);
581
+ }
582
+ output.source = nextCss;
583
+ markCssAssetProcessed(output, file);
584
+ opts.onUpdate(file, rawSource, nextCss);
585
+ debug("css finalizer handle: %s", file);
586
+ }));
587
+ }
588
+ }
589
+ };
590
+ }
591
+ //#endregion
592
+ //#region src/bundlers/vite/generate-bundle/candidates.ts
593
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
594
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
595
+ function isArbitraryValueCandidate(candidate) {
596
+ return candidate.includes("[") && candidate.includes("]");
597
+ }
598
+ function collectUnescapedDynamicCandidates(source) {
599
+ const matches = /* @__PURE__ */ new Set();
600
+ for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
601
+ QUOTED_LITERAL_RE.lastIndex = 0;
602
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
603
+ while (quoted !== null) {
604
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
605
+ for (const candidate of splitCode(literal, true)) {
606
+ const normalized = candidate.trim();
607
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
608
+ matches.add(normalized);
609
+ }
610
+ quoted = QUOTED_LITERAL_RE.exec(expression);
611
+ }
612
+ }
613
+ return [...matches];
614
+ }
615
+ function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
616
+ if (candidates.has("container")) return candidates;
617
+ if (!sourceCandidates.has("container")) return candidates;
618
+ return new Set([...candidates, "container"]);
619
+ }
620
+ //#endregion
621
+ //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
622
+ function createCssHandlerOptionsCache(options) {
623
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
624
+ const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
625
+ const getCssHandlerOptions = (file) => {
626
+ const majorVersion = options.getMajorVersion();
627
+ const isMainChunk = options.mainCssChunkMatcher(file, options.appType);
628
+ const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
629
+ const cached = cssHandlerOptionsCache.get(cacheKey);
630
+ if (cached) return cached;
631
+ const created = {
632
+ isMainChunk,
633
+ postcssOptions: { options: { from: file } },
634
+ majorVersion
635
+ };
636
+ cssHandlerOptionsCache.set(cacheKey, created);
637
+ return created;
638
+ };
639
+ const getCssUserHandlerOptions = (file) => {
640
+ const cacheKey = `${options.getMajorVersion() ?? "unknown"}:${file}`;
641
+ const cached = cssUserHandlerOptionsCache.get(cacheKey);
642
+ if (cached) return cached;
643
+ const created = {
644
+ ...getCssHandlerOptions(file),
645
+ isMainChunk: false
646
+ };
647
+ cssUserHandlerOptionsCache.set(cacheKey, created);
648
+ return created;
649
+ };
650
+ return {
651
+ getCssHandlerOptions,
652
+ getCssUserHandlerOptions
653
+ };
654
+ }
655
+ //#endregion
656
+ //#region src/bundlers/vite/generate-bundle/css-share-scope.ts
657
+ const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
658
+ const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
659
+ const CSS_IMPORT_RE = /@import\b/i;
660
+ function isPathIndependentCssUrl(value) {
661
+ const normalized = value.trim();
662
+ return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
663
+ }
664
+ function hasPathDependentCssUrl(rawSource) {
665
+ CSS_URL_FUNCTION_RE.lastIndex = 0;
666
+ let match = CSS_URL_FUNCTION_RE.exec(rawSource);
667
+ while (match !== null) {
668
+ if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
669
+ match = CSS_URL_FUNCTION_RE.exec(rawSource);
670
+ }
671
+ return false;
672
+ }
673
+ function createCssTransformShareScope(file, rawSource) {
674
+ if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${normalizeOutputPathKey(path.dirname(file))}`;
675
+ return "global";
676
+ }
677
+ function createCssTransformShareScopeKey(opts, file, rawSource) {
678
+ if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${normalizeOutputPathKey(file)}`;
679
+ return createCssTransformShareScope(file, rawSource);
680
+ }
681
+ function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
682
+ return `${runtimeSignature}:${generatorCandidateSignature}`;
683
+ }
684
+ //#endregion
685
+ //#region src/bundlers/vite/generate-bundle/dirty-state.ts
686
+ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
687
+ const currentFileSet = new Set(currentBundleFiles);
688
+ for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
689
+ return false;
690
+ }
691
+ //#endregion
692
+ //#region src/bundlers/vite/generate-bundle/js-entries.ts
693
+ function createJsEntryResolver(jsEntries) {
694
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
695
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(normalizeOutputPathKey(id), entry);
696
+ return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(normalizeOutputPathKey(id));
697
+ }
698
+ //#endregion
699
+ //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
700
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
701
+ return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
702
+ }
703
+ function createJsHandlerOptionsFactory(options) {
704
+ return (absoluteFilename, extra) => ({
705
+ ...extra,
706
+ filename: absoluteFilename,
707
+ tailwindcssMajorVersion: options.getMajorVersion(),
708
+ moduleGraph: options.moduleGraph,
709
+ babelParserOptions: {
710
+ ...extra?.babelParserOptions ?? {},
711
+ sourceFilename: absoluteFilename
712
+ }
713
+ });
714
+ }
715
+ //#endregion
716
+ //#region src/bundlers/vite/generate-bundle/js-linking.ts
717
+ function createLinkedUpdateHelpers(options) {
718
+ const pendingLinkedUpdates = [];
719
+ const handleLinkedUpdate = (fileName, previous, next) => {
720
+ options.onUpdate(fileName, previous, next);
721
+ options.debug("js linked handle: %s", fileName);
722
+ };
723
+ const scheduleLinkedApply = (entry, code) => {
724
+ pendingLinkedUpdates.push(() => {
725
+ if (entry.output.type === "chunk") entry.output.code = code;
726
+ else entry.output.source = code;
727
+ });
728
+ };
729
+ const applyLinkedUpdates = (linked) => {
730
+ applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
731
+ };
732
+ return {
733
+ applyLinkedUpdates,
734
+ pendingLinkedUpdates
735
+ };
736
+ }
737
+ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
738
+ if (!linked || !linkedSet) return;
739
+ for (const id of Object.keys(linked)) {
740
+ const linkedEntry = getJsEntry(id);
741
+ if (linkedEntry) linkedSet.add(linkedEntry.fileName);
742
+ }
743
+ }
744
+ //#endregion
745
+ //#region src/bundlers/vite/generate-bundle/metrics.ts
746
+ function formatDebugFileList(files, limit = 8) {
747
+ if (files.size === 0) return "-";
748
+ const sorted = [...files].sort();
749
+ if (sorted.length <= limit) return sorted.join(",");
750
+ return `${sorted.slice(0, limit).join(",")},...(+${sorted.length - limit})`;
751
+ }
752
+ function createEmptyMetric() {
753
+ return {
754
+ total: 0,
755
+ transformed: 0,
756
+ cacheHits: 0,
757
+ elapsed: 0
758
+ };
759
+ }
760
+ function createEmptyMetrics() {
761
+ return {
762
+ runtimeSet: 0,
763
+ html: createEmptyMetric(),
764
+ js: createEmptyMetric(),
765
+ css: createEmptyMetric()
766
+ };
767
+ }
768
+ function measureElapsed(start) {
769
+ return performance.now() - start;
770
+ }
771
+ function formatCacheHitRate(metric) {
772
+ if (metric.total === 0) return "0.00%";
773
+ return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
774
+ }
775
+ function formatMs(value) {
776
+ return value.toFixed(2);
777
+ }
778
+ //#endregion
779
+ //#region src/bundlers/vite/generate-bundle/process-plan.ts
780
+ function logBundleProcessPlan(options) {
781
+ const { debug, snapshot, useIncrementalMode, iteration } = options;
782
+ const { processFiles } = snapshot;
783
+ if (useIncrementalMode) {
784
+ debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", iteration, snapshot.changedByType.html.size, formatDebugFileList(snapshot.changedByType.html), snapshot.changedByType.js.size, formatDebugFileList(snapshot.changedByType.js), snapshot.changedByType.css.size, formatDebugFileList(snapshot.changedByType.css), snapshot.changedByType.other.size, formatDebugFileList(snapshot.changedByType.other));
785
+ debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", iteration, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
786
+ return;
787
+ }
788
+ debug("build mode full process html=%d[%s] js=%d[%s] css=%d[%s]", processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
789
+ }
790
+ //#endregion
791
+ //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
792
+ function createReplayCssAsset(fileName, source) {
793
+ return {
794
+ type: "asset",
795
+ fileName,
796
+ name: void 0,
797
+ source,
798
+ needsCodeReference: false,
799
+ names: [],
800
+ originalFileName: null,
801
+ originalFileNames: []
802
+ };
803
+ }
804
+ function isAddWatchFileInvalidRollupPhaseError(error) {
805
+ const candidate = error;
806
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
807
+ }
808
+ function registerGeneratorDependencies(ctx, dependencies) {
809
+ if (typeof ctx.addWatchFile !== "function") return;
810
+ for (const dependency of dependencies ?? []) try {
811
+ ctx.addWatchFile(dependency);
812
+ } catch (error) {
813
+ if (isAddWatchFileInvalidRollupPhaseError(error)) {
814
+ logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
815
+ continue;
816
+ }
817
+ throw error;
818
+ }
819
+ }
820
+ //#endregion
821
+ //#region src/bundlers/vite/generate-bundle/signatures.ts
822
+ function summarizeStringDiff(previous, next) {
823
+ if (previous === next) return "same";
824
+ const previousLength = previous.length;
825
+ const nextLength = next.length;
826
+ const minLength = Math.min(previousLength, nextLength);
827
+ let prefixLength = 0;
828
+ while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) prefixLength += 1;
829
+ let previousSuffixCursor = previousLength - 1;
830
+ let nextSuffixCursor = nextLength - 1;
831
+ while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) {
832
+ previousSuffixCursor -= 1;
833
+ nextSuffixCursor -= 1;
834
+ }
835
+ const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0;
836
+ const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0;
837
+ return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`;
838
+ }
839
+ function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) {
840
+ const changedLinkedFiles = linkedImpactsByEntry.get(entry);
841
+ if (!changedLinkedFiles || changedLinkedFiles.size === 0) return;
842
+ return [...changedLinkedFiles].sort().map((file) => {
843
+ return `${file}:${sourceHashByFile.get(file) ?? "missing"}`;
844
+ }).join(",");
845
+ }
846
+ function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
847
+ if (!linkedImpactSignature) return runtimeSignature;
848
+ return `${runtimeSignature}:linked:${linkedImpactSignature}`;
849
+ }
850
+ function createStableTextSignature(input) {
851
+ let hash = 2166136261;
852
+ for (let i = 0; i < input.length; i++) {
853
+ hash ^= input.charCodeAt(i);
854
+ hash = Math.imul(hash, 16777619);
855
+ }
856
+ return (hash >>> 0).toString(36);
857
+ }
858
+ function createCandidateSignature(candidates) {
859
+ if (candidates.size === 0) return "empty";
860
+ return createStableTextSignature([...candidates].sort().join("\n"));
861
+ }
862
+ function getSnapshotHash(snapshotMap, file, fallback) {
863
+ return snapshotMap.get(file) ?? fallback;
864
+ }
865
+ function hasRuntimeAffectingSourceChanges(changedByType) {
866
+ return changedByType.html.size > 0 || changedByType.js.size > 0;
867
+ }
868
+ //#endregion
869
+ //#region src/bundlers/vite/generate-bundle.ts
870
+ function createGenerateBundleHook(context) {
871
+ const state = createBundleBuildState();
872
+ const cssHandlerOptions = createCssHandlerOptionsCache({
873
+ appType: context.opts.appType,
874
+ mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
875
+ getMajorVersion: () => context.runtimeState.twPatcher.majorVersion
876
+ });
877
+ return async function generateBundle(_opt, bundle) {
878
+ const addWatchFile = (id) => this.addWatchFile?.(id);
879
+ const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates } = context;
880
+ const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
881
+ const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
882
+ const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
883
+ await runtimeState.readyPromise;
884
+ debug("start");
885
+ onStart();
886
+ const metrics = createEmptyMetrics();
887
+ const forceRuntimeRefreshByEnv = process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
888
+ const disableDirtyOptimization = process.env.WEAPP_TW_VITE_DISABLE_DIRTY === "1";
889
+ const disableJsPrecheck = process.env.WEAPP_TW_VITE_DISABLE_JS_PRECHECK === "1";
890
+ const debugCssDiff = process.env.WEAPP_TW_VITE_DEBUG_CSS_DIFF === "1";
891
+ const resolvedConfig = getResolvedConfig();
892
+ const bundleFiles = Object.keys(bundle);
893
+ const useIncrementalMode = !(resolvedConfig?.command === "build") || hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
894
+ const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process.cwd();
895
+ const outDir = resolvedConfig?.build?.outDir ? path.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
896
+ const snapshot = buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode);
897
+ const useBundleRuntimeClassSet = useIncrementalMode || runtimeState.twPatcher.majorVersion === 4;
898
+ const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
899
+ const processFiles = snapshot.processFiles;
900
+ logBundleProcessPlan({
901
+ debug,
902
+ snapshot,
903
+ useIncrementalMode,
904
+ iteration: state.iteration + 1
905
+ });
906
+ const jsEntries = snapshot.jsEntries;
907
+ const getJsEntry = createJsEntryResolver(jsEntries);
908
+ const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
909
+ const runtimeStart = performance.now();
910
+ const runtime = useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
911
+ const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
912
+ await waitForSourceCandidateSyncs?.();
913
+ const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
914
+ const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
915
+ const generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
916
+ const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
917
+ recordGeneratorCandidates?.(generatorRuntime);
918
+ let transformRuntime = runtime;
919
+ if (runtimeState.twPatcher.majorVersion === 3 && generatorRuntime.size > 0) {
920
+ const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
921
+ const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
922
+ if (mainCssEntry) {
923
+ const validatedRuntime = await validateCandidatesByGenerator({
924
+ opts,
925
+ runtimeState,
926
+ candidates: generatorRuntime,
927
+ rawSource: mainCssEntry.source,
928
+ file: mainCssEntry.file,
929
+ cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
930
+ cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
931
+ styleHandler,
932
+ debug
933
+ });
934
+ if (validatedRuntime.size > 0) transformRuntime = new Set([...runtime, ...validatedRuntime]);
935
+ }
936
+ }
937
+ const defaultTemplateHandlerOptions = { runtimeSet: transformRuntime };
938
+ metrics.runtimeSet = measureElapsed(runtimeStart);
939
+ if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
940
+ debug("get runtimeSet, class count: %d, transform class count: %d", runtime.size, transformRuntime.size);
941
+ const runtimeSignature = getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
942
+ const { applyLinkedUpdates, pendingLinkedUpdates } = createLinkedUpdateHelpers({
943
+ jsEntries,
944
+ onUpdate,
945
+ debug
946
+ });
947
+ const createHandlerOptions = createJsHandlerOptionsFactory({
948
+ getMajorVersion: () => runtimeState.twPatcher.majorVersion,
949
+ moduleGraph: moduleGraphOptions
950
+ });
951
+ const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
952
+ const sharedCssResultCache = /* @__PURE__ */ new Map();
953
+ const tasks = [];
954
+ const jsTaskFactories = [];
955
+ for (const entry of snapshot.entries) {
956
+ const { file, output: originalSource, source: originalEntrySource, type } = entry;
957
+ if (type === "html" && originalSource.type === "asset") {
958
+ metrics.html.total++;
959
+ if (!processFiles.html.has(file)) continue;
960
+ const rawSource = originalEntrySource;
961
+ tasks.push(processCachedTask({
962
+ cache,
963
+ cacheKey: file,
964
+ hashKey: `${file}:html:${runtimeSignature}`,
965
+ hash: getSnapshotHash(snapshot.sourceHashByFile, file, rawSource),
966
+ applyResult(source) {
967
+ originalSource.source = source;
968
+ },
969
+ onCacheHit() {
970
+ metrics.html.cacheHits++;
971
+ debug("html cache hit: %s", file);
972
+ },
973
+ async transform() {
974
+ const start = performance.now();
975
+ let transformed = await templateHandler(rawSource, defaultTemplateHandlerOptions);
976
+ let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
977
+ if (unresolvedDynamicCandidates.length > 0) {
978
+ logger.warn("检测到 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
979
+ transformed = await templateHandler(rawSource, { runtimeSet: new Set([...await context.ensureRuntimeClassSet(true), ...unresolvedDynamicCandidates]) });
980
+ unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
981
+ if (unresolvedDynamicCandidates.length > 0) logger.warn("WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
982
+ }
983
+ metrics.html.elapsed += measureElapsed(start);
984
+ metrics.html.transformed++;
985
+ onUpdate(file, rawSource, transformed);
986
+ debug("html handle: %s", file);
987
+ return { result: transformed };
988
+ }
989
+ }));
990
+ continue;
991
+ }
992
+ if (type === "css" && originalSource.type === "asset") {
993
+ metrics.css.total++;
994
+ const rawSource = originalEntrySource;
995
+ const cssRuntimeAffectingSignature = snapshot.runtimeAffectingSignatureByFile.get(file) ?? rawSource;
996
+ const cssShareScope = createCssTransformShareScopeKey(opts, file, rawSource);
997
+ const cssHandlerOptions = getCssHandlerOptions(file);
998
+ const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
999
+ const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
1000
+ tasks.push(processCachedTask({
1001
+ cache,
1002
+ cacheKey: file,
1003
+ hashKey: `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1004
+ hash: `${getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature)}:${generatorCandidateSignature}`,
1005
+ applyResult(source) {
1006
+ originalSource.source = source;
1007
+ markCssAssetProcessed?.(originalSource, file);
1008
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, rawSource, cssRuntimeSignature);
1009
+ },
1010
+ onCacheHit() {
1011
+ metrics.css.cacheHits++;
1012
+ debug("css cache hit: %s", file);
1013
+ },
1014
+ async transform() {
1015
+ if (cssSharedCacheKey) {
1016
+ const sharedCssTask = sharedCssResultCache.get(cssSharedCacheKey);
1017
+ if (sharedCssTask != null) {
1018
+ metrics.css.cacheHits++;
1019
+ debug("css shared hit: %s", file);
1020
+ const sharedCss = await sharedCssTask;
1021
+ onUpdate(file, rawSource, sharedCss);
1022
+ return { result: sharedCss };
1023
+ }
1024
+ }
1025
+ const runTransform = async () => {
1026
+ const start = performance.now();
1027
+ await runtimeState.readyPromise;
1028
+ const generated = await generateCssByGenerator({
1029
+ opts,
1030
+ runtimeState,
1031
+ runtime: generatorRuntime,
1032
+ rawSource,
1033
+ file,
1034
+ cssHandlerOptions,
1035
+ cssUserHandlerOptions: getCssUserHandlerOptions(file),
1036
+ styleHandler,
1037
+ debug
1038
+ });
1039
+ if (generated) {
1040
+ registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
1041
+ if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, generated.css));
1042
+ debug("css generated result: %s bytes=%d", file, generated.css.length);
1043
+ recordCssAssetResult?.(file, generated.css);
1044
+ metrics.css.elapsed += measureElapsed(start);
1045
+ metrics.css.transformed++;
1046
+ debug("css handle via tailwind v%s engine(%s): %s", runtimeState.twPatcher.majorVersion, generated.target, file);
1047
+ return generated.css;
1048
+ }
1049
+ const { css } = await styleHandler(rawSource, getCssHandlerOptions(file));
1050
+ if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, css));
1051
+ metrics.css.elapsed += measureElapsed(start);
1052
+ metrics.css.transformed++;
1053
+ return css;
1054
+ };
1055
+ const cssTask = cssSharedCacheKey ? sharedCssResultCache.get(cssSharedCacheKey) ?? runTransform() : runTransform();
1056
+ if (cssSharedCacheKey && !sharedCssResultCache.has(cssSharedCacheKey)) sharedCssResultCache.set(cssSharedCacheKey, cssTask);
1057
+ const css = await cssTask;
1058
+ onUpdate(file, rawSource, css);
1059
+ debug("css handle: %s", file);
1060
+ return { result: css };
1061
+ }
1062
+ }));
1063
+ continue;
1064
+ }
1065
+ if (type !== "js") continue;
1066
+ metrics.js.total++;
1067
+ const shouldTransformJs = !useIncrementalMode || processFiles.js.has(file);
1068
+ if (!shouldTransformJs) debug("js skip transform (clean), replay cache: %s", file);
1069
+ if (originalSource.type === "chunk") {
1070
+ const absoluteFile = path.resolve(outDir, file);
1071
+ const initialRawSource = originalEntrySource;
1072
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1073
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1074
+ jsTaskFactories.push(async () => {
1075
+ const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1076
+ await processCachedTask({
1077
+ cache,
1078
+ cacheKey: file,
1079
+ hashKey: `${file}:js`,
1080
+ hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
1081
+ applyResult(source) {
1082
+ originalSource.code = source;
1083
+ },
1084
+ onCacheHit() {
1085
+ metrics.js.cacheHits++;
1086
+ debug("js cache hit: %s", file);
1087
+ },
1088
+ async transform() {
1089
+ const start = performance.now();
1090
+ const rawSource = originalSource.code;
1091
+ if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1092
+ const handlerOptions = createHandlerOptions(absoluteFile);
1093
+ if (!disableJsPrecheck && shouldSkipJsTransform(rawSource, handlerOptions)) {
1094
+ metrics.js.elapsed += measureElapsed(start);
1095
+ metrics.js.transformed++;
1096
+ return { result: rawSource };
1097
+ }
1098
+ const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
1099
+ metrics.js.elapsed += measureElapsed(start);
1100
+ metrics.js.transformed++;
1101
+ onUpdate(file, rawSource, code);
1102
+ debug("js handle: %s", file);
1103
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1104
+ applyLinkedUpdates(linked);
1105
+ return { result: code };
1106
+ }
1107
+ });
1108
+ });
1109
+ } else if (uniAppX && originalSource.type === "asset") {
1110
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1111
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1112
+ const baseApplyLinkedUpdates = applyLinkedUpdates;
1113
+ const wrappedApplyLinkedUpdates = (linked) => {
1114
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1115
+ baseApplyLinkedUpdates(linked);
1116
+ };
1117
+ const factory = createUniAppXAssetTask(file, originalSource, outDir, {
1118
+ cache,
1119
+ hashKey: `${file}:js`,
1120
+ hashSalt: createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0),
1121
+ createHandlerOptions,
1122
+ debug,
1123
+ jsHandler,
1124
+ onUpdate,
1125
+ runtimeSet: transformRuntime,
1126
+ applyLinkedResults: wrappedApplyLinkedUpdates,
1127
+ uniAppX
1128
+ });
1129
+ jsTaskFactories.push(async () => {
1130
+ const start = performance.now();
1131
+ if (!shouldTransformJs) {
1132
+ debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
1133
+ await factory();
1134
+ metrics.js.elapsed += measureElapsed(start);
1135
+ metrics.js.transformed++;
1136
+ return;
1137
+ }
1138
+ const currentSource = originalEntrySource;
1139
+ const precheckOptions = createHandlerOptions(path.resolve(outDir, file), {
1140
+ uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
1141
+ babelParserOptions: {
1142
+ plugins: ["typescript"],
1143
+ sourceType: "unambiguous"
1144
+ }
1145
+ });
1146
+ if (!disableJsPrecheck && shouldSkipJsTransform(currentSource, precheckOptions)) {
1147
+ metrics.js.elapsed += measureElapsed(start);
1148
+ metrics.js.transformed++;
1149
+ return;
1150
+ }
1151
+ await factory();
1152
+ metrics.js.elapsed += measureElapsed(start);
1153
+ metrics.js.transformed++;
1154
+ });
1155
+ }
1156
+ }
1157
+ const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1158
+ if (useIncrementalMode) for (const [file, rawSource] of getRememberedMainCssSources?.() ?? []) {
1159
+ if (bundleFiles.includes(file) || getRememberedMainCssSignature?.(file) === cssRuntimeSignature) continue;
1160
+ tasks.push((async () => {
1161
+ const start = performance.now();
1162
+ const cssHandlerOptions = getCssHandlerOptions(file);
1163
+ const generated = await generateCssByGenerator({
1164
+ opts,
1165
+ runtimeState,
1166
+ runtime: generatorRuntime,
1167
+ rawSource,
1168
+ file,
1169
+ cssHandlerOptions,
1170
+ cssUserHandlerOptions: getCssUserHandlerOptions(file),
1171
+ styleHandler,
1172
+ debug
1173
+ });
1174
+ const css = generated?.css ?? (await styleHandler(rawSource, cssHandlerOptions)).css;
1175
+ setRememberedMainCssSignature?.(file, cssRuntimeSignature);
1176
+ if (generated) {
1177
+ registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
1178
+ recordCssAssetResult?.(file, generated.css);
1179
+ debug("css replay generated result: %s bytes=%d", file, css.length);
1180
+ }
1181
+ const replayAsset = createReplayCssAsset(file, css);
1182
+ if (typeof this.emitFile === "function") this.emitFile({
1183
+ type: "asset",
1184
+ fileName: file,
1185
+ source: css
1186
+ });
1187
+ else bundle[file] = replayAsset;
1188
+ markCssAssetProcessed?.(replayAsset, file);
1189
+ metrics.css.elapsed += measureElapsed(start);
1190
+ metrics.css.transformed++;
1191
+ onUpdate(file, rawSource, css);
1192
+ debug("css replay handle: %s", file);
1193
+ })());
1194
+ }
1195
+ pushConcurrentTaskFactories(tasks, jsTaskFactories);
1196
+ await Promise.all(tasks);
1197
+ for (const apply of pendingLinkedUpdates) apply();
1198
+ updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1199
+ debug("metrics iteration=%d runtime=%sms html(total=%d transform=%d hit=%d rate=%s elapsed=%sms) js(total=%d transform=%d hit=%d rate=%s elapsed=%sms) css(total=%d transform=%d hit=%d rate=%s elapsed=%sms)", useIncrementalMode ? state.iteration : 0, formatMs(metrics.runtimeSet), metrics.html.total, metrics.html.transformed, metrics.html.cacheHits, formatCacheHitRate(metrics.html), formatMs(metrics.html.elapsed), metrics.js.total, metrics.js.transformed, metrics.js.cacheHits, formatCacheHitRate(metrics.js), formatMs(metrics.js.elapsed), metrics.css.total, metrics.css.transformed, metrics.css.cacheHits, formatCacheHitRate(metrics.css), formatMs(metrics.css.elapsed));
1200
+ onEnd();
1201
+ debug("end");
1202
+ };
1203
+ }
1204
+ //#endregion
1205
+ //#region src/bundlers/vite/official-tailwind-plugins.ts
1206
+ const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1207
+ function getPostcssPluginName(plugin) {
1208
+ if (!plugin) return;
1209
+ if (typeof plugin === "function" && "postcss" in plugin) try {
1210
+ return getPostcssPluginName(plugin());
1211
+ } catch {
1212
+ return;
1213
+ }
1214
+ if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1215
+ const { postcssPlugin } = plugin;
1216
+ return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1217
+ }
1218
+ function isTailwindPostcssPlugin(plugin) {
1219
+ const name = getPostcssPluginName(plugin);
1220
+ return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1221
+ }
1222
+ function removeTailwindPostcssPlugins(plugins) {
1223
+ let removed = 0;
1224
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1225
+ plugins.splice(i, 1);
1226
+ removed++;
1227
+ }
1228
+ return removed;
1229
+ }
1230
+ function isTailwindVitePlugin(plugin) {
1231
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1232
+ const { name } = plugin;
1233
+ return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1234
+ }
1235
+ function removeTailwindVitePlugins(plugins) {
1236
+ let removed = 0;
1237
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1238
+ plugins.splice(i, 1);
1239
+ removed++;
1240
+ }
1241
+ return removed;
1242
+ }
1243
+ function disableTailwindVitePlugin(plugin) {
1244
+ if (!isTailwindVitePlugin(plugin)) return false;
1245
+ const mutablePlugin = plugin;
1246
+ for (const hook of [
1247
+ "configResolved",
1248
+ "configureServer",
1249
+ "transform",
1250
+ "hotUpdate",
1251
+ "handleHotUpdate"
1252
+ ]) delete mutablePlugin[hook];
1253
+ return true;
1254
+ }
1255
+ function disableAndRemoveTailwindVitePlugins(plugins) {
1256
+ let removed = 0;
1257
+ for (let i = plugins.length - 1; i >= 0; i--) {
1258
+ const plugin = plugins[i];
1259
+ if (Array.isArray(plugin)) {
1260
+ removed += disableAndRemoveTailwindVitePlugins(plugin);
1261
+ if (plugin.length === 0) plugins.splice(i, 1);
1262
+ continue;
1263
+ }
1264
+ if (disableTailwindVitePlugin(plugin)) {
1265
+ plugins.splice(i, 1);
1266
+ removed++;
1267
+ }
1268
+ }
1269
+ return removed;
1270
+ }
1271
+ //#endregion
1272
+ //#region src/bundlers/vite/postcss-config.ts
1273
+ async function resolveFilteredPostcssConfig(root) {
1274
+ try {
1275
+ const loaded = await postcssrc({}, root);
1276
+ const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1277
+ const removed = removeTailwindPostcssPlugins(plugins);
1278
+ if (removed === 0) return;
1279
+ return {
1280
+ options: loaded.options,
1281
+ plugins,
1282
+ removed
1283
+ };
1284
+ } catch (error) {
1285
+ if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1286
+ throw error;
1287
+ }
1288
+ }
1289
+ //#endregion
1290
+ //#region src/bundlers/vite/resolve-app-type.ts
1291
+ const PACKAGE_JSON_FILE$1 = "package.json";
1292
+ const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
1293
+ const TARO_SCRIPT_RE = /\btaro\b/u;
1294
+ const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
1295
+ function resolveDependencyNames(pkg) {
1296
+ return new Set([
1297
+ ...Object.keys(pkg.dependencies ?? {}),
1298
+ ...Object.keys(pkg.devDependencies ?? {}),
1299
+ ...Object.keys(pkg.peerDependencies ?? {}),
1300
+ ...Object.keys(pkg.optionalDependencies ?? {})
1301
+ ]);
1302
+ }
1303
+ function hasScriptMatch(pkg, pattern) {
1304
+ return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
1305
+ }
1306
+ function resolveAppTypeFromPackageJson(pkg) {
1307
+ const dependencyNames = resolveDependencyNames(pkg);
1308
+ if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
1309
+ if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
1310
+ if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
1311
+ if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
1312
+ if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
1313
+ }
1314
+ function tryReadUniAppManifest(root) {
1315
+ const manifestPath = path.join(root, "manifest.json");
1316
+ if (!existsSync(manifestPath)) return;
1317
+ try {
1318
+ return JSON.parse(readFileSync(manifestPath, "utf8"));
1319
+ } catch {}
1320
+ }
1321
+ function tryReadPackageJson(root) {
1322
+ const packageJsonPath = path.join(root, PACKAGE_JSON_FILE$1);
1323
+ if (!existsSync(packageJsonPath)) return;
1324
+ try {
1325
+ return JSON.parse(readFileSync(packageJsonPath, "utf8"));
1326
+ } catch {}
1327
+ }
1328
+ function resolveAppTypeFromMarkers(root) {
1329
+ for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if (existsSync(path.join(root, relativePath))) return appType;
1330
+ }
1331
+ function resolveImplicitAppTypeFromViteRoot(root) {
1332
+ const resolvedRoot = path.resolve(root);
1333
+ if (!existsSync(resolvedRoot)) return;
1334
+ const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
1335
+ if (markerDetected) return markerDetected;
1336
+ let current = resolvedRoot;
1337
+ while (true) {
1338
+ const manifest = tryReadUniAppManifest(current);
1339
+ if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
1340
+ const pkg = tryReadPackageJson(current);
1341
+ if (pkg) {
1342
+ const detected = resolveAppTypeFromPackageJson(pkg);
1343
+ if (detected) return detected;
1344
+ }
1345
+ const parent = path.dirname(current);
1346
+ if (parent === current) break;
1347
+ current = parent;
1348
+ }
1349
+ }
1350
+ //#endregion
1351
+ //#region src/bundlers/shared/css-imports.ts
1352
+ const tailwindcssImportRE = /^tailwindcss(?:\/.*)?$/;
1353
+ const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])(tailwindcss(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
1354
+ function normalizeTailwindcssSpecifier(specifier) {
1355
+ if (specifier === "tailwindcss$") return "tailwindcss";
1356
+ return specifier;
1357
+ }
1358
+ function getTailwindcssSubpath(specifier) {
1359
+ if (specifier === "tailwindcss") return "index.css";
1360
+ return specifier.slice(12);
1361
+ }
1362
+ function resolveTailwindcssImport(specifier, pkgDir, options) {
1363
+ const normalized = normalizeTailwindcssSpecifier(specifier);
1364
+ if (!tailwindcssImportRE.test(normalized)) return null;
1365
+ if (normalized === "tailwindcss") return options?.rootImport ?? "weapp-tailwindcss/index.css";
1366
+ return (options?.join ?? path.join)(pkgDir, getTailwindcssSubpath(normalized));
1367
+ }
1368
+ function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
1369
+ let hasReplacements = false;
1370
+ const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
1371
+ const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
1372
+ if (!replacement) return full;
1373
+ hasReplacements = true;
1374
+ return `${prefix}${quote}${replacement}${suffix}`;
1375
+ });
1376
+ return hasReplacements ? rewritten : void 0;
1377
+ }
1378
+ //#endregion
1379
+ //#region src/bundlers/vite/rewrite-css-imports.ts
1380
+ function joinPosixPath(base, subpath) {
1381
+ if (base.endsWith("/")) return `${base}${subpath}`;
1382
+ return `${base}/${subpath}`;
1383
+ }
1384
+ function isCssLikeImporter(importer) {
1385
+ if (!importer) return false;
1386
+ const normalized = cleanUrl$1(importer);
1387
+ return isCSSRequest(normalized) || normalized.endsWith("/*");
1388
+ }
1389
+ function stripTailwindConfigDirectives(code) {
1390
+ return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
1391
+ }
1392
+ function createRewriteCssImportsPlugins(options) {
1393
+ if (!options.shouldRewrite) return [];
1394
+ const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
1395
+ const resolveAppType = () => getAppType?.() ?? appType;
1396
+ return [{
1397
+ name: `${vitePluginName}:rewrite-css-imports`,
1398
+ enforce: "pre",
1399
+ resolveId: {
1400
+ order: "pre",
1401
+ handler(id, importer) {
1402
+ const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1403
+ join: joinPosixPath,
1404
+ appType: resolveAppType(),
1405
+ rootImport
1406
+ });
1407
+ if (!replacement) return null;
1408
+ if (importer && !isCssLikeImporter(importer)) return null;
1409
+ return replacement;
1410
+ }
1411
+ },
1412
+ transform: {
1413
+ order: "pre",
1414
+ async handler(code, id) {
1415
+ if (!isCSSRequest(id)) return null;
1416
+ if (hasTailwindRootDirectives(code)) await options.onTailwindRootCss?.(id, code);
1417
+ const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1418
+ join: joinPosixPath,
1419
+ appType: resolveAppType(),
1420
+ rootImport
1421
+ });
1422
+ const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? code) : rewritten;
1423
+ if (!nextCode || nextCode === code) return null;
1424
+ return {
1425
+ code: nextCode,
1426
+ map: null
1427
+ };
1428
+ }
1429
+ }
1430
+ }];
1431
+ }
1432
+ //#endregion
1433
+ //#region src/bundlers/vite/runtime-class-set.ts
1434
+ function createViteRuntimeClassSet(options) {
1435
+ const { opts, initialTwPatcher, refreshTailwindcssPatcher, uniAppXEnabled, customAttributesEntities, disabledDefaultTemplateHandler, debug } = options;
1436
+ const runtimeState = {
1437
+ twPatcher: initialTwPatcher,
1438
+ readyPromise: createTailwindRuntimeReadyPromise(initialTwPatcher),
1439
+ refreshTailwindcssPatcher
1440
+ };
1441
+ const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1442
+ let runtimeSet;
1443
+ let runtimeSetPromise;
1444
+ let runtimeRefreshSignature;
1445
+ let runtimeRefreshOptionsKey;
1446
+ function resolveRuntimeRefreshOptions() {
1447
+ const configPath = resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1448
+ const signature = getRuntimeClassSetSignature(runtimeState.twPatcher);
1449
+ const optionsKey = JSON.stringify({
1450
+ appType: opts.appType,
1451
+ uniAppX: uniAppXEnabled,
1452
+ customAttributesEntities,
1453
+ disabledDefaultTemplateHandler,
1454
+ configPath
1455
+ });
1456
+ const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1457
+ runtimeRefreshSignature = signature;
1458
+ runtimeRefreshOptionsKey = optionsKey;
1459
+ return {
1460
+ changed,
1461
+ signature,
1462
+ optionsKey
1463
+ };
1464
+ }
1465
+ async function refreshRuntimeState(force) {
1466
+ const invalidation = resolveRuntimeRefreshOptions();
1467
+ const refreshed = await refreshTailwindRuntimeState(runtimeState, {
1468
+ force: force || invalidation.changed,
1469
+ clearCache: force || invalidation.changed
1470
+ });
1471
+ if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
1472
+ if (refreshed) {
1473
+ runtimeSet = void 0;
1474
+ runtimeSetPromise = void 0;
1475
+ }
1476
+ }
1477
+ async function ensureRuntimeClassSet(force = false) {
1478
+ const forceRuntimeRefresh = force || process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1479
+ await refreshRuntimeState(force);
1480
+ await runtimeState.readyPromise;
1481
+ if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
1482
+ if (forceRuntimeRefresh || !runtimeSetPromise) {
1483
+ const invalidation = resolveRuntimeRefreshOptions();
1484
+ runtimeSetPromise = collectRuntimeClassSet(runtimeState.twPatcher, {
1485
+ force: forceRuntimeRefresh || invalidation.changed,
1486
+ skipRefresh: forceRuntimeRefresh,
1487
+ clearCache: forceRuntimeRefresh || invalidation.changed
1488
+ });
1489
+ }
1490
+ const task = runtimeSetPromise;
1491
+ try {
1492
+ runtimeSet = await task;
1493
+ return runtimeSet;
1494
+ } finally {
1495
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1496
+ }
1497
+ }
1498
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
1499
+ const forceRuntimeRefresh = forceRefresh || process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1500
+ const invalidation = resolveRuntimeRefreshOptions();
1501
+ const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
1502
+ const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
1503
+ await refreshRuntimeState(shouldRefreshPatcher);
1504
+ await runtimeState.readyPromise;
1505
+ if (shouldRefreshPatcher) {
1506
+ runtimeSet = void 0;
1507
+ runtimeSetPromise = void 0;
1508
+ await bundleRuntimeClassSetManager.reset();
1509
+ }
1510
+ if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
1511
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
1512
+ runtimeSet = nextRuntimeSet;
1513
+ return nextRuntimeSet;
1514
+ } catch (error) {
1515
+ debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1516
+ await bundleRuntimeClassSetManager.reset();
1517
+ }
1518
+ if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
1519
+ const task = collectRuntimeClassSet(runtimeState.twPatcher, {
1520
+ force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
1521
+ skipRefresh: forceRuntimeRefresh,
1522
+ clearCache: forceRuntimeRefresh || invalidation.changed
1523
+ });
1524
+ runtimeSetPromise = task;
1525
+ try {
1526
+ runtimeSet = await task;
1527
+ return runtimeSet;
1528
+ } finally {
1529
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1530
+ }
1531
+ }
1532
+ return {
1533
+ runtimeState,
1534
+ refreshRuntimeState,
1535
+ ensureRuntimeClassSet,
1536
+ ensureBundleRuntimeClassSet
1537
+ };
1538
+ }
1539
+ //#endregion
1540
+ //#region src/bundlers/vite/source-candidates.ts
1541
+ const CLEAN_URL_RE = /[?#].*$/;
1542
+ const SOURCE_CANDIDATE_EXTENSIONS = [
1543
+ "js",
1544
+ "jsx",
1545
+ "mjs",
1546
+ "cjs",
1547
+ "ts",
1548
+ "tsx",
1549
+ "mts",
1550
+ "cts",
1551
+ "vue",
1552
+ "uvue",
1553
+ "nvue",
1554
+ "svelte",
1555
+ "mpx",
1556
+ "html",
1557
+ "wxml",
1558
+ "axml",
1559
+ "jxml",
1560
+ "ksml",
1561
+ "ttml",
1562
+ "qml",
1563
+ "tyml",
1564
+ "xhsml",
1565
+ "swan",
1566
+ "css",
1567
+ "wxss",
1568
+ "acss",
1569
+ "jxss",
1570
+ "ttss",
1571
+ "qss",
1572
+ "tyss",
1573
+ "scss",
1574
+ "sass",
1575
+ "less",
1576
+ "styl",
1577
+ "stylus"
1578
+ ];
1579
+ const SOURCE_CANDIDATE_EXTENSION_RE = /\.(?:[cm]?[jt]sx?|vue|uvue|nvue|svelte|mpx|html|wxml|axml|jxml|ksml|ttml|qml|tyml|xhsml|swan|css|wxss|acss|jxss|ttss|qss|tyss|scss|sass|less|stylus?)$/;
1580
+ const CSS_SOURCE_CANDIDATE_EXTENSION_RE = /^(?:css|wxss|acss|jxss|ttss|qss|tyss|scss|sass|less|styl|stylus)$/;
1581
+ const SOURCE_CANDIDATE_GLOB = `**/*.{${SOURCE_CANDIDATE_EXTENSIONS.join(",")}}`;
1582
+ const DEFAULT_SCAN_IGNORE = ["**/node_modules/**", "**/.git/**"];
1583
+ function cleanUrl(id) {
1584
+ return id.replace(CLEAN_URL_RE, "");
1585
+ }
1586
+ function toPosixPath$1(value) {
1587
+ return value.split(path.sep).join("/");
1588
+ }
1589
+ function resolveOutDirIgnorePattern(root, outDir) {
1590
+ if (!outDir) return;
1591
+ const relative = path.relative(root, path.resolve(root, outDir));
1592
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return;
1593
+ return `${toPosixPath$1(relative)}/**`;
1594
+ }
1595
+ function resolveSourceCandidateExtension(id) {
1596
+ const normalized = cleanUrl(id);
1597
+ return /\.([^.\\/]+)$/.exec(normalized)?.[1] ?? "html";
1598
+ }
1599
+ function isSourceCandidateRequest(id) {
1600
+ return SOURCE_CANDIDATE_EXTENSION_RE.test(cleanUrl(id));
1601
+ }
1602
+ function removeCandidateSet(candidateCount, candidates) {
1603
+ for (const candidate of candidates) {
1604
+ const count = candidateCount.get(candidate);
1605
+ if (count == null) continue;
1606
+ if (count <= 1) {
1607
+ candidateCount.delete(candidate);
1608
+ continue;
1609
+ }
1610
+ candidateCount.set(candidate, count - 1);
1611
+ }
1612
+ }
1613
+ function addCandidateSet(candidateCount, candidates) {
1614
+ for (const candidate of candidates) candidateCount.set(candidate, (candidateCount.get(candidate) ?? 0) + 1);
1615
+ }
1616
+ const CSS_APPLY_RE = /@apply\s+([^;{}]+)/g;
1617
+ const CSS_APPLY_IMPORTANT = "!important";
1618
+ function extractCssApplyCandidates(source) {
1619
+ const candidates = /* @__PURE__ */ new Set();
1620
+ CSS_APPLY_RE.lastIndex = 0;
1621
+ let match = CSS_APPLY_RE.exec(source);
1622
+ while (match !== null) {
1623
+ const params = match[1] ?? "";
1624
+ for (const candidate of splitCode(params, true)) {
1625
+ const normalized = candidate.trim();
1626
+ if (normalized && normalized !== CSS_APPLY_IMPORTANT) candidates.add(normalized);
1627
+ }
1628
+ match = CSS_APPLY_RE.exec(source);
1629
+ }
1630
+ return candidates;
1631
+ }
1632
+ function createSourceCandidateCollector() {
1633
+ const candidatesById = /* @__PURE__ */ new Map();
1634
+ const candidateCount = /* @__PURE__ */ new Map();
1635
+ let inlineIncludedCandidates = /* @__PURE__ */ new Set();
1636
+ let inlineExcludedCandidates = /* @__PURE__ */ new Set();
1637
+ async function sync(id, source) {
1638
+ const normalizedId = cleanUrl(id);
1639
+ const extension = resolveSourceCandidateExtension(normalizedId);
1640
+ const nextCandidates = /* @__PURE__ */ new Set();
1641
+ if (CSS_SOURCE_CANDIDATE_EXTENSION_RE.test(extension)) for (const candidate of extractCssApplyCandidates(source)) nextCandidates.add(candidate);
1642
+ else {
1643
+ const matches = await extractRawCandidatesWithPositions(source, extension);
1644
+ for (const match of matches) {
1645
+ const candidate = match.rawCandidate;
1646
+ if (typeof candidate === "string" && candidate.length > 0) nextCandidates.add(candidate);
1647
+ }
1648
+ }
1649
+ remove(normalizedId);
1650
+ if (nextCandidates.size === 0) return;
1651
+ candidatesById.set(normalizedId, nextCandidates);
1652
+ addCandidateSet(candidateCount, nextCandidates);
1653
+ }
1654
+ async function syncFile(id) {
1655
+ const normalizedId = cleanUrl(id);
1656
+ await sync(normalizedId, await readFile(normalizedId, "utf8"));
1657
+ }
1658
+ async function scanRoot({ entries, root, outDir }) {
1659
+ const resolvedRoot = path.resolve(root);
1660
+ const outDirIgnore = resolveOutDirIgnorePattern(resolvedRoot, outDir);
1661
+ const ignore = outDirIgnore ? [...DEFAULT_SCAN_IGNORE, outDirIgnore] : DEFAULT_SCAN_IGNORE;
1662
+ const files = entries ? await expandTailwindSourceEntries(entries, { ignore }) : await fg(SOURCE_CANDIDATE_GLOB, {
1663
+ absolute: true,
1664
+ cwd: resolvedRoot,
1665
+ ignore,
1666
+ onlyFiles: true,
1667
+ unique: true
1668
+ });
1669
+ await Promise.all(files.map((file) => syncFile(file)));
1670
+ }
1671
+ function syncInline(inlineCandidates) {
1672
+ inlineIncludedCandidates = new Set(inlineCandidates?.included ?? []);
1673
+ inlineExcludedCandidates = new Set(inlineCandidates?.excluded ?? []);
1674
+ }
1675
+ function remove(id) {
1676
+ const normalizedId = cleanUrl(id);
1677
+ const previousCandidates = candidatesById.get(normalizedId);
1678
+ if (!previousCandidates) return;
1679
+ removeCandidateSet(candidateCount, previousCandidates);
1680
+ candidatesById.delete(normalizedId);
1681
+ }
1682
+ function values() {
1683
+ const values = new Set([...candidateCount.keys(), ...inlineIncludedCandidates]);
1684
+ for (const candidate of inlineExcludedCandidates) values.delete(candidate);
1685
+ return values;
1686
+ }
1687
+ function clear() {
1688
+ candidatesById.clear();
1689
+ candidateCount.clear();
1690
+ inlineIncludedCandidates.clear();
1691
+ inlineExcludedCandidates.clear();
1692
+ }
1693
+ return {
1694
+ sync,
1695
+ syncFile,
1696
+ scanRoot,
1697
+ syncInline,
1698
+ remove,
1699
+ values,
1700
+ clear
1701
+ };
1702
+ }
1703
+ //#endregion
1704
+ //#region src/bundlers/vite/source-scan.ts
1705
+ const VITE_SOURCE_CANDIDATE_PATTERN = createSourceScanPattern([
1706
+ "js",
1707
+ "jsx",
1708
+ "mjs",
1709
+ "cjs",
1710
+ "ts",
1711
+ "tsx",
1712
+ "mts",
1713
+ "cts",
1714
+ "vue",
1715
+ "uvue",
1716
+ "nvue",
1717
+ "svelte",
1718
+ "mpx",
1719
+ "html",
1720
+ "wxml",
1721
+ "axml",
1722
+ "jxml",
1723
+ "ksml",
1724
+ "ttml",
1725
+ "qml",
1726
+ "tyml",
1727
+ "xhsml",
1728
+ "swan",
1729
+ "css",
1730
+ "wxss",
1731
+ "acss",
1732
+ "jxss",
1733
+ "ttss",
1734
+ "qss",
1735
+ "tyss",
1736
+ "scss",
1737
+ "sass",
1738
+ "less",
1739
+ "styl",
1740
+ "stylus"
1741
+ ]);
1742
+ function parseImportSourceParam(params) {
1743
+ const match = /\bsource\(\s*(none|(['"])(.*?)\2)\s*\)/.exec(params);
1744
+ if (!match) return;
1745
+ return {
1746
+ none: match[1] === "none",
1747
+ sourcePath: match[3]
1748
+ };
1749
+ }
1750
+ function isTailwindCssImport(params) {
1751
+ return /^\s*(['"])tailwindcss(?:\/[^'"]*)?\1/.test(params);
1752
+ }
1753
+ function resolveSourceBase(base, sourcePath) {
1754
+ return path.isAbsolute(sourcePath) ? sourcePath : path.resolve(base, sourcePath);
1755
+ }
1756
+ async function resolveTailwindV4EntriesFromCss(css, base) {
1757
+ let root;
1758
+ try {
1759
+ root = postcss.parse(css);
1760
+ } catch {
1761
+ return;
1762
+ }
1763
+ let importSourceBase;
1764
+ let hasSourceNone = false;
1765
+ const entries = await resolveCssSourceEntries(root, base, VITE_SOURCE_CANDIDATE_PATTERN);
1766
+ const inlineCandidates = collectCssInlineSourceCandidates(root);
1767
+ root.walkAtRules("import", (rule) => {
1768
+ if (!isTailwindCssImport(rule.params)) return;
1769
+ const sourceParam = parseImportSourceParam(rule.params);
1770
+ if (sourceParam?.none) hasSourceNone = true;
1771
+ if (sourceParam?.sourcePath) importSourceBase = resolveSourceBase(base, sourceParam.sourcePath);
1772
+ });
1773
+ if (importSourceBase) return {
1774
+ entries: [{
1775
+ base: importSourceBase,
1776
+ negated: false,
1777
+ pattern: VITE_SOURCE_CANDIDATE_PATTERN
1778
+ }, ...entries],
1779
+ explicit: true,
1780
+ inlineCandidates
1781
+ };
1782
+ if (hasSourceNone) return {
1783
+ entries,
1784
+ explicit: true,
1785
+ inlineCandidates
1786
+ };
1787
+ return entries.length > 0 ? {
1788
+ entries,
1789
+ explicit: true,
1790
+ inlineCandidates
1791
+ } : inlineCandidates.included.size > 0 || inlineCandidates.excluded.size > 0 ? {
1792
+ entries: [],
1793
+ explicit: true,
1794
+ inlineCandidates
1795
+ } : void 0;
1796
+ }
1797
+ function collectExistingCssEntries(options) {
1798
+ return [
1799
+ ...options.cssEntries ?? [],
1800
+ ...options.tailwindcss?.v4?.cssEntries ?? [],
1801
+ ...options.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssEntries ?? []
1802
+ ].filter((item) => typeof item === "string" && item.length > 0).map((item) => path.resolve(item)).filter((item) => existsSync(item));
1803
+ }
1804
+ function mergeInlineCandidates(allInlineCandidates) {
1805
+ const merged = {
1806
+ included: /* @__PURE__ */ new Set(),
1807
+ excluded: /* @__PURE__ */ new Set()
1808
+ };
1809
+ for (const inlineCandidates of allInlineCandidates) {
1810
+ if (!inlineCandidates) continue;
1811
+ for (const candidate of inlineCandidates.included) if (!merged.excluded.has(candidate)) merged.included.add(candidate);
1812
+ for (const candidate of inlineCandidates.excluded) {
1813
+ merged.excluded.add(candidate);
1814
+ merged.included.delete(candidate);
1815
+ }
1816
+ }
1817
+ return merged.included.size > 0 || merged.excluded.size > 0 ? merged : void 0;
1818
+ }
1819
+ async function resolveViteSourceScanEntries(options, patcher) {
1820
+ if (patcher.majorVersion === 3) {
1821
+ const source = await resolveTailwindV3SourceFromPatcher(patcher);
1822
+ const contentEntries = normalizeLegacyContentEntries(source.configObject?.content, source.config ? path.dirname(source.config) : source.cwd);
1823
+ return contentEntries.length > 0 ? { entries: contentEntries } : void 0;
1824
+ }
1825
+ if (patcher.majorVersion === 4) {
1826
+ const sourceOptions = resolveTailwindV4SourceOptionsFromPatcher(patcher);
1827
+ const cssEntries = collectExistingCssEntries(options);
1828
+ const entries = [];
1829
+ const cssInlineCandidates = [];
1830
+ for (const cssEntry of cssEntries) {
1831
+ const resolved = await resolveTailwindV4EntriesFromCss(readFileSync(cssEntry, "utf8"), path.dirname(cssEntry));
1832
+ if (resolved) {
1833
+ entries.push(...resolved.entries);
1834
+ cssInlineCandidates.push(resolved.inlineCandidates);
1835
+ }
1836
+ }
1837
+ const inlineCandidates = mergeInlineCandidates(cssInlineCandidates);
1838
+ if (entries.length > 0 || inlineCandidates) return {
1839
+ entries,
1840
+ inlineCandidates
1841
+ };
1842
+ if (typeof sourceOptions.css === "string" && sourceOptions.css.length > 0) {
1843
+ const resolved = await resolveTailwindV4EntriesFromCss(sourceOptions.css, sourceOptions.base ?? sourceOptions.projectRoot ?? process.cwd());
1844
+ return resolved ? {
1845
+ entries: resolved.entries,
1846
+ inlineCandidates: resolved.inlineCandidates
1847
+ } : void 0;
1848
+ }
1849
+ const source = await resolveTailwindV4SourceFromPatcher(patcher);
1850
+ const resolved = await resolveTailwindV4EntriesFromCss(source.css, source.base);
1851
+ return resolved ? {
1852
+ entries: resolved.entries,
1853
+ inlineCandidates: resolved.inlineCandidates
1854
+ } : void 0;
1855
+ }
1856
+ }
1857
+ function toPosixPath(value) {
1858
+ return value.split(path.sep).join("/");
1859
+ }
1860
+ function createViteSourceScanMatcher(entries) {
1861
+ if (!entries?.length) return;
1862
+ const positiveEntries = entries.filter((entry) => !entry.negated);
1863
+ const negativeEntries = entries.filter((entry) => entry.negated);
1864
+ if (positiveEntries.length === 0) return () => false;
1865
+ return (file) => {
1866
+ const resolvedFile = path.resolve(file);
1867
+ if (!positiveEntries.some((entry) => {
1868
+ const relative = toPosixPath(path.relative(path.resolve(entry.base), resolvedFile));
1869
+ return relative && !relative.startsWith("../") && !path.isAbsolute(relative) && micromatch.isMatch(relative, entry.pattern);
1870
+ })) return false;
1871
+ return !negativeEntries.some((entry) => {
1872
+ const relative = toPosixPath(path.relative(path.resolve(entry.base), resolvedFile));
1873
+ return relative && !relative.startsWith("../") && !path.isAbsolute(relative) && micromatch.isMatch(relative, entry.pattern);
1874
+ });
1875
+ };
1876
+ }
1877
+ //#endregion
1878
+ //#region src/bundlers/vite/tailwind-basedir.ts
1879
+ const PACKAGE_JSON_FILE = "package.json";
1880
+ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1881
+ const resolvedRoot = path.resolve(root);
1882
+ if (!existsSync(resolvedRoot)) return resolvedRoot;
1883
+ const searchRoots = [];
1884
+ let current = resolvedRoot;
1885
+ while (true) {
1886
+ searchRoots.push(current);
1887
+ const parent = path.dirname(current);
1888
+ if (parent === current) break;
1889
+ current = parent;
1890
+ }
1891
+ const tailwindConfigPath = findTailwindConfig(searchRoots);
1892
+ if (tailwindConfigPath) return path.dirname(tailwindConfigPath);
1893
+ const packageRoot = findNearestPackageRoot(resolvedRoot);
1894
+ if (packageRoot && existsSync(path.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1895
+ return resolvedRoot;
1896
+ }
1897
+ //#endregion
1898
+ //#region src/bundlers/vite/index.ts
1899
+ const debug = createDebug();
1900
+ const weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
1901
+ const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1902
+ function normalizeSignaturePath(value) {
1903
+ return slash(path.resolve(value));
1904
+ }
1905
+ function serializeInlineCandidates(inlineCandidates) {
1906
+ return {
1907
+ excluded: [...inlineCandidates?.excluded ?? []].sort(),
1908
+ included: [...inlineCandidates?.included ?? []].sort()
1909
+ };
1910
+ }
1911
+ function serializeSourceEntries(entries) {
1912
+ return (entries ?? []).map((entry) => ({
1913
+ base: normalizeSignaturePath(entry.base),
1914
+ negated: entry.negated,
1915
+ pattern: entry.pattern
1916
+ })).sort((a, b) => `${a.base}\0${a.pattern}\0${a.negated}`.localeCompare(`${b.base}\0${b.pattern}\0${b.negated}`));
1917
+ }
1918
+ function createSourceCandidateScanSignature(input) {
1919
+ return JSON.stringify({
1920
+ inlineCandidates: serializeInlineCandidates(input.inlineCandidates),
1921
+ outDir: input.outDir ? normalizeSignaturePath(input.outDir) : void 0,
1922
+ roots: input.roots.map((root) => ({
1923
+ entries: serializeSourceEntries(root.entries),
1924
+ root: normalizeSignaturePath(root.root)
1925
+ }))
1926
+ });
1927
+ }
1928
+ /**
1929
+ * @name WeappTailwindcss
1930
+ * @description uni-app vite / uni-app-x 版本插件
1931
+ * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
1932
+ */
1933
+ function WeappTailwindcss(options = {}) {
1934
+ const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
1935
+ const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1936
+ const opts = getCompilerContext({
1937
+ ...options,
1938
+ __internalDeferMissingCssEntriesWarning: true
1939
+ });
1940
+ const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
1941
+ const uniAppXEnabled = isUniAppXEnabled(uniAppX);
1942
+ const disabledOptions = resolvePluginDisabledState(disabled);
1943
+ const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1944
+ const shouldOwnTailwindGeneration = !disabledOptions.plugin;
1945
+ const shouldRewriteCssImports = tailwindcssMajorVersion >= 4;
1946
+ const hasInitialTailwindCssRoots = hasConfiguredTailwindV4CssRoots({
1947
+ ...options,
1948
+ cssEntries: opts.cssEntries ?? options.cssEntries
1949
+ });
1950
+ const autoCssSourceContent = /* @__PURE__ */ new Map();
1951
+ let refreshRuntimeStateForAutoCssSources;
1952
+ let autoCssSourcesRefresh;
1953
+ const registerAutoCssSource = async (id, css) => {
1954
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots) return;
1955
+ const file = cleanUrl$1(id);
1956
+ if (!path.isAbsolute(file)) return;
1957
+ const sourceFile = path.normalize(file);
1958
+ if (autoCssSourceContent.get(sourceFile) === css) return;
1959
+ autoCssSourceContent.set(sourceFile, css);
1960
+ upsertTailwindV4CssSource(opts, {
1961
+ file: sourceFile,
1962
+ css
1963
+ });
1964
+ debug("detected tailwindcss v4 css source from vite css module: %s", sourceFile);
1965
+ autoCssSourcesRefresh = (autoCssSourcesRefresh ?? Promise.resolve()).then(async () => {
1966
+ await refreshRuntimeStateForAutoCssSources?.(true);
1967
+ });
1968
+ await autoCssSourcesRefresh;
1969
+ };
1970
+ const rewritePlugins = createRewriteCssImportsPlugins({
1971
+ getAppType: () => opts.appType,
1972
+ rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
1973
+ onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
1974
+ shouldOwnTailwindGeneration,
1975
+ shouldRewrite: shouldRewriteCssImports,
1976
+ weappTailwindcssDirPosix
1977
+ });
1978
+ if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
1979
+ const customAttributesEntities = toCustomAttributesEntities(customAttributes);
1980
+ let resolvedConfig;
1981
+ let recordedGeneratorCandidates;
1982
+ const sourceCandidateCollector = createSourceCandidateCollector();
1983
+ let sourceScanEntries;
1984
+ let sourceScanMatcher;
1985
+ let sourceCandidateScanSignature;
1986
+ const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
1987
+ const processedCssAssets = /* @__PURE__ */ new WeakSet();
1988
+ const processedCssAssetFiles = /* @__PURE__ */ new Set();
1989
+ const rememberedMainCssSources = /* @__PURE__ */ new Map();
1990
+ const rememberedMainCssSignatureByFile = /* @__PURE__ */ new Map();
1991
+ const { runtimeState, refreshRuntimeState, ensureRuntimeClassSet, ensureBundleRuntimeClassSet } = createViteRuntimeClassSet({
1992
+ opts,
1993
+ initialTwPatcher,
1994
+ refreshTailwindcssPatcher,
1995
+ uniAppXEnabled,
1996
+ customAttributesEntities,
1997
+ disabledDefaultTemplateHandler,
1998
+ debug
1999
+ });
2000
+ refreshRuntimeStateForAutoCssSources = refreshRuntimeState;
2001
+ onLoad();
2002
+ const getResolvedConfig = () => resolvedConfig;
2003
+ const markCssAssetProcessed = (asset, file) => {
2004
+ processedCssAssets.add(asset);
2005
+ if (file) processedCssAssetFiles.add(normalizeOutputPathKey(file));
2006
+ };
2007
+ const isCssAssetProcessed = (asset, file) => {
2008
+ return processedCssAssets.has(asset) || (file ? processedCssAssetFiles.has(normalizeOutputPathKey(file)) : false);
2009
+ };
2010
+ const recordGeneratorCandidates = (candidates) => {
2011
+ recordedGeneratorCandidates = new Set(candidates);
2012
+ };
2013
+ const getRecordedGeneratorCandidates = () => recordedGeneratorCandidates;
2014
+ const getSourceCandidates = () => sourceCandidateCollector.values();
2015
+ const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
2016
+ const collectSourceCandidateScanRoots = (root, entries) => {
2017
+ const roots = [{
2018
+ entries,
2019
+ root
2020
+ }];
2021
+ const normalizedRoot = path.resolve(root);
2022
+ const seenRoots = new Set([normalizedRoot]);
2023
+ const basedir = opts.tailwindcssBasedir ? path.resolve(opts.tailwindcssBasedir) : void 0;
2024
+ if (basedir && !seenRoots.has(basedir)) {
2025
+ roots.push({ root: basedir });
2026
+ seenRoots.add(basedir);
2027
+ }
2028
+ for (const cssEntry of opts.tailwindcss?.cssEntries ?? []) {
2029
+ const cssEntryRoot = path.dirname(path.resolve(cssEntry));
2030
+ if (seenRoots.has(cssEntryRoot)) continue;
2031
+ roots.push({ root: cssEntryRoot });
2032
+ seenRoots.add(cssEntryRoot);
2033
+ }
2034
+ return roots;
2035
+ };
2036
+ const scanSourceCandidateRoots = async (roots, outDir) => {
2037
+ await Promise.all(roots.map((root) => sourceCandidateCollector.scanRoot({
2038
+ entries: root.entries,
2039
+ root: root.root,
2040
+ outDir
2041
+ })));
2042
+ };
2043
+ const waitForSourceCandidateSyncs = async () => {
2044
+ while (pendingSourceCandidateSyncs.size > 0) await Promise.all(pendingSourceCandidateSyncs);
2045
+ };
2046
+ const syncChangedSourceCandidateFile = (id) => {
2047
+ if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return Promise.resolve();
2048
+ const file = cleanUrl$1(id);
2049
+ if (sourceScanMatcher && !sourceScanMatcher(file)) {
2050
+ sourceCandidateCollector.remove(file);
2051
+ return Promise.resolve();
2052
+ }
2053
+ const task = sourceCandidateCollector.syncFile(id).catch((error) => {
2054
+ debug("source candidate watch sync failed: %s %O", id, error);
2055
+ }).finally(() => {
2056
+ pendingSourceCandidateSyncs.delete(task);
2057
+ });
2058
+ pendingSourceCandidateSyncs.add(task);
2059
+ return task;
2060
+ };
2061
+ const rememberMainCssSource = (file, rawSource, cssRuntimeSignature) => {
2062
+ rememberedMainCssSources.set(file, rawSource);
2063
+ if (cssRuntimeSignature) rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2064
+ };
2065
+ const getRememberedMainCssSources = () => rememberedMainCssSources;
2066
+ const getRememberedMainCssSignature = (file) => rememberedMainCssSignatureByFile.get(file);
2067
+ const setRememberedMainCssSignature = (file, cssRuntimeSignature) => {
2068
+ rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2069
+ };
2070
+ const generateBundleHook = createGenerateBundleHook({
2071
+ opts,
2072
+ runtimeState,
2073
+ ensureRuntimeClassSet,
2074
+ ensureBundleRuntimeClassSet,
2075
+ debug,
2076
+ getResolvedConfig,
2077
+ markCssAssetProcessed,
2078
+ getSourceCandidates,
2079
+ waitForSourceCandidateSyncs,
2080
+ rememberMainCssSource,
2081
+ getRememberedMainCssSources,
2082
+ getRememberedMainCssSignature,
2083
+ setRememberedMainCssSignature,
2084
+ recordGeneratorCandidates
2085
+ });
2086
+ const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
2087
+ opts,
2088
+ runtimeState,
2089
+ ensureRuntimeClassSet,
2090
+ debug,
2091
+ getResolvedConfig,
2092
+ markCssAssetProcessed,
2093
+ isCssAssetProcessed,
2094
+ getRecordedGeneratorCandidates,
2095
+ getSourceCandidates,
2096
+ waitForSourceCandidateSyncs,
2097
+ rememberMainCssSource
2098
+ });
2099
+ const isIosPlatform = resolveUniUtsPlatform().isAppIos;
2100
+ const uniAppXPlugins = uniAppXEnabled ? createUniAppXPlugins({
2101
+ appType: opts.appType ?? "uni-app-x",
2102
+ customAttributesEntities,
2103
+ disabledDefaultTemplateHandler,
2104
+ isIosPlatform,
2105
+ mainCssChunkMatcher,
2106
+ runtimeState,
2107
+ styleHandler,
2108
+ jsHandler,
2109
+ ensureRuntimeClassSet,
2110
+ getResolvedConfig,
2111
+ uniAppX
2112
+ }) : void 0;
2113
+ const plugins = [
2114
+ ...rewritePlugins,
2115
+ {
2116
+ name: `${vitePluginName}:source-candidates`,
2117
+ enforce: "pre",
2118
+ async transform(code, id) {
2119
+ if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return;
2120
+ const file = cleanUrl$1(id);
2121
+ if (sourceScanMatcher && !sourceScanMatcher(file)) {
2122
+ sourceCandidateCollector.remove(file);
2123
+ return;
2124
+ }
2125
+ await sourceCandidateCollector.sync(id, code);
2126
+ },
2127
+ async watchChange(id, change) {
2128
+ if (change.event === "delete") {
2129
+ sourceCandidateCollector.remove(id);
2130
+ return;
2131
+ }
2132
+ await syncChangedSourceCandidateFile(id);
2133
+ },
2134
+ async handleHotUpdate(ctx) {
2135
+ await syncChangedSourceCandidateFile(ctx.file);
2136
+ },
2137
+ async buildStart() {
2138
+ if (!shouldOwnTailwindGeneration) return;
2139
+ const root = resolvedConfig?.root ?? process.cwd();
2140
+ const outDir = resolvedConfig?.build?.outDir;
2141
+ const sourceScan = await resolveViteSourceScanEntries(opts, runtimeState.twPatcher);
2142
+ sourceScanEntries = sourceScan?.entries;
2143
+ sourceScanMatcher = createViteSourceScanMatcher(sourceScanEntries);
2144
+ const roots = collectSourceCandidateScanRoots(root, sourceScanEntries);
2145
+ const nextScanSignature = createSourceCandidateScanSignature({
2146
+ inlineCandidates: sourceScan?.inlineCandidates,
2147
+ outDir,
2148
+ roots
2149
+ });
2150
+ if (isWatchBuild() && sourceCandidateScanSignature === nextScanSignature) {
2151
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2152
+ debug("reuse vite source candidate scan for watch rebuild");
2153
+ return;
2154
+ }
2155
+ sourceCandidateCollector.clear();
2156
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2157
+ await scanSourceCandidateRoots(roots, outDir);
2158
+ sourceCandidateScanSignature = nextScanSignature;
2159
+ }
2160
+ },
2161
+ {
2162
+ name: `${vitePluginName}:post`,
2163
+ enforce: "post",
2164
+ config(config) {
2165
+ if (!shouldOwnTailwindGeneration) return;
2166
+ if (Array.isArray(config.plugins)) {
2167
+ const removed = disableAndRemoveTailwindVitePlugins(config.plugins);
2168
+ if (removed > 0) debug("disable official tailwind vite plugins in generator mode: %d", removed);
2169
+ }
2170
+ const root = config.root ? path.resolve(config.root) : process.cwd();
2171
+ const baseConfig = { resolve: { alias: [{
2172
+ find: /^tailwindcss$/,
2173
+ replacement: path.join(weappTailwindcssPackageDir, "generator-placeholder.css")
2174
+ }] } };
2175
+ if (config.css?.postcss !== void 0) return baseConfig;
2176
+ return resolveFilteredPostcssConfig(root).then((postcssConfig) => {
2177
+ if (!postcssConfig) return baseConfig;
2178
+ debug("inline filtered postcss config without official tailwind plugins in generator mode: %d", postcssConfig.removed);
2179
+ return {
2180
+ ...baseConfig,
2181
+ css: { postcss: {
2182
+ ...postcssConfig.options,
2183
+ plugins: postcssConfig.plugins
2184
+ } }
2185
+ };
2186
+ });
2187
+ },
2188
+ async configResolved(config) {
2189
+ resolvedConfig = config;
2190
+ if (shouldOwnTailwindGeneration) {
2191
+ const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
2192
+ if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
2193
+ }
2194
+ const resolvedRoot = config.root ? path.resolve(config.root) : void 0;
2195
+ let shouldRefreshRuntime = false;
2196
+ if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
2197
+ const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
2198
+ if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
2199
+ const previousBasedir = opts.tailwindcssBasedir;
2200
+ opts.tailwindcssBasedir = nextTailwindcssBasedir;
2201
+ debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
2202
+ shouldRefreshRuntime = true;
2203
+ }
2204
+ }
2205
+ if (!hasExplicitAppType && resolvedRoot) {
2206
+ const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
2207
+ if (nextAppType && opts.appType !== nextAppType) {
2208
+ const previousAppType = opts.appType;
2209
+ opts.appType = nextAppType;
2210
+ logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
2211
+ debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
2212
+ shouldRefreshRuntime = true;
2213
+ }
2214
+ }
2215
+ if (shouldRefreshRuntime) await refreshRuntimeState(true);
2216
+ if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
2217
+ const postcssPlugins = config.css.postcss.plugins;
2218
+ if (shouldOwnTailwindGeneration) {
2219
+ const removed = removeTailwindPostcssPlugins(postcssPlugins);
2220
+ if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
2221
+ }
2222
+ const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
2223
+ if (idx > -1) {
2224
+ postcssPlugins.splice(idx, 1, postcssHtmlTransform());
2225
+ debug("remove postcss-html-transform plugin from vite config");
2226
+ }
2227
+ }
2228
+ },
2229
+ generateBundle: {
2230
+ order: "post",
2231
+ handler: generateBundleHook
2232
+ },
2233
+ outputOptions(options) {
2234
+ const plugins = options.plugins;
2235
+ return {
2236
+ ...options,
2237
+ plugins: Array.isArray(plugins) ? [...plugins, cssFinalizerOutputPlugin] : [cssFinalizerOutputPlugin]
2238
+ };
2239
+ }
2240
+ }
2241
+ ];
2242
+ if (uniAppXPlugins) plugins.push(...uniAppXPlugins);
2243
+ return plugins;
2244
+ }
2245
+ //#endregion
2246
+ export { WeappTailwindcss as t };