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