weapp-tailwindcss 4.12.0 → 5.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/dist/babel/index.d.ts +3 -0
  2. package/dist/bundlers/gulp/index.d.ts +7 -0
  3. package/dist/bundlers/shared/cache.d.ts +16 -0
  4. package/dist/bundlers/shared/css-cleanup.d.ts +4 -0
  5. package/dist/bundlers/shared/css-imports.d.ts +8 -0
  6. package/dist/bundlers/shared/generator-candidates.d.ts +5 -0
  7. package/dist/bundlers/shared/generator-css.d.ts +41 -0
  8. package/dist/bundlers/shared/module-graph.d.ts +5 -0
  9. package/dist/bundlers/shared/run-tasks.d.ts +2 -0
  10. package/dist/bundlers/vite/bundle-entries.d.ts +14 -0
  11. package/dist/bundlers/vite/bundle-state.d.ts +43 -0
  12. package/dist/bundlers/vite/css-finalizer.d.ts +19 -0
  13. package/dist/bundlers/vite/generate-bundle.d.ts +20 -0
  14. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +21 -0
  15. package/dist/bundlers/vite/index.d.ts +3 -0
  16. package/dist/bundlers/vite/js-precheck.d.ts +1 -0
  17. package/dist/bundlers/vite/query.d.ts +15 -0
  18. package/dist/bundlers/vite/resolve-app-type.d.ts +2 -0
  19. package/dist/bundlers/vite/rewrite-css-imports.d.ts +11 -0
  20. package/dist/bundlers/vite/runtime-affecting-signature.d.ts +2 -0
  21. package/dist/bundlers/vite/utils.d.ts +9 -0
  22. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +20 -0
  23. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-assets.d.ts +14 -0
  24. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-loaders.d.ts +15 -0
  25. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4.d.ts +9 -0
  26. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +17 -0
  27. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +19 -0
  28. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +9 -0
  29. package/dist/bundlers/webpack/index.d.ts +1 -0
  30. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +12 -0
  31. package/dist/bundlers/webpack/loaders/weapp-tw-runtime-classset-loader.d.ts +11 -0
  32. package/dist/bundlers/webpack/shared/css-imports.d.ts +6 -0
  33. package/dist/bundlers/webpack/shared/loader-anchors.d.ts +8 -0
  34. package/dist/cache/index.d.ts +38 -0
  35. package/dist/cache/md5.d.ts +1 -0
  36. package/dist/chunk-8l464Juk.js +28 -0
  37. package/dist/cli/config.d.ts +5 -0
  38. package/dist/cli/context.d.ts +16 -0
  39. package/dist/cli/doctor/constants.d.ts +7 -0
  40. package/dist/cli/doctor/types.d.ts +31 -0
  41. package/dist/cli/doctor.d.ts +4 -0
  42. package/dist/cli/helpers/options/format.d.ts +2 -0
  43. package/dist/cli/helpers/options/parse.d.ts +3 -0
  44. package/dist/cli/helpers/options/resolve.d.ts +1 -0
  45. package/dist/cli/helpers/options.d.ts +3 -0
  46. package/dist/cli/helpers/patch-cwd.d.ts +1 -0
  47. package/dist/cli/helpers.d.ts +5 -0
  48. package/dist/cli/mount-options/patch-status.d.ts +2 -0
  49. package/dist/cli/mount-options.d.ts +2 -0
  50. package/dist/cli/patch-options.d.ts +6 -0
  51. package/dist/cli/tokens.d.ts +4 -0
  52. package/dist/cli/types.d.ts +17 -0
  53. package/dist/cli/vscode-entry.d.ts +14 -0
  54. package/dist/cli/workspace/package-dirs.d.ts +3 -0
  55. package/dist/cli/workspace/patch-package.d.ts +3 -0
  56. package/dist/cli/workspace/patch-utils.d.ts +3 -0
  57. package/dist/cli/workspace/types.d.ts +11 -0
  58. package/dist/cli/workspace/workspace-globs.d.ts +2 -0
  59. package/dist/cli/workspace/workspace-io.d.ts +1 -0
  60. package/dist/cli/workspace/workspace-lock.d.ts +1 -0
  61. package/dist/cli/workspace.d.ts +2 -0
  62. package/dist/cli.d.ts +1 -2
  63. package/dist/cli.js +2425 -3524
  64. package/dist/cli.mjs +2402 -3505
  65. package/dist/constants-B-_T5UnW.mjs +44 -0
  66. package/dist/constants-p1dyh1x1.js +73 -0
  67. package/dist/constants.d.ts +13 -0
  68. package/dist/context/compiler-context-cache.d.ts +3 -0
  69. package/dist/context/custom-attributes.d.ts +2 -0
  70. package/dist/context/handlers.d.ts +6 -0
  71. package/dist/context/index.d.ts +7 -0
  72. package/dist/context/logger.d.ts +4 -0
  73. package/dist/context/tailwindcss/basedir.d.ts +1 -0
  74. package/dist/context/tailwindcss/rax.d.ts +2 -0
  75. package/dist/context/tailwindcss.d.ts +4 -0
  76. package/dist/context/workspace.d.ts +3 -0
  77. package/dist/core.d.ts +5 -21
  78. package/dist/core.js +138 -180
  79. package/dist/core.mjs +135 -180
  80. package/dist/css-imports-BbrbluP9.js +177 -0
  81. package/dist/css-imports-CSdPq_Sc.mjs +128 -0
  82. package/dist/css-macro/constants.d.ts +14 -0
  83. package/dist/css-macro/index.d.ts +15 -0
  84. package/dist/css-macro/postcss.d.ts +3 -7
  85. package/dist/css-macro/postcss.js +44 -58
  86. package/dist/css-macro/postcss.mjs +44 -56
  87. package/dist/css-macro.d.ts +1 -20
  88. package/dist/css-macro.js +37 -50
  89. package/dist/css-macro.mjs +33 -47
  90. package/dist/debug/index.d.ts +5 -0
  91. package/dist/defaults.d.ts +2 -11
  92. package/dist/defaults.js +132 -8
  93. package/dist/defaults.mjs +128 -7
  94. package/dist/escape.js +31 -54
  95. package/dist/escape.mjs +18 -25
  96. package/dist/experimental/index.d.ts +2 -0
  97. package/dist/experimental/oxc/ast-utils.d.ts +30 -0
  98. package/dist/experimental/oxc/index.d.ts +2 -0
  99. package/dist/experimental/oxc/module-specifiers.d.ts +2 -0
  100. package/dist/experimental/shared/cache.d.ts +3 -0
  101. package/dist/experimental/shared/transform.d.ts +3 -0
  102. package/dist/experimental/shared.d.ts +8 -0
  103. package/dist/experimental/swc/ast-utils.d.ts +30 -0
  104. package/dist/experimental/swc/index.d.ts +2 -0
  105. package/dist/experimental/swc/module-specifiers.d.ts +2 -0
  106. package/dist/generator/index.d.ts +11 -0
  107. package/dist/generator/options.d.ts +15 -0
  108. package/dist/generator/types.d.ts +19 -0
  109. package/dist/generator-CZ-JXw6T.js +492 -0
  110. package/dist/generator-Dwxgra97.mjs +399 -0
  111. package/dist/generator-css-CnYjiMrD.js +1084 -0
  112. package/dist/generator-css-DhPFjSzK.mjs +1057 -0
  113. package/dist/generator.d.ts +1 -0
  114. package/dist/generator.js +19 -0
  115. package/dist/generator.mjs +2 -0
  116. package/dist/gulp.d.ts +4 -24
  117. package/dist/gulp.js +271 -13
  118. package/dist/gulp.mjs +263 -13
  119. package/dist/index.d.ts +8 -15
  120. package/dist/index.js +12 -24
  121. package/dist/index.mjs +6 -24
  122. package/dist/js/JsTokenUpdater.d.ts +14 -0
  123. package/dist/js/ModuleGraph.d.ts +18 -0
  124. package/dist/js/NodePathWalker.d.ts +33 -0
  125. package/dist/js/babel/parse.d.ts +9 -0
  126. package/dist/js/babel/process.d.ts +4 -0
  127. package/dist/js/babel.d.ts +13 -0
  128. package/dist/js/class-context.d.ts +3 -0
  129. package/dist/js/evalTransforms.d.ts +7 -0
  130. package/dist/js/handlers.d.ts +5 -0
  131. package/dist/js/index.d.ts +4 -0
  132. package/dist/js/module-graph/ignored-exports.d.ts +18 -0
  133. package/dist/js/module-graph/types.d.ts +17 -0
  134. package/dist/js/node-path-walker/export-handlers.d.ts +12 -0
  135. package/dist/js/node-path-walker/import-tokens.d.ts +24 -0
  136. package/dist/js/precheck.d.ts +2 -0
  137. package/dist/js/sourceAnalysis.d.ts +17 -0
  138. package/dist/js/syntax.d.ts +10 -0
  139. package/dist/js/taggedTemplateIgnore.d.ts +13 -0
  140. package/dist/js/types.d.ts +11 -0
  141. package/dist/lightningcss/index.d.ts +8 -0
  142. package/dist/lightningcss/style-handler/options.d.ts +3 -0
  143. package/dist/lightningcss/style-handler/selector-transform.d.ts +10 -0
  144. package/dist/lightningcss/style-handler/selector-utils.d.ts +10 -0
  145. package/dist/lightningcss/style-handler.d.ts +17 -0
  146. package/dist/loader-anchors-DvwgIYdA.mjs +205 -0
  147. package/dist/loader-anchors-cprm4Klq.js +273 -0
  148. package/dist/logger/index.d.ts +2 -0
  149. package/dist/logger-BZ45DZJT.js +1003 -0
  150. package/dist/logger-BoVx1Dbt.mjs +935 -0
  151. package/dist/patcher-options-6gJN2EXy.js +115 -0
  152. package/dist/patcher-options-DQfR5xxT.mjs +92 -0
  153. package/dist/postcss-html-transform.d.ts +3 -3
  154. package/dist/postcss-html-transform.js +7 -10
  155. package/dist/postcss-html-transform.mjs +3 -6
  156. package/dist/postcss.d.ts +15 -0
  157. package/dist/postcss.js +278 -0
  158. package/dist/postcss.mjs +268 -0
  159. package/dist/presets/hbuilderx.d.ts +4 -0
  160. package/dist/presets/index.d.ts +3 -0
  161. package/dist/presets/shared.d.ts +10 -0
  162. package/dist/presets/taro.d.ts +4 -0
  163. package/dist/presets/uni-app-x.d.ts +16 -0
  164. package/dist/presets/uni-app.d.ts +4 -0
  165. package/dist/presets.d.ts +1 -76
  166. package/dist/presets.js +115 -163
  167. package/dist/presets.mjs +107 -163
  168. package/dist/recorder-B_XyZ576.mjs +2763 -0
  169. package/dist/recorder-rn_2v_nd.js +2878 -0
  170. package/dist/reset/index.d.ts +2 -0
  171. package/dist/reset.d.ts +1 -4
  172. package/dist/reset.js +19 -8
  173. package/dist/reset.mjs +2 -8
  174. package/dist/shared/classname-transform.d.ts +14 -0
  175. package/dist/shared/mpx.d.ts +7 -0
  176. package/dist/shared/tailwindcss-css-redirect.d.ts +1 -0
  177. package/dist/tailwindcss/index.d.ts +11 -0
  178. package/dist/tailwindcss/miniprogram.d.ts +1 -0
  179. package/dist/tailwindcss/patcher-options.d.ts +56 -0
  180. package/dist/tailwindcss/patcher-resolve.d.ts +4 -0
  181. package/dist/tailwindcss/patcher.d.ts +13 -0
  182. package/dist/tailwindcss/recorder.d.ts +13 -0
  183. package/dist/tailwindcss/remove-unsupported-css.d.ts +2 -0
  184. package/dist/tailwindcss/runtime/cache.d.ts +11 -0
  185. package/dist/tailwindcss/runtime-logs.d.ts +3 -0
  186. package/dist/tailwindcss/runtime.d.ts +29 -0
  187. package/dist/tailwindcss/targets/paths.d.ts +13 -0
  188. package/dist/tailwindcss/targets/record-io.d.ts +5 -0
  189. package/dist/tailwindcss/targets/recorder.d.ts +3 -0
  190. package/dist/tailwindcss/targets/types.d.ts +35 -0
  191. package/dist/tailwindcss/targets.d.ts +6 -0
  192. package/dist/tailwindcss/v3-engine/generator.d.ts +2 -0
  193. package/dist/tailwindcss/v3-engine/index.d.ts +4 -0
  194. package/dist/tailwindcss/v3-engine/miniprogram.d.ts +4 -0
  195. package/dist/tailwindcss/v3-engine/source.d.ts +5 -0
  196. package/dist/tailwindcss/v3-engine/types.d.ts +55 -0
  197. package/dist/tailwindcss/v4/config.d.ts +5 -0
  198. package/dist/tailwindcss/v4/css-entries.d.ts +7 -0
  199. package/dist/tailwindcss/v4/index.d.ts +2 -0
  200. package/dist/tailwindcss/v4/multi-patcher.d.ts +2 -0
  201. package/dist/tailwindcss/v4/patcher-options.d.ts +24 -0
  202. package/dist/tailwindcss/v4/patcher.d.ts +14 -0
  203. package/dist/tailwindcss/v4-engine/design-system.d.ts +1 -0
  204. package/dist/tailwindcss/v4-engine/generator.d.ts +2 -0
  205. package/dist/tailwindcss/v4-engine/index.d.ts +5 -0
  206. package/dist/tailwindcss/v4-engine/miniprogram.d.ts +4 -0
  207. package/dist/tailwindcss/v4-engine/source.d.ts +7 -0
  208. package/dist/tailwindcss/v4-engine/types.d.ts +17 -0
  209. package/dist/typedoc.export.d.ts +5 -0
  210. package/dist/types/base.d.ts +1 -0
  211. package/dist/types/disabled-options.d.ts +4 -0
  212. package/dist/types/index.d.ts +104 -0
  213. package/dist/types/shared.d.ts +7 -0
  214. package/dist/types/user-defined-options/general.d.ts +31 -0
  215. package/dist/types/user-defined-options/important.d.ts +37 -0
  216. package/dist/types/user-defined-options/index.d.ts +11 -0
  217. package/dist/types/user-defined-options/lifecycle.d.ts +6 -0
  218. package/dist/types/user-defined-options/matcher.d.ts +9 -0
  219. package/dist/types.d.ts +1 -150
  220. package/dist/types.js +0 -1
  221. package/dist/types.mjs +1 -1
  222. package/dist/uni-app-x/component-local-style.d.ts +19 -0
  223. package/dist/uni-app-x/index.d.ts +2 -0
  224. package/dist/uni-app-x/options.d.ts +12 -0
  225. package/dist/uni-app-x/style-isolation.d.ts +2 -0
  226. package/dist/uni-app-x/transform.d.ts +9 -0
  227. package/dist/uni-app-x/vite.d.ts +36 -0
  228. package/dist/utils/decode.d.ts +2 -0
  229. package/dist/utils/disabled.d.ts +6 -0
  230. package/dist/utils/hbuilderx.d.ts +5 -0
  231. package/dist/utils/index.d.ts +7 -0
  232. package/dist/utils/nameMatcher.d.ts +4 -0
  233. package/dist/utils/resolve-package.d.ts +1 -0
  234. package/dist/utils/uni-platform.d.ts +11 -0
  235. package/dist/utils-7DUGTFED.mjs +48 -0
  236. package/dist/utils-DmC9_In3.js +61 -0
  237. package/dist/vite-BHpAqldo.js +1952 -0
  238. package/dist/vite-C8JlHiyR.mjs +1940 -0
  239. package/dist/vite.d.ts +4 -17
  240. package/dist/vite.js +5 -14
  241. package/dist/vite.mjs +2 -14
  242. package/dist/weapp-tw-css-import-rewrite-loader.js +59 -92
  243. package/dist/weapp-tw-runtime-classset-loader.js +31 -50
  244. package/dist/webpack-CABjKGGQ.mjs +441 -0
  245. package/dist/webpack-DNIJ0ysE.js +456 -0
  246. package/dist/webpack.d.ts +4 -25
  247. package/dist/webpack.js +6 -17
  248. package/dist/webpack.mjs +2 -17
  249. package/dist/webpack4.d.ts +4 -26
  250. package/dist/webpack4.js +375 -481
  251. package/dist/webpack4.mjs +366 -482
  252. package/dist/wxml/Tokenizer.d.ts +15 -0
  253. package/dist/wxml/custom-attributes.d.ts +4 -0
  254. package/dist/wxml/index.d.ts +2 -0
  255. package/dist/wxml/shared.d.ts +2 -0
  256. package/dist/wxml/tokenizer/types.d.ts +18 -0
  257. package/dist/wxml/utils/codegen/legacy-rewriter.d.ts +2 -0
  258. package/dist/wxml/utils/codegen/legacy-visitor.d.ts +8 -0
  259. package/dist/wxml/utils/codegen.d.ts +2 -0
  260. package/dist/wxml/utils/custom-template.d.ts +3 -0
  261. package/dist/wxml/utils/fragment-helpers.d.ts +6 -0
  262. package/dist/wxml/utils/fragment-updater.d.ts +4 -0
  263. package/dist/wxml/utils/template-fragments.d.ts +3 -0
  264. package/dist/wxml/utils.d.ts +8 -0
  265. package/dist/wxml/whitespace.d.ts +2 -0
  266. package/generator-placeholder.css +1 -0
  267. package/package.json +19 -5
  268. package/dist/chunk-24AGZQVR.js +0 -183
  269. package/dist/chunk-3VQKDHGP.mjs +0 -179
  270. package/dist/chunk-4AFQP74Z.js +0 -24
  271. package/dist/chunk-57SOQCAU.mjs +0 -582
  272. package/dist/chunk-5ZYHNDEK.mjs +0 -2439
  273. package/dist/chunk-76S2EME4.mjs +0 -34
  274. package/dist/chunk-A5PB4KZT.js +0 -138
  275. package/dist/chunk-DUHYLR2R.js +0 -276
  276. package/dist/chunk-DYLQ6UOI.js +0 -71
  277. package/dist/chunk-E7I5TW5K.js +0 -52
  278. package/dist/chunk-FS2NOOEB.js +0 -292
  279. package/dist/chunk-HVNGIKLS.js +0 -3930
  280. package/dist/chunk-JZQBZHN5.js +0 -579
  281. package/dist/chunk-KGTVD4EP.mjs +0 -3930
  282. package/dist/chunk-NNOQDMUP.mjs +0 -10
  283. package/dist/chunk-OF6MFURR.js +0 -34
  284. package/dist/chunk-OFB2KBRP.js +0 -2442
  285. package/dist/chunk-OOHJLO5M.mjs +0 -71
  286. package/dist/chunk-PCDYXXSK.mjs +0 -1515
  287. package/dist/chunk-RKISS72P.js +0 -7
  288. package/dist/chunk-RRQZL7FQ.mjs +0 -292
  289. package/dist/chunk-XAKAD2CR.mjs +0 -138
  290. package/dist/chunk-XZP3MREK.mjs +0 -276
  291. package/dist/chunk-ZAA5ZG3D.js +0 -1518
  292. package/dist/chunk-ZCH4YINE.mjs +0 -52
  293. package/dist/cli.d.mts +0 -2
  294. package/dist/core.d.mts +0 -26
  295. package/dist/css-macro/postcss.d.mts +0 -7
  296. package/dist/css-macro.d.mts +0 -18
  297. package/dist/defaults.d.mts +0 -11
  298. package/dist/gulp.d.mts +0 -24
  299. package/dist/index-BXrmQelt.d.mts +0 -672
  300. package/dist/index-BXrmQelt.d.ts +0 -672
  301. package/dist/index.d.mts +0 -15
  302. package/dist/postcss-html-transform.d.mts +0 -2
  303. package/dist/presets.d.mts +0 -76
  304. package/dist/reset.d.mts +0 -1
  305. package/dist/types.d.mts +0 -150
  306. package/dist/vite.d.mts +0 -17
  307. package/dist/webpack.d.mts +0 -25
  308. package/dist/webpack4.d.mts +0 -26
@@ -0,0 +1,1952 @@
1
+ const require_chunk = require("./chunk-8l464Juk.js");
2
+ const require_generator = require("./generator-CZ-JXw6T.js");
3
+ const require_patcher_options = require("./patcher-options-6gJN2EXy.js");
4
+ const require_recorder = require("./recorder-rn_2v_nd.js");
5
+ const require_utils = require("./utils-DmC9_In3.js");
6
+ const require_logger = require("./logger-BZ45DZJT.js");
7
+ const require_generator_css = require("./generator-css-CnYjiMrD.js");
8
+ const require_css_imports = require("./css-imports-BbrbluP9.js");
9
+ let node_path = require("node:path");
10
+ node_path = require_chunk.__toESM(node_path);
11
+ let node_process = require("node:process");
12
+ node_process = require_chunk.__toESM(node_process);
13
+ let tailwindcss_patch = require("tailwindcss-patch");
14
+ let node_buffer = require("node:buffer");
15
+ let node_fs = require("node:fs");
16
+ node_fs = require_chunk.__toESM(node_fs);
17
+ let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
18
+ let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
19
+ let magic_string = require("magic-string");
20
+ magic_string = require_chunk.__toESM(magic_string);
21
+ let _weapp_tailwindcss_shared_extractors = require("@weapp-tailwindcss/shared/extractors");
22
+ let htmlparser2 = require("htmlparser2");
23
+ let _weapp_tailwindcss_postcss_html_transform = require("@weapp-tailwindcss/postcss/html-transform");
24
+ _weapp_tailwindcss_postcss_html_transform = require_chunk.__toESM(_weapp_tailwindcss_postcss_html_transform);
25
+ let postcss_load_config = require("postcss-load-config");
26
+ postcss_load_config = require_chunk.__toESM(postcss_load_config);
27
+ let _vue_compiler_dom = require("@vue/compiler-dom");
28
+ let _vue_compiler_sfc = require("@vue/compiler-sfc");
29
+ let comment_json = require("comment-json");
30
+ //#region src/uni-app-x/component-local-style.ts
31
+ const EXPRESSION_WRAPPER_PREFIX = "(\n";
32
+ const EXPRESSION_WRAPPER_SUFFIX = "\n)";
33
+ const COMPONENT_RE = /(?:^|[/\\])components(?:[/\\].+)?\.(?:uvue|nvue)$/;
34
+ function createStableHash(input) {
35
+ let hash = 2166136261;
36
+ for (let i = 0; i < input.length; i++) {
37
+ hash ^= input.charCodeAt(i);
38
+ hash = Math.imul(hash, 16777619);
39
+ }
40
+ return (hash >>> 0).toString(36);
41
+ }
42
+ function extractLiteralValue(path) {
43
+ const allowDoubleQuotes = path.isTemplateElement();
44
+ if (path.isStringLiteral()) return {
45
+ allowDoubleQuotes,
46
+ literal: path.node.value,
47
+ offset: 1
48
+ };
49
+ return {
50
+ allowDoubleQuotes,
51
+ literal: typeof path.node.value === "string" ? path.node.value : path.node.value.raw,
52
+ offset: 0
53
+ };
54
+ }
55
+ function createAlias(fileId, utility, index) {
56
+ return `wtu-${createStableHash(`${fileId}:${utility}`)}-${index.toString(36)}`;
57
+ }
58
+ function isRuntimeCandidate(candidate, runtimeSet) {
59
+ if (!runtimeSet || runtimeSet.size === 0) return false;
60
+ return runtimeSet.has(candidate) || runtimeSet.has(require_recorder.replaceWxml(candidate));
61
+ }
62
+ function shouldEnableComponentLocalStyle(id) {
63
+ return COMPONENT_RE.test(id);
64
+ }
65
+ var UniAppXComponentLocalStyleCollector = class {
66
+ constructor(fileId, runtimeSet) {
67
+ this.fileId = fileId;
68
+ this.runtimeSet = runtimeSet;
69
+ this.aliasByUtility = /* @__PURE__ */ new Map();
70
+ this.aliasByLookup = /* @__PURE__ */ new Map();
71
+ }
72
+ ensureAlias(utility) {
73
+ const cached = this.aliasByUtility.get(utility);
74
+ if (cached) return cached;
75
+ const alias = createAlias(this.fileId, utility, this.aliasByUtility.size);
76
+ this.aliasByUtility.set(utility, alias);
77
+ this.aliasByLookup.set(utility, alias);
78
+ this.aliasByLookup.set(require_recorder.replaceWxml(utility), alias);
79
+ return alias;
80
+ }
81
+ rewriteLiteral(literal, shouldInclude) {
82
+ const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal);
83
+ if (candidates.length === 0) return literal;
84
+ let rewritten = literal;
85
+ for (const candidate of candidates) {
86
+ if (!shouldInclude(candidate)) continue;
87
+ rewritten = rewritten.replace(candidate, this.ensureAlias(candidate));
88
+ }
89
+ return rewritten;
90
+ }
91
+ collectAndRewriteStaticClass(literal) {
92
+ return this.rewriteLiteral(literal, (candidate) => isRuntimeCandidate(candidate, this.runtimeSet));
93
+ }
94
+ collectRuntimeClasses(rawSource, options = {}) {
95
+ const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
96
+ try {
97
+ const analysis = require_recorder.analyzeSource(require_recorder.babelParse(wrapped, {
98
+ plugins: ["typescript"],
99
+ sourceType: options.wrapExpression ? "module" : "unambiguous"
100
+ }), {}, void 0, false);
101
+ for (const path of analysis.targetPaths) {
102
+ const { literal, allowDoubleQuotes } = extractLiteralValue(path);
103
+ const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
104
+ const classContext = options.wrapExpression || require_recorder.isClassContextLiteralPath(path);
105
+ for (const candidate of candidates) {
106
+ if (!candidate || !classContext && !isRuntimeCandidate(candidate, this.runtimeSet)) continue;
107
+ if (isRuntimeCandidate(candidate, this.runtimeSet)) this.ensureAlias(candidate);
108
+ }
109
+ }
110
+ } catch {}
111
+ }
112
+ rewriteTransformedCode(rawSource, options = {}) {
113
+ if (this.aliasByLookup.size === 0) return rawSource;
114
+ const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
115
+ try {
116
+ const analysis = require_recorder.analyzeSource(require_recorder.babelParse(wrapped, {
117
+ plugins: ["typescript"],
118
+ sourceType: options.wrapExpression ? "module" : "unambiguous"
119
+ }), {}, void 0, false);
120
+ if (analysis.targetPaths.length === 0) return rawSource;
121
+ const updater = new require_recorder.JsTokenUpdater();
122
+ for (const path of analysis.targetPaths) {
123
+ const { literal, allowDoubleQuotes, offset } = extractLiteralValue(path);
124
+ const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
125
+ if (candidates.length === 0) continue;
126
+ let rewritten = literal;
127
+ let mutated = false;
128
+ for (const candidate of candidates) {
129
+ const alias = this.aliasByLookup.get(candidate);
130
+ if (!alias) continue;
131
+ const replaced = rewritten.replace(candidate, alias);
132
+ if (replaced !== rewritten) {
133
+ rewritten = replaced;
134
+ mutated = true;
135
+ }
136
+ }
137
+ if (!mutated || typeof path.node.start !== "number" || typeof path.node.end !== "number") continue;
138
+ updater.addToken({
139
+ start: path.node.start + offset,
140
+ end: path.node.end - offset,
141
+ value: rewritten,
142
+ path
143
+ });
144
+ }
145
+ if (updater.length === 0) return rawSource;
146
+ const ms = new magic_string.default(wrapped);
147
+ updater.updateMagicString(ms);
148
+ if (options.wrapExpression) {
149
+ ms.remove(0, 2);
150
+ ms.remove(wrapped.length - 2, wrapped.length);
151
+ }
152
+ return ms.toString();
153
+ } catch {
154
+ return rawSource;
155
+ }
156
+ }
157
+ hasStyles() {
158
+ return this.aliasByUtility.size > 0;
159
+ }
160
+ toStyleBlock() {
161
+ if (!this.hasStyles()) return "";
162
+ const lines = ["<style scoped>"];
163
+ for (const [utility, alias] of this.aliasByUtility) {
164
+ lines.push(`.${alias} {`);
165
+ lines.push(` @apply ${utility};`);
166
+ lines.push("}");
167
+ }
168
+ lines.push("</style>");
169
+ return `${lines.join("\n")}\n`;
170
+ }
171
+ };
172
+ //#endregion
173
+ //#region src/uni-app-x/transform.ts
174
+ function traverse(node, visitor) {
175
+ visitor(node);
176
+ if (Array.isArray(node.children)) {
177
+ for (const child of node.children) if (child && typeof child === "object" && "type" in child) traverse(child, visitor);
178
+ }
179
+ }
180
+ function updateStaticAttribute(ms, prop, content = prop.value?.content) {
181
+ if (!prop.value) return;
182
+ const start = prop.value.loc.start.offset + 1;
183
+ const end = prop.value.loc.end.offset - 1;
184
+ if (start < end) ms.update(start, end, require_recorder.replaceWxml(content ?? ""));
185
+ }
186
+ function updateStaticAttributeWithLocalStyle(ms, prop, collector, content = prop.value?.content) {
187
+ if (!prop.value) return;
188
+ const start = prop.value.loc.start.offset + 1;
189
+ const end = prop.value.loc.end.offset - 1;
190
+ if (start < end) ms.update(start, end, collector.collectAndRewriteStaticClass(content ?? ""));
191
+ }
192
+ function updateDirectiveExpression(ms, prop, jsHandler, runtimeSet) {
193
+ if (prop.exp?.type !== _vue_compiler_dom.NodeTypes.SIMPLE_EXPRESSION) return;
194
+ const expression = prop.exp.content;
195
+ const start = prop.exp.loc.start.offset;
196
+ const end = prop.exp.loc.end.offset;
197
+ if (start >= end) return;
198
+ const generated = require_recorder.generateCode(expression, {
199
+ jsHandler,
200
+ runtimeSet,
201
+ wrapExpression: true
202
+ });
203
+ ms.update(start, end, generated);
204
+ }
205
+ function updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, collector, runtimeSet) {
206
+ if (prop.exp?.type !== _vue_compiler_dom.NodeTypes.SIMPLE_EXPRESSION) return;
207
+ const expression = prop.exp.content;
208
+ const start = prop.exp.loc.start.offset;
209
+ const end = prop.exp.loc.end.offset;
210
+ if (start >= end) return;
211
+ collector.collectRuntimeClasses(expression, { wrapExpression: true });
212
+ const generated = require_recorder.generateCode(expression, {
213
+ jsHandler,
214
+ runtimeSet,
215
+ wrapExpression: true
216
+ });
217
+ ms.update(start, end, collector.rewriteTransformedCode(generated, { wrapExpression: true }));
218
+ }
219
+ function shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute) {
220
+ const lowerName = attrName.toLowerCase();
221
+ const shouldHandleDefault = !disabledDefaultTemplateHandler && lowerName === "class";
222
+ const shouldHandleCustom = matchCustomAttribute?.(tag, attrName) ?? false;
223
+ return {
224
+ shouldHandleDefault,
225
+ shouldHandleCustom,
226
+ shouldHandle: shouldHandleDefault || shouldHandleCustom
227
+ };
228
+ }
229
+ const defaultCreateJsHandlerOptions = { babelParserOptions: { plugins: ["typescript"] } };
230
+ const UVUE_NVUE_RE$1 = /\.(?:uvue|nvue)(?:\?.*)?$/;
231
+ function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
232
+ if (!UVUE_NVUE_RE$1.test(id)) return;
233
+ const { customAttributesEntities, disabledDefaultTemplateHandler = false } = options;
234
+ const matchCustomAttribute = require_recorder.createAttributeMatcher(customAttributesEntities);
235
+ const ms = new magic_string.default(code);
236
+ const { descriptor, errors } = (0, _vue_compiler_sfc.parse)(code);
237
+ const localStyleCollector = options.enableComponentLocalStyle && shouldEnableComponentLocalStyle(id) ? new UniAppXComponentLocalStyleCollector(id, runtimeSet) : void 0;
238
+ if (errors.length === 0) {
239
+ if (descriptor.template?.ast) traverse(descriptor.template.ast, (node) => {
240
+ if (node.type !== _vue_compiler_dom.NodeTypes.ELEMENT) return;
241
+ const tag = node.tag;
242
+ for (const prop of node.props) if (prop.type === _vue_compiler_dom.NodeTypes.ATTRIBUTE) {
243
+ const { shouldHandle, shouldHandleDefault } = shouldHandleAttribute(tag, prop.name, disabledDefaultTemplateHandler, matchCustomAttribute);
244
+ if (!shouldHandle) continue;
245
+ if (shouldHandleDefault && localStyleCollector) updateStaticAttributeWithLocalStyle(ms, prop, localStyleCollector);
246
+ else updateStaticAttribute(ms, prop);
247
+ if (shouldHandleDefault) continue;
248
+ } else if (prop.type === _vue_compiler_dom.NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === _vue_compiler_dom.NodeTypes.SIMPLE_EXPRESSION && prop.arg.isStatic) {
249
+ const attrName = prop.arg.content;
250
+ const { shouldHandle } = shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute);
251
+ if (!shouldHandle) continue;
252
+ if (attrName.toLowerCase() === "class" && localStyleCollector) updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, localStyleCollector, runtimeSet);
253
+ else updateDirectiveExpression(ms, prop, jsHandler, runtimeSet);
254
+ }
255
+ });
256
+ if (descriptor.script) {
257
+ localStyleCollector?.collectRuntimeClasses(descriptor.script.content);
258
+ const { code } = jsHandler(descriptor.script.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
259
+ ms.update(descriptor.script.loc.start.offset, descriptor.script.loc.end.offset, localStyleCollector ? localStyleCollector.rewriteTransformedCode(code) : code);
260
+ }
261
+ if (descriptor.scriptSetup) {
262
+ localStyleCollector?.collectRuntimeClasses(descriptor.scriptSetup.content);
263
+ const { code } = jsHandler(descriptor.scriptSetup.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
264
+ ms.update(descriptor.scriptSetup.loc.start.offset, descriptor.scriptSetup.loc.end.offset, localStyleCollector ? localStyleCollector.rewriteTransformedCode(code) : code);
265
+ }
266
+ if (localStyleCollector?.hasStyles()) ms.append(`\n${localStyleCollector.toStyleBlock()}`);
267
+ }
268
+ const result = {
269
+ code: ms.toString(),
270
+ map: null
271
+ };
272
+ Object.defineProperty(result, "map", {
273
+ configurable: true,
274
+ enumerable: true,
275
+ get() {
276
+ return ms.generateMap();
277
+ }
278
+ });
279
+ return result;
280
+ }
281
+ //#endregion
282
+ //#region src/bundlers/vite/query.ts
283
+ function parseVueRequest(id) {
284
+ const [filename, rawQuery] = id.split(`?`, 2);
285
+ const searchParams = new URLSearchParams(rawQuery);
286
+ const query = Object.fromEntries(searchParams);
287
+ if (query.vue != null) query.vue = true;
288
+ if (query.index != null) query.index = Number(query.index);
289
+ if (query.raw != null) query.raw = true;
290
+ if (query.url != null) query.url = true;
291
+ if (query.scoped != null) query.scoped = true;
292
+ const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
293
+ const langType = query.lang || (langTypeMatch ? langTypeMatch.slice(5) : void 0);
294
+ if (langType) query.lang = langType;
295
+ return {
296
+ filename,
297
+ query
298
+ };
299
+ }
300
+ //#endregion
301
+ //#region src/bundlers/vite/utils.ts
302
+ function slash(p) {
303
+ return (0, _weapp_tailwindcss_shared.ensurePosix)(p);
304
+ }
305
+ const isWindows = node_process.default.platform === "win32";
306
+ const cssLangRE = new RegExp(`\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`);
307
+ function isCSSRequest(request) {
308
+ return cssLangRE.test(request);
309
+ }
310
+ function normalizePath(id) {
311
+ return node_path.default.posix.normalize(isWindows ? (0, _weapp_tailwindcss_shared.ensurePosix)(id) : id);
312
+ }
313
+ async function formatPostcssSourceMap(rawMap, file) {
314
+ const inputFileDir = node_path.default.dirname(file);
315
+ const sources = rawMap.sources.map((source) => {
316
+ const cleanSource = (0, _weapp_tailwindcss_shared.cleanUrl)(decodeURIComponent(source));
317
+ if (cleanSource[0] === "<" && cleanSource.endsWith(">")) return `\0${cleanSource}`;
318
+ return normalizePath(node_path.default.resolve(inputFileDir, cleanSource));
319
+ });
320
+ return {
321
+ file,
322
+ mappings: rawMap.mappings,
323
+ names: rawMap.names,
324
+ sources,
325
+ sourcesContent: rawMap.sourcesContent,
326
+ version: rawMap.version
327
+ };
328
+ }
329
+ //#endregion
330
+ //#region src/uni-app-x/style-isolation.ts
331
+ const manifestCache = /* @__PURE__ */ new Map();
332
+ function resolveUniAppXStyleIsolationEnabled(root) {
333
+ if (!root) return false;
334
+ const normalizedRoot = node_path.default.resolve(root);
335
+ const cached = manifestCache.get(normalizedRoot);
336
+ if (cached !== void 0) return cached;
337
+ const manifestPath = node_path.default.join(normalizedRoot, "manifest.json");
338
+ let enabled = false;
339
+ try {
340
+ enabled = `${(0, comment_json.parse)(node_fs.default.readFileSync(manifestPath, "utf8"))["uni-app-x"]?.styleIsolationVersion ?? ""}` === "2";
341
+ } catch {
342
+ enabled = false;
343
+ }
344
+ manifestCache.set(normalizedRoot, enabled);
345
+ return enabled;
346
+ }
347
+ //#endregion
348
+ //#region src/uni-app-x/vite.ts
349
+ const preprocessorLangs = new Set([
350
+ "scss",
351
+ "sass",
352
+ "less",
353
+ "styl",
354
+ "stylus"
355
+ ]);
356
+ const INLINE_LANG_RE = /lang\.([a-z]+)/i;
357
+ const PREPROCESSOR_EXT_RE = /\.(?:scss|sass|less|styl|stylus)(?:\?|$)/i;
358
+ const UVUE_NVUE_QUERY_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
359
+ const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
360
+ function isPreprocessorRequest(id, lang) {
361
+ const normalizedLang = lang?.toLowerCase();
362
+ if (normalizedLang && preprocessorLangs.has(normalizedLang)) return true;
363
+ const inlineLangMatch = id.match(INLINE_LANG_RE);
364
+ if (inlineLangMatch && preprocessorLangs.has(inlineLangMatch[1].toLowerCase())) return true;
365
+ return PREPROCESSOR_EXT_RE.test(id);
366
+ }
367
+ function resolveUniAppXCssTarget(id) {
368
+ return UVUE_NVUE_RE.test((0, _weapp_tailwindcss_shared.cleanUrl)(id)) ? "uvue" : void 0;
369
+ }
370
+ function resolveUniAppXJsTransformEnabled$1(uniAppX) {
371
+ return uniAppX === void 0 ? true : require_logger.isUniAppXEnabled(uniAppX);
372
+ }
373
+ function createUniAppXPlugins(options) {
374
+ const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, jsHandler, ensureRuntimeClassSet, getResolvedConfig, uniAppX } = options;
375
+ const resolvedUniAppXOptions = require_logger.resolveUniAppXOptions(uniAppX);
376
+ const isIosPlatform = providedIosPlatform ?? require_utils.resolveUniUtsPlatform().isAppIos;
377
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
378
+ let componentLocalStyleEnabled;
379
+ function shouldEnableComponentLocalStyle() {
380
+ if (!resolvedUniAppXOptions.componentLocalStyles.enabled) {
381
+ componentLocalStyleEnabled = false;
382
+ return false;
383
+ }
384
+ if (!resolvedUniAppXOptions.componentLocalStyles.onlyWhenStyleIsolationVersion2) {
385
+ componentLocalStyleEnabled = true;
386
+ return true;
387
+ }
388
+ if (componentLocalStyleEnabled !== void 0) return componentLocalStyleEnabled;
389
+ const root = getResolvedConfig()?.root;
390
+ componentLocalStyleEnabled = resolveUniAppXStyleIsolationEnabled(root);
391
+ return componentLocalStyleEnabled;
392
+ }
393
+ async function transformStyle(code, id, query) {
394
+ const parsed = query ?? parseVueRequest(id).query;
395
+ if (isCSSRequest(id) || parsed.vue && parsed.type === "style") {
396
+ const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
397
+ let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
398
+ if (!styleHandlerOptions) {
399
+ styleHandlerOptions = {
400
+ isMainChunk: mainCssChunkMatcher(id, appType),
401
+ uniAppXCssTarget: resolveUniAppXCssTarget(id),
402
+ uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
403
+ postcssOptions: { options: {
404
+ from: id,
405
+ map: {
406
+ inline: false,
407
+ annotation: false,
408
+ sourcesContent: true
409
+ }
410
+ } }
411
+ };
412
+ cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
413
+ }
414
+ const postcssResult = await styleHandler(code, styleHandlerOptions);
415
+ const warnings = typeof postcssResult.warnings === "function" ? postcssResult.warnings() : [];
416
+ for (const warning of warnings) _weapp_tailwindcss_logger.logger.warn(warning.toString());
417
+ const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), (0, _weapp_tailwindcss_shared.cleanUrl)(id));
418
+ return {
419
+ code: postcssResult.css,
420
+ map: postcssMap
421
+ };
422
+ }
423
+ }
424
+ const cssPlugins = [{
425
+ name: "weapp-tailwindcss:uni-app-x:css",
426
+ async transform(code, id) {
427
+ await runtimeState.patchPromise;
428
+ return transformStyle(code, id);
429
+ }
430
+ }, {
431
+ name: "weapp-tailwindcss:uni-app-x:css:pre",
432
+ enforce: "pre",
433
+ async transform(code, id) {
434
+ await runtimeState.patchPromise;
435
+ const { query } = parseVueRequest(id);
436
+ const lang = query.lang;
437
+ if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
438
+ return transformStyle(code, id, query);
439
+ }
440
+ }];
441
+ const nvuePlugin = {
442
+ name: "weapp-tailwindcss:uni-app-x:nvue",
443
+ enforce: "pre",
444
+ async buildStart() {
445
+ await ensureRuntimeClassSet(true);
446
+ },
447
+ async transform(code, id) {
448
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
449
+ const resolvedConfig = getResolvedConfig();
450
+ const isServeCommand = resolvedConfig?.command === "serve";
451
+ const isWatchBuild = resolvedConfig?.command === "build" && !!resolvedConfig.build?.watch;
452
+ const isNonWatchBuild = resolvedConfig?.command === "build" && !resolvedConfig.build?.watch;
453
+ const currentRuntimeSet = isServeCommand || isWatchBuild || isNonWatchBuild ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
454
+ const extraOptions = customAttributesEntities.length > 0 || disabledDefaultTemplateHandler ? {
455
+ customAttributesEntities,
456
+ disabledDefaultTemplateHandler,
457
+ enableComponentLocalStyle: shouldEnableComponentLocalStyle()
458
+ } : void 0;
459
+ if (extraOptions) return transformUVue(code, id, jsHandler, currentRuntimeSet, extraOptions);
460
+ if (shouldEnableComponentLocalStyle()) return transformUVue(code, id, jsHandler, currentRuntimeSet, { enableComponentLocalStyle: true });
461
+ return transformUVue(code, id, jsHandler, currentRuntimeSet);
462
+ },
463
+ async handleHotUpdate(ctx) {
464
+ if (getResolvedConfig()?.command !== "serve") return;
465
+ if (!UVUE_NVUE_RE.test(ctx.file)) return;
466
+ await ensureRuntimeClassSet(true);
467
+ },
468
+ async watchChange(id) {
469
+ const resolvedConfig = getResolvedConfig();
470
+ if (resolvedConfig?.command !== "build" || !resolvedConfig.build?.watch) return;
471
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
472
+ await ensureRuntimeClassSet(true);
473
+ }
474
+ };
475
+ return [...cssPlugins, nvuePlugin];
476
+ }
477
+ function createUniAppXAssetTask(file, originalSource, outDir, options) {
478
+ return async () => {
479
+ const { cache, hashKey, createHandlerOptions, debug, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
480
+ const absoluteFile = require_css_imports.toAbsoluteOutputPath(file, outDir);
481
+ const rawSource = originalSource.source.toString();
482
+ await require_generator_css.processCachedTask({
483
+ cache,
484
+ cacheKey: file,
485
+ hashKey,
486
+ rawSource: options.hashSalt ? `${rawSource}\n/*${options.hashSalt}*/` : rawSource,
487
+ applyResult(source) {
488
+ originalSource.source = source;
489
+ },
490
+ onCacheHit() {
491
+ debug("js cache hit: %s", file);
492
+ },
493
+ async transform() {
494
+ const currentSource = originalSource.source.toString();
495
+ const { code, linked } = await jsHandler(currentSource, runtimeSet, createHandlerOptions(absoluteFile, {
496
+ uniAppX: resolveUniAppXJsTransformEnabled$1(options.uniAppX),
497
+ babelParserOptions: {
498
+ plugins: ["typescript"],
499
+ sourceType: "unambiguous"
500
+ }
501
+ }));
502
+ onUpdate(file, currentSource, code);
503
+ debug("js handle: %s", file);
504
+ applyLinkedResults(linked);
505
+ return { result: code };
506
+ }
507
+ });
508
+ };
509
+ }
510
+ //#endregion
511
+ //#region src/bundlers/shared/generator-candidates.ts
512
+ async function collectGeneratorCandidatesFromSources(sources, baseCandidates = []) {
513
+ const candidates = new Set(baseCandidates);
514
+ await Promise.all(sources.map(async (source) => {
515
+ const matches = await (0, tailwindcss_patch.extractRawCandidatesWithPositions)(source.content, source.extension);
516
+ for (const match of matches) {
517
+ const candidate = match.rawCandidate;
518
+ if (typeof candidate === "string" && candidate.length > 0) candidates.add(candidate);
519
+ }
520
+ }));
521
+ return candidates;
522
+ }
523
+ //#endregion
524
+ //#region src/bundlers/vite/css-finalizer.ts
525
+ function createCssHandlerOptions(opts, majorVersion, file) {
526
+ return {
527
+ isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
528
+ postcssOptions: { options: { from: file } },
529
+ majorVersion
530
+ };
531
+ }
532
+ function shouldGenerateCssByGenerator(opts, file, rawSource, processed) {
533
+ if (require_generator_css.hasTailwindGeneratedCssMarkers(rawSource) || require_generator_css.hasTailwindSourceDirectives(rawSource)) return true;
534
+ return processed && shouldFinalizeProcessedCssAsset(opts, file);
535
+ }
536
+ function shouldFinalizeProcessedCssAsset(opts, file) {
537
+ return require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force" && opts.mainCssChunkMatcher(file, opts.appType);
538
+ }
539
+ function createViteCssFinalizerOutputPlugin(context) {
540
+ return {
541
+ name: "weapp-tailwindcss:adaptor:css-finalizer",
542
+ generateBundle: {
543
+ order: "post",
544
+ async handler(_options, bundle) {
545
+ const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, getRecordedGeneratorCandidates } = context;
546
+ if (getResolvedConfig()?.command !== "build") return;
547
+ const entries = Object.entries(bundle).filter(([, output]) => output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName)));
548
+ if (entries.length === 0) return;
549
+ await runtimeState.patchPromise;
550
+ const runtime = getRecordedGeneratorCandidates?.() ?? await ensureRuntimeClassSet();
551
+ const generatorRuntime = await collectGeneratorCandidatesFromSources(Object.entries(bundle).filter(([, output]) => output.type === "asset" || output.type === "chunk").filter(([file]) => opts.htmlMatcher(file) || opts.jsMatcher(file) || opts.wxsMatcher(file)).map(([file, output]) => ({
552
+ content: output.type === "chunk" ? output.code : output.source.toString(),
553
+ extension: node_path.default.extname(file).replace(/^\./, "") || (opts.htmlMatcher(file) ? "html" : "js")
554
+ })), runtime);
555
+ await Promise.all(entries.map(async ([bundleFile, output]) => {
556
+ const file = output.fileName || bundleFile;
557
+ const rawSource = output.source.toString();
558
+ const cssHandlerOptions = createCssHandlerOptions(opts, runtimeState.twPatcher.majorVersion, file);
559
+ const cssUserHandlerOptions = {
560
+ ...cssHandlerOptions,
561
+ isMainChunk: false
562
+ };
563
+ const generated = shouldGenerateCssByGenerator(opts, file, rawSource, isCssAssetProcessed(output, file)) ? await require_generator_css.generateCssByGenerator({
564
+ opts,
565
+ runtimeState,
566
+ runtime: generatorRuntime,
567
+ rawSource,
568
+ file,
569
+ cssHandlerOptions,
570
+ cssUserHandlerOptions,
571
+ styleHandler: opts.styleHandler,
572
+ debug
573
+ }) : void 0;
574
+ const nextCss = generated?.css ?? (await opts.styleHandler(rawSource, cssHandlerOptions)).css;
575
+ if (generated) {
576
+ debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
577
+ recordCssAssetResult?.(file, nextCss);
578
+ }
579
+ output.source = nextCss;
580
+ markCssAssetProcessed(output, file);
581
+ opts.onUpdate(file, rawSource, nextCss);
582
+ debug("css finalizer handle: %s", file);
583
+ }));
584
+ }
585
+ }
586
+ };
587
+ }
588
+ //#endregion
589
+ //#region src/bundlers/vite/bundle-entries.ts
590
+ function readOutputEntry(entry) {
591
+ if (entry.output.type === "chunk") return entry.output.code;
592
+ const source = entry.output.source;
593
+ if (typeof source === "string") return source;
594
+ if (source instanceof Uint8Array) return node_buffer.Buffer.from(source).toString();
595
+ const fallbackSource = source;
596
+ if (fallbackSource == null) return;
597
+ if (typeof fallbackSource.toString === "function") return fallbackSource.toString();
598
+ }
599
+ function isJavaScriptEntry(entry) {
600
+ if (entry.output.type === "chunk") return true;
601
+ return entry.fileName.endsWith(".js");
602
+ }
603
+ function createBundleModuleGraphOptions(outputDir, entries) {
604
+ const normalizedEntries = /* @__PURE__ */ new Map();
605
+ for (const [id, entry] of entries) normalizedEntries.set(require_css_imports.normalizeOutputPathKey(id), entry);
606
+ const getEntry = (id) => entries.get(id) ?? normalizedEntries.get(require_css_imports.normalizeOutputPathKey(id));
607
+ return {
608
+ resolve(specifier, importer) {
609
+ return require_css_imports.resolveOutputSpecifier(specifier, importer, outputDir, (candidate) => Boolean(getEntry(candidate)));
610
+ },
611
+ load(id) {
612
+ const entry = getEntry(id);
613
+ if (!entry) return;
614
+ return readOutputEntry(entry);
615
+ },
616
+ filter(id) {
617
+ return Boolean(getEntry(id));
618
+ }
619
+ };
620
+ }
621
+ function applyLinkedResults(linked, entries, onLinkedUpdate, onApplied) {
622
+ if (!linked) return;
623
+ const normalizedEntries = /* @__PURE__ */ new Map();
624
+ for (const [entryId, entry] of entries) normalizedEntries.set(require_css_imports.normalizeOutputPathKey(entryId), entry);
625
+ for (const [id, { code }] of Object.entries(linked)) {
626
+ const entry = entries.get(id) ?? normalizedEntries.get(require_css_imports.normalizeOutputPathKey(id));
627
+ if (!entry) continue;
628
+ const previous = readOutputEntry(entry);
629
+ if (previous == null || previous === code) continue;
630
+ if (entry.output.type === "chunk") entry.output.code = code;
631
+ else entry.output.source = code;
632
+ onApplied?.(entry, code);
633
+ onLinkedUpdate(entry.fileName, previous, code);
634
+ }
635
+ }
636
+ //#endregion
637
+ //#region src/bundlers/vite/runtime-affecting-signature.ts
638
+ const CSS_BLOCK_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
639
+ const CSS_AROUND_PUNCTUATION_RE = /\s*([{}:;,>+~()])\s*/g;
640
+ const CSS_TRAILING_DECLARATION_SEMICOLON_RE = /;\}/g;
641
+ const CSS_WHITESPACE_RE = /\s+/g;
642
+ function createHtmlRuntimeAffectingSignature(source) {
643
+ try {
644
+ const parts = [];
645
+ const parser = new htmlparser2.Parser({
646
+ onattribute(name, value) {
647
+ parts.push(`a:${name}=${value}`);
648
+ },
649
+ oncomment(data) {
650
+ parts.push(`c:${data}`);
651
+ },
652
+ ontext(data) {
653
+ const value = data.trim();
654
+ if (value.length > 0) parts.push(`t:${value}`);
655
+ }
656
+ }, { xmlMode: true });
657
+ parser.write(source);
658
+ parser.end();
659
+ return parts.join("\n");
660
+ } catch {
661
+ return source;
662
+ }
663
+ }
664
+ function createJsRuntimeAffectingSignature(source) {
665
+ try {
666
+ const ast = require_recorder.babelParse(source, {
667
+ cache: true,
668
+ cacheKey: "vite-runtime-affecting:unambiguous",
669
+ plugins: ["jsx", "typescript"],
670
+ sourceType: "unambiguous"
671
+ });
672
+ const parts = [];
673
+ require_recorder.traverse(ast, {
674
+ noScope: true,
675
+ StringLiteral(path) {
676
+ parts.push(`s:${path.node.value}`);
677
+ },
678
+ TemplateElement(path) {
679
+ parts.push(`t:${path.node.value.raw}`);
680
+ },
681
+ JSXText(path) {
682
+ const value = path.node.value.trim();
683
+ if (value.length > 0) parts.push(`x:${value}`);
684
+ }
685
+ });
686
+ const comments = ast.comments;
687
+ if (Array.isArray(comments)) {
688
+ for (const comment of comments) if (typeof comment?.value === "string" && comment.value.length > 0) parts.push(`c:${comment.value}`);
689
+ }
690
+ return parts.join("\n");
691
+ } catch {
692
+ return source;
693
+ }
694
+ }
695
+ function createCssRuntimeAffectingSignature(source) {
696
+ return source.replace(CSS_BLOCK_COMMENT_RE, "").replace(CSS_AROUND_PUNCTUATION_RE, "$1").replace(CSS_TRAILING_DECLARATION_SEMICOLON_RE, "}").replace(CSS_WHITESPACE_RE, " ").trim();
697
+ }
698
+ function createRuntimeAffectingSourceSignature(source, type) {
699
+ if (type === "html") return createHtmlRuntimeAffectingSignature(source);
700
+ if (type === "js") return createJsRuntimeAffectingSignature(source);
701
+ if (type === "css") return createCssRuntimeAffectingSignature(source);
702
+ return source;
703
+ }
704
+ //#endregion
705
+ //#region src/bundlers/vite/bundle-state.ts
706
+ function createBundleBuildState() {
707
+ return {
708
+ iteration: 0,
709
+ sourceHashByFile: /* @__PURE__ */ new Map(),
710
+ runtimeAffectingSignatureByFile: /* @__PURE__ */ new Map(),
711
+ runtimeAffectingHashByFile: /* @__PURE__ */ new Map(),
712
+ linkedByEntry: /* @__PURE__ */ new Map(),
713
+ dependentsByLinkedFile: /* @__PURE__ */ new Map()
714
+ };
715
+ }
716
+ function createChangedByType() {
717
+ return {
718
+ html: /* @__PURE__ */ new Set(),
719
+ js: /* @__PURE__ */ new Set(),
720
+ css: /* @__PURE__ */ new Set(),
721
+ other: /* @__PURE__ */ new Set()
722
+ };
723
+ }
724
+ function createProcessFiles() {
725
+ return {
726
+ html: /* @__PURE__ */ new Set(),
727
+ js: /* @__PURE__ */ new Set(),
728
+ css: /* @__PURE__ */ new Set()
729
+ };
730
+ }
731
+ function readEntrySource(output) {
732
+ if (output.type === "chunk") return output.code;
733
+ return output.source.toString();
734
+ }
735
+ function classifyBundleEntry(file, opts) {
736
+ if (opts.cssMatcher(file)) return "css";
737
+ if (opts.htmlMatcher(file)) return "html";
738
+ if (opts.jsMatcher(file) || opts.wxsMatcher(file)) return "js";
739
+ return "other";
740
+ }
741
+ function collectJsEntries(fileName, output, outDir, store) {
742
+ const entry = {
743
+ fileName,
744
+ output
745
+ };
746
+ if (!isJavaScriptEntry(entry)) return;
747
+ const absolute = require_css_imports.toAbsoluteOutputPath(fileName, outDir);
748
+ store.set(absolute, entry);
749
+ }
750
+ function markProcessFile(type, file, processFiles) {
751
+ if (type === "html" || type === "js" || type === "css") processFiles[type].add(file);
752
+ }
753
+ function buildBundleSnapshot(bundle, opts, outDir, state, forceAll = false) {
754
+ const sourceHashByFile = /* @__PURE__ */ new Map();
755
+ const runtimeAffectingSignatureByFile = /* @__PURE__ */ new Map();
756
+ const runtimeAffectingHashByFile = /* @__PURE__ */ new Map();
757
+ const changedByType = createChangedByType();
758
+ const runtimeAffectingChangedByType = createChangedByType();
759
+ const processFiles = createProcessFiles();
760
+ const linkedImpactsByEntry = /* @__PURE__ */ new Map();
761
+ const jsEntries = /* @__PURE__ */ new Map();
762
+ const entries = [];
763
+ const firstRun = state.linkedByEntry.size === 0;
764
+ for (const [file, output] of Object.entries(bundle)) {
765
+ const type = classifyBundleEntry(file, opts);
766
+ const source = readEntrySource(output);
767
+ const hash = opts.cache.computeHash(source);
768
+ sourceHashByFile.set(file, hash);
769
+ const previousHash = state.sourceHashByFile.get(file);
770
+ const changed = previousHash == null || previousHash !== hash;
771
+ const previousRuntimeAffectingSignature = state.runtimeAffectingSignatureByFile.get(file);
772
+ const previousRuntimeAffectingHash = state.runtimeAffectingHashByFile.get(file);
773
+ const canReuseRuntimeAffectingSignature = !changed && previousRuntimeAffectingSignature != null && previousRuntimeAffectingHash != null;
774
+ const runtimeAffectingSignature = canReuseRuntimeAffectingSignature ? previousRuntimeAffectingSignature : createRuntimeAffectingSourceSignature(source, type);
775
+ const runtimeAffectingHash = canReuseRuntimeAffectingSignature ? previousRuntimeAffectingHash : opts.cache.computeHash(runtimeAffectingSignature);
776
+ runtimeAffectingSignatureByFile.set(file, runtimeAffectingSignature);
777
+ runtimeAffectingHashByFile.set(file, runtimeAffectingHash);
778
+ if (changed) changedByType[type].add(file);
779
+ if (previousRuntimeAffectingHash == null || previousRuntimeAffectingHash !== runtimeAffectingHash) runtimeAffectingChangedByType[type].add(file);
780
+ if (forceAll || firstRun) markProcessFile(type, file, processFiles);
781
+ else if (type === "html") processFiles.html.add(file);
782
+ else if (changed && (type === "js" || type === "css")) processFiles[type].add(file);
783
+ collectJsEntries(file, output, outDir, jsEntries);
784
+ entries.push({
785
+ file,
786
+ output,
787
+ source,
788
+ type
789
+ });
790
+ }
791
+ if (!forceAll && !firstRun) for (const changedFile of changedByType.js) {
792
+ const dependents = state.dependentsByLinkedFile.get(changedFile);
793
+ if (!dependents) continue;
794
+ for (const entryFile of dependents) {
795
+ processFiles.js.add(entryFile);
796
+ let impacts = linkedImpactsByEntry.get(entryFile);
797
+ if (!impacts) {
798
+ impacts = /* @__PURE__ */ new Set();
799
+ linkedImpactsByEntry.set(entryFile, impacts);
800
+ }
801
+ impacts.add(changedFile);
802
+ }
803
+ }
804
+ return {
805
+ entries,
806
+ jsEntries,
807
+ sourceHashByFile,
808
+ runtimeAffectingSignatureByFile,
809
+ runtimeAffectingHashByFile,
810
+ changedByType,
811
+ runtimeAffectingChangedByType,
812
+ processFiles,
813
+ linkedImpactsByEntry
814
+ };
815
+ }
816
+ function invertLinkedByEntry(linkedByEntry) {
817
+ const dependentsByLinkedFile = /* @__PURE__ */ new Map();
818
+ for (const [entryFile, linkedFiles] of linkedByEntry.entries()) for (const linkedFile of linkedFiles) {
819
+ let dependents = dependentsByLinkedFile.get(linkedFile);
820
+ if (!dependents) {
821
+ dependents = /* @__PURE__ */ new Set();
822
+ dependentsByLinkedFile.set(linkedFile, dependents);
823
+ }
824
+ dependents.add(entryFile);
825
+ }
826
+ return dependentsByLinkedFile;
827
+ }
828
+ function updateBundleBuildState(state, snapshot, linkedByEntry, options = {}) {
829
+ const incremental = options.incremental === true;
830
+ state.iteration += 1;
831
+ state.sourceHashByFile = incremental ? new Map([...state.sourceHashByFile, ...snapshot.sourceHashByFile]) : snapshot.sourceHashByFile;
832
+ state.runtimeAffectingSignatureByFile = incremental ? new Map([...state.runtimeAffectingSignatureByFile, ...snapshot.runtimeAffectingSignatureByFile]) : snapshot.runtimeAffectingSignatureByFile;
833
+ state.runtimeAffectingHashByFile = incremental ? new Map([...state.runtimeAffectingHashByFile, ...snapshot.runtimeAffectingHashByFile]) : snapshot.runtimeAffectingHashByFile;
834
+ state.linkedByEntry = incremental ? new Map([...state.linkedByEntry, ...linkedByEntry]) : linkedByEntry;
835
+ state.dependentsByLinkedFile = invertLinkedByEntry(state.linkedByEntry);
836
+ }
837
+ //#endregion
838
+ //#region src/bundlers/vite/generate-bundle.ts
839
+ function formatDebugFileList(files, limit = 8) {
840
+ if (files.size === 0) return "-";
841
+ const sorted = [...files].sort();
842
+ if (sorted.length <= limit) return sorted.join(",");
843
+ return `${sorted.slice(0, limit).join(",")},...(+${sorted.length - limit})`;
844
+ }
845
+ function createEmptyMetric() {
846
+ return {
847
+ total: 0,
848
+ transformed: 0,
849
+ cacheHits: 0,
850
+ elapsed: 0
851
+ };
852
+ }
853
+ function createEmptyMetrics() {
854
+ return {
855
+ runtimeSet: 0,
856
+ html: createEmptyMetric(),
857
+ js: createEmptyMetric(),
858
+ css: createEmptyMetric()
859
+ };
860
+ }
861
+ function measureElapsed(start) {
862
+ return performance.now() - start;
863
+ }
864
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
865
+ return uniAppX === void 0 ? true : require_logger.isUniAppXEnabled(uniAppX);
866
+ }
867
+ function formatCacheHitRate(metric) {
868
+ if (metric.total === 0) return "0.00%";
869
+ return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
870
+ }
871
+ function formatMs(value) {
872
+ return value.toFixed(2);
873
+ }
874
+ function summarizeStringDiff(previous, next) {
875
+ if (previous === next) return "same";
876
+ const previousLength = previous.length;
877
+ const nextLength = next.length;
878
+ const minLength = Math.min(previousLength, nextLength);
879
+ let prefixLength = 0;
880
+ while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) prefixLength += 1;
881
+ let previousSuffixCursor = previousLength - 1;
882
+ let nextSuffixCursor = nextLength - 1;
883
+ while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) {
884
+ previousSuffixCursor -= 1;
885
+ nextSuffixCursor -= 1;
886
+ }
887
+ const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0;
888
+ const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0;
889
+ return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`;
890
+ }
891
+ function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) {
892
+ const changedLinkedFiles = linkedImpactsByEntry.get(entry);
893
+ if (!changedLinkedFiles || changedLinkedFiles.size === 0) return;
894
+ return [...changedLinkedFiles].sort().map((file) => {
895
+ return `${file}:${sourceHashByFile.get(file) ?? "missing"}`;
896
+ }).join(",");
897
+ }
898
+ function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
899
+ if (!linkedImpactSignature) return runtimeSignature;
900
+ return `${runtimeSignature}:linked:${linkedImpactSignature}`;
901
+ }
902
+ function getSnapshotHash(snapshotMap, file, fallback) {
903
+ return snapshotMap.get(file) ?? fallback;
904
+ }
905
+ function hasRuntimeAffectingSourceChanges(changedByType) {
906
+ return changedByType.html.size > 0 || changedByType.js.size > 0;
907
+ }
908
+ const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
909
+ const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
910
+ const CSS_IMPORT_RE = /@import\b/i;
911
+ function isPathIndependentCssUrl(value) {
912
+ const normalized = value.trim();
913
+ return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
914
+ }
915
+ function hasPathDependentCssUrl(rawSource) {
916
+ CSS_URL_FUNCTION_RE.lastIndex = 0;
917
+ let match = CSS_URL_FUNCTION_RE.exec(rawSource);
918
+ while (match !== null) {
919
+ if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
920
+ match = CSS_URL_FUNCTION_RE.exec(rawSource);
921
+ }
922
+ return false;
923
+ }
924
+ function createCssTransformShareScope(file, rawSource) {
925
+ if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${require_css_imports.normalizeOutputPathKey(node_path.default.dirname(file))}`;
926
+ return "global";
927
+ }
928
+ function createCssTransformShareScopeKey(opts, file, rawSource) {
929
+ if (require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force" && opts.mainCssChunkMatcher(file, opts.appType)) return `main:${require_css_imports.normalizeOutputPathKey(file)}`;
930
+ return createCssTransformShareScope(file, rawSource);
931
+ }
932
+ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
933
+ const currentFileSet = new Set(currentBundleFiles);
934
+ for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
935
+ return false;
936
+ }
937
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
938
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
939
+ function isArbitraryValueCandidate(candidate) {
940
+ return candidate.includes("[") && candidate.includes("]");
941
+ }
942
+ function collectUnescapedDynamicCandidates(source) {
943
+ const matches = /* @__PURE__ */ new Set();
944
+ for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
945
+ QUOTED_LITERAL_RE.lastIndex = 0;
946
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
947
+ while (quoted !== null) {
948
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
949
+ for (const candidate of (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, true)) {
950
+ const normalized = candidate.trim();
951
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
952
+ matches.add(normalized);
953
+ }
954
+ quoted = QUOTED_LITERAL_RE.exec(expression);
955
+ }
956
+ }
957
+ return [...matches];
958
+ }
959
+ function collectLegacyContainerCompatCandidates(sources, runtime) {
960
+ if (runtime.has("container")) return runtime;
961
+ if (!sources.some((source) => /\bcontainer\b/.test(source.content))) return runtime;
962
+ return new Set([...runtime, "container"]);
963
+ }
964
+ async function collectTailwindV4ContentCandidates(runtimeState, runtime, generatorMode, debug) {
965
+ const collectContentTokens = runtimeState.twPatcher.collectContentTokens;
966
+ if (generatorMode !== "force" || runtimeState.twPatcher.majorVersion !== 4 || typeof collectContentTokens !== "function") return runtime;
967
+ try {
968
+ const generator = require_generator.createWeappTailwindcssGenerator(await require_generator.resolveTailwindV4SourceFromPatcher(runtimeState.twPatcher));
969
+ const report = await collectContentTokens.call(runtimeState.twPatcher);
970
+ const rawCandidates = new Set(report.entries.map((entry) => entry.rawCandidate));
971
+ const validCandidates = await generator.validateCandidates(rawCandidates);
972
+ if (rawCandidates.size === 0 && validCandidates.size === 0) return runtime;
973
+ return new Set([
974
+ ...runtime,
975
+ ...rawCandidates,
976
+ ...validCandidates
977
+ ]);
978
+ } catch (error) {
979
+ debug("collect Tailwind v4 content candidates for generator failed: %O", error);
980
+ return runtime;
981
+ }
982
+ }
983
+ function createGenerateBundleHook(context) {
984
+ const state = createBundleBuildState();
985
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
986
+ const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
987
+ return async function generateBundle(_opt, bundle) {
988
+ const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, recordGeneratorCandidates } = context;
989
+ const { appType, cache, mainCssChunkMatcher, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
990
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
991
+ const getCssHandlerOptions = (file) => {
992
+ const majorVersion = runtimeState.twPatcher.majorVersion;
993
+ const isMainChunk = mainCssChunkMatcher(file, appType);
994
+ const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
995
+ const cached = cssHandlerOptionsCache.get(cacheKey);
996
+ if (cached) return cached;
997
+ const created = {
998
+ isMainChunk,
999
+ postcssOptions: { options: { from: file } },
1000
+ majorVersion
1001
+ };
1002
+ cssHandlerOptionsCache.set(cacheKey, created);
1003
+ return created;
1004
+ };
1005
+ const getCssUserHandlerOptions = (file) => {
1006
+ const cacheKey = `${runtimeState.twPatcher.majorVersion ?? "unknown"}:${file}`;
1007
+ const cached = cssUserHandlerOptionsCache.get(cacheKey);
1008
+ if (cached) return cached;
1009
+ const created = {
1010
+ ...getCssHandlerOptions(file),
1011
+ isMainChunk: false
1012
+ };
1013
+ cssUserHandlerOptionsCache.set(cacheKey, created);
1014
+ return created;
1015
+ };
1016
+ await runtimeState.patchPromise;
1017
+ debug("start");
1018
+ onStart();
1019
+ const metrics = createEmptyMetrics();
1020
+ const forceRuntimeRefreshByEnv = node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1021
+ const disableDirtyOptimization = node_process.default.env.WEAPP_TW_VITE_DISABLE_DIRTY === "1";
1022
+ const disableJsPrecheck = node_process.default.env.WEAPP_TW_VITE_DISABLE_JS_PRECHECK === "1";
1023
+ const debugCssDiff = node_process.default.env.WEAPP_TW_VITE_DEBUG_CSS_DIFF === "1";
1024
+ const resolvedConfig = getResolvedConfig();
1025
+ const bundleFiles = Object.keys(bundle);
1026
+ const useIncrementalMode = !(resolvedConfig?.command === "build") || hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
1027
+ const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
1028
+ const outDir = resolvedConfig?.build?.outDir ? node_path.default.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
1029
+ const snapshot = buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode);
1030
+ const useBundleRuntimeClassSet = useIncrementalMode || runtimeState.twPatcher.majorVersion === 4;
1031
+ const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1032
+ const processFiles = snapshot.processFiles;
1033
+ if (useIncrementalMode) {
1034
+ debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", state.iteration + 1, 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));
1035
+ debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", state.iteration + 1, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
1036
+ } else 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));
1037
+ const jsEntries = snapshot.jsEntries;
1038
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
1039
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(require_css_imports.normalizeOutputPathKey(id), entry);
1040
+ const getJsEntry = (id) => jsEntries.get(id) ?? normalizedJsEntries.get(require_css_imports.normalizeOutputPathKey(id));
1041
+ const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
1042
+ const runtimeStart = performance.now();
1043
+ const runtime = useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1044
+ const generatorBaseRuntime = await collectTailwindV4ContentCandidates(runtimeState, runtime, generatorOptions.mode, debug);
1045
+ const generatorCandidateSources = snapshot.entries.filter((entry) => entry.type === "html" || entry.type === "js").map((entry) => ({
1046
+ content: entry.source,
1047
+ extension: node_path.default.extname(entry.file).replace(/^\./, "") || (entry.type === "html" ? "html" : "js")
1048
+ }));
1049
+ const generatorRuntime = collectLegacyContainerCompatCandidates(generatorCandidateSources, await collectGeneratorCandidatesFromSources(generatorCandidateSources, generatorBaseRuntime));
1050
+ recordGeneratorCandidates?.(generatorRuntime);
1051
+ const defaultTemplateHandlerOptions = { runtimeSet: runtime };
1052
+ metrics.runtimeSet = measureElapsed(runtimeStart);
1053
+ if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
1054
+ debug("get runtimeSet, class count: %d", runtime.size);
1055
+ const runtimeSignature = require_logger.getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1056
+ const handleLinkedUpdate = (fileName, previous, next) => {
1057
+ onUpdate(fileName, previous, next);
1058
+ debug("js linked handle: %s", fileName);
1059
+ };
1060
+ const pendingLinkedUpdates = [];
1061
+ const scheduleLinkedApply = (entry, code) => {
1062
+ pendingLinkedUpdates.push(() => {
1063
+ if (entry.output.type === "chunk") entry.output.code = code;
1064
+ else entry.output.source = code;
1065
+ });
1066
+ };
1067
+ const applyLinkedUpdates = (linked) => {
1068
+ applyLinkedResults(linked, jsEntries, handleLinkedUpdate, scheduleLinkedApply);
1069
+ };
1070
+ const createHandlerOptions = (absoluteFilename, extra) => ({
1071
+ ...extra,
1072
+ filename: absoluteFilename,
1073
+ tailwindcssMajorVersion: runtimeState.twPatcher.majorVersion,
1074
+ moduleGraph: moduleGraphOptions,
1075
+ babelParserOptions: {
1076
+ ...extra?.babelParserOptions ?? {},
1077
+ sourceFilename: absoluteFilename
1078
+ }
1079
+ });
1080
+ const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
1081
+ const sharedCssResultCache = /* @__PURE__ */ new Map();
1082
+ const tasks = [];
1083
+ const jsTaskFactories = [];
1084
+ for (const entry of snapshot.entries) {
1085
+ const { file, output: originalSource, source: originalEntrySource, type } = entry;
1086
+ if (type === "html" && originalSource.type === "asset") {
1087
+ metrics.html.total++;
1088
+ if (!processFiles.html.has(file)) continue;
1089
+ const rawSource = originalEntrySource;
1090
+ tasks.push(require_generator_css.processCachedTask({
1091
+ cache,
1092
+ cacheKey: file,
1093
+ hashKey: `${file}:html:${runtimeSignature}`,
1094
+ hash: getSnapshotHash(snapshot.sourceHashByFile, file, rawSource),
1095
+ applyResult(source) {
1096
+ originalSource.source = source;
1097
+ },
1098
+ onCacheHit() {
1099
+ metrics.html.cacheHits++;
1100
+ debug("html cache hit: %s", file);
1101
+ },
1102
+ async transform() {
1103
+ const start = performance.now();
1104
+ let transformed = await templateHandler(rawSource, defaultTemplateHandlerOptions);
1105
+ let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1106
+ if (unresolvedDynamicCandidates.length > 0) {
1107
+ _weapp_tailwindcss_logger.logger.warn("检测到 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
1108
+ transformed = await templateHandler(rawSource, { runtimeSet: await context.ensureRuntimeClassSet(true) });
1109
+ unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1110
+ if (unresolvedDynamicCandidates.length > 0) _weapp_tailwindcss_logger.logger.warn("WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
1111
+ }
1112
+ metrics.html.elapsed += measureElapsed(start);
1113
+ metrics.html.transformed++;
1114
+ onUpdate(file, rawSource, transformed);
1115
+ debug("html handle: %s", file);
1116
+ return { result: transformed };
1117
+ }
1118
+ }));
1119
+ continue;
1120
+ }
1121
+ if (type === "css" && originalSource.type === "asset") {
1122
+ metrics.css.total++;
1123
+ const rawSource = originalEntrySource;
1124
+ const cssRuntimeAffectingSignature = snapshot.runtimeAffectingSignatureByFile.get(file) ?? rawSource;
1125
+ const cssShareScope = createCssTransformShareScopeKey(opts, file, rawSource);
1126
+ const cssHandlerOptions = getCssHandlerOptions(file);
1127
+ const cssSharedCacheKey = `${cssShareScope}:${runtimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
1128
+ tasks.push(require_generator_css.processCachedTask({
1129
+ cache,
1130
+ cacheKey: file,
1131
+ hashKey: `${file}:css:${runtimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1132
+ hash: getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature),
1133
+ applyResult(source) {
1134
+ originalSource.source = source;
1135
+ markCssAssetProcessed?.(originalSource, file);
1136
+ },
1137
+ onCacheHit() {
1138
+ metrics.css.cacheHits++;
1139
+ debug("css cache hit: %s", file);
1140
+ },
1141
+ async transform() {
1142
+ if (cssSharedCacheKey) {
1143
+ const sharedCssTask = sharedCssResultCache.get(cssSharedCacheKey);
1144
+ if (sharedCssTask != null) {
1145
+ metrics.css.cacheHits++;
1146
+ debug("css shared hit: %s", file);
1147
+ const sharedCss = await sharedCssTask;
1148
+ onUpdate(file, rawSource, sharedCss);
1149
+ return { result: sharedCss };
1150
+ }
1151
+ }
1152
+ const runTransform = async () => {
1153
+ const start = performance.now();
1154
+ await runtimeState.patchPromise;
1155
+ const generated = await require_generator_css.generateCssByGenerator({
1156
+ opts,
1157
+ runtimeState,
1158
+ runtime: generatorRuntime,
1159
+ rawSource,
1160
+ file,
1161
+ cssHandlerOptions,
1162
+ cssUserHandlerOptions: getCssUserHandlerOptions(file),
1163
+ styleHandler,
1164
+ debug
1165
+ });
1166
+ if (generated) {
1167
+ if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, generated.css));
1168
+ debug("css generated result: %s bytes=%d", file, generated.css.length);
1169
+ recordCssAssetResult?.(file, generated.css);
1170
+ metrics.css.elapsed += measureElapsed(start);
1171
+ metrics.css.transformed++;
1172
+ debug("css handle via tailwind v%s engine(%s): %s", runtimeState.twPatcher.majorVersion, generated.target, file);
1173
+ return generated.css;
1174
+ }
1175
+ const { css } = await styleHandler(rawSource, getCssHandlerOptions(file));
1176
+ if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, css));
1177
+ metrics.css.elapsed += measureElapsed(start);
1178
+ metrics.css.transformed++;
1179
+ return css;
1180
+ };
1181
+ const cssTask = cssSharedCacheKey ? sharedCssResultCache.get(cssSharedCacheKey) ?? runTransform() : runTransform();
1182
+ if (cssSharedCacheKey && !sharedCssResultCache.has(cssSharedCacheKey)) sharedCssResultCache.set(cssSharedCacheKey, cssTask);
1183
+ const css = await cssTask;
1184
+ onUpdate(file, rawSource, css);
1185
+ debug("css handle: %s", file);
1186
+ return { result: css };
1187
+ }
1188
+ }));
1189
+ continue;
1190
+ }
1191
+ if (type !== "js") continue;
1192
+ metrics.js.total++;
1193
+ const shouldTransformJs = !useIncrementalMode || processFiles.js.has(file);
1194
+ if (!shouldTransformJs) debug("js skip transform (clean), replay cache: %s", file);
1195
+ if (originalSource.type === "chunk") {
1196
+ const absoluteFile = node_path.default.resolve(outDir, file);
1197
+ const initialRawSource = originalEntrySource;
1198
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1199
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1200
+ jsTaskFactories.push(async () => {
1201
+ const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1202
+ await require_generator_css.processCachedTask({
1203
+ cache,
1204
+ cacheKey: file,
1205
+ hashKey: `${file}:js`,
1206
+ hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
1207
+ applyResult(source) {
1208
+ originalSource.code = source;
1209
+ },
1210
+ onCacheHit() {
1211
+ metrics.js.cacheHits++;
1212
+ debug("js cache hit: %s", file);
1213
+ },
1214
+ async transform() {
1215
+ const start = performance.now();
1216
+ const rawSource = originalSource.code;
1217
+ if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1218
+ const handlerOptions = createHandlerOptions(absoluteFile);
1219
+ if (!disableJsPrecheck && require_recorder.shouldSkipJsTransform(rawSource, handlerOptions)) {
1220
+ metrics.js.elapsed += measureElapsed(start);
1221
+ metrics.js.transformed++;
1222
+ return { result: rawSource };
1223
+ }
1224
+ const { code, linked } = await jsHandler(rawSource, runtime, handlerOptions);
1225
+ metrics.js.elapsed += measureElapsed(start);
1226
+ metrics.js.transformed++;
1227
+ onUpdate(file, rawSource, code);
1228
+ debug("js handle: %s", file);
1229
+ if (linked) for (const id of Object.keys(linked)) {
1230
+ const linkedEntry = getJsEntry(id);
1231
+ if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1232
+ }
1233
+ applyLinkedUpdates(linked);
1234
+ return { result: code };
1235
+ }
1236
+ });
1237
+ });
1238
+ } else if (uniAppX && originalSource.type === "asset") {
1239
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1240
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1241
+ const baseApplyLinkedUpdates = applyLinkedUpdates;
1242
+ const wrappedApplyLinkedUpdates = (linked) => {
1243
+ if (linked) for (const id of Object.keys(linked)) {
1244
+ const linkedEntry = getJsEntry(id);
1245
+ if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1246
+ }
1247
+ baseApplyLinkedUpdates(linked);
1248
+ };
1249
+ const factory = createUniAppXAssetTask(file, originalSource, outDir, {
1250
+ cache,
1251
+ hashKey: `${file}:js`,
1252
+ hashSalt: createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0),
1253
+ createHandlerOptions,
1254
+ debug,
1255
+ jsHandler,
1256
+ onUpdate,
1257
+ runtimeSet: runtime,
1258
+ applyLinkedResults: wrappedApplyLinkedUpdates,
1259
+ uniAppX
1260
+ });
1261
+ jsTaskFactories.push(async () => {
1262
+ const start = performance.now();
1263
+ if (!shouldTransformJs) {
1264
+ debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
1265
+ await factory();
1266
+ metrics.js.elapsed += measureElapsed(start);
1267
+ metrics.js.transformed++;
1268
+ return;
1269
+ }
1270
+ const currentSource = originalEntrySource;
1271
+ const precheckOptions = createHandlerOptions(node_path.default.resolve(outDir, file), {
1272
+ uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
1273
+ babelParserOptions: {
1274
+ plugins: ["typescript"],
1275
+ sourceType: "unambiguous"
1276
+ }
1277
+ });
1278
+ if (!disableJsPrecheck && require_recorder.shouldSkipJsTransform(currentSource, precheckOptions)) {
1279
+ metrics.js.elapsed += measureElapsed(start);
1280
+ metrics.js.transformed++;
1281
+ return;
1282
+ }
1283
+ await factory();
1284
+ metrics.js.elapsed += measureElapsed(start);
1285
+ metrics.js.transformed++;
1286
+ });
1287
+ }
1288
+ }
1289
+ require_css_imports.pushConcurrentTaskFactories(tasks, jsTaskFactories);
1290
+ await Promise.all(tasks);
1291
+ for (const apply of pendingLinkedUpdates) apply();
1292
+ updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1293
+ 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));
1294
+ onEnd();
1295
+ debug("end");
1296
+ };
1297
+ }
1298
+ //#endregion
1299
+ //#region src/bundlers/vite/incremental-runtime-class-set.ts
1300
+ const debug$1 = require_recorder.createDebug("[vite:runtime-set] ");
1301
+ const EXTENSION_DOT_PREFIX_RE = /^\./;
1302
+ function createExtractOptions(context, source) {
1303
+ return {
1304
+ cwd: context.projectRoot,
1305
+ base: context.base,
1306
+ baseFallbacks: context.baseFallbacks,
1307
+ css: context.css,
1308
+ content: source,
1309
+ extension: "html"
1310
+ };
1311
+ }
1312
+ function createRuntimeEntries(snapshot) {
1313
+ return snapshot.entries.filter((entry) => entry.type === "html" || entry.type === "js");
1314
+ }
1315
+ function collectChangedRuntimeFiles(snapshot) {
1316
+ return new Set([...snapshot.runtimeAffectingChangedByType.html, ...snapshot.runtimeAffectingChangedByType.js]);
1317
+ }
1318
+ function resolveEntryExtension(entry) {
1319
+ const ext = entry.file.split(/[?#]/, 1)[0]?.split(".").pop()?.replace(EXTENSION_DOT_PREFIX_RE, "") ?? "";
1320
+ if (ext.length > 0) return ext;
1321
+ return entry.type === "html" ? "html" : "js";
1322
+ }
1323
+ function createCandidateValidationSource(candidates) {
1324
+ return [...new Set(candidates)].sort().join("\n");
1325
+ }
1326
+ function removeCandidateSet(candidateCountByClass, runtimeSet, candidates) {
1327
+ for (const className of candidates) {
1328
+ const count = candidateCountByClass.get(className);
1329
+ if (count == null) continue;
1330
+ if (count <= 1) {
1331
+ candidateCountByClass.delete(className);
1332
+ runtimeSet.delete(className);
1333
+ continue;
1334
+ }
1335
+ candidateCountByClass.set(className, count - 1);
1336
+ }
1337
+ }
1338
+ function addCandidateSet(candidateCountByClass, runtimeSet, candidates) {
1339
+ for (const className of candidates) {
1340
+ const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
1341
+ candidateCountByClass.set(className, nextCount);
1342
+ runtimeSet.add(className);
1343
+ }
1344
+ }
1345
+ function createBundleRuntimeClassSetManager(options = {}) {
1346
+ const customExtractCandidates = options.extractCandidates;
1347
+ const extractCandidates = customExtractCandidates ?? tailwindcss_patch.extractValidCandidates;
1348
+ const extractRawCandidates = options.extractRawCandidates ?? tailwindcss_patch.extractRawCandidatesWithPositions;
1349
+ const runtimeSet = /* @__PURE__ */ new Set();
1350
+ const candidateCountByClass = /* @__PURE__ */ new Map();
1351
+ const candidatesByFile = /* @__PURE__ */ new Map();
1352
+ const candidateValidityCache = /* @__PURE__ */ new Map();
1353
+ let runtimeSignature;
1354
+ let validationContext;
1355
+ let designSystemPromise;
1356
+ async function reset() {
1357
+ runtimeSet.clear();
1358
+ candidateCountByClass.clear();
1359
+ candidatesByFile.clear();
1360
+ candidateValidityCache.clear();
1361
+ runtimeSignature = void 0;
1362
+ validationContext = void 0;
1363
+ designSystemPromise = void 0;
1364
+ }
1365
+ async function resolveValidationContextCached(patcher) {
1366
+ if (!validationContext) validationContext = await require_generator.resolveTailwindV4SourceFromPatcher(patcher);
1367
+ return validationContext;
1368
+ }
1369
+ async function loadDesignSystem(context) {
1370
+ if (!designSystemPromise) designSystemPromise = (0, tailwindcss_patch.loadTailwindV4DesignSystem)(context);
1371
+ return designSystemPromise;
1372
+ }
1373
+ function populateCandidateValidityCacheFromDesignSystem(designSystem, unknownCandidates) {
1374
+ const parsedCandidates = [...unknownCandidates].filter((candidate) => designSystem.parseCandidate(candidate).length > 0);
1375
+ const cssByCandidate = parsedCandidates.length > 0 ? designSystem.candidatesToCss(parsedCandidates) : [];
1376
+ const validCandidates = /* @__PURE__ */ new Set();
1377
+ for (let index = 0; index < parsedCandidates.length; index += 1) {
1378
+ const candidate = parsedCandidates[index];
1379
+ const css = cssByCandidate[index];
1380
+ if (candidate && typeof css === "string" && css.trim().length > 0) validCandidates.add(candidate);
1381
+ }
1382
+ for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1383
+ }
1384
+ async function validateUnknownCandidates(patcher, unknownCandidates) {
1385
+ if (unknownCandidates.size === 0) return;
1386
+ const context = await resolveValidationContextCached(patcher);
1387
+ if (!customExtractCandidates) try {
1388
+ populateCandidateValidityCacheFromDesignSystem(await loadDesignSystem(context), unknownCandidates);
1389
+ return;
1390
+ } catch (error) {
1391
+ debug$1("incremental design-system validation failed: %O", error);
1392
+ designSystemPromise = void 0;
1393
+ throw error;
1394
+ }
1395
+ const source = createCandidateValidationSource(unknownCandidates);
1396
+ const validCandidates = new Set(await extractCandidates(createExtractOptions(context, source)));
1397
+ for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1398
+ }
1399
+ async function extractEntryRawCandidates(entry) {
1400
+ const matches = await extractRawCandidates(entry.source, resolveEntryExtension(entry));
1401
+ const candidates = /* @__PURE__ */ new Set();
1402
+ for (const match of matches) {
1403
+ const candidate = match?.rawCandidate;
1404
+ if (typeof candidate === "string" && candidate.length > 0) candidates.add(candidate);
1405
+ }
1406
+ return candidates;
1407
+ }
1408
+ async function sync(patcher, snapshot) {
1409
+ const nextSignature = require_logger.getRuntimeClassSetSignature(patcher) ?? "runtime:missing";
1410
+ const runtimeEntries = createRuntimeEntries(snapshot);
1411
+ const runtimeEntriesByFile = new Map(runtimeEntries.map((entry) => [entry.file, entry]));
1412
+ const currentRuntimeFiles = new Set(runtimeEntriesByFile.keys());
1413
+ const fullRebuild = runtimeSignature !== nextSignature || candidatesByFile.size === 0;
1414
+ if (runtimeSignature !== nextSignature) {
1415
+ debug$1("runtime signature changed, reset incremental runtime set: %s", nextSignature);
1416
+ await reset();
1417
+ }
1418
+ runtimeSignature = nextSignature;
1419
+ for (const [file, previousCandidates] of candidatesByFile) {
1420
+ if (currentRuntimeFiles.has(file)) continue;
1421
+ removeCandidateSet(candidateCountByClass, runtimeSet, previousCandidates);
1422
+ candidatesByFile.delete(file);
1423
+ }
1424
+ const changedRuntimeFiles = fullRebuild ? [...runtimeEntriesByFile.keys()] : [...collectChangedRuntimeFiles(snapshot)];
1425
+ if (changedRuntimeFiles.length === 0) return new Set(runtimeSet);
1426
+ const rawCandidatesByFile = /* @__PURE__ */ new Map();
1427
+ const unknownCandidates = /* @__PURE__ */ new Set();
1428
+ await Promise.all(changedRuntimeFiles.map(async (file) => {
1429
+ const entry = runtimeEntriesByFile.get(file);
1430
+ if (!entry) return;
1431
+ const candidates = await extractEntryRawCandidates(entry);
1432
+ rawCandidatesByFile.set(file, candidates);
1433
+ for (const candidate of candidates) if (!candidateValidityCache.has(candidate)) unknownCandidates.add(candidate);
1434
+ }));
1435
+ await validateUnknownCandidates(patcher, unknownCandidates);
1436
+ let rawCandidateCount = 0;
1437
+ for (const file of changedRuntimeFiles) {
1438
+ const nextRawCandidates = rawCandidatesByFile.get(file);
1439
+ const previousCandidates = candidatesByFile.get(file);
1440
+ if (previousCandidates) removeCandidateSet(candidateCountByClass, runtimeSet, previousCandidates);
1441
+ if (!nextRawCandidates || nextRawCandidates.size === 0) {
1442
+ candidatesByFile.delete(file);
1443
+ continue;
1444
+ }
1445
+ rawCandidateCount += nextRawCandidates.size;
1446
+ const nextCandidates = new Set([...nextRawCandidates].filter((candidate) => candidateValidityCache.get(candidate) === true));
1447
+ if (nextCandidates.size === 0) {
1448
+ candidatesByFile.delete(file);
1449
+ continue;
1450
+ }
1451
+ addCandidateSet(candidateCountByClass, runtimeSet, nextCandidates);
1452
+ candidatesByFile.set(file, nextCandidates);
1453
+ }
1454
+ debug$1("incremental runtime set synced, changedFiles=%d rawCandidates=%d validateMisses=%d runtimeSize=%d trackedFiles=%d", changedRuntimeFiles.length, rawCandidateCount, unknownCandidates.size, runtimeSet.size, candidatesByFile.size);
1455
+ return new Set(runtimeSet);
1456
+ }
1457
+ return {
1458
+ sync,
1459
+ reset
1460
+ };
1461
+ }
1462
+ //#endregion
1463
+ //#region src/bundlers/vite/resolve-app-type.ts
1464
+ const PACKAGE_JSON_FILE$1 = "package.json";
1465
+ const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
1466
+ const TARO_SCRIPT_RE = /\btaro\b/u;
1467
+ const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
1468
+ function resolveDependencyNames(pkg) {
1469
+ return new Set([
1470
+ ...Object.keys(pkg.dependencies ?? {}),
1471
+ ...Object.keys(pkg.devDependencies ?? {}),
1472
+ ...Object.keys(pkg.peerDependencies ?? {}),
1473
+ ...Object.keys(pkg.optionalDependencies ?? {})
1474
+ ]);
1475
+ }
1476
+ function hasScriptMatch(pkg, pattern) {
1477
+ return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
1478
+ }
1479
+ function resolveAppTypeFromPackageJson(pkg) {
1480
+ const dependencyNames = resolveDependencyNames(pkg);
1481
+ if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
1482
+ if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
1483
+ if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
1484
+ if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
1485
+ if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
1486
+ }
1487
+ function tryReadUniAppManifest(root) {
1488
+ const manifestPath = node_path.default.join(root, "manifest.json");
1489
+ if (!(0, node_fs.existsSync)(manifestPath)) return;
1490
+ try {
1491
+ return JSON.parse((0, node_fs.readFileSync)(manifestPath, "utf8"));
1492
+ } catch {}
1493
+ }
1494
+ function tryReadPackageJson(root) {
1495
+ const packageJsonPath = node_path.default.join(root, PACKAGE_JSON_FILE$1);
1496
+ if (!(0, node_fs.existsSync)(packageJsonPath)) return;
1497
+ try {
1498
+ return JSON.parse((0, node_fs.readFileSync)(packageJsonPath, "utf8"));
1499
+ } catch {}
1500
+ }
1501
+ function resolveAppTypeFromMarkers(root) {
1502
+ for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if ((0, node_fs.existsSync)(node_path.default.join(root, relativePath))) return appType;
1503
+ }
1504
+ function resolveImplicitAppTypeFromViteRoot(root) {
1505
+ const resolvedRoot = node_path.default.resolve(root);
1506
+ if (!(0, node_fs.existsSync)(resolvedRoot)) return;
1507
+ const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
1508
+ if (markerDetected) return markerDetected;
1509
+ let current = resolvedRoot;
1510
+ while (true) {
1511
+ const manifest = tryReadUniAppManifest(current);
1512
+ if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
1513
+ const pkg = tryReadPackageJson(current);
1514
+ if (pkg) {
1515
+ const detected = resolveAppTypeFromPackageJson(pkg);
1516
+ if (detected) return detected;
1517
+ }
1518
+ const parent = node_path.default.dirname(current);
1519
+ if (parent === current) break;
1520
+ current = parent;
1521
+ }
1522
+ }
1523
+ //#endregion
1524
+ //#region src/bundlers/vite/rewrite-css-imports.ts
1525
+ function joinPosixPath(base, subpath) {
1526
+ if (base.endsWith("/")) return `${base}${subpath}`;
1527
+ return `${base}/${subpath}`;
1528
+ }
1529
+ function isCssLikeImporter(importer) {
1530
+ if (!importer) return false;
1531
+ const normalized = (0, _weapp_tailwindcss_shared.cleanUrl)(importer);
1532
+ return isCSSRequest(normalized) || normalized.endsWith("/*");
1533
+ }
1534
+ function createRewriteCssImportsPlugins(options) {
1535
+ if (!options.shouldRewrite) return [];
1536
+ const { appType, getAppType, rootImport, weappTailwindcssDirPosix } = options;
1537
+ const resolveAppType = () => getAppType?.() ?? appType;
1538
+ return [{
1539
+ name: `${require_recorder.vitePluginName}:rewrite-css-imports`,
1540
+ enforce: "pre",
1541
+ resolveId: {
1542
+ order: "pre",
1543
+ handler(id, importer) {
1544
+ const replacement = require_css_imports.resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1545
+ join: joinPosixPath,
1546
+ appType: resolveAppType(),
1547
+ rootImport
1548
+ });
1549
+ if (!replacement) return null;
1550
+ if (importer && !isCssLikeImporter(importer)) return null;
1551
+ return replacement;
1552
+ }
1553
+ },
1554
+ transform: {
1555
+ order: "pre",
1556
+ handler(code, id) {
1557
+ if (!isCSSRequest(id)) return null;
1558
+ const rewritten = require_css_imports.rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1559
+ join: joinPosixPath,
1560
+ appType: resolveAppType(),
1561
+ rootImport
1562
+ });
1563
+ if (!rewritten) return null;
1564
+ return {
1565
+ code: rewritten,
1566
+ map: null
1567
+ };
1568
+ }
1569
+ }
1570
+ }];
1571
+ }
1572
+ //#endregion
1573
+ //#region src/bundlers/vite/index.ts
1574
+ const debug = require_recorder.createDebug();
1575
+ const weappTailwindcssPackageDir = require_css_imports.resolvePackageDir("weapp-tailwindcss");
1576
+ const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1577
+ const PACKAGE_JSON_FILE = "package.json";
1578
+ const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1579
+ function getPostcssPluginName(plugin) {
1580
+ if (!plugin) return;
1581
+ if (typeof plugin === "function" && "postcss" in plugin) try {
1582
+ return getPostcssPluginName(plugin());
1583
+ } catch {
1584
+ return;
1585
+ }
1586
+ if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1587
+ const { postcssPlugin } = plugin;
1588
+ return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1589
+ }
1590
+ function isTailwindPostcssPlugin(plugin) {
1591
+ const name = getPostcssPluginName(plugin);
1592
+ return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1593
+ }
1594
+ function removeTailwindPostcssPlugins(plugins) {
1595
+ let removed = 0;
1596
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1597
+ plugins.splice(i, 1);
1598
+ removed++;
1599
+ }
1600
+ return removed;
1601
+ }
1602
+ async function resolveFilteredPostcssConfig(root) {
1603
+ try {
1604
+ const loaded = await (0, postcss_load_config.default)({}, root);
1605
+ const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1606
+ const removed = removeTailwindPostcssPlugins(plugins);
1607
+ if (removed === 0) return;
1608
+ return {
1609
+ options: loaded.options,
1610
+ plugins,
1611
+ removed
1612
+ };
1613
+ } catch (error) {
1614
+ if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1615
+ throw error;
1616
+ }
1617
+ }
1618
+ function isTailwindVitePlugin(plugin) {
1619
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1620
+ const { name } = plugin;
1621
+ return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1622
+ }
1623
+ function removeTailwindVitePlugins(plugins) {
1624
+ let removed = 0;
1625
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1626
+ plugins.splice(i, 1);
1627
+ removed++;
1628
+ }
1629
+ return removed;
1630
+ }
1631
+ function disableTailwindVitePlugin(plugin) {
1632
+ if (!isTailwindVitePlugin(plugin)) return false;
1633
+ const mutablePlugin = plugin;
1634
+ for (const hook of [
1635
+ "configResolved",
1636
+ "configureServer",
1637
+ "transform",
1638
+ "hotUpdate",
1639
+ "handleHotUpdate"
1640
+ ]) delete mutablePlugin[hook];
1641
+ return true;
1642
+ }
1643
+ function disableAndRemoveTailwindVitePlugins(plugins) {
1644
+ let removed = 0;
1645
+ for (let i = plugins.length - 1; i >= 0; i--) {
1646
+ const plugin = plugins[i];
1647
+ if (Array.isArray(plugin)) {
1648
+ removed += disableAndRemoveTailwindVitePlugins(plugin);
1649
+ if (plugin.length === 0) plugins.splice(i, 1);
1650
+ continue;
1651
+ }
1652
+ if (disableTailwindVitePlugin(plugin)) {
1653
+ plugins.splice(i, 1);
1654
+ removed++;
1655
+ }
1656
+ }
1657
+ return removed;
1658
+ }
1659
+ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1660
+ const resolvedRoot = node_path.default.resolve(root);
1661
+ if (!(0, node_fs.existsSync)(resolvedRoot)) return resolvedRoot;
1662
+ const searchRoots = [];
1663
+ let current = resolvedRoot;
1664
+ while (true) {
1665
+ searchRoots.push(current);
1666
+ const parent = node_path.default.dirname(current);
1667
+ if (parent === current) break;
1668
+ current = parent;
1669
+ }
1670
+ const tailwindConfigPath = require_logger.findTailwindConfig(searchRoots);
1671
+ if (tailwindConfigPath) return node_path.default.dirname(tailwindConfigPath);
1672
+ const packageRoot = require_logger.findNearestPackageRoot(resolvedRoot);
1673
+ if (packageRoot && (0, node_fs.existsSync)(node_path.default.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1674
+ return resolvedRoot;
1675
+ }
1676
+ /**
1677
+ * @name UnifiedViteWeappTailwindcssPlugin
1678
+ * @description uni-app vite / uni-app-x 版本插件
1679
+ * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
1680
+ */
1681
+ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1682
+ const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
1683
+ const rewriteCssImportsSpecified = Object.hasOwn(options, "rewriteCssImports");
1684
+ const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1685
+ const opts = require_recorder.getCompilerContext(options);
1686
+ const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
1687
+ const uniAppXEnabled = require_logger.isUniAppXEnabled(uniAppX);
1688
+ const disabledOptions = require_css_imports.resolveDisabledOptions(disabled);
1689
+ const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1690
+ const shouldOwnTailwindGeneration = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force";
1691
+ const shouldRewriteCssImports = opts.rewriteCssImports !== false && !disabledOptions.rewriteCssImports && (rewriteCssImportsSpecified || tailwindcssMajorVersion >= 4);
1692
+ const rewritePlugins = createRewriteCssImportsPlugins({
1693
+ getAppType: () => opts.appType,
1694
+ rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
1695
+ shouldRewrite: shouldRewriteCssImports,
1696
+ weappTailwindcssDirPosix
1697
+ });
1698
+ if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
1699
+ const customAttributesEntities = require_recorder.toCustomAttributesEntities(customAttributes);
1700
+ const patchRecorderState = require_recorder.setupPatchRecorder(initialTwPatcher, opts.tailwindcssBasedir, {
1701
+ source: "runtime",
1702
+ cwd: opts.tailwindcssBasedir ?? node_process.default.cwd()
1703
+ });
1704
+ const runtimeState = {
1705
+ twPatcher: initialTwPatcher,
1706
+ patchPromise: patchRecorderState.patchPromise,
1707
+ refreshTailwindcssPatcher,
1708
+ onPatchCompleted: patchRecorderState.onPatchCompleted
1709
+ };
1710
+ let runtimeSet;
1711
+ let runtimeSetPromise;
1712
+ let resolvedConfig;
1713
+ let runtimeRefreshSignature;
1714
+ let runtimeRefreshOptionsKey;
1715
+ let recordedGeneratorCandidates;
1716
+ const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1717
+ const processedCssAssets = /* @__PURE__ */ new WeakSet();
1718
+ const processedCssAssetFiles = /* @__PURE__ */ new Set();
1719
+ function resolveRuntimeRefreshOptions() {
1720
+ const configPath = require_patcher_options.resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1721
+ const signature = require_logger.getRuntimeClassSetSignature(runtimeState.twPatcher);
1722
+ const optionsKey = JSON.stringify({
1723
+ appType: opts.appType,
1724
+ uniAppX: uniAppXEnabled,
1725
+ customAttributesEntities,
1726
+ disabledDefaultTemplateHandler,
1727
+ configPath,
1728
+ rewriteCssImports: shouldRewriteCssImports
1729
+ });
1730
+ const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1731
+ runtimeRefreshSignature = signature;
1732
+ runtimeRefreshOptionsKey = optionsKey;
1733
+ return {
1734
+ changed,
1735
+ signature,
1736
+ optionsKey
1737
+ };
1738
+ }
1739
+ async function refreshRuntimeState(force) {
1740
+ const invalidation = resolveRuntimeRefreshOptions();
1741
+ const refreshed = await require_recorder.refreshTailwindRuntimeState(runtimeState, {
1742
+ force: force || invalidation.changed,
1743
+ clearCache: force || invalidation.changed
1744
+ });
1745
+ if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
1746
+ if (refreshed) {
1747
+ runtimeSet = void 0;
1748
+ runtimeSetPromise = void 0;
1749
+ }
1750
+ }
1751
+ async function ensureRuntimeClassSet(force = false) {
1752
+ const forceRuntimeRefresh = force || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1753
+ await refreshRuntimeState(force);
1754
+ await runtimeState.patchPromise;
1755
+ if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
1756
+ if (forceRuntimeRefresh || !runtimeSetPromise) {
1757
+ const invalidation = resolveRuntimeRefreshOptions();
1758
+ runtimeSetPromise = require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
1759
+ force: forceRuntimeRefresh || invalidation.changed,
1760
+ skipRefresh: forceRuntimeRefresh,
1761
+ clearCache: forceRuntimeRefresh || invalidation.changed
1762
+ });
1763
+ }
1764
+ const task = runtimeSetPromise;
1765
+ try {
1766
+ runtimeSet = await task;
1767
+ return runtimeSet;
1768
+ } finally {
1769
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1770
+ }
1771
+ }
1772
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
1773
+ const forceRuntimeRefresh = forceRefresh || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1774
+ const invalidation = resolveRuntimeRefreshOptions();
1775
+ const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
1776
+ const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
1777
+ await refreshRuntimeState(shouldRefreshPatcher);
1778
+ await runtimeState.patchPromise;
1779
+ if (shouldRefreshPatcher) {
1780
+ runtimeSet = void 0;
1781
+ runtimeSetPromise = void 0;
1782
+ await bundleRuntimeClassSetManager.reset();
1783
+ }
1784
+ if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
1785
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
1786
+ const shouldForceFullRuntimeSet = forceRuntimeRefresh || invalidation.changed || forceCollectBySource;
1787
+ const fullRuntimeSet = !shouldForceFullRuntimeSet && runtimeSet ? runtimeSet : await require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
1788
+ force: shouldForceFullRuntimeSet,
1789
+ skipRefresh: forceRuntimeRefresh,
1790
+ clearCache: forceRuntimeRefresh || invalidation.changed
1791
+ });
1792
+ const mergedRuntimeSet = new Set([...fullRuntimeSet, ...nextRuntimeSet]);
1793
+ runtimeSet = mergedRuntimeSet;
1794
+ return mergedRuntimeSet;
1795
+ } catch (error) {
1796
+ debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1797
+ await bundleRuntimeClassSetManager.reset();
1798
+ }
1799
+ if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
1800
+ const task = require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
1801
+ force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
1802
+ skipRefresh: forceRuntimeRefresh,
1803
+ clearCache: forceRuntimeRefresh || invalidation.changed
1804
+ });
1805
+ runtimeSetPromise = task;
1806
+ try {
1807
+ runtimeSet = await task;
1808
+ return runtimeSet;
1809
+ } finally {
1810
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1811
+ }
1812
+ }
1813
+ onLoad();
1814
+ const getResolvedConfig = () => resolvedConfig;
1815
+ const markCssAssetProcessed = (asset, file) => {
1816
+ processedCssAssets.add(asset);
1817
+ if (file) processedCssAssetFiles.add(require_css_imports.normalizeOutputPathKey(file));
1818
+ };
1819
+ const isCssAssetProcessed = (asset, file) => {
1820
+ return processedCssAssets.has(asset) || (file ? processedCssAssetFiles.has(require_css_imports.normalizeOutputPathKey(file)) : false);
1821
+ };
1822
+ const recordGeneratorCandidates = (candidates) => {
1823
+ if (!recordedGeneratorCandidates) {
1824
+ recordedGeneratorCandidates = new Set(candidates);
1825
+ return;
1826
+ }
1827
+ for (const candidate of candidates) recordedGeneratorCandidates.add(candidate);
1828
+ };
1829
+ const getRecordedGeneratorCandidates = () => recordedGeneratorCandidates;
1830
+ const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
1831
+ opts,
1832
+ runtimeState,
1833
+ ensureRuntimeClassSet,
1834
+ debug,
1835
+ getResolvedConfig,
1836
+ markCssAssetProcessed,
1837
+ isCssAssetProcessed,
1838
+ getRecordedGeneratorCandidates
1839
+ });
1840
+ const isIosPlatform = require_utils.resolveUniUtsPlatform().isAppIos;
1841
+ const uniAppXPlugins = uniAppXEnabled ? createUniAppXPlugins({
1842
+ appType: opts.appType ?? "uni-app-x",
1843
+ customAttributesEntities,
1844
+ disabledDefaultTemplateHandler,
1845
+ isIosPlatform,
1846
+ mainCssChunkMatcher,
1847
+ runtimeState,
1848
+ styleHandler,
1849
+ jsHandler,
1850
+ ensureRuntimeClassSet,
1851
+ getResolvedConfig,
1852
+ uniAppX
1853
+ }) : void 0;
1854
+ const plugins = [...rewritePlugins, {
1855
+ name: `${require_recorder.vitePluginName}:post`,
1856
+ enforce: "post",
1857
+ config(config) {
1858
+ if (!shouldOwnTailwindGeneration) return;
1859
+ if (Array.isArray(config.plugins)) {
1860
+ const removed = disableAndRemoveTailwindVitePlugins(config.plugins);
1861
+ if (removed > 0) debug("disable official tailwind vite plugins in generator mode: %d", removed);
1862
+ }
1863
+ const root = config.root ? node_path.default.resolve(config.root) : node_process.default.cwd();
1864
+ const baseConfig = { resolve: { alias: [{
1865
+ find: /^tailwindcss$/,
1866
+ replacement: node_path.default.join(weappTailwindcssPackageDir, "generator-placeholder.css")
1867
+ }] } };
1868
+ if (config.css?.postcss !== void 0) return baseConfig;
1869
+ return resolveFilteredPostcssConfig(root).then((postcssConfig) => {
1870
+ if (!postcssConfig) return baseConfig;
1871
+ debug("inline filtered postcss config without official tailwind plugins in generator mode: %d", postcssConfig.removed);
1872
+ return {
1873
+ ...baseConfig,
1874
+ css: { postcss: {
1875
+ ...postcssConfig.options,
1876
+ plugins: postcssConfig.plugins
1877
+ } }
1878
+ };
1879
+ });
1880
+ },
1881
+ async configResolved(config) {
1882
+ resolvedConfig = config;
1883
+ if (shouldOwnTailwindGeneration) {
1884
+ const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
1885
+ if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
1886
+ }
1887
+ const resolvedRoot = config.root ? node_path.default.resolve(config.root) : void 0;
1888
+ let shouldRefreshRuntime = false;
1889
+ if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
1890
+ const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
1891
+ if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
1892
+ const previousBasedir = opts.tailwindcssBasedir;
1893
+ opts.tailwindcssBasedir = nextTailwindcssBasedir;
1894
+ debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
1895
+ shouldRefreshRuntime = true;
1896
+ }
1897
+ }
1898
+ if (!hasExplicitAppType && resolvedRoot) {
1899
+ const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
1900
+ if (nextAppType && opts.appType !== nextAppType) {
1901
+ const previousAppType = opts.appType;
1902
+ opts.appType = nextAppType;
1903
+ _weapp_tailwindcss_logger.logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
1904
+ debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
1905
+ shouldRefreshRuntime = true;
1906
+ }
1907
+ }
1908
+ if (shouldRefreshRuntime) await refreshRuntimeState(true);
1909
+ if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
1910
+ const postcssPlugins = config.css.postcss.plugins;
1911
+ if (shouldOwnTailwindGeneration) {
1912
+ const removed = removeTailwindPostcssPlugins(postcssPlugins);
1913
+ if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
1914
+ }
1915
+ const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
1916
+ if (idx > -1) {
1917
+ postcssPlugins.splice(idx, 1, (0, _weapp_tailwindcss_postcss_html_transform.default)());
1918
+ debug("remove postcss-html-transform plugin from vite config");
1919
+ }
1920
+ }
1921
+ },
1922
+ generateBundle: {
1923
+ order: "post",
1924
+ handler: createGenerateBundleHook({
1925
+ opts,
1926
+ runtimeState,
1927
+ ensureRuntimeClassSet,
1928
+ ensureBundleRuntimeClassSet,
1929
+ debug,
1930
+ getResolvedConfig,
1931
+ markCssAssetProcessed,
1932
+ recordGeneratorCandidates
1933
+ })
1934
+ },
1935
+ outputOptions(options) {
1936
+ const plugins = options.plugins;
1937
+ return {
1938
+ ...options,
1939
+ plugins: Array.isArray(plugins) ? [...plugins, cssFinalizerOutputPlugin] : [cssFinalizerOutputPlugin]
1940
+ };
1941
+ }
1942
+ }];
1943
+ if (uniAppXPlugins) plugins.push(...uniAppXPlugins);
1944
+ return plugins;
1945
+ }
1946
+ //#endregion
1947
+ Object.defineProperty(exports, "UnifiedViteWeappTailwindcssPlugin", {
1948
+ enumerable: true,
1949
+ get: function() {
1950
+ return UnifiedViteWeappTailwindcssPlugin;
1951
+ }
1952
+ });