weapp-tailwindcss 4.12.0 → 5.0.0-next.2

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 (313) 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 +43 -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 +22 -0
  13. package/dist/bundlers/vite/generate-bundle.d.ts +33 -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/source-candidates.d.ts +15 -0
  22. package/dist/bundlers/vite/utils.d.ts +9 -0
  23. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +20 -0
  24. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-assets.d.ts +14 -0
  25. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-loaders.d.ts +15 -0
  26. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4.d.ts +9 -0
  27. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +17 -0
  28. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +19 -0
  29. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +9 -0
  30. package/dist/bundlers/webpack/index.d.ts +1 -0
  31. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +12 -0
  32. package/dist/bundlers/webpack/loaders/weapp-tw-runtime-classset-loader.d.ts +11 -0
  33. package/dist/bundlers/webpack/shared/css-imports.d.ts +6 -0
  34. package/dist/bundlers/webpack/shared/loader-anchors.d.ts +8 -0
  35. package/dist/cache/index.d.ts +38 -0
  36. package/dist/cache/md5.d.ts +1 -0
  37. package/dist/chunk-8l464Juk.js +28 -0
  38. package/dist/cli/config.d.ts +5 -0
  39. package/dist/cli/context.d.ts +16 -0
  40. package/dist/cli/doctor/constants.d.ts +7 -0
  41. package/dist/cli/doctor/types.d.ts +31 -0
  42. package/dist/cli/doctor.d.ts +4 -0
  43. package/dist/cli/helpers/options/format.d.ts +2 -0
  44. package/dist/cli/helpers/options/parse.d.ts +3 -0
  45. package/dist/cli/helpers/options/resolve.d.ts +1 -0
  46. package/dist/cli/helpers/options.d.ts +3 -0
  47. package/dist/cli/helpers/patch-cwd.d.ts +1 -0
  48. package/dist/cli/helpers.d.ts +5 -0
  49. package/dist/cli/mount-options/patch-status.d.ts +2 -0
  50. package/dist/cli/mount-options.d.ts +2 -0
  51. package/dist/cli/patch-options.d.ts +6 -0
  52. package/dist/cli/tokens.d.ts +4 -0
  53. package/dist/cli/types.d.ts +17 -0
  54. package/dist/cli/vscode-entry.d.ts +14 -0
  55. package/dist/cli/workspace/package-dirs.d.ts +3 -0
  56. package/dist/cli/workspace/patch-package.d.ts +3 -0
  57. package/dist/cli/workspace/patch-utils.d.ts +3 -0
  58. package/dist/cli/workspace/types.d.ts +11 -0
  59. package/dist/cli/workspace/workspace-globs.d.ts +2 -0
  60. package/dist/cli/workspace/workspace-io.d.ts +1 -0
  61. package/dist/cli/workspace/workspace-lock.d.ts +1 -0
  62. package/dist/cli/workspace.d.ts +2 -0
  63. package/dist/cli.d.ts +1 -2
  64. package/dist/cli.js +2425 -3524
  65. package/dist/cli.mjs +2402 -3505
  66. package/dist/constants-B-_T5UnW.mjs +44 -0
  67. package/dist/constants-p1dyh1x1.js +73 -0
  68. package/dist/constants.d.ts +13 -0
  69. package/dist/context/compiler-context-cache.d.ts +3 -0
  70. package/dist/context/custom-attributes.d.ts +2 -0
  71. package/dist/context/handlers.d.ts +6 -0
  72. package/dist/context/index.d.ts +7 -0
  73. package/dist/context/logger.d.ts +4 -0
  74. package/dist/context/tailwindcss/basedir.d.ts +1 -0
  75. package/dist/context/tailwindcss/rax.d.ts +2 -0
  76. package/dist/context/tailwindcss.d.ts +4 -0
  77. package/dist/context/workspace.d.ts +3 -0
  78. package/dist/core.d.ts +5 -21
  79. package/dist/core.js +138 -180
  80. package/dist/core.mjs +135 -180
  81. package/dist/css-imports-BbrbluP9.js +177 -0
  82. package/dist/css-imports-CSdPq_Sc.mjs +128 -0
  83. package/dist/css-macro/constants.d.ts +14 -0
  84. package/dist/css-macro/index.d.ts +15 -0
  85. package/dist/css-macro/postcss.d.ts +3 -7
  86. package/dist/css-macro/postcss.js +44 -58
  87. package/dist/css-macro/postcss.mjs +44 -56
  88. package/dist/css-macro.d.ts +1 -20
  89. package/dist/css-macro.js +37 -50
  90. package/dist/css-macro.mjs +33 -47
  91. package/dist/debug/index.d.ts +5 -0
  92. package/dist/defaults.d.ts +2 -11
  93. package/dist/defaults.js +132 -8
  94. package/dist/defaults.mjs +128 -7
  95. package/dist/escape.js +31 -54
  96. package/dist/escape.mjs +18 -25
  97. package/dist/experimental/index.d.ts +2 -0
  98. package/dist/experimental/oxc/ast-utils.d.ts +30 -0
  99. package/dist/experimental/oxc/index.d.ts +2 -0
  100. package/dist/experimental/oxc/module-specifiers.d.ts +2 -0
  101. package/dist/experimental/shared/cache.d.ts +3 -0
  102. package/dist/experimental/shared/transform.d.ts +3 -0
  103. package/dist/experimental/shared.d.ts +8 -0
  104. package/dist/experimental/swc/ast-utils.d.ts +30 -0
  105. package/dist/experimental/swc/index.d.ts +2 -0
  106. package/dist/experimental/swc/module-specifiers.d.ts +2 -0
  107. package/dist/generator/index.d.ts +11 -0
  108. package/dist/generator/options.d.ts +17 -0
  109. package/dist/generator/types.d.ts +20 -0
  110. package/dist/generator-Y-Ikv4Fu.mjs +1177 -0
  111. package/dist/generator-css-B5ejWUMv.mjs +1098 -0
  112. package/dist/generator-css-D3OdPRiS.js +1125 -0
  113. package/dist/generator-mmhXzZnv.js +1276 -0
  114. package/dist/generator.d.ts +1 -0
  115. package/dist/generator.js +19 -0
  116. package/dist/generator.mjs +2 -0
  117. package/dist/gulp.d.ts +4 -24
  118. package/dist/gulp.js +271 -13
  119. package/dist/gulp.mjs +263 -13
  120. package/dist/index.d.ts +8 -15
  121. package/dist/index.js +12 -24
  122. package/dist/index.mjs +6 -24
  123. package/dist/js/JsTokenUpdater.d.ts +14 -0
  124. package/dist/js/ModuleGraph.d.ts +18 -0
  125. package/dist/js/NodePathWalker.d.ts +33 -0
  126. package/dist/js/babel/parse.d.ts +9 -0
  127. package/dist/js/babel/process.d.ts +4 -0
  128. package/dist/js/babel.d.ts +13 -0
  129. package/dist/js/class-context.d.ts +3 -0
  130. package/dist/js/evalTransforms.d.ts +7 -0
  131. package/dist/js/handlers.d.ts +5 -0
  132. package/dist/js/index.d.ts +4 -0
  133. package/dist/js/module-graph/ignored-exports.d.ts +18 -0
  134. package/dist/js/module-graph/types.d.ts +17 -0
  135. package/dist/js/node-path-walker/export-handlers.d.ts +12 -0
  136. package/dist/js/node-path-walker/import-tokens.d.ts +24 -0
  137. package/dist/js/precheck.d.ts +2 -0
  138. package/dist/js/sourceAnalysis.d.ts +17 -0
  139. package/dist/js/syntax.d.ts +10 -0
  140. package/dist/js/taggedTemplateIgnore.d.ts +13 -0
  141. package/dist/js/types.d.ts +11 -0
  142. package/dist/lightningcss/index.d.ts +8 -0
  143. package/dist/lightningcss/style-handler/options.d.ts +3 -0
  144. package/dist/lightningcss/style-handler/selector-transform.d.ts +10 -0
  145. package/dist/lightningcss/style-handler/selector-utils.d.ts +10 -0
  146. package/dist/lightningcss/style-handler.d.ts +17 -0
  147. package/dist/loader-anchors-CNkWT8hx.js +273 -0
  148. package/dist/loader-anchors-TrU7EUr7.mjs +205 -0
  149. package/dist/logger/index.d.ts +2 -0
  150. package/dist/logger-BZ45DZJT.js +1003 -0
  151. package/dist/logger-BoVx1Dbt.mjs +935 -0
  152. package/dist/patcher-options-6gJN2EXy.js +115 -0
  153. package/dist/patcher-options-DQfR5xxT.mjs +92 -0
  154. package/dist/postcss-html-transform.d.ts +3 -3
  155. package/dist/postcss-html-transform.js +7 -10
  156. package/dist/postcss-html-transform.mjs +3 -6
  157. package/dist/postcss.d.ts +15 -0
  158. package/dist/postcss.js +280 -0
  159. package/dist/postcss.mjs +270 -0
  160. package/dist/presets/hbuilderx.d.ts +4 -0
  161. package/dist/presets/index.d.ts +3 -0
  162. package/dist/presets/shared.d.ts +10 -0
  163. package/dist/presets/taro.d.ts +4 -0
  164. package/dist/presets/uni-app-x.d.ts +16 -0
  165. package/dist/presets/uni-app.d.ts +4 -0
  166. package/dist/presets.d.ts +1 -76
  167. package/dist/presets.js +115 -163
  168. package/dist/presets.mjs +107 -163
  169. package/dist/recorder-gYSNLfOP.js +2878 -0
  170. package/dist/recorder-zsgatmkB.mjs +2763 -0
  171. package/dist/reset/index.d.ts +2 -0
  172. package/dist/reset.d.ts +1 -4
  173. package/dist/reset.js +19 -8
  174. package/dist/reset.mjs +2 -8
  175. package/dist/shared/classname-transform.d.ts +14 -0
  176. package/dist/shared/mpx.d.ts +7 -0
  177. package/dist/shared/tailwindcss-css-redirect.d.ts +1 -0
  178. package/dist/tailwindcss/index.d.ts +11 -0
  179. package/dist/tailwindcss/miniprogram.d.ts +1 -0
  180. package/dist/tailwindcss/patcher-options.d.ts +56 -0
  181. package/dist/tailwindcss/patcher-resolve.d.ts +4 -0
  182. package/dist/tailwindcss/patcher.d.ts +13 -0
  183. package/dist/tailwindcss/recorder.d.ts +13 -0
  184. package/dist/tailwindcss/remove-unsupported-css.d.ts +2 -0
  185. package/dist/tailwindcss/runtime/cache.d.ts +11 -0
  186. package/dist/tailwindcss/runtime-logs.d.ts +3 -0
  187. package/dist/tailwindcss/runtime.d.ts +29 -0
  188. package/dist/tailwindcss/targets/paths.d.ts +13 -0
  189. package/dist/tailwindcss/targets/record-io.d.ts +5 -0
  190. package/dist/tailwindcss/targets/recorder.d.ts +3 -0
  191. package/dist/tailwindcss/targets/types.d.ts +35 -0
  192. package/dist/tailwindcss/targets.d.ts +6 -0
  193. package/dist/tailwindcss/v3-engine/generator.d.ts +2 -0
  194. package/dist/tailwindcss/v3-engine/index.d.ts +4 -0
  195. package/dist/tailwindcss/v3-engine/miniprogram.d.ts +4 -0
  196. package/dist/tailwindcss/v3-engine/source.d.ts +5 -0
  197. package/dist/tailwindcss/v3-engine/types.d.ts +55 -0
  198. package/dist/tailwindcss/v4/config.d.ts +5 -0
  199. package/dist/tailwindcss/v4/css-entries.d.ts +7 -0
  200. package/dist/tailwindcss/v4/index.d.ts +2 -0
  201. package/dist/tailwindcss/v4/multi-patcher.d.ts +2 -0
  202. package/dist/tailwindcss/v4/patcher-options.d.ts +24 -0
  203. package/dist/tailwindcss/v4/patcher.d.ts +14 -0
  204. package/dist/tailwindcss/v4-engine/candidates.d.ts +2 -0
  205. package/dist/tailwindcss/v4-engine/design-system.d.ts +1 -0
  206. package/dist/tailwindcss/v4-engine/generator.d.ts +2 -0
  207. package/dist/tailwindcss/v4-engine/index.d.ts +5 -0
  208. package/dist/tailwindcss/v4-engine/miniprogram.d.ts +5 -0
  209. package/dist/tailwindcss/v4-engine/source.d.ts +7 -0
  210. package/dist/tailwindcss/v4-engine/tailwind-v3-compatibility.d.ts +1 -0
  211. package/dist/tailwindcss/v4-engine/tailwind-v3-default-colors.d.ts +1 -0
  212. package/dist/tailwindcss/v4-engine/tailwind-v4-default-colors.d.ts +1 -0
  213. package/dist/tailwindcss/v4-engine/types.d.ts +19 -0
  214. package/dist/typedoc.export.d.ts +5 -0
  215. package/dist/types/base.d.ts +1 -0
  216. package/dist/types/disabled-options.d.ts +4 -0
  217. package/dist/types/index.d.ts +104 -0
  218. package/dist/types/shared.d.ts +7 -0
  219. package/dist/types/user-defined-options/general.d.ts +31 -0
  220. package/dist/types/user-defined-options/important.d.ts +37 -0
  221. package/dist/types/user-defined-options/index.d.ts +11 -0
  222. package/dist/types/user-defined-options/lifecycle.d.ts +6 -0
  223. package/dist/types/user-defined-options/matcher.d.ts +9 -0
  224. package/dist/types.d.ts +1 -150
  225. package/dist/types.js +0 -1
  226. package/dist/types.mjs +1 -1
  227. package/dist/uni-app-x/component-local-style.d.ts +19 -0
  228. package/dist/uni-app-x/index.d.ts +2 -0
  229. package/dist/uni-app-x/options.d.ts +12 -0
  230. package/dist/uni-app-x/style-isolation.d.ts +2 -0
  231. package/dist/uni-app-x/transform.d.ts +9 -0
  232. package/dist/uni-app-x/vite.d.ts +36 -0
  233. package/dist/utils/decode.d.ts +2 -0
  234. package/dist/utils/disabled.d.ts +6 -0
  235. package/dist/utils/hbuilderx.d.ts +5 -0
  236. package/dist/utils/index.d.ts +7 -0
  237. package/dist/utils/nameMatcher.d.ts +4 -0
  238. package/dist/utils/resolve-package.d.ts +1 -0
  239. package/dist/utils/uni-platform.d.ts +11 -0
  240. package/dist/utils-7DUGTFED.mjs +48 -0
  241. package/dist/utils-DmC9_In3.js +61 -0
  242. package/dist/vite-BC9U7ahn.js +2199 -0
  243. package/dist/vite-CrlzCNqz.mjs +2186 -0
  244. package/dist/vite.d.ts +4 -17
  245. package/dist/vite.js +5 -14
  246. package/dist/vite.mjs +2 -14
  247. package/dist/weapp-tw-css-import-rewrite-loader.js +59 -92
  248. package/dist/weapp-tw-runtime-classset-loader.js +31 -50
  249. package/dist/webpack-Bu6M-Hbw.mjs +441 -0
  250. package/dist/webpack-DD7A6V0u.js +456 -0
  251. package/dist/webpack.d.ts +4 -25
  252. package/dist/webpack.js +6 -17
  253. package/dist/webpack.mjs +2 -17
  254. package/dist/webpack4.d.ts +4 -26
  255. package/dist/webpack4.js +375 -481
  256. package/dist/webpack4.mjs +366 -482
  257. package/dist/wxml/Tokenizer.d.ts +15 -0
  258. package/dist/wxml/custom-attributes.d.ts +4 -0
  259. package/dist/wxml/index.d.ts +2 -0
  260. package/dist/wxml/shared.d.ts +2 -0
  261. package/dist/wxml/tokenizer/types.d.ts +18 -0
  262. package/dist/wxml/utils/codegen/legacy-rewriter.d.ts +2 -0
  263. package/dist/wxml/utils/codegen/legacy-visitor.d.ts +8 -0
  264. package/dist/wxml/utils/codegen.d.ts +2 -0
  265. package/dist/wxml/utils/custom-template.d.ts +3 -0
  266. package/dist/wxml/utils/fragment-helpers.d.ts +6 -0
  267. package/dist/wxml/utils/fragment-updater.d.ts +4 -0
  268. package/dist/wxml/utils/template-fragments.d.ts +3 -0
  269. package/dist/wxml/utils.d.ts +8 -0
  270. package/dist/wxml/whitespace.d.ts +2 -0
  271. package/generator-placeholder.css +1 -0
  272. package/package.json +19 -8
  273. package/dist/chunk-24AGZQVR.js +0 -183
  274. package/dist/chunk-3VQKDHGP.mjs +0 -179
  275. package/dist/chunk-4AFQP74Z.js +0 -24
  276. package/dist/chunk-57SOQCAU.mjs +0 -582
  277. package/dist/chunk-5ZYHNDEK.mjs +0 -2439
  278. package/dist/chunk-76S2EME4.mjs +0 -34
  279. package/dist/chunk-A5PB4KZT.js +0 -138
  280. package/dist/chunk-DUHYLR2R.js +0 -276
  281. package/dist/chunk-DYLQ6UOI.js +0 -71
  282. package/dist/chunk-E7I5TW5K.js +0 -52
  283. package/dist/chunk-FS2NOOEB.js +0 -292
  284. package/dist/chunk-HVNGIKLS.js +0 -3930
  285. package/dist/chunk-JZQBZHN5.js +0 -579
  286. package/dist/chunk-KGTVD4EP.mjs +0 -3930
  287. package/dist/chunk-NNOQDMUP.mjs +0 -10
  288. package/dist/chunk-OF6MFURR.js +0 -34
  289. package/dist/chunk-OFB2KBRP.js +0 -2442
  290. package/dist/chunk-OOHJLO5M.mjs +0 -71
  291. package/dist/chunk-PCDYXXSK.mjs +0 -1515
  292. package/dist/chunk-RKISS72P.js +0 -7
  293. package/dist/chunk-RRQZL7FQ.mjs +0 -292
  294. package/dist/chunk-XAKAD2CR.mjs +0 -138
  295. package/dist/chunk-XZP3MREK.mjs +0 -276
  296. package/dist/chunk-ZAA5ZG3D.js +0 -1518
  297. package/dist/chunk-ZCH4YINE.mjs +0 -52
  298. package/dist/cli.d.mts +0 -2
  299. package/dist/core.d.mts +0 -26
  300. package/dist/css-macro/postcss.d.mts +0 -7
  301. package/dist/css-macro.d.mts +0 -18
  302. package/dist/defaults.d.mts +0 -11
  303. package/dist/gulp.d.mts +0 -24
  304. package/dist/index-BXrmQelt.d.mts +0 -672
  305. package/dist/index-BXrmQelt.d.ts +0 -672
  306. package/dist/index.d.mts +0 -15
  307. package/dist/postcss-html-transform.d.mts +0 -2
  308. package/dist/presets.d.mts +0 -76
  309. package/dist/reset.d.mts +0 -1
  310. package/dist/types.d.mts +0 -150
  311. package/dist/vite.d.mts +0 -17
  312. package/dist/webpack.d.mts +0 -25
  313. package/dist/webpack4.d.mts +0 -26
@@ -0,0 +1,2763 @@
1
+ import { i as isMap, n as defuOverrideArray } from "./utils-7DUGTFED.mjs";
2
+ import { getDefaultOptions } from "./defaults.mjs";
3
+ import { a as resolveUniAppXOptions, c as warnMissingCssEntries, d as getRuntimeClassSetSignature, f as invalidateRuntimeClassSet, i as isUniAppXEnabled, l as findNearestPackageRoot, n as createTailwindcssPatcherFromContext, s as applyV4CssCalcDefaults, t as logger$1, u as getRuntimeClassSetCacheEntry } from "./logger-BoVx1Dbt.mjs";
4
+ import { createStyleHandler } from "@weapp-tailwindcss/postcss";
5
+ import path from "node:path";
6
+ import process from "node:process";
7
+ import { Buffer } from "node:buffer";
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { mkdir, rm, writeFile } from "node:fs/promises";
10
+ import { logger, pc } from "@weapp-tailwindcss/logger";
11
+ import { LRUCache } from "lru-cache";
12
+ import { md5 as md5Hash } from "@weapp-tailwindcss/shared/node";
13
+ import { MappingChars2String, escape } from "@weapp-core/escape";
14
+ import _createDebug from "debug";
15
+ import _babelTraverse from "@babel/traverse";
16
+ import { parse, parseExpression } from "@babel/parser";
17
+ import { escapeStringRegexp } from "@weapp-core/regex";
18
+ import MagicString from "magic-string";
19
+ import { jsStringEscape } from "@ast-core/escape";
20
+ import { splitCode } from "@weapp-tailwindcss/shared/extractors";
21
+ import * as t from "@babel/types";
22
+ import { Parser } from "htmlparser2";
23
+ //#region src/cache/index.ts
24
+ function isProcessResult(value) {
25
+ return typeof value === "object" && value !== null && "result" in value;
26
+ }
27
+ function createCache(options) {
28
+ const disabled = options === false;
29
+ const hashMap = /* @__PURE__ */ new Map();
30
+ const instance = new LRUCache({
31
+ max: 1024,
32
+ ttl: 0,
33
+ ttlAutopurge: false
34
+ });
35
+ const cache = {
36
+ hashMap,
37
+ instance,
38
+ hasHashKey(key) {
39
+ return hashMap.has(key);
40
+ },
41
+ getHashValue(key) {
42
+ return hashMap.get(key);
43
+ },
44
+ setHashValue(key, value) {
45
+ return hashMap.set(key, value);
46
+ },
47
+ get(key) {
48
+ return instance.get(key);
49
+ },
50
+ set(key, value) {
51
+ return instance.set(key, value);
52
+ },
53
+ computeHash(message) {
54
+ return md5Hash(message);
55
+ },
56
+ calcHashValueChanged(key, hash) {
57
+ const hit = hashMap.get(key);
58
+ if (hit) hashMap.set(key, {
59
+ changed: hash !== hit.hash,
60
+ hash
61
+ });
62
+ else hashMap.set(key, {
63
+ changed: true,
64
+ hash
65
+ });
66
+ return cache;
67
+ },
68
+ has(key) {
69
+ return instance.has(key);
70
+ },
71
+ async process({ key, hashKey, rawSource, hash, resolveCache, transform, onCacheHit }) {
72
+ if (disabled) {
73
+ const value = await transform();
74
+ return isProcessResult(value) ? value.result : value;
75
+ }
76
+ const cacheHashKey = hashKey ?? key;
77
+ let hasChanged = true;
78
+ if (hash != null || rawSource != null) {
79
+ const nextHash = hash ?? cache.computeHash(rawSource);
80
+ cache.calcHashValueChanged(cacheHashKey, nextHash);
81
+ hasChanged = cache.getHashValue(cacheHashKey)?.changed ?? true;
82
+ }
83
+ const readCache = resolveCache ?? (() => cache.get(key));
84
+ if (!hasChanged) {
85
+ const cached = readCache();
86
+ if (cached !== void 0) {
87
+ await onCacheHit?.(cached);
88
+ return cached;
89
+ }
90
+ }
91
+ const value = await transform();
92
+ const normalized = isProcessResult(value) ? value : { result: value };
93
+ const stored = normalized.cacheValue ?? normalized.result;
94
+ cache.set(key, stored);
95
+ return normalized.result;
96
+ }
97
+ };
98
+ return cache;
99
+ }
100
+ function initializeCache(cacheConfig) {
101
+ if (typeof cacheConfig === "boolean" || cacheConfig === void 0) return createCache(cacheConfig);
102
+ return cacheConfig;
103
+ }
104
+ //#endregion
105
+ //#region src/debug/index.ts
106
+ const _debug = _createDebug("weapp-tw");
107
+ function createDebug(prefix) {
108
+ const debug = ((formatter, ...args) => {
109
+ return _debug((prefix ?? "") + formatter, ...args);
110
+ });
111
+ Object.defineProperty(debug, "enabled", {
112
+ enumerable: false,
113
+ configurable: false,
114
+ get() {
115
+ return _debug.enabled;
116
+ }
117
+ });
118
+ return debug;
119
+ }
120
+ //#endregion
121
+ //#region src/tailwindcss/runtime.ts
122
+ const debug$1 = createDebug("[tailwindcss:runtime] ");
123
+ const refreshTailwindcssPatcherSymbol = Symbol.for("weapp-tailwindcss.refreshTailwindcssPatcher");
124
+ function createTailwindPatchPromise(twPatcher, onPatched) {
125
+ return Promise.resolve(twPatcher.patch()).then(async () => {
126
+ invalidateRuntimeClassSet(twPatcher);
127
+ if (onPatched) try {
128
+ await onPatched();
129
+ } catch (error) {
130
+ debug$1("failed to persist patch target after patch(): %O", error);
131
+ }
132
+ });
133
+ }
134
+ const runtimeClassSetStateCache = /* @__PURE__ */ new WeakMap();
135
+ function getRuntimeClassSetStateEntry(state) {
136
+ let entry = runtimeClassSetStateCache.get(state);
137
+ if (!entry) {
138
+ entry = {};
139
+ runtimeClassSetStateCache.set(state, entry);
140
+ }
141
+ return entry;
142
+ }
143
+ async function refreshTailwindRuntimeState(state, forceOrOptions) {
144
+ const normalizedOptions = typeof forceOrOptions === "boolean" ? { force: forceOrOptions } : forceOrOptions;
145
+ const force = normalizedOptions.force;
146
+ const clearCache = normalizedOptions.clearCache === true;
147
+ if (!force) return false;
148
+ debug$1("refresh runtime state start, clearCache=%s major=%s", clearCache, state.twPatcher.majorVersion ?? "unknown");
149
+ await state.patchPromise;
150
+ let refreshed = false;
151
+ if (typeof state.refreshTailwindcssPatcher === "function") {
152
+ const next = await state.refreshTailwindcssPatcher({ clearCache });
153
+ if (next !== state.twPatcher) state.twPatcher = next;
154
+ refreshed = true;
155
+ }
156
+ if (refreshed) state.patchPromise = createTailwindPatchPromise(state.twPatcher, state.onPatchCompleted);
157
+ debug$1("refresh runtime state end, refreshed=%s major=%s", refreshed, state.twPatcher.majorVersion ?? "unknown");
158
+ return refreshed;
159
+ }
160
+ async function ensureRuntimeClassSet(state, options = {}) {
161
+ const forceRefresh = options.forceRefresh === true;
162
+ const forceCollect = options.forceCollect === true;
163
+ const clearCache = options.clearCache === true;
164
+ const allowEmpty = options.allowEmpty === true;
165
+ if (forceRefresh) await refreshTailwindRuntimeState(state, {
166
+ force: true,
167
+ clearCache
168
+ });
169
+ await state.patchPromise;
170
+ const entry = getRuntimeClassSetStateEntry(state);
171
+ const signature = getRuntimeClassSetSignature(state.twPatcher);
172
+ const signatureChanged = entry.signature !== signature;
173
+ const shouldForceCollect = forceCollect || forceRefresh || signatureChanged;
174
+ if (!shouldForceCollect) {
175
+ if (entry.value && (allowEmpty || entry.value.size > 0)) return entry.value;
176
+ if (entry.promise) return entry.promise;
177
+ }
178
+ const task = (async () => {
179
+ const collected = await collectRuntimeClassSet(state.twPatcher, {
180
+ force: shouldForceCollect,
181
+ skipRefresh: true,
182
+ clearCache
183
+ });
184
+ if (allowEmpty || collected.size > 0) return collected;
185
+ await refreshTailwindRuntimeState(state, {
186
+ force: true,
187
+ clearCache: true
188
+ });
189
+ await state.patchPromise;
190
+ return collectRuntimeClassSet(state.twPatcher, {
191
+ force: true,
192
+ skipRefresh: true,
193
+ clearCache: true
194
+ });
195
+ })();
196
+ entry.promise = task;
197
+ try {
198
+ const runtimeSet = await task;
199
+ entry.value = runtimeSet;
200
+ entry.signature = getRuntimeClassSetSignature(state.twPatcher);
201
+ return runtimeSet;
202
+ } finally {
203
+ if (entry.promise === task) entry.promise = void 0;
204
+ }
205
+ }
206
+ function shouldPreferSync(majorVersion) {
207
+ if (majorVersion == null) return true;
208
+ if (majorVersion === 3) return true;
209
+ if (majorVersion === 4) return true;
210
+ return false;
211
+ }
212
+ function tryGetRuntimeClassSetSync(twPatcher) {
213
+ if (typeof twPatcher.getClassSetSync !== "function") return;
214
+ if (!shouldPreferSync(twPatcher.majorVersion)) return;
215
+ try {
216
+ const set = twPatcher.getClassSetSync();
217
+ if (set && set.size === 0) return;
218
+ return set;
219
+ } catch (error) {
220
+ if (twPatcher.majorVersion === 4) debug$1("getClassSetSync() unavailable for tailwindcss v4, fallback to async getClassSet(): %O", error);
221
+ else debug$1("getClassSetSync() failed, fallback to async getClassSet(): %O", error);
222
+ return;
223
+ }
224
+ }
225
+ async function collectRuntimeClassSet(twPatcher, options = {}) {
226
+ let activePatcher = twPatcher;
227
+ if (options.force && !options.skipRefresh) {
228
+ const refresh = activePatcher[refreshTailwindcssPatcherSymbol];
229
+ if (typeof refresh === "function") try {
230
+ const refreshed = await refresh({ clearCache: options.clearCache === true });
231
+ if (refreshed) activePatcher = refreshed;
232
+ } catch (error) {
233
+ debug$1("refreshTailwindcssPatcher failed, continuing with existing patcher: %O", error);
234
+ }
235
+ }
236
+ const entry = getRuntimeClassSetCacheEntry(activePatcher);
237
+ const signature = getRuntimeClassSetSignature(activePatcher);
238
+ if (!options.force) {
239
+ if (entry.value && entry.signature === signature) return entry.value;
240
+ if (entry.promise) return entry.promise;
241
+ } else entry.value = void 0;
242
+ const task = (async () => {
243
+ const preExtractSyncSet = options.force ? tryGetRuntimeClassSetSync(activePatcher) : void 0;
244
+ if (preExtractSyncSet) debug$1("runtime class set snapshot via getClassSetSync() before extract(), size=%d", preExtractSyncSet.size);
245
+ const preferExtract = options.force === true;
246
+ try {
247
+ const result = await activePatcher.extract({ write: false });
248
+ if (result?.classSet) {
249
+ if (result.classSet.size > 0) {
250
+ debug$1("runtime class set resolved via extract(), size=%d", result.classSet.size);
251
+ return result.classSet;
252
+ }
253
+ if (preferExtract) debug$1("runtime class set from extract() is empty on force collect, fallback to sync/async class set");
254
+ else debug$1("runtime class set from extract() is empty, fallback to sync/async class set");
255
+ }
256
+ } catch (error) {
257
+ debug$1("extract() failed, fallback to getClassSet(): %O", error);
258
+ }
259
+ if (preExtractSyncSet) {
260
+ debug$1("runtime class set fallback to pre-extract sync snapshot, size=%d", preExtractSyncSet.size);
261
+ return preExtractSyncSet;
262
+ }
263
+ const syncSet = tryGetRuntimeClassSetSync(activePatcher);
264
+ if (syncSet) {
265
+ debug$1("runtime class set resolved via getClassSetSync(), size=%d", syncSet.size);
266
+ return syncSet;
267
+ }
268
+ try {
269
+ const fallbackSet = await Promise.resolve(activePatcher.getClassSet());
270
+ if (fallbackSet) {
271
+ debug$1("runtime class set resolved via getClassSet(), size=%d", fallbackSet.size);
272
+ return fallbackSet;
273
+ }
274
+ } catch (error) {
275
+ debug$1("getClassSet() failed, returning empty set: %O", error);
276
+ }
277
+ return /* @__PURE__ */ new Set();
278
+ })();
279
+ entry.promise = task;
280
+ entry.signature = signature;
281
+ try {
282
+ const resolved = await task;
283
+ entry.value = resolved;
284
+ entry.promise = void 0;
285
+ entry.signature = signature;
286
+ return resolved;
287
+ } catch (error) {
288
+ entry.promise = void 0;
289
+ throw error;
290
+ }
291
+ }
292
+ //#endregion
293
+ //#region src/tailwindcss/runtime-logs.ts
294
+ const runtimeLogDedupeHolder = globalThis;
295
+ const runtimeLogDedupe = runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ ?? (runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ = /* @__PURE__ */ new Set());
296
+ function createRuntimeLogKey(category, baseDir, rootPath, version) {
297
+ return JSON.stringify([
298
+ category,
299
+ baseDir ?? process.cwd(),
300
+ rootPath ?? "",
301
+ version ?? ""
302
+ ]);
303
+ }
304
+ function markRuntimeLog(category, baseDir, rootPath, version) {
305
+ const key = createRuntimeLogKey(category, baseDir, rootPath, version);
306
+ if (runtimeLogDedupe.has(key)) return false;
307
+ runtimeLogDedupe.add(key);
308
+ return true;
309
+ }
310
+ function logRuntimeTailwindcssTarget(baseDir, rootPath, version) {
311
+ if (!markRuntimeLog("target", baseDir, rootPath, version)) return;
312
+ const versionText = version ? ` (v${version})` : "";
313
+ logger.info("%s 使用 Tailwind CSS%s", "Weapp-tailwindcss", versionText);
314
+ }
315
+ function logRuntimeTailwindcssVersion(baseDir, rootPath, version) {
316
+ if (version) {
317
+ if (!markRuntimeLog("version", baseDir, rootPath, version)) return;
318
+ logger.success(`当前使用 ${pc.cyanBright("Tailwind CSS")} 版本为: ${pc.underline(pc.bold(pc.green(version)))}`);
319
+ return;
320
+ }
321
+ if (!markRuntimeLog("missing", baseDir, rootPath, version)) return;
322
+ logger.warn(`${pc.cyanBright("Tailwind CSS")} 未安装,已跳过版本检测与补丁应用。`);
323
+ }
324
+ //#endregion
325
+ //#region src/tailwindcss/targets/paths.ts
326
+ const PATCH_INFO_FILENAME = "tailwindcss-target.json";
327
+ const PATCH_INFO_CACHE_RELATIVE_PATH = path.join("node_modules", ".cache", "weapp-tailwindcss", PATCH_INFO_FILENAME);
328
+ const PATCH_INFO_LEGACY_RELATIVE_PATH = path.join(".tw-patch", PATCH_INFO_FILENAME);
329
+ function toDisplayPath(value) {
330
+ return path.normalize(value).replace(/\\/g, "/");
331
+ }
332
+ function formatRelativeToBase(targetPath, baseDir) {
333
+ if (!baseDir) return toDisplayPath(targetPath);
334
+ const relative = path.relative(baseDir, targetPath);
335
+ if (!relative || relative === ".") return ".";
336
+ if (relative.startsWith("..")) return toDisplayPath(targetPath);
337
+ return toDisplayPath(path.join(".", relative));
338
+ }
339
+ function resolveRecordLocation(baseDir) {
340
+ const normalizedBase = path.normalize(baseDir);
341
+ const packageRoot = findNearestPackageRoot(normalizedBase) ?? normalizedBase;
342
+ const packageJsonPath = path.join(packageRoot, "package.json");
343
+ const hasPackageJson = existsSync(packageJsonPath);
344
+ const recordKeySource = hasPackageJson ? packageJsonPath : normalizedBase;
345
+ const recordKey = md5Hash(path.normalize(recordKeySource));
346
+ const recordDir = path.join(packageRoot, "node_modules", ".cache", "weapp-tailwindcss", recordKey);
347
+ return {
348
+ normalizedBase,
349
+ packageRoot,
350
+ recordDir,
351
+ recordKey,
352
+ recordPath: path.join(recordDir, PATCH_INFO_FILENAME),
353
+ packageJsonPath: hasPackageJson ? packageJsonPath : void 0
354
+ };
355
+ }
356
+ function getRecordFileCandidates(baseDir) {
357
+ const { normalizedBase, packageRoot, recordPath } = resolveRecordLocation(baseDir);
358
+ return [...new Set([
359
+ recordPath,
360
+ path.join(packageRoot, PATCH_INFO_CACHE_RELATIVE_PATH),
361
+ path.join(normalizedBase, PATCH_INFO_CACHE_RELATIVE_PATH),
362
+ path.join(normalizedBase, PATCH_INFO_LEGACY_RELATIVE_PATH)
363
+ ])];
364
+ }
365
+ //#endregion
366
+ //#region package.json
367
+ var version = "5.0.0-next.2";
368
+ //#endregion
369
+ //#region src/constants.ts
370
+ const pluginName = "weapp-tailwindcss-webpack-plugin";
371
+ const vitePluginName = "weapp-tailwindcss:adaptor";
372
+ const WEAPP_TW_VERSION = version;
373
+ const DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS = {
374
+ "tailwind-merge": "@weapp-tailwindcss/merge",
375
+ "class-variance-authority": "@weapp-tailwindcss/cva",
376
+ "tailwind-variants": "@weapp-tailwindcss/variants"
377
+ };
378
+ //#endregion
379
+ //#region src/tailwindcss/targets/record-io.ts
380
+ const loggedInvalidPatchRecords = /* @__PURE__ */ new Set();
381
+ function warnInvalidPatchTargetRecord(baseDir, recordPath, reason) {
382
+ const normalizedPath = path.normalize(recordPath);
383
+ if (loggedInvalidPatchRecords.has(normalizedPath)) return;
384
+ loggedInvalidPatchRecords.add(normalizedPath);
385
+ const fileDisplay = formatRelativeToBase(normalizedPath, baseDir);
386
+ const baseDisplay = formatRelativeToBase(path.normalize(baseDir), process.cwd());
387
+ const reasonMessage = reason ? `:${reason}` : "";
388
+ logger.warn(`检测到损坏的 Tailwind CSS 目标记录 ${fileDisplay}${reasonMessage}。请在 ${baseDisplay} 重新执行 "weapp-tw patch --record-target" 或删除该文件后再运行。`);
389
+ }
390
+ function readPatchTargetRecord(baseDir) {
391
+ if (!baseDir) return;
392
+ const normalizedBase = path.normalize(baseDir);
393
+ for (const recordPath of getRecordFileCandidates(normalizedBase)) {
394
+ if (!existsSync(recordPath)) continue;
395
+ try {
396
+ const content = readFileSync(recordPath, "utf8");
397
+ const parsed = JSON.parse(content);
398
+ if (!parsed || typeof parsed.tailwindPackagePath !== "string") {
399
+ warnInvalidPatchTargetRecord(normalizedBase, recordPath, "缺少 tailwindPackagePath 字段");
400
+ continue;
401
+ }
402
+ return {
403
+ baseDir: normalizedBase,
404
+ path: recordPath,
405
+ record: parsed
406
+ };
407
+ } catch (error) {
408
+ warnInvalidPatchTargetRecord(normalizedBase, recordPath, error instanceof Error ? error.message : String(error));
409
+ continue;
410
+ }
411
+ }
412
+ }
413
+ async function saveCliPatchTargetRecord(baseDir, patcher, options) {
414
+ if (!baseDir || !patcher?.packageInfo?.rootPath) return;
415
+ const normalizedBase = path.normalize(baseDir);
416
+ const location = resolveRecordLocation(normalizedBase);
417
+ const recordPath = options?.recordPath ? path.normalize(options.recordPath) : location.recordPath;
418
+ const record = {
419
+ tailwindPackagePath: path.normalize(patcher.packageInfo.rootPath),
420
+ packageVersion: patcher.packageInfo.version,
421
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
422
+ source: options?.source ?? "cli",
423
+ tailwindcssBasedir: normalizedBase,
424
+ cwd: options?.cwd ? path.normalize(options.cwd) : normalizedBase,
425
+ patchVersion: WEAPP_TW_VERSION,
426
+ packageJsonPath: options?.packageJsonPath ?? location.packageJsonPath,
427
+ recordKey: options?.recordKey ?? location.recordKey
428
+ };
429
+ try {
430
+ await mkdir(path.dirname(recordPath), { recursive: true });
431
+ await writeFile(recordPath, `${JSON.stringify(record, null, 2)}\n`, "utf8");
432
+ return recordPath;
433
+ } catch (error) {
434
+ const baseDisplay = formatRelativeToBase(normalizedBase, process.cwd());
435
+ logger.warn("自动更新 Tailwind CSS 补丁记录失败,请在 %s 运行 \"weapp-tw patch --cwd %s\"。", baseDisplay, normalizedBase);
436
+ logger.debug("failed to persist patch target record %s: %O", recordPath, error);
437
+ return;
438
+ }
439
+ }
440
+ //#endregion
441
+ //#region src/tailwindcss/targets/recorder.ts
442
+ function findPatchTargetRecord(baseDir) {
443
+ const visited = /* @__PURE__ */ new Set();
444
+ const fallback = baseDir ?? process.cwd();
445
+ let current = path.resolve(fallback);
446
+ while (!visited.has(current)) {
447
+ const record = readPatchTargetRecord(current);
448
+ if (record) return record;
449
+ const parent = path.dirname(current);
450
+ if (parent === current) break;
451
+ visited.add(current);
452
+ current = parent;
453
+ }
454
+ }
455
+ function createPatchTargetRecorder(baseDir, patcher, options) {
456
+ if (!baseDir || !patcher?.packageInfo?.rootPath || options?.recordTarget === false) return;
457
+ const normalizedBase = path.normalize(baseDir);
458
+ const recorded = findPatchTargetRecord(normalizedBase);
459
+ const location = resolveRecordLocation(normalizedBase);
460
+ const expectedPath = path.normalize(patcher.packageInfo.rootPath);
461
+ let reason;
462
+ if (!recorded) reason = "missing";
463
+ else if (path.normalize(recorded.record.tailwindPackagePath) !== expectedPath) reason = "mismatch";
464
+ else if (path.normalize(recorded.path) !== path.normalize(location.recordPath) || !recorded.record.recordKey || recorded.record.recordKey !== location.recordKey) reason = "migrate";
465
+ else if (!recorded.record.patchVersion || recorded.record.patchVersion !== WEAPP_TW_VERSION) reason = "stale";
466
+ else if (options?.cwd && recorded.record.cwd && path.normalize(recorded.record.cwd) !== path.normalize(options.cwd)) reason = "metadata";
467
+ else if (!recorded.record.cwd && options?.cwd) reason = "metadata";
468
+ if (!(options?.alwaysRecord || !recorded || Boolean(reason))) return;
469
+ let message;
470
+ switch (reason) {
471
+ case "mismatch":
472
+ message = "检测到 Tailwind CSS 目标记录与当前解析结果不一致,正在自动重新 patch 并刷新缓存。";
473
+ break;
474
+ case "migrate":
475
+ case "stale":
476
+ message = "正在刷新当前子包的 Tailwind CSS 补丁记录,确保缓存隔离。";
477
+ break;
478
+ case "missing":
479
+ message = "未找到当前子包的 Tailwind CSS 目标记录,正在生成。";
480
+ break;
481
+ default: break;
482
+ }
483
+ const onPatched = async () => saveCliPatchTargetRecord(normalizedBase, patcher, {
484
+ cwd: options?.cwd ?? normalizedBase,
485
+ source: options?.source ?? "cli",
486
+ recordPath: location.recordPath,
487
+ recordKey: location.recordKey,
488
+ packageJsonPath: location.packageJsonPath
489
+ });
490
+ return {
491
+ recordPath: location.recordPath,
492
+ message,
493
+ reason,
494
+ onPatched
495
+ };
496
+ }
497
+ //#endregion
498
+ //#region src/tailwindcss/targets.ts
499
+ function logTailwindcssTarget(kind, patcher, baseDir) {
500
+ const packageInfo = patcher?.packageInfo;
501
+ const label = kind === "cli" ? "weapp-tw patch" : "Weapp-tailwindcss";
502
+ if (!packageInfo?.rootPath) {
503
+ logger.warn("%s 未找到 Tailwind CSS 依赖,请检查在 %s 是否已安装 tailwindcss", label, baseDir ?? process.cwd());
504
+ return;
505
+ }
506
+ const displayPath = formatRelativeToBase(packageInfo.rootPath, baseDir);
507
+ const version = packageInfo.version ? ` (v${packageInfo.version})` : "";
508
+ if (kind === "runtime") {
509
+ logRuntimeTailwindcssTarget(baseDir, packageInfo.rootPath, packageInfo.version);
510
+ return;
511
+ }
512
+ logger.info("%s 绑定 Tailwind CSS -> %s%s", label, displayPath, version);
513
+ }
514
+ //#endregion
515
+ //#region src/context/compiler-context-cache.ts
516
+ const PAREN_CONTENT_RE = /\(([^)]+)\)/u;
517
+ const AT_LOCATION_RE = /at\s+(\S.*)$/u;
518
+ const TRAILING_LINE_COL_RE = /:\d+(?::\d+)?$/u;
519
+ const globalCacheHolder = globalThis;
520
+ const compilerContextCache = globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ ?? (globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ = /* @__PURE__ */ new Map());
521
+ const compilerContextKeyCacheByOptions = /* @__PURE__ */ new WeakMap();
522
+ const compilerContextKeyCacheWithoutOptions = /* @__PURE__ */ new Map();
523
+ function withCircularGuard(value, stack, factory) {
524
+ if (stack.has(value)) throw new TypeError("Cannot serialize circular structure in compiler context options");
525
+ stack.add(value);
526
+ try {
527
+ return factory();
528
+ } finally {
529
+ stack.delete(value);
530
+ }
531
+ }
532
+ function encodeTaggedValue(type, value) {
533
+ const record = { __type: type };
534
+ if (value !== void 0) record.value = value;
535
+ return record;
536
+ }
537
+ function hasExplicitOptionBasedir(opts) {
538
+ return typeof opts?.tailwindcssBasedir === "string" && opts.tailwindcssBasedir.length > 0;
539
+ }
540
+ function shouldProbeCallerLocation(opts) {
541
+ if (hasExplicitOptionBasedir(opts)) return false;
542
+ return !(process.env.WEAPP_TAILWINDCSS_BASEDIR || process.env.WEAPP_TAILWINDCSS_BASE_DIR || process.env.TAILWINDCSS_BASEDIR || process.env.TAILWINDCSS_BASE_DIR);
543
+ }
544
+ function detectCallerLocation() {
545
+ const stack = (/* @__PURE__ */ new Error("compiler-context-cache stack probe")).stack;
546
+ if (!stack) return;
547
+ const lines = stack.split("\n");
548
+ for (const line of lines) {
549
+ const location = (line.match(PAREN_CONTENT_RE) ?? line.match(AT_LOCATION_RE))?.[1];
550
+ if (!location) continue;
551
+ const candidatePath = location.replace(TRAILING_LINE_COL_RE, "");
552
+ if (!candidatePath || !path.isAbsolute(candidatePath)) continue;
553
+ if (candidatePath.includes(`${path.sep}weapp-tailwindcss${path.sep}src${path.sep}`) || candidatePath.includes(`${path.sep}weapp-tailwindcss${path.sep}dist${path.sep}`) || candidatePath.includes(`${path.sep}node_modules${path.sep}weapp-tailwindcss${path.sep}`)) continue;
554
+ return candidatePath;
555
+ }
556
+ }
557
+ function getRuntimeCacheScope(opts) {
558
+ if (hasExplicitOptionBasedir(opts)) return { caller: void 0 };
559
+ const runtimeScope = {
560
+ caller: void 0,
561
+ cwd: process.cwd(),
562
+ init_cwd: process.env.INIT_CWD,
563
+ npm_config_local_prefix: process.env.npm_config_local_prefix,
564
+ npm_package_json: process.env.npm_package_json,
565
+ pnpm_package_name: process.env.PNPM_PACKAGE_NAME,
566
+ pwd: process.env.PWD,
567
+ tailwindcss_base_dir: process.env.TAILWINDCSS_BASE_DIR,
568
+ tailwindcss_basedir: process.env.TAILWINDCSS_BASEDIR,
569
+ uni_app_input_dir: process.env.UNI_APP_INPUT_DIR,
570
+ uni_cli_root: process.env.UNI_CLI_ROOT,
571
+ uni_input_dir: process.env.UNI_INPUT_DIR,
572
+ uni_input_root: process.env.UNI_INPUT_ROOT,
573
+ weapp_tailwindcss_base_dir: process.env.WEAPP_TAILWINDCSS_BASE_DIR,
574
+ weapp_tailwindcss_basedir: process.env.WEAPP_TAILWINDCSS_BASEDIR
575
+ };
576
+ if (shouldProbeCallerLocation(opts)) runtimeScope.caller = detectCallerLocation();
577
+ return runtimeScope;
578
+ }
579
+ function serializeNormalizedValue(value) {
580
+ return JSON.stringify(value);
581
+ }
582
+ function createRuntimeCacheScopeKey(opts) {
583
+ return serializeNormalizedValue(normalizeOptionsValue(getRuntimeCacheScope(opts)));
584
+ }
585
+ function getCompilerContextKeyCacheStore(opts) {
586
+ if (!opts) return compilerContextKeyCacheWithoutOptions;
587
+ let store = compilerContextKeyCacheByOptions.get(opts);
588
+ if (!store) {
589
+ store = /* @__PURE__ */ new Map();
590
+ compilerContextKeyCacheByOptions.set(opts, store);
591
+ }
592
+ return store;
593
+ }
594
+ function createComparableNormalizedValue(rawValue, stack) {
595
+ const normalized = normalizeOptionsValue(rawValue, stack);
596
+ return {
597
+ normalized,
598
+ sortKey: serializeNormalizedValue(normalized)
599
+ };
600
+ }
601
+ function getRuntimeCacheScopeValue(opts) {
602
+ return {
603
+ options: opts ?? {},
604
+ runtime: getRuntimeCacheScope(opts)
605
+ };
606
+ }
607
+ function normalizeOptionsValue(rawValue, stack = /* @__PURE__ */ new WeakSet()) {
608
+ if (rawValue === null) return null;
609
+ if (rawValue === void 0) return encodeTaggedValue("Undefined");
610
+ const type = typeof rawValue;
611
+ if (type === "string") return rawValue;
612
+ if (type === "boolean") return rawValue;
613
+ if (type === "number") {
614
+ const numericValue = rawValue;
615
+ if (Number.isNaN(numericValue)) return encodeTaggedValue("Number", "NaN");
616
+ if (!Number.isFinite(numericValue)) return encodeTaggedValue("Number", numericValue > 0 ? "Infinity" : "-Infinity");
617
+ if (Object.is(numericValue, -0)) return encodeTaggedValue("Number", "-0");
618
+ return numericValue;
619
+ }
620
+ if (type === "bigint") return encodeTaggedValue("BigInt", rawValue.toString());
621
+ if (type === "symbol") {
622
+ const symbolValue = rawValue;
623
+ return encodeTaggedValue("Symbol", symbolValue.description ?? String(symbolValue));
624
+ }
625
+ if (type === "function") return encodeTaggedValue("Function", rawValue.toString());
626
+ if (Array.isArray(rawValue)) return withCircularGuard(rawValue, stack, () => rawValue.map((item) => normalizeOptionsValue(item, stack)));
627
+ if (rawValue instanceof Date) return encodeTaggedValue("Date", rawValue.toISOString());
628
+ if (rawValue instanceof RegExp) return {
629
+ __type: "RegExp",
630
+ source: rawValue.source,
631
+ flags: rawValue.flags
632
+ };
633
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(rawValue)) return encodeTaggedValue("Buffer", rawValue.toString("base64"));
634
+ if (ArrayBuffer.isView(rawValue)) {
635
+ const view = rawValue;
636
+ const buffer = Buffer.from(view.buffer, view.byteOffset, view.byteLength);
637
+ return encodeTaggedValue(view.constructor?.name ?? "ArrayBufferView", buffer.toString("base64"));
638
+ }
639
+ if (rawValue instanceof ArrayBuffer) return encodeTaggedValue("ArrayBuffer", Buffer.from(rawValue).toString("base64"));
640
+ if (rawValue instanceof Set) return withCircularGuard(rawValue, stack, () => {
641
+ const normalizedEntries = Array.from(rawValue, (element) => createComparableNormalizedValue(element, stack));
642
+ normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
643
+ return {
644
+ __type: "Set",
645
+ value: normalizedEntries.map((entry) => entry.normalized)
646
+ };
647
+ });
648
+ if (rawValue instanceof Map) return withCircularGuard(rawValue, stack, () => {
649
+ const normalizedEntries = Array.from(rawValue.entries(), ([key, entryValue]) => {
650
+ const normalizedKey = createComparableNormalizedValue(key, stack);
651
+ return {
652
+ key: normalizedKey.normalized,
653
+ sortKey: normalizedKey.sortKey,
654
+ value: normalizeOptionsValue(entryValue, stack)
655
+ };
656
+ });
657
+ normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
658
+ return {
659
+ __type: "Map",
660
+ value: normalizedEntries.map((entry) => [entry.key, entry.value])
661
+ };
662
+ });
663
+ if (typeof URL !== "undefined" && rawValue instanceof URL) return encodeTaggedValue("URL", rawValue.toString());
664
+ if (rawValue instanceof Error) {
665
+ const errorValue = rawValue;
666
+ return {
667
+ __type: "Error",
668
+ name: errorValue.name,
669
+ message: errorValue.message,
670
+ stack: errorValue.stack ?? ""
671
+ };
672
+ }
673
+ if (rawValue instanceof Promise) return encodeTaggedValue("Promise");
674
+ if (rawValue instanceof WeakMap) return encodeTaggedValue("WeakMap");
675
+ if (rawValue instanceof WeakSet) return encodeTaggedValue("WeakSet");
676
+ if (rawValue && typeof rawValue === "object") return withCircularGuard(rawValue, stack, () => {
677
+ const result = {};
678
+ const entries = Object.entries(rawValue);
679
+ entries.sort(([a], [b]) => a.localeCompare(b));
680
+ for (const [key, entryValue] of entries) result[key] = normalizeOptionsValue(entryValue, stack);
681
+ return result;
682
+ });
683
+ return encodeTaggedValue(typeof rawValue, String(rawValue));
684
+ }
685
+ function createCompilerContextCacheKey(opts) {
686
+ try {
687
+ const runtimeCacheScopeKey = createRuntimeCacheScopeKey(opts);
688
+ const keyStore = getCompilerContextKeyCacheStore(opts);
689
+ const cached = keyStore.get(runtimeCacheScopeKey);
690
+ if (cached !== void 0) return cached;
691
+ const cacheKey = md5Hash(serializeNormalizedValue(normalizeOptionsValue(getRuntimeCacheScopeValue(opts))));
692
+ keyStore.set(runtimeCacheScopeKey, cacheKey);
693
+ return cacheKey;
694
+ } catch (error) {
695
+ logger.debug("skip compiler context cache: %O", error);
696
+ return;
697
+ }
698
+ }
699
+ function withCompilerContextCache(opts, factory) {
700
+ const cacheKey = createCompilerContextCacheKey(opts);
701
+ if (cacheKey) {
702
+ const cached = compilerContextCache.get(cacheKey);
703
+ if (cached) return cached;
704
+ }
705
+ const ctx = factory();
706
+ if (cacheKey) compilerContextCache.set(cacheKey, ctx);
707
+ return ctx;
708
+ }
709
+ //#endregion
710
+ //#region src/context/custom-attributes.ts
711
+ function toCustomAttributesEntities(customAttributes) {
712
+ if (!customAttributes) return [];
713
+ if (isMap(customAttributes)) return [...customAttributes.entries()];
714
+ return Object.entries(customAttributes);
715
+ }
716
+ //#endregion
717
+ //#region src/babel/index.ts
718
+ function _interopDefaultCompat(e) {
719
+ return e && typeof e === "object" && "default" in e ? e.default : e;
720
+ }
721
+ const traverse = _interopDefaultCompat(_babelTraverse);
722
+ //#endregion
723
+ //#region src/utils/nameMatcher.ts
724
+ const NEVER_MATCH_NAME$1 = () => false;
725
+ const GLOBAL_FLAG_REGEXP = /g/g;
726
+ function buildFuzzyMatcher(fuzzyStrings) {
727
+ if (fuzzyStrings.length === 0) return;
728
+ if (fuzzyStrings.length === 1) {
729
+ const [needle] = fuzzyStrings;
730
+ return (value) => value.includes(needle);
731
+ }
732
+ const unique = [...new Set(fuzzyStrings)];
733
+ const pattern = new RegExp(unique.map(escapeStringRegexp).join("|"));
734
+ return (value) => pattern.test(value);
735
+ }
736
+ function normaliseRegex(regex) {
737
+ const { source, flags } = regex;
738
+ if (!flags.includes("g")) return regex;
739
+ return new RegExp(source, flags.replace(GLOBAL_FLAG_REGEXP, ""));
740
+ }
741
+ function createNameMatcher(list, { exact = false } = {}) {
742
+ if (!list || list.length === 0) return NEVER_MATCH_NAME$1;
743
+ const exactStrings = exact ? /* @__PURE__ */ new Set() : void 0;
744
+ const fuzzyStrings = [];
745
+ const regexList = [];
746
+ for (const item of list) if (typeof item === "string") if (exact) exactStrings.add(item);
747
+ else fuzzyStrings.push(item);
748
+ else regexList.push(normaliseRegex(item));
749
+ if (exact) {
750
+ const exactStringCount = exactStrings?.size ?? 0;
751
+ if (exactStringCount === 1 && regexList.length === 0) {
752
+ const [needle] = exactStrings;
753
+ return (value) => value === needle;
754
+ }
755
+ if (regexList.length === 0) return (value) => exactStrings.has(value);
756
+ if (exactStringCount === 0 && regexList.length === 1) {
757
+ const [regex] = regexList;
758
+ return (value) => regex.test(value);
759
+ }
760
+ return (value) => {
761
+ if (exactStrings?.has(value)) return true;
762
+ return regexList.some((regex) => regex.test(value));
763
+ };
764
+ }
765
+ const fuzzyMatcher = exact ? void 0 : buildFuzzyMatcher(fuzzyStrings);
766
+ const hasRegex = regexList.length > 0;
767
+ if (fuzzyMatcher && !hasRegex) return fuzzyMatcher;
768
+ if (!fuzzyMatcher && regexList.length === 1) {
769
+ const [regex] = regexList;
770
+ return (value) => regex.test(value);
771
+ }
772
+ return (value) => {
773
+ if (fuzzyMatcher?.(value)) return true;
774
+ if (!hasRegex) return false;
775
+ return regexList.some((regex) => regex.test(value));
776
+ };
777
+ }
778
+ //#endregion
779
+ //#region src/js/babel/parse.ts
780
+ const parseCache = new LRUCache({ max: 1024 });
781
+ function genCacheKey(source, options) {
782
+ if (typeof options === "string") return source + options;
783
+ return source + JSON.stringify(options, (_, val) => typeof val === "function" ? val.toString() : val);
784
+ }
785
+ function babelParse(code, opts = {}) {
786
+ const { cache, cacheKey, ...rest } = opts;
787
+ const cacheKeyString = genCacheKey(code, cacheKey ?? rest);
788
+ let result;
789
+ if (cache) result = parseCache.get(cacheKeyString);
790
+ if (!result) {
791
+ const { cache: _cache, cacheKey: _cacheKey, ...parseOptions } = opts;
792
+ result = parse(code, parseOptions);
793
+ if (cache) parseCache.set(cacheKeyString, result);
794
+ }
795
+ return result;
796
+ }
797
+ //#endregion
798
+ //#region src/wxml/shared.ts
799
+ const NEWLINE_RE = /[\n\r]+/g;
800
+ function replaceWxml(original, options = {
801
+ keepEOL: false,
802
+ escapeMap: MappingChars2String
803
+ }) {
804
+ const { keepEOL, escapeMap, ignoreHead } = options;
805
+ let res = original;
806
+ if (!keepEOL) res = res.replaceAll(NEWLINE_RE, "");
807
+ res = escape(res, {
808
+ map: escapeMap,
809
+ ignoreHead
810
+ });
811
+ return res;
812
+ }
813
+ //#endregion
814
+ //#region src/shared/classname-transform.ts
815
+ const escapedCandidateCacheByEscapeMap = /* @__PURE__ */ new WeakMap();
816
+ const defaultEscapedCandidateCache = /* @__PURE__ */ new Map();
817
+ let lastEscapedCandidateEscapeMap;
818
+ let lastEscapedCandidateCacheStore;
819
+ function isUrlLikeCandidate(candidate) {
820
+ return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
821
+ }
822
+ function isArbitraryValueCandidate(candidate) {
823
+ let hasOpenBracket = false;
824
+ let hasCloseBracket = false;
825
+ for (let i = 0; i < candidate.length; i++) {
826
+ const char = candidate[i];
827
+ if (char === "[") hasOpenBracket = true;
828
+ else if (char === "]") hasCloseBracket = true;
829
+ if (hasOpenBracket && hasCloseBracket) break;
830
+ }
831
+ if (!hasOpenBracket || !hasCloseBracket) return false;
832
+ if (isUrlLikeCandidate(candidate.trim())) return false;
833
+ return true;
834
+ }
835
+ function shouldEnableArbitraryValueFallbackByInputs(classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion) {
836
+ if (jsArbitraryValueFallback === true) return true;
837
+ if (jsArbitraryValueFallback === false) return false;
838
+ return tailwindcssMajorVersion === 4 && (!classNameSet || classNameSet.size === 0);
839
+ }
840
+ function shouldEnableArbitraryValueFallback({ classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion }) {
841
+ return shouldEnableArbitraryValueFallbackByInputs(classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion);
842
+ }
843
+ const SKIP_RESULT = { decision: "skip" };
844
+ const DIRECT_RESULT = { decision: "direct" };
845
+ const FALLBACK_RESULT = { decision: "fallback" };
846
+ function getEscapedCandidateCacheStore(escapeMap) {
847
+ if (!escapeMap) return defaultEscapedCandidateCache;
848
+ if (escapeMap === lastEscapedCandidateEscapeMap && lastEscapedCandidateCacheStore) return lastEscapedCandidateCacheStore;
849
+ let store = escapedCandidateCacheByEscapeMap.get(escapeMap);
850
+ if (!store) {
851
+ store = /* @__PURE__ */ new Map();
852
+ escapedCandidateCacheByEscapeMap.set(escapeMap, store);
853
+ }
854
+ lastEscapedCandidateEscapeMap = escapeMap;
855
+ lastEscapedCandidateCacheStore = store;
856
+ return store;
857
+ }
858
+ function getEscapedCandidate(candidate, escapeMap, store = getEscapedCandidateCacheStore(escapeMap)) {
859
+ let cached = store.get(candidate);
860
+ if (cached === void 0) {
861
+ cached = replaceWxml(candidate, { escapeMap });
862
+ store.set(candidate, cached);
863
+ }
864
+ return cached;
865
+ }
866
+ /**
867
+ * JS 转译严格遵循 runtime class set:
868
+ * 1. 直接命中 classNameSet 原始值;
869
+ * 2. 兼容命中 classNameSet 中已转义值;
870
+ * 3. 仅在受控条件下允许 class 语义兜底。
871
+ *
872
+ * 返回结构化结果,附带已计算的 escapedValue 以避免下游重复 escape。
873
+ */
874
+ function resolveClassNameTransformWithResult(candidate, { alwaysEscape, classNameSet, escapeMap, jsArbitraryValueFallback, jsPreserveClass, tailwindcssMajorVersion, classContext }) {
875
+ if (alwaysEscape) return DIRECT_RESULT;
876
+ if (jsPreserveClass?.(candidate)) return SKIP_RESULT;
877
+ if (classNameSet?.has(candidate)) return DIRECT_RESULT;
878
+ if (classNameSet && classNameSet.size > 0) {
879
+ const escapedCandidate = getEscapedCandidate(candidate, escapeMap);
880
+ if (escapedCandidate !== candidate && classNameSet.has(escapedCandidate)) return {
881
+ decision: "escaped",
882
+ escapedValue: escapedCandidate
883
+ };
884
+ }
885
+ if (classContext && shouldEnableArbitraryValueFallbackByInputs(classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion) && isArbitraryValueCandidate(candidate)) return FALLBACK_RESULT;
886
+ return SKIP_RESULT;
887
+ }
888
+ //#endregion
889
+ //#region src/utils/decode.ts
890
+ const unicodeEscapeRE = /\\u([\dA-Fa-f]{4})/g;
891
+ const unicodeEscapeTestRE = /\\u[\dA-Fa-f]{4}/;
892
+ function decodeUnicode(value) {
893
+ if (!unicodeEscapeTestRE.test(value)) return value;
894
+ return value.replace(unicodeEscapeRE, (_match, hex) => {
895
+ const codePoint = Number.parseInt(hex, 16);
896
+ return Number.isNaN(codePoint) ? _match : String.fromCharCode(codePoint);
897
+ });
898
+ }
899
+ function decodeUnicode2(input) {
900
+ if (!unicodeEscapeTestRE.test(input)) return input;
901
+ try {
902
+ return JSON.parse(`"${input}"`);
903
+ } catch (_error) {
904
+ return decodeUnicode(input);
905
+ }
906
+ }
907
+ //#endregion
908
+ //#region src/js/class-context.ts
909
+ const CLASS_LIKE_KEYWORDS = new Set([
910
+ "class",
911
+ "classname",
912
+ "hoverclass",
913
+ "virtualhostclass",
914
+ "rootclass"
915
+ ]);
916
+ const CLASS_HELPER_IDENTIFIERS = new Set([
917
+ "cn",
918
+ "clsx",
919
+ "classnames",
920
+ "twmerge",
921
+ "cva",
922
+ "tv",
923
+ "cx",
924
+ "r"
925
+ ]);
926
+ const DASH_CODE = 45;
927
+ const COLON_CODE = 58;
928
+ const UPPERCASE_A_CODE = 65;
929
+ const UPPERCASE_Z_CODE = 90;
930
+ const UNDERSCORE_CODE = 95;
931
+ const ASCII_MAX_CODE = 127;
932
+ const NORMALIZE_KEYWORD_REGEXP = /[-_:]/g;
933
+ function normalizeKeyword(name) {
934
+ const length = name.length;
935
+ let firstNormalizedIndex = -1;
936
+ for (let i = 0; i < length; i++) {
937
+ const code = name.charCodeAt(i);
938
+ if (code === DASH_CODE || code === UNDERSCORE_CODE || code === COLON_CODE || code >= UPPERCASE_A_CODE && code <= UPPERCASE_Z_CODE) {
939
+ firstNormalizedIndex = i;
940
+ break;
941
+ }
942
+ if (code > ASCII_MAX_CODE) return name.replace(NORMALIZE_KEYWORD_REGEXP, "").toLowerCase();
943
+ }
944
+ if (firstNormalizedIndex === -1) return name;
945
+ let normalized = name.slice(0, firstNormalizedIndex);
946
+ for (let i = firstNormalizedIndex; i < length; i++) {
947
+ const code = name.charCodeAt(i);
948
+ if (code === DASH_CODE || code === UNDERSCORE_CODE || code === COLON_CODE) continue;
949
+ if (code >= UPPERCASE_A_CODE && code <= UPPERCASE_Z_CODE) {
950
+ normalized += String.fromCharCode(code + 32);
951
+ continue;
952
+ }
953
+ if (code > ASCII_MAX_CODE) return name.replace(NORMALIZE_KEYWORD_REGEXP, "").toLowerCase();
954
+ normalized += name[i];
955
+ }
956
+ return normalized;
957
+ }
958
+ function readObjectKeyName(path) {
959
+ if (path.isIdentifier()) return path.node.name;
960
+ if (path.isStringLiteral()) return path.node.value;
961
+ if (path.isTemplateLiteral() && path.node.expressions.length === 0) return path.node.quasis[0]?.value.cooked ?? path.node.quasis[0]?.value.raw;
962
+ }
963
+ function isClassLikeObjectProperty(path, valuePath) {
964
+ if (!path.isObjectProperty()) return false;
965
+ if (path.get("value") !== valuePath) return false;
966
+ const keyName = readObjectKeyName(path.get("key"));
967
+ if (!keyName) return false;
968
+ return CLASS_LIKE_KEYWORDS.has(normalizeKeyword(keyName));
969
+ }
970
+ function isClassLikeJsxAttribute(path) {
971
+ if (!path.isJSXAttribute()) return false;
972
+ const namePath = path.get("name");
973
+ if (!namePath.isJSXIdentifier()) return false;
974
+ return CLASS_LIKE_KEYWORDS.has(normalizeKeyword(namePath.node.name));
975
+ }
976
+ function readCallHelperName(calleePath) {
977
+ if (calleePath.isIdentifier()) return calleePath.node.name;
978
+ if (calleePath.isMemberExpression()) {
979
+ const propertyPath = calleePath.get("property");
980
+ if (propertyPath.isIdentifier()) return propertyPath.node.name;
981
+ if (propertyPath.isStringLiteral()) return propertyPath.node.value;
982
+ }
983
+ }
984
+ function isClassLikeCallExpression(path, valuePath) {
985
+ if (!path.isCallExpression()) return false;
986
+ const helperName = readCallHelperName(path.get("callee"));
987
+ if (!helperName || !CLASS_HELPER_IDENTIFIERS.has(normalizeKeyword(helperName))) return false;
988
+ return path.get("arguments").some((argumentPath) => argumentPath.node === valuePath.node);
989
+ }
990
+ /**
991
+ * 判断字符串字面量是否处于 class 语义上下文。
992
+ * 仅用于受控兜底场景,避免将普通业务文本误判为 class。
993
+ */
994
+ function isClassContextLiteralPath(path) {
995
+ let current = path;
996
+ while (current.parentPath) {
997
+ const parent = current.parentPath;
998
+ if (isClassLikeObjectProperty(parent, current)) return true;
999
+ if (isClassLikeJsxAttribute(parent)) return true;
1000
+ if (isClassLikeCallExpression(parent, current)) return true;
1001
+ current = parent;
1002
+ }
1003
+ return false;
1004
+ }
1005
+ //#endregion
1006
+ //#region src/js/handlers.ts
1007
+ const debug = createDebug("[js:handlers] ");
1008
+ const replacementCacheByEscapeMap = /* @__PURE__ */ new WeakMap();
1009
+ const defaultReplacementCache = /* @__PURE__ */ new Map();
1010
+ const WEAPP_TW_IGNORE_MARKER = "weapp-tw";
1011
+ const IGNORE_MARKER = "ignore";
1012
+ function getReplacementCacheStore(escapeMap) {
1013
+ if (!escapeMap) return defaultReplacementCache;
1014
+ let store = replacementCacheByEscapeMap.get(escapeMap);
1015
+ if (!store) {
1016
+ store = /* @__PURE__ */ new Map();
1017
+ replacementCacheByEscapeMap.set(escapeMap, store);
1018
+ }
1019
+ return store;
1020
+ }
1021
+ function getReplacement(candidate, escapeMap, store = getReplacementCacheStore(escapeMap)) {
1022
+ let cached = store.get(candidate);
1023
+ if (cached === void 0) {
1024
+ cached = replaceWxml(candidate, { escapeMap });
1025
+ store.set(candidate, cached);
1026
+ }
1027
+ return cached;
1028
+ }
1029
+ function hasIgnoreComment(node) {
1030
+ const { leadingComments } = node;
1031
+ if (!Array.isArray(leadingComments) || leadingComments.length === 0) return false;
1032
+ for (const comment of leadingComments) {
1033
+ const { value } = comment;
1034
+ if (value.includes(WEAPP_TW_IGNORE_MARKER) && value.includes(IGNORE_MARKER)) return true;
1035
+ }
1036
+ return false;
1037
+ }
1038
+ function extractLiteralValue(path, { unescapeUnicode, arbitraryValues }) {
1039
+ const allowDoubleQuotes = arbitraryValues?.allowDoubleQuotes;
1040
+ const { node } = path;
1041
+ let offset = 0;
1042
+ let original;
1043
+ if (node.type === "StringLiteral") {
1044
+ offset = 1;
1045
+ original = node.value;
1046
+ } else if (node.type === "TemplateElement") original = node.value.raw;
1047
+ else original = "";
1048
+ let literal = original;
1049
+ if (unescapeUnicode && original.includes("\\u")) literal = decodeUnicode2(original);
1050
+ return {
1051
+ allowDoubleQuotes,
1052
+ literal,
1053
+ offset,
1054
+ original
1055
+ };
1056
+ }
1057
+ function createCandidatePlanResolver(options, classContext) {
1058
+ const { escapeMap } = options;
1059
+ const replacementCache = getReplacementCacheStore(escapeMap);
1060
+ const transformOptions = classContext ? {
1061
+ ...options,
1062
+ classContext
1063
+ } : options;
1064
+ let firstCandidate = "";
1065
+ let firstPlan;
1066
+ let cache;
1067
+ const buildCandidatePlan = (candidate) => {
1068
+ const result = resolveClassNameTransformWithResult(candidate, transformOptions);
1069
+ if (result.decision === "skip") return { result };
1070
+ let replacement;
1071
+ if (result.decision === "escaped" && result.escapedValue) {
1072
+ replacement = result.escapedValue;
1073
+ replacementCache.set(candidate, replacement);
1074
+ } else replacement = getReplacement(candidate, escapeMap, replacementCache);
1075
+ return {
1076
+ result,
1077
+ replacement
1078
+ };
1079
+ };
1080
+ return (candidate) => {
1081
+ if (cache) {
1082
+ const cached = cache.get(candidate);
1083
+ if (cached) return cached;
1084
+ } else if (firstPlan && candidate === firstCandidate) return firstPlan;
1085
+ const plan = buildCandidatePlan(candidate);
1086
+ if (!firstPlan) {
1087
+ firstCandidate = candidate;
1088
+ firstPlan = plan;
1089
+ return plan;
1090
+ }
1091
+ if (!cache) {
1092
+ cache = /* @__PURE__ */ new Map();
1093
+ cache.set(firstCandidate, firstPlan);
1094
+ }
1095
+ cache.set(candidate, plan);
1096
+ return plan;
1097
+ };
1098
+ }
1099
+ function replaceHandleValue(path, options) {
1100
+ const { needEscaped = false } = options;
1101
+ const { classNameSet, alwaysEscape } = options;
1102
+ const fallbackEnabled = shouldEnableArbitraryValueFallback(options);
1103
+ if (!alwaysEscape && !fallbackEnabled && (!classNameSet || classNameSet.size === 0)) return;
1104
+ if (hasIgnoreComment(path.node)) return;
1105
+ const { literal, original, allowDoubleQuotes, offset } = extractLiteralValue(path, options);
1106
+ const candidates = splitCode(literal, allowDoubleQuotes);
1107
+ if (candidates.length === 0) return;
1108
+ const debugEnabled = debug.enabled;
1109
+ const classContext = options.wrapExpression || isClassContextLiteralPath(path);
1110
+ let transformed = literal;
1111
+ let mutated = false;
1112
+ let matchedCandidateCount = 0;
1113
+ let escapedDecisionCount = 0;
1114
+ let fallbackDecisionCount = 0;
1115
+ let escapedSamples;
1116
+ let skippedSamples;
1117
+ const resolveCandidatePlan = createCandidatePlanResolver(options, classContext);
1118
+ for (const candidate of candidates) {
1119
+ const plan = resolveCandidatePlan(candidate);
1120
+ if (plan.result.decision === "skip") {
1121
+ if (debugEnabled) {
1122
+ if (!skippedSamples) skippedSamples = [];
1123
+ if (skippedSamples.length < 6) skippedSamples.push(candidate);
1124
+ }
1125
+ continue;
1126
+ }
1127
+ if (debugEnabled) {
1128
+ matchedCandidateCount += 1;
1129
+ if (plan.result.decision === "escaped") {
1130
+ escapedDecisionCount += 1;
1131
+ if (!escapedSamples) escapedSamples = [];
1132
+ if (escapedSamples.length < 6) escapedSamples.push(candidate);
1133
+ }
1134
+ if (plan.result.decision === "fallback") fallbackDecisionCount += 1;
1135
+ }
1136
+ const replaced = transformed.replace(candidate, plan.replacement);
1137
+ if (replaced !== transformed) {
1138
+ transformed = replaced;
1139
+ mutated = true;
1140
+ }
1141
+ }
1142
+ const node = path.node;
1143
+ if (!mutated || typeof node.start !== "number" || typeof node.end !== "number") return;
1144
+ if (debugEnabled) debug("runtimeSet size=%d fallbackTriggered=%s candidates=%d matched=%d escapedHits=%d skipped=%d file=%s escapedSamples=%s skippedSamples=%s", classNameSet?.size ?? 0, fallbackDecisionCount > 0, candidates.length, matchedCandidateCount, escapedDecisionCount, skippedSamples?.length ?? 0, options.filename ?? "unknown", escapedSamples?.join(",") || "-", skippedSamples?.join(",") || "-");
1145
+ const start = node.start + offset;
1146
+ const end = node.end - offset;
1147
+ if (start >= end || transformed === original) return;
1148
+ return {
1149
+ start,
1150
+ end,
1151
+ value: needEscaped ? jsStringEscape(transformed) : transformed,
1152
+ path
1153
+ };
1154
+ }
1155
+ //#endregion
1156
+ //#region src/js/sourceAnalysis.ts
1157
+ function hasReplacementEntries(replacements) {
1158
+ for (const key in replacements) if (Object.hasOwn(replacements, key)) return true;
1159
+ return false;
1160
+ }
1161
+ function createModuleSpecifierReplacementToken(path, replacement) {
1162
+ const node = path.node;
1163
+ if (node.value === replacement) return;
1164
+ if (typeof node.start !== "number" || typeof node.end !== "number") return;
1165
+ const start = node.start + 1;
1166
+ const end = node.end - 1;
1167
+ if (start >= end) return;
1168
+ return {
1169
+ start,
1170
+ end,
1171
+ value: replacement,
1172
+ path
1173
+ };
1174
+ }
1175
+ function collectModuleSpecifierReplacementTokens(analysis, replacements) {
1176
+ if (!hasReplacementEntries(replacements)) return [];
1177
+ if (analysis.importDeclarations.size === 0 && analysis.exportDeclarations.size === 0 && analysis.requireCallPaths.length === 0 && analysis.walker.imports.size === 0) return [];
1178
+ const tokens = [];
1179
+ const applyReplacement = (path) => {
1180
+ const replacement = replacements[path.node.value];
1181
+ if (!replacement) return;
1182
+ const token = createModuleSpecifierReplacementToken(path, replacement);
1183
+ if (token) tokens.push(token);
1184
+ };
1185
+ for (const importPath of analysis.importDeclarations) {
1186
+ const source = importPath.get("source");
1187
+ if (source.isStringLiteral()) applyReplacement(source);
1188
+ }
1189
+ for (const exportPath of analysis.exportDeclarations) if (exportPath.isExportNamedDeclaration() || exportPath.isExportAllDeclaration()) {
1190
+ const source = exportPath.get("source");
1191
+ if (source && !Array.isArray(source) && source.isStringLiteral()) applyReplacement(source);
1192
+ }
1193
+ for (const literalPath of analysis.requireCallPaths) applyReplacement(literalPath);
1194
+ for (const token of analysis.walker.imports) {
1195
+ const replacement = replacements[token.source];
1196
+ if (replacement) token.source = replacement;
1197
+ }
1198
+ return tokens;
1199
+ }
1200
+ //#endregion
1201
+ //#region src/js/babel/process.ts
1202
+ const optionVariantsCache = /* @__PURE__ */ new WeakMap();
1203
+ function getNeedEscapedOptions(options, needEscaped) {
1204
+ if (options.needEscaped === needEscaped) return options;
1205
+ let cached = optionVariantsCache.get(options);
1206
+ if (!cached) {
1207
+ cached = {};
1208
+ optionVariantsCache.set(options, cached);
1209
+ }
1210
+ if (needEscaped) {
1211
+ if (!cached.stringLiteralOptions) cached.stringLiteralOptions = {
1212
+ ...options,
1213
+ needEscaped: true
1214
+ };
1215
+ return cached.stringLiteralOptions;
1216
+ }
1217
+ if (!cached.templateLiteralOptions) cached.templateLiteralOptions = {
1218
+ ...options,
1219
+ needEscaped: false
1220
+ };
1221
+ return cached.templateLiteralOptions;
1222
+ }
1223
+ function processUpdatedSource(rawSource, options, analysis) {
1224
+ const { targetPaths, jsTokenUpdater, ignoredPaths } = analysis;
1225
+ if (targetPaths.length === 0 && !options.moduleSpecifierReplacements && jsTokenUpdater.length === 0) return new MagicString(rawSource);
1226
+ const replacementTokens = [];
1227
+ for (const path of targetPaths) {
1228
+ if (ignoredPaths.has(path)) continue;
1229
+ const token = replaceHandleValue(path, path.isStringLiteral() ? getNeedEscapedOptions(options, true) : getNeedEscapedOptions(options, false));
1230
+ if (token) replacementTokens.push(token);
1231
+ }
1232
+ if (options.moduleSpecifierReplacements) replacementTokens.push(...collectModuleSpecifierReplacementTokens(analysis, options.moduleSpecifierReplacements));
1233
+ if (jsTokenUpdater.length + replacementTokens.length === 0) return new MagicString(rawSource);
1234
+ const ms = new MagicString(rawSource);
1235
+ jsTokenUpdater.push(...replacementTokens).filter((token) => !ignoredPaths.has(token.path)).updateMagicString(ms);
1236
+ return ms;
1237
+ }
1238
+ //#endregion
1239
+ //#region src/js/evalTransforms.ts
1240
+ const evalHandlerOptionsCache = /* @__PURE__ */ new WeakMap();
1241
+ const EVAL_SCOPE_ERROR_REGEXP = /pass a scope and parentPath|traversing a Program\/File/i;
1242
+ function isEvalPath(path) {
1243
+ if (path.isCallExpression()) return path.get("callee").isIdentifier({ name: "eval" });
1244
+ return false;
1245
+ }
1246
+ function createEvalReplacementToken(path, updated) {
1247
+ const node = path.node;
1248
+ let offset = 0;
1249
+ let original;
1250
+ if (path.isStringLiteral()) {
1251
+ offset = 1;
1252
+ original = path.node.value;
1253
+ } else if (path.isTemplateElement()) original = path.node.value.raw;
1254
+ else original = "";
1255
+ if (typeof node.start !== "number" || typeof node.end !== "number") return;
1256
+ const start = node.start + offset;
1257
+ const end = node.end - offset;
1258
+ if (start >= end) return;
1259
+ if (original === updated) return;
1260
+ return {
1261
+ start,
1262
+ end,
1263
+ value: path.isStringLiteral() ? jsStringEscape(updated) : updated,
1264
+ path
1265
+ };
1266
+ }
1267
+ function handleEvalStringLiteral(path, handlerOptions, updater, handler) {
1268
+ const { code } = handler(path.node.value, handlerOptions);
1269
+ if (!code) return;
1270
+ const token = createEvalReplacementToken(path, code);
1271
+ if (token) updater.addToken(token);
1272
+ }
1273
+ function handleEvalTemplateElement(path, handlerOptions, updater, handler) {
1274
+ const { code } = handler(path.node.value.raw, handlerOptions);
1275
+ if (!code) return;
1276
+ const token = createEvalReplacementToken(path, code);
1277
+ if (token) updater.addToken(token);
1278
+ }
1279
+ function getEvalStringHandlerOptions(options) {
1280
+ if (options.needEscaped === false && options.generateMap === false) return options;
1281
+ let cached = evalHandlerOptionsCache.get(options);
1282
+ if (!cached) {
1283
+ cached = {};
1284
+ evalHandlerOptionsCache.set(options, cached);
1285
+ }
1286
+ if (!cached.stringLiteralOptions) cached.stringLiteralOptions = {
1287
+ ...options,
1288
+ needEscaped: false,
1289
+ generateMap: false
1290
+ };
1291
+ return cached.stringLiteralOptions;
1292
+ }
1293
+ function getEvalTemplateHandlerOptions(options) {
1294
+ if (options.generateMap === false) return options;
1295
+ let cached = evalHandlerOptionsCache.get(options);
1296
+ if (!cached) {
1297
+ cached = {};
1298
+ evalHandlerOptionsCache.set(options, cached);
1299
+ }
1300
+ if (!cached.templateLiteralOptions) cached.templateLiteralOptions = {
1301
+ ...options,
1302
+ generateMap: false
1303
+ };
1304
+ return cached.templateLiteralOptions;
1305
+ }
1306
+ function walkEvalExpression(path, options, updater, handler) {
1307
+ const stringHandlerOptions = getEvalStringHandlerOptions(options);
1308
+ const templateHandlerOptions = getEvalTemplateHandlerOptions(options);
1309
+ const maybeTraverse = path?.traverse;
1310
+ if (typeof maybeTraverse === "function") try {
1311
+ return maybeTraverse.call(path, {
1312
+ StringLiteral(innerPath) {
1313
+ handleEvalStringLiteral(innerPath, stringHandlerOptions, updater, handler);
1314
+ },
1315
+ TemplateElement(innerPath) {
1316
+ handleEvalTemplateElement(innerPath, templateHandlerOptions, updater, handler);
1317
+ }
1318
+ });
1319
+ } catch (error) {
1320
+ const msg = error?.message ?? "";
1321
+ if (!EVAL_SCOPE_ERROR_REGEXP.test(msg)) throw error;
1322
+ }
1323
+ const getArgs = path?.get?.("arguments");
1324
+ if (Array.isArray(getArgs)) {
1325
+ for (const arg of getArgs) {
1326
+ if (arg?.isStringLiteral?.()) {
1327
+ handleEvalStringLiteral(arg, stringHandlerOptions, updater, handler);
1328
+ continue;
1329
+ }
1330
+ if (arg?.isTemplateLiteral?.()) for (const quasi of arg.get("quasis")) handleEvalTemplateElement(quasi, templateHandlerOptions, updater, handler);
1331
+ }
1332
+ return;
1333
+ }
1334
+ const nodeArgs = path?.node?.arguments;
1335
+ if (Array.isArray(nodeArgs)) {
1336
+ for (const n of nodeArgs) if (n?.type === "StringLiteral") handleEvalStringLiteral({
1337
+ node: n,
1338
+ isStringLiteral: () => true
1339
+ }, stringHandlerOptions, updater, handler);
1340
+ else if (n?.type === "TemplateLiteral" && Array.isArray(n.quasis)) for (const q of n.quasis) handleEvalTemplateElement({
1341
+ node: q,
1342
+ isStringLiteral: () => false,
1343
+ isTemplateElement: () => true
1344
+ }, templateHandlerOptions, updater, handler);
1345
+ }
1346
+ }
1347
+ //#endregion
1348
+ //#region src/js/JsTokenUpdater.ts
1349
+ /**
1350
+ * Lightweight helper that batches updates to {@link MagicString}.
1351
+ * It keeps the transformation logic out of the traversal code and makes
1352
+ * it easier to reason about the order in which tokens are written back.
1353
+ */
1354
+ var JsTokenUpdater = class {
1355
+ constructor({ value } = {}) {
1356
+ this.tokens = value ? [...value] : [];
1357
+ }
1358
+ addToken(token) {
1359
+ if (token) this.tokens.push(token);
1360
+ }
1361
+ push(...args) {
1362
+ this.tokens.push(...args);
1363
+ return this;
1364
+ }
1365
+ /**
1366
+ * 待写入的 token 数量。
1367
+ */
1368
+ get length() {
1369
+ return this.tokens.length;
1370
+ }
1371
+ map(callbackfn) {
1372
+ this.tokens = this.tokens.map(callbackfn);
1373
+ return this;
1374
+ }
1375
+ filter(callbackfn) {
1376
+ this.tokens = this.tokens.filter(callbackfn);
1377
+ return this;
1378
+ }
1379
+ updateMagicString(ms) {
1380
+ for (const { start, end, value } of this.tokens) ms.update(start, end, value);
1381
+ return ms;
1382
+ }
1383
+ };
1384
+ //#endregion
1385
+ //#region src/js/module-graph/ignored-exports.ts
1386
+ var IgnoredExportsTracker = class {
1387
+ constructor(options) {
1388
+ this.options = options;
1389
+ this.ignoredExportNames = /* @__PURE__ */ new Map();
1390
+ }
1391
+ addIgnoredExport(filename, exportName) {
1392
+ if (!exportName) return;
1393
+ let pending = this.ignoredExportNames.get(filename);
1394
+ if (!pending) {
1395
+ pending = /* @__PURE__ */ new Set();
1396
+ this.ignoredExportNames.set(filename, pending);
1397
+ }
1398
+ if (pending.has(exportName)) return;
1399
+ pending.add(exportName);
1400
+ const existing = this.options.modules.get(filename);
1401
+ if (existing) this.applyIgnoredExportsToAnalysis(filename, existing.analysis);
1402
+ }
1403
+ registerIgnoredExportsFromTokens(resolved, tokens) {
1404
+ for (const token of tokens) if (token.type === "ImportSpecifier") this.addIgnoredExport(resolved, token.imported);
1405
+ else if (token.type === "ImportDefaultSpecifier") this.addIgnoredExport(resolved, "default");
1406
+ }
1407
+ applyIgnoredExportsToAnalysis(filename, analysis) {
1408
+ const pending = this.ignoredExportNames.get(filename);
1409
+ if (!pending || pending.size === 0) return;
1410
+ const names = new Set(pending);
1411
+ pending.clear();
1412
+ const propagate = [];
1413
+ for (const exportPath of analysis.exportDeclarations) {
1414
+ if (names.size === 0) break;
1415
+ if (exportPath.isExportDefaultDeclaration()) {
1416
+ if (names.has("default")) {
1417
+ analysis.walker.walkExportDefaultDeclaration(exportPath);
1418
+ names.delete("default");
1419
+ }
1420
+ continue;
1421
+ }
1422
+ if (exportPath.isExportNamedDeclaration()) {
1423
+ const source = exportPath.node.source?.value;
1424
+ if (typeof source === "string") {
1425
+ for (const spec of exportPath.get("specifiers")) {
1426
+ if (!spec.isExportSpecifier()) continue;
1427
+ const exported = spec.get("exported");
1428
+ let exportedName;
1429
+ if (exported.isIdentifier()) exportedName = exported.node.name;
1430
+ else if (exported.isStringLiteral()) exportedName = exported.node.value;
1431
+ if (!exportedName || !names.has(exportedName)) continue;
1432
+ const local = spec.get("local");
1433
+ if (local.isIdentifier()) {
1434
+ propagate.push({
1435
+ specifier: source,
1436
+ exportName: local.node.name
1437
+ });
1438
+ names.delete(exportedName);
1439
+ } else if (local.isStringLiteral()) {
1440
+ propagate.push({
1441
+ specifier: source,
1442
+ exportName: local.node.value
1443
+ });
1444
+ names.delete(exportedName);
1445
+ }
1446
+ }
1447
+ continue;
1448
+ }
1449
+ const declaration = exportPath.get("declaration");
1450
+ if (declaration.isVariableDeclaration()) for (const decl of declaration.get("declarations")) {
1451
+ const id = decl.get("id");
1452
+ if (id.isIdentifier()) {
1453
+ const exportName = id.node.name;
1454
+ if (names.has(exportName)) {
1455
+ analysis.walker.walkVariableDeclarator(decl);
1456
+ names.delete(exportName);
1457
+ }
1458
+ }
1459
+ }
1460
+ for (const spec of exportPath.get("specifiers")) {
1461
+ if (!spec.isExportSpecifier()) continue;
1462
+ const exported = spec.get("exported");
1463
+ let exportedName;
1464
+ if (exported.isIdentifier()) exportedName = exported.node.name;
1465
+ else if (exported.isStringLiteral()) exportedName = exported.node.value;
1466
+ if (!exportedName || !names.has(exportedName)) continue;
1467
+ const local = spec.get("local");
1468
+ analysis.walker.walkNode(local);
1469
+ names.delete(exportedName);
1470
+ }
1471
+ continue;
1472
+ }
1473
+ if (exportPath.isExportAllDeclaration()) {
1474
+ const source = exportPath.node.source?.value;
1475
+ if (typeof source === "string") {
1476
+ for (const exportName of names) propagate.push({
1477
+ specifier: source,
1478
+ exportName
1479
+ });
1480
+ names.clear();
1481
+ }
1482
+ }
1483
+ }
1484
+ for (const { specifier, exportName } of propagate) {
1485
+ let resolved;
1486
+ try {
1487
+ resolved = this.options.resolve(specifier, filename);
1488
+ } catch {
1489
+ resolved = void 0;
1490
+ }
1491
+ if (!resolved) {
1492
+ pending.add(exportName);
1493
+ continue;
1494
+ }
1495
+ if (this.options.filter && !this.options.filter(resolved, specifier, filename)) {
1496
+ pending.add(exportName);
1497
+ continue;
1498
+ }
1499
+ this.addIgnoredExport(resolved, exportName);
1500
+ }
1501
+ for (const name of names) pending.add(name);
1502
+ }
1503
+ };
1504
+ //#endregion
1505
+ //#region src/js/ModuleGraph.ts
1506
+ var JsModuleGraph = class {
1507
+ constructor(entry, graphOptions) {
1508
+ this.modules = /* @__PURE__ */ new Map();
1509
+ this.queue = [];
1510
+ this.resolve = graphOptions.resolve;
1511
+ this.load = graphOptions.load;
1512
+ this.filter = graphOptions.filter;
1513
+ this.maxDepth = graphOptions.maxDepth ?? Number.POSITIVE_INFINITY;
1514
+ const { moduleGraph: _moduleGraph, filename: _ignoredFilename, ...rest } = entry.handlerOptions;
1515
+ this.baseOptions = {
1516
+ ...rest,
1517
+ filename: entry.filename
1518
+ };
1519
+ this.parserOptions = entry.handlerOptions.babelParserOptions;
1520
+ this.rootFilename = entry.filename;
1521
+ this.ignoredExports = new IgnoredExportsTracker({
1522
+ resolve: this.resolve,
1523
+ filter: this.filter,
1524
+ modules: this.modules
1525
+ });
1526
+ this.modules.set(entry.filename, {
1527
+ filename: entry.filename,
1528
+ source: entry.source,
1529
+ analysis: entry.analysis
1530
+ });
1531
+ this.queue.push({
1532
+ filename: entry.filename,
1533
+ depth: 0
1534
+ });
1535
+ }
1536
+ build() {
1537
+ this.collectDependencies();
1538
+ let linked;
1539
+ for (const [filename, state] of this.modules) {
1540
+ if (filename === this.rootFilename) continue;
1541
+ const childOptions = {
1542
+ ...this.baseOptions,
1543
+ filename
1544
+ };
1545
+ const code = processUpdatedSource(state.source, childOptions, state.analysis).toString();
1546
+ if (code !== state.source) {
1547
+ if (!linked) linked = {};
1548
+ linked[filename] = { code };
1549
+ }
1550
+ }
1551
+ return linked;
1552
+ }
1553
+ collectDependencies() {
1554
+ while (this.queue.length > 0) {
1555
+ const { filename, depth } = this.queue.shift();
1556
+ if (depth >= this.maxDepth) continue;
1557
+ const state = this.modules.get(filename);
1558
+ if (!state) continue;
1559
+ const dependencySpecifiers = /* @__PURE__ */ new Map();
1560
+ for (const token of state.analysis.walker.imports) {
1561
+ if (!dependencySpecifiers.has(token.source)) dependencySpecifiers.set(token.source, []);
1562
+ dependencySpecifiers.get(token.source).push(token);
1563
+ }
1564
+ for (const exportPath of state.analysis.exportDeclarations) if (exportPath.isExportAllDeclaration() || exportPath.isExportNamedDeclaration()) {
1565
+ const source = exportPath.node.source?.value;
1566
+ if (typeof source === "string" && !dependencySpecifiers.has(source)) dependencySpecifiers.set(source, []);
1567
+ }
1568
+ for (const [specifier, tokens] of dependencySpecifiers) {
1569
+ let resolved;
1570
+ try {
1571
+ resolved = this.resolve(specifier, filename);
1572
+ } catch {
1573
+ continue;
1574
+ }
1575
+ if (!resolved) continue;
1576
+ if (this.filter && !this.filter(resolved, specifier, filename)) continue;
1577
+ if (tokens.length > 0) this.ignoredExports.registerIgnoredExportsFromTokens(resolved, tokens);
1578
+ if (this.modules.has(resolved)) continue;
1579
+ let source;
1580
+ try {
1581
+ source = this.load(resolved);
1582
+ } catch {
1583
+ continue;
1584
+ }
1585
+ if (typeof source !== "string") continue;
1586
+ let analysis;
1587
+ try {
1588
+ analysis = analyzeSource(babelParse(source, {
1589
+ ...this.parserOptions,
1590
+ sourceFilename: resolved
1591
+ }), {
1592
+ ...this.baseOptions,
1593
+ filename: resolved
1594
+ });
1595
+ this.ignoredExports.applyIgnoredExportsToAnalysis(resolved, analysis);
1596
+ } catch {
1597
+ continue;
1598
+ }
1599
+ this.modules.set(resolved, {
1600
+ filename: resolved,
1601
+ source,
1602
+ analysis
1603
+ });
1604
+ this.queue.push({
1605
+ filename: resolved,
1606
+ depth: depth + 1
1607
+ });
1608
+ }
1609
+ }
1610
+ }
1611
+ };
1612
+ //#endregion
1613
+ //#region src/js/node-path-walker/export-handlers.ts
1614
+ function walkExportDeclaration(ctx, path) {
1615
+ if (path.isExportDeclaration()) {
1616
+ if (path.isExportNamedDeclaration()) walkExportNamedDeclaration(ctx, path);
1617
+ else if (path.isExportDefaultDeclaration()) walkExportDefaultDeclaration(ctx, path);
1618
+ else if (path.isExportAllDeclaration()) walkExportAllDeclaration(ctx, path);
1619
+ }
1620
+ }
1621
+ function walkExportNamedDeclaration(ctx, path) {
1622
+ const declaration = path.get("declaration");
1623
+ if (declaration.isVariableDeclaration()) for (const decl of declaration.get("declarations")) ctx.walkNode(decl);
1624
+ const specifiers = path.get("specifiers");
1625
+ for (const spec of specifiers) if (spec.isExportSpecifier()) {
1626
+ const local = spec.get("local");
1627
+ if (local.isIdentifier()) ctx.walkNode(local);
1628
+ }
1629
+ }
1630
+ function walkExportDefaultDeclaration(ctx, path) {
1631
+ const decl = path.get("declaration");
1632
+ if (decl.isIdentifier()) ctx.walkNode(decl);
1633
+ else ctx.walkNode(decl);
1634
+ }
1635
+ function walkExportAllDeclaration(ctx, path) {
1636
+ const source = path.get("source");
1637
+ if (source.isStringLiteral()) ctx.addImportToken({
1638
+ declaration: path,
1639
+ source: source.node.value,
1640
+ type: "ExportAllDeclaration"
1641
+ });
1642
+ }
1643
+ //#endregion
1644
+ //#region src/js/node-path-walker/import-tokens.ts
1645
+ function maybeAddImportToken(imports, arg) {
1646
+ if (!(arg.isImportSpecifier() && arg.node.importKind !== "type" || arg.isImportDefaultSpecifier())) return false;
1647
+ const importDeclaration = arg.parentPath;
1648
+ if (!importDeclaration.isImportDeclaration() || importDeclaration.node.importKind === "type") return false;
1649
+ if (arg.isImportSpecifier()) {
1650
+ const imported = arg.get("imported");
1651
+ if (imported.isIdentifier()) imports.add({
1652
+ declaration: importDeclaration,
1653
+ specifier: arg,
1654
+ imported: imported.node.name,
1655
+ local: arg.node.local.name,
1656
+ source: importDeclaration.node.source.value,
1657
+ type: "ImportSpecifier"
1658
+ });
1659
+ return true;
1660
+ }
1661
+ imports.add({
1662
+ declaration: importDeclaration,
1663
+ specifier: arg,
1664
+ local: arg.node.local.name,
1665
+ source: importDeclaration.node.source.value,
1666
+ type: "ImportDefaultSpecifier"
1667
+ });
1668
+ return true;
1669
+ }
1670
+ //#endregion
1671
+ //#region src/js/NodePathWalker.ts
1672
+ const EMPTY_IGNORE_CALL_EXPRESSION_IDENTIFIERS = [];
1673
+ const EMPTY_IMPORT_TOKENS = /* @__PURE__ */ new Set();
1674
+ function NOOP_STRING_PATH_CALLBACK() {}
1675
+ const NEVER_MATCH_NAME = () => false;
1676
+ /**
1677
+ * 遍历我们关注的调用表达式所关联的绑定,收集后续需要转换的字符串节点。
1678
+ */
1679
+ var NodePathWalker = class {
1680
+ constructor({ ignoreCallExpressionIdentifiers, callback } = {}) {
1681
+ this.hasIgnoredCallIdentifiers = Boolean(ignoreCallExpressionIdentifiers && ignoreCallExpressionIdentifiers.length > 0);
1682
+ this.ignoreCallExpressionIdentifiers = ignoreCallExpressionIdentifiers ?? EMPTY_IGNORE_CALL_EXPRESSION_IDENTIFIERS;
1683
+ this.callback = callback ?? NOOP_STRING_PATH_CALLBACK;
1684
+ this.isIgnoredCallIdentifier = this.hasIgnoredCallIdentifiers ? createNameMatcher(this.ignoreCallExpressionIdentifiers, { exact: true }) : NEVER_MATCH_NAME;
1685
+ }
1686
+ get imports() {
1687
+ return this.importsStore ?? EMPTY_IMPORT_TOKENS;
1688
+ }
1689
+ getWritableImports() {
1690
+ if (!this.importsStore) this.importsStore = /* @__PURE__ */ new Set();
1691
+ return this.importsStore;
1692
+ }
1693
+ addImportToken(token) {
1694
+ this.getWritableImports().add(token);
1695
+ }
1696
+ getVisited() {
1697
+ if (!this.visitedStore) this.visitedStore = /* @__PURE__ */ new WeakSet();
1698
+ return this.visitedStore;
1699
+ }
1700
+ walkVariableDeclarator(path) {
1701
+ const init = path.get("init");
1702
+ this.walkNode(init);
1703
+ }
1704
+ walkTemplateLiteral(path) {
1705
+ for (const exp of path.get("expressions")) this.walkNode(exp);
1706
+ for (const quasis of path.get("quasis")) this.callback(quasis);
1707
+ }
1708
+ walkStringLiteral(path) {
1709
+ this.callback(path);
1710
+ }
1711
+ walkBinaryExpression(path) {
1712
+ const left = path.get("left");
1713
+ this.walkNode(left);
1714
+ const right = path.get("right");
1715
+ this.walkNode(right);
1716
+ }
1717
+ walkLogicalExpression(path) {
1718
+ const left = path.get("left");
1719
+ this.walkNode(left);
1720
+ const right = path.get("right");
1721
+ this.walkNode(right);
1722
+ }
1723
+ walkObjectExpression(path) {
1724
+ const props = path.get("properties");
1725
+ for (const prop of props) if (prop.isObjectProperty()) {
1726
+ const key = prop.get("key");
1727
+ this.walkNode(key);
1728
+ const value = prop.get("value");
1729
+ this.walkNode(value);
1730
+ }
1731
+ }
1732
+ walkArrayExpression(path) {
1733
+ const elements = path.get("elements");
1734
+ for (const element of elements) this.walkNode(element);
1735
+ }
1736
+ walkNode(arg) {
1737
+ const visited = this.getVisited();
1738
+ if (visited.has(arg)) return;
1739
+ visited.add(arg);
1740
+ if (arg.isIdentifier()) {
1741
+ const binding = arg?.scope?.getBinding?.(arg.node.name);
1742
+ if (binding) this.walkNode(binding.path);
1743
+ } else if (arg.isMemberExpression()) {
1744
+ const objectPath = arg.get("object");
1745
+ if (objectPath.isIdentifier()) {
1746
+ const binding = arg?.scope?.getBinding?.(objectPath.node.name);
1747
+ if (binding) {
1748
+ if (binding.path.isVariableDeclarator()) this.walkVariableDeclarator(binding.path);
1749
+ }
1750
+ }
1751
+ } else if (arg.isTemplateLiteral()) this.walkTemplateLiteral(arg);
1752
+ else if (arg.isStringLiteral()) this.walkStringLiteral(arg);
1753
+ else if (arg.isBinaryExpression()) this.walkBinaryExpression(arg);
1754
+ else if (arg.isLogicalExpression()) this.walkLogicalExpression(arg);
1755
+ else if (arg.isObjectExpression()) this.walkObjectExpression(arg);
1756
+ else if (arg.isArrayExpression()) this.walkArrayExpression(arg);
1757
+ else if (arg.isVariableDeclarator()) this.walkVariableDeclarator(arg);
1758
+ else if (maybeAddImportToken(this.getWritableImports(), arg)) {}
1759
+ }
1760
+ /**
1761
+ * Walk the arguments of a desired call expression so their bindings can be analysed.
1762
+ */
1763
+ walkCallExpression(path) {
1764
+ if (!this.hasIgnoredCallIdentifiers) return;
1765
+ const calleePath = path.get("callee");
1766
+ if (calleePath.isIdentifier() && this.isIgnoredCallIdentifier(calleePath.node.name)) for (const arg of path.get("arguments")) this.walkNode(arg);
1767
+ }
1768
+ walkExportDeclaration(path) {
1769
+ walkExportDeclaration(this, path);
1770
+ }
1771
+ walkExportNamedDeclaration(path) {
1772
+ walkExportNamedDeclaration(this, path);
1773
+ }
1774
+ walkExportDefaultDeclaration(path) {
1775
+ walkExportDefaultDeclaration(this, path);
1776
+ }
1777
+ walkExportAllDeclaration(path) {
1778
+ walkExportAllDeclaration(this, path);
1779
+ }
1780
+ };
1781
+ //#endregion
1782
+ //#region src/js/taggedTemplateIgnore.ts
1783
+ function createTaggedTemplateIgnore({ matcher, names }) {
1784
+ const bindingIgnoreCache = /* @__PURE__ */ new Map();
1785
+ const taggedTemplateIgnoreCache = /* @__PURE__ */ new WeakMap();
1786
+ const seenBindings = /* @__PURE__ */ new Set();
1787
+ let singleCanonicalIgnoreName;
1788
+ let canonicalIgnoreNames;
1789
+ for (const item of names ?? []) {
1790
+ if (typeof item !== "string") continue;
1791
+ if (singleCanonicalIgnoreName === void 0) {
1792
+ singleCanonicalIgnoreName = item;
1793
+ continue;
1794
+ }
1795
+ if (item === singleCanonicalIgnoreName) continue;
1796
+ if (!canonicalIgnoreNames) {
1797
+ canonicalIgnoreNames = new Set([singleCanonicalIgnoreName, item]);
1798
+ continue;
1799
+ }
1800
+ canonicalIgnoreNames.add(item);
1801
+ }
1802
+ const hasCanonicalIgnoreNames = singleCanonicalIgnoreName !== void 0;
1803
+ const matchesIgnoreName = (value) => {
1804
+ if (hasCanonicalIgnoreNames) {
1805
+ if (canonicalIgnoreNames) {
1806
+ if (canonicalIgnoreNames.has(value)) return true;
1807
+ } else if (value === singleCanonicalIgnoreName) return true;
1808
+ }
1809
+ return matcher(value);
1810
+ };
1811
+ const propertyMatches = (propertyPath) => {
1812
+ if (!propertyPath) return false;
1813
+ if (propertyPath.isIdentifier()) return matchesIgnoreName(propertyPath.node.name);
1814
+ if (propertyPath.isStringLiteral()) return matchesIgnoreName(propertyPath.node.value);
1815
+ return false;
1816
+ };
1817
+ const resolvesMemberExpressionToIgnore = (path, seen) => {
1818
+ if (propertyMatches(path.get("property"))) return true;
1819
+ const objectPath = path.get("object");
1820
+ if (objectPath.isIdentifier()) {
1821
+ const binding = (objectPath?.scope)?.getBinding?.(objectPath.node.name);
1822
+ if (binding) return resolvesToWeappTwIgnore(binding, seen);
1823
+ }
1824
+ return false;
1825
+ };
1826
+ const resolvesToWeappTwIgnore = (binding, seen) => {
1827
+ const cached = bindingIgnoreCache.get(binding);
1828
+ if (cached !== void 0) return cached;
1829
+ if (seen.has(binding)) return false;
1830
+ seen.add(binding);
1831
+ let result = false;
1832
+ const bindingPath = binding.path;
1833
+ if (bindingPath.isImportSpecifier()) {
1834
+ const imported = bindingPath.node.imported;
1835
+ if (imported.type === "Identifier" && matchesIgnoreName(imported.name)) result = true;
1836
+ else if (imported.type === "StringLiteral" && matchesIgnoreName(imported.value)) result = true;
1837
+ } else if (bindingPath.isVariableDeclarator()) {
1838
+ const init = bindingPath.get("init");
1839
+ if (init && init.node) {
1840
+ if (init.isIdentifier()) {
1841
+ const target = binding?.scope?.getBinding?.(init.node.name);
1842
+ if (target) result = resolvesToWeappTwIgnore(target, seen);
1843
+ } else if (init.isMemberExpression()) result = resolvesMemberExpressionToIgnore(init, seen);
1844
+ }
1845
+ }
1846
+ bindingIgnoreCache.set(binding, result);
1847
+ seen.delete(binding);
1848
+ return result;
1849
+ };
1850
+ const getEffectiveTagPath = (tagPath) => {
1851
+ let current = tagPath;
1852
+ while (true) {
1853
+ if (current.isParenthesizedExpression?.() || current.node.type === "ParenthesizedExpression") {
1854
+ current = current.get("expression");
1855
+ continue;
1856
+ }
1857
+ if (current.isTSAsExpression() || current.isTSTypeAssertion()) {
1858
+ current = current.get("expression");
1859
+ continue;
1860
+ }
1861
+ if (current.isTSNonNullExpression()) {
1862
+ current = current.get("expression");
1863
+ continue;
1864
+ }
1865
+ if (current.isTypeCastExpression?.()) {
1866
+ current = current.get("expression");
1867
+ continue;
1868
+ }
1869
+ if (current.isSequenceExpression()) {
1870
+ const last = current.get("expressions").at(-1);
1871
+ if (last) {
1872
+ current = last;
1873
+ continue;
1874
+ }
1875
+ }
1876
+ if (current.isCallExpression?.() || current.node.type === "CallExpression") {
1877
+ current = current.get("callee");
1878
+ continue;
1879
+ }
1880
+ break;
1881
+ }
1882
+ return current;
1883
+ };
1884
+ const evaluateTagPath = (tagPath, seen) => {
1885
+ if (tagPath.isCallExpression?.() || tagPath.node.type === "CallExpression") return evaluateTagPath(tagPath.get("callee"), seen);
1886
+ if (tagPath.isIdentifier()) {
1887
+ if (matchesIgnoreName(tagPath.node.name)) return true;
1888
+ const binding = tagPath?.scope?.getBinding?.(tagPath.node.name);
1889
+ if (binding) return resolvesToWeappTwIgnore(binding, seen);
1890
+ return false;
1891
+ }
1892
+ if (tagPath.isMemberExpression()) return resolvesMemberExpressionToIgnore(tagPath, seen);
1893
+ return false;
1894
+ };
1895
+ const computeIgnore = (tagPath) => {
1896
+ const cached = taggedTemplateIgnoreCache.get(tagPath.node);
1897
+ if (cached !== void 0) return cached;
1898
+ const effectiveTagPath = getEffectiveTagPath(tagPath);
1899
+ const effectiveCached = taggedTemplateIgnoreCache.get(effectiveTagPath.node);
1900
+ if (effectiveCached !== void 0) {
1901
+ taggedTemplateIgnoreCache.set(tagPath.node, effectiveCached);
1902
+ return effectiveCached;
1903
+ }
1904
+ seenBindings.clear();
1905
+ const result = evaluateTagPath(effectiveTagPath, seenBindings);
1906
+ taggedTemplateIgnoreCache.set(effectiveTagPath.node, result);
1907
+ taggedTemplateIgnoreCache.set(tagPath.node, result);
1908
+ return result;
1909
+ };
1910
+ return {
1911
+ shouldIgnore(tagPath) {
1912
+ return computeIgnore(tagPath);
1913
+ },
1914
+ getEffectiveTagPath
1915
+ };
1916
+ }
1917
+ //#endregion
1918
+ //#region src/js/babel.ts
1919
+ const EXPRESSION_WRAPPER_PREFIX = "(\n";
1920
+ const EXPRESSION_WRAPPER_SUFFIX = "\n)";
1921
+ const EMPTY_IGNORED_PATHS = /* @__PURE__ */ new WeakSet();
1922
+ const EMPTY_IMPORT_DECLARATIONS = /* @__PURE__ */ new Set();
1923
+ const EMPTY_EXPORT_DECLARATIONS = /* @__PURE__ */ new Set();
1924
+ const EMPTY_REQUIRE_CALL_PATHS = [];
1925
+ const ignoredTaggedTemplateMatcherCache = /* @__PURE__ */ new WeakMap();
1926
+ let defaultEvalHandler;
1927
+ function getIgnoredTaggedTemplateMatcher(options) {
1928
+ const cached = ignoredTaggedTemplateMatcherCache.get(options);
1929
+ if (cached) return cached;
1930
+ const created = createNameMatcher(options.ignoreTaggedTemplateExpressionIdentifiers, { exact: true });
1931
+ ignoredTaggedTemplateMatcherCache.set(options, created);
1932
+ return created;
1933
+ }
1934
+ function getDefaultEvalHandler() {
1935
+ if (!defaultEvalHandler) throw new Error("Default JS eval handler is not initialized.");
1936
+ return defaultEvalHandler;
1937
+ }
1938
+ function analyzeSource(ast, options, handler, collectModuleMetadata = true) {
1939
+ const jsTokenUpdater = new JsTokenUpdater();
1940
+ const needScope = Boolean(options.ignoreCallExpressionIdentifiers && options.ignoreCallExpressionIdentifiers.length > 0);
1941
+ const ignoredPaths = needScope ? /* @__PURE__ */ new WeakSet() : EMPTY_IGNORED_PATHS;
1942
+ const walker = needScope ? new NodePathWalker({
1943
+ ignoreCallExpressionIdentifiers: options.ignoreCallExpressionIdentifiers,
1944
+ callback(path) {
1945
+ ignoredPaths.add(path);
1946
+ }
1947
+ }) : new NodePathWalker();
1948
+ let taggedTemplateIgnore;
1949
+ const hasTaggedTemplateIgnoreIdentifiers = Boolean(options.ignoreTaggedTemplateExpressionIdentifiers && options.ignoreTaggedTemplateExpressionIdentifiers.length > 0);
1950
+ function getTaggedTemplateIgnore() {
1951
+ if (!taggedTemplateIgnore) taggedTemplateIgnore = createTaggedTemplateIgnore({
1952
+ matcher: getIgnoredTaggedTemplateMatcher(options),
1953
+ names: options.ignoreTaggedTemplateExpressionIdentifiers
1954
+ });
1955
+ return taggedTemplateIgnore;
1956
+ }
1957
+ const targetPaths = [];
1958
+ const importDeclarations = collectModuleMetadata ? /* @__PURE__ */ new Set() : EMPTY_IMPORT_DECLARATIONS;
1959
+ const exportDeclarations = collectModuleMetadata ? /* @__PURE__ */ new Set() : EMPTY_EXPORT_DECLARATIONS;
1960
+ const requireCallPaths = collectModuleMetadata ? [] : EMPTY_REQUIRE_CALL_PATHS;
1961
+ const evalHandler = handler ?? getDefaultEvalHandler();
1962
+ traverse(ast, {
1963
+ StringLiteral: { enter(p) {
1964
+ if (isEvalPath(p.parentPath)) return;
1965
+ targetPaths.push(p);
1966
+ } },
1967
+ TemplateElement: { enter: hasTaggedTemplateIgnoreIdentifiers ? (p) => {
1968
+ const pp = p.parentPath;
1969
+ if (pp.isTemplateLiteral()) {
1970
+ const ppp = pp.parentPath;
1971
+ if (isEvalPath(ppp)) return;
1972
+ if (ppp.isTaggedTemplateExpression()) {
1973
+ const tagPath = ppp.get("tag");
1974
+ if (getTaggedTemplateIgnore().shouldIgnore(tagPath)) return;
1975
+ }
1976
+ }
1977
+ targetPaths.push(p);
1978
+ } : (p) => {
1979
+ const pp = p.parentPath;
1980
+ if (pp.isTemplateLiteral()) {
1981
+ const ppp = pp.parentPath;
1982
+ if (isEvalPath(ppp)) return;
1983
+ }
1984
+ targetPaths.push(p);
1985
+ } },
1986
+ CallExpression: { enter: !collectModuleMetadata && !needScope ? (p) => {
1987
+ if (isEvalPath(p)) walkEvalExpression(p, options, jsTokenUpdater, evalHandler);
1988
+ } : (p) => {
1989
+ if (isEvalPath(p)) {
1990
+ walkEvalExpression(p, options, jsTokenUpdater, evalHandler);
1991
+ return;
1992
+ }
1993
+ const calleePath = p.get("callee");
1994
+ if (collectModuleMetadata && calleePath.isIdentifier({ name: "require" }) && !p?.scope?.hasBinding?.("require")) {
1995
+ const args = p.get("arguments");
1996
+ if (Array.isArray(args) && args.length > 0) {
1997
+ const first = args[0];
1998
+ if (first?.isStringLiteral()) requireCallPaths.push(first);
1999
+ }
2000
+ }
2001
+ if (needScope) walker.walkCallExpression(p);
2002
+ } },
2003
+ ...collectModuleMetadata ? {
2004
+ ImportDeclaration: { enter(p) {
2005
+ importDeclarations.add(p);
2006
+ } },
2007
+ ExportDeclaration: { enter(p) {
2008
+ exportDeclarations.add(p);
2009
+ } }
2010
+ } : {},
2011
+ noScope: !needScope
2012
+ });
2013
+ return {
2014
+ walker,
2015
+ jsTokenUpdater,
2016
+ ast,
2017
+ targetPaths,
2018
+ importDeclarations,
2019
+ exportDeclarations,
2020
+ requireCallPaths,
2021
+ ignoredPaths
2022
+ };
2023
+ }
2024
+ function jsHandler(rawSource, options) {
2025
+ const shouldWrapExpression = Boolean(options.wrapExpression);
2026
+ const source = shouldWrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
2027
+ let ast;
2028
+ try {
2029
+ ast = babelParse(source, options.babelParserOptions);
2030
+ } catch (error) {
2031
+ return {
2032
+ code: rawSource,
2033
+ error
2034
+ };
2035
+ }
2036
+ const needsModuleMetadata = Boolean(options.moduleSpecifierReplacements || options.moduleGraph && options.filename);
2037
+ const analysis = analyzeSource(ast, options, jsHandler, needsModuleMetadata);
2038
+ const ms = processUpdatedSource(source, options, analysis);
2039
+ if (shouldWrapExpression) {
2040
+ const start = 0;
2041
+ const end = source.length;
2042
+ const prefixLength = 2;
2043
+ const suffixLength = 2;
2044
+ ms.remove(start, start + prefixLength);
2045
+ ms.remove(end - suffixLength, end);
2046
+ }
2047
+ const result = { code: ms.toString() };
2048
+ if (options.generateMap) Object.defineProperty(result, "map", {
2049
+ configurable: true,
2050
+ enumerable: true,
2051
+ get() {
2052
+ return ms.generateMap();
2053
+ }
2054
+ });
2055
+ if (options.moduleGraph && options.filename) {
2056
+ const linked = new JsModuleGraph({
2057
+ filename: options.filename,
2058
+ source: rawSource,
2059
+ analysis,
2060
+ handlerOptions: options
2061
+ }, options.moduleGraph).build();
2062
+ if (linked) result.linked = linked;
2063
+ }
2064
+ return result;
2065
+ }
2066
+ defaultEvalHandler = jsHandler;
2067
+ //#endregion
2068
+ //#region src/js/index.ts
2069
+ /** 默认 LRU 缓存最大条目数 */
2070
+ const RESULT_CACHE_MAX = 512;
2071
+ /** 仅对短片段做内层结果缓存,避免 bundler 热路径重复 hash 大块 JS。 */
2072
+ const CACHEABLE_SOURCE_MAX_LENGTH = 512;
2073
+ /** 为每个 ClassNameSet 实例分配递增 ID */
2074
+ const classNameSetIds = /* @__PURE__ */ new WeakMap();
2075
+ let nextClassNameSetId = 0;
2076
+ /**
2077
+ * 获取 ClassNameSet 的唯一身份 ID。
2078
+ * 每个 Set 引用分配一个递增整数,用于指纹计算。
2079
+ */
2080
+ function getClassNameSetId(set) {
2081
+ if (!set) return "none";
2082
+ const existing = classNameSetIds.get(set);
2083
+ if (existing !== void 0) return String(existing);
2084
+ const id = nextClassNameSetId++;
2085
+ classNameSetIds.set(set, id);
2086
+ return String(id);
2087
+ }
2088
+ /** 缓存 IJsHandlerOptions -> fingerprint 的映射 */
2089
+ const fingerprintCache = /* @__PURE__ */ new WeakMap();
2090
+ /**
2091
+ * 计算选项指纹,包含所有影响转译结果的字段。
2092
+ * 不包含 filename、moduleGraph、jsPreserveClass。
2093
+ */
2094
+ function getOptionsFingerprint(options) {
2095
+ const cached = fingerprintCache.get(options);
2096
+ if (cached) return cached;
2097
+ const fingerprint = [
2098
+ getClassNameSetId(options.classNameSet),
2099
+ JSON.stringify(options.escapeMap ?? null),
2100
+ options.needEscaped ? "1" : "0",
2101
+ options.alwaysEscape ? "1" : "0",
2102
+ options.unescapeUnicode ? "1" : "0",
2103
+ options.generateMap ? "1" : "0",
2104
+ options.uniAppX ? "1" : "0",
2105
+ options.wrapExpression ? "1" : "0",
2106
+ String(options.tailwindcssMajorVersion ?? ""),
2107
+ String(options.staleClassNameFallback ?? ""),
2108
+ String(options.jsArbitraryValueFallback ?? ""),
2109
+ JSON.stringify(options.arbitraryValues ?? null),
2110
+ JSON.stringify(options.ignoreCallExpressionIdentifiers ?? null),
2111
+ JSON.stringify(options.ignoreTaggedTemplateExpressionIdentifiers?.map((v) => v instanceof RegExp ? v.source : v) ?? null),
2112
+ JSON.stringify(options.moduleSpecifierReplacements ?? null),
2113
+ JSON.stringify(options.babelParserOptions ?? null)
2114
+ ].join("|");
2115
+ fingerprintCache.set(options, fingerprint);
2116
+ return fingerprint;
2117
+ }
2118
+ function hasDefinedOverrides(options) {
2119
+ if (!options) return false;
2120
+ for (const key in options) if (options[key] !== void 0) return true;
2121
+ return false;
2122
+ }
2123
+ function shouldCacheJsResult(rawSource, options) {
2124
+ if (rawSource.length === 0 || rawSource.length > CACHEABLE_SOURCE_MAX_LENGTH) return false;
2125
+ if (options.moduleGraph || options.filename) return false;
2126
+ return true;
2127
+ }
2128
+ function createJsHandler(options) {
2129
+ const defaults = {
2130
+ escapeMap: options.escapeMap,
2131
+ staleClassNameFallback: options.staleClassNameFallback,
2132
+ jsArbitraryValueFallback: options.jsArbitraryValueFallback,
2133
+ tailwindcssMajorVersion: options.tailwindcssMajorVersion,
2134
+ arbitraryValues: options.arbitraryValues,
2135
+ jsPreserveClass: options.jsPreserveClass,
2136
+ generateMap: options.generateMap,
2137
+ needEscaped: options.needEscaped,
2138
+ alwaysEscape: options.alwaysEscape,
2139
+ unescapeUnicode: options.unescapeUnicode,
2140
+ babelParserOptions: options.babelParserOptions,
2141
+ ignoreCallExpressionIdentifiers: options.ignoreCallExpressionIdentifiers,
2142
+ ignoreTaggedTemplateExpressionIdentifiers: options.ignoreTaggedTemplateExpressionIdentifiers,
2143
+ uniAppX: options.uniAppX,
2144
+ moduleSpecifierReplacements: options.moduleSpecifierReplacements
2145
+ };
2146
+ /** 层1: 无 override 时,classNameSet -> resolvedOptions */
2147
+ const defaultOptionsCache = /* @__PURE__ */ new WeakMap();
2148
+ let resolvedOptionsWithoutClassNameSet;
2149
+ /** 层2: 有 override 时,overrideOptions -> { bySet, noSet } */
2150
+ const overrideOptionsCache = /* @__PURE__ */ new WeakMap();
2151
+ const resultCache = new LRUCache({ max: RESULT_CACHE_MAX });
2152
+ function resolveDefaultOptions(classNameSet) {
2153
+ if (!classNameSet) {
2154
+ if (!resolvedOptionsWithoutClassNameSet) resolvedOptionsWithoutClassNameSet = {
2155
+ ...defaults,
2156
+ classNameSet
2157
+ };
2158
+ return resolvedOptionsWithoutClassNameSet;
2159
+ }
2160
+ const cached = defaultOptionsCache.get(classNameSet);
2161
+ if (cached) return cached;
2162
+ const created = {
2163
+ ...defaults,
2164
+ classNameSet
2165
+ };
2166
+ defaultOptionsCache.set(classNameSet, created);
2167
+ return created;
2168
+ }
2169
+ function getCachedJsResult(rawSource, resolvedOptions) {
2170
+ if (!shouldCacheJsResult(rawSource, resolvedOptions)) return;
2171
+ const key = `${getOptionsFingerprint(resolvedOptions)}:${md5Hash(rawSource)}`;
2172
+ return resultCache.get(key);
2173
+ }
2174
+ function setCachedJsResult(rawSource, resolvedOptions, result) {
2175
+ if (!shouldCacheJsResult(rawSource, resolvedOptions) || result.error || result.linked) return result;
2176
+ const key = `${getOptionsFingerprint(resolvedOptions)}:${md5Hash(rawSource)}`;
2177
+ resultCache.set(key, result);
2178
+ return result;
2179
+ }
2180
+ function resolveOptions(classNameSet, overrideOptions) {
2181
+ if (!hasDefinedOverrides(overrideOptions)) return resolveDefaultOptions(classNameSet);
2182
+ let entry = overrideOptionsCache.get(overrideOptions);
2183
+ if (!entry) {
2184
+ entry = { bySet: /* @__PURE__ */ new WeakMap() };
2185
+ overrideOptionsCache.set(overrideOptions, entry);
2186
+ }
2187
+ if (!classNameSet) {
2188
+ if (entry.noSet) return entry.noSet;
2189
+ const created = defuOverrideArray({
2190
+ ...overrideOptions,
2191
+ classNameSet
2192
+ }, defaults);
2193
+ entry.noSet = created;
2194
+ return created;
2195
+ }
2196
+ const cached = entry.bySet.get(classNameSet);
2197
+ if (cached) return cached;
2198
+ const created = defuOverrideArray({
2199
+ ...overrideOptions,
2200
+ classNameSet
2201
+ }, defaults);
2202
+ entry.bySet.set(classNameSet, created);
2203
+ return created;
2204
+ }
2205
+ function handler(rawSource, classNameSet, options) {
2206
+ const resolvedOptions = resolveOptions(classNameSet, options);
2207
+ const cached = getCachedJsResult(rawSource, resolvedOptions);
2208
+ if (cached) return cached;
2209
+ return setCachedJsResult(rawSource, resolvedOptions, jsHandler(rawSource, resolvedOptions));
2210
+ }
2211
+ return handler;
2212
+ }
2213
+ //#endregion
2214
+ //#region src/wxml/custom-attributes.ts
2215
+ function regTest(reg, str) {
2216
+ reg.lastIndex = 0;
2217
+ return reg.test(str);
2218
+ }
2219
+ function isPropsMatch(props, attr) {
2220
+ if (Array.isArray(props)) {
2221
+ let lowerAttr;
2222
+ for (const prop of props) if (typeof prop === "string") {
2223
+ lowerAttr ?? (lowerAttr = attr.toLowerCase());
2224
+ if (prop.toLowerCase() === lowerAttr) return true;
2225
+ } else if (regTest(prop, attr)) return true;
2226
+ return false;
2227
+ } else if (typeof props === "string") return props === attr;
2228
+ else return regTest(props, attr);
2229
+ }
2230
+ function createAttributeMatcher(entities) {
2231
+ if (!entities || entities.length === 0) return;
2232
+ const wildcardAttributeRules = [];
2233
+ const tagAttributeRuleMap = /* @__PURE__ */ new Map();
2234
+ const regexpAttributeRules = [];
2235
+ for (const [selector, props] of entities) if (selector === "*") wildcardAttributeRules.push(props);
2236
+ else if (typeof selector === "string") {
2237
+ const list = tagAttributeRuleMap.get(selector);
2238
+ if (list) list.push(props);
2239
+ else tagAttributeRuleMap.set(selector, [props]);
2240
+ } else regexpAttributeRules.push([selector, props]);
2241
+ return (tag, attr) => {
2242
+ for (const props of wildcardAttributeRules) if (isPropsMatch(props, attr)) return true;
2243
+ const tagRules = tagAttributeRuleMap.get(tag);
2244
+ if (tagRules) {
2245
+ for (const props of tagRules) if (isPropsMatch(props, attr)) return true;
2246
+ }
2247
+ for (const [selector, props] of regexpAttributeRules) if (regTest(selector, tag) && isPropsMatch(props, attr)) return true;
2248
+ return false;
2249
+ };
2250
+ }
2251
+ //#endregion
2252
+ //#region src/wxml/utils/codegen/legacy-visitor.ts
2253
+ function shouldSkipLegacyStringLiteral(path) {
2254
+ if (t.isMemberExpression(path.parent)) return true;
2255
+ return Boolean(t.isBinaryExpression(path.parent) && (t.isConditionalExpression(path.parentPath?.parent) || t.isLogicalExpression(path.parentPath?.parent)));
2256
+ }
2257
+ function createLegacyTraverseOptions(options, jsTokenUpdater) {
2258
+ const legacyReplaceOptions = {
2259
+ escapeMap: options.escapeMap,
2260
+ classNameSet: options.runtimeSet,
2261
+ needEscaped: true,
2262
+ alwaysEscape: true
2263
+ };
2264
+ return {
2265
+ StringLiteral(path) {
2266
+ if (shouldSkipLegacyStringLiteral(path)) return;
2267
+ jsTokenUpdater.addToken(replaceHandleValue(path, legacyReplaceOptions));
2268
+ },
2269
+ noScope: true
2270
+ };
2271
+ }
2272
+ //#endregion
2273
+ //#region src/wxml/utils/codegen/legacy-rewriter.ts
2274
+ function rewriteLegacyExpression(match, options) {
2275
+ const ast = parseExpression(match);
2276
+ const jsTokenUpdater = new JsTokenUpdater();
2277
+ traverse(ast, createLegacyTraverseOptions(options, jsTokenUpdater));
2278
+ if (jsTokenUpdater.length === 0) return match;
2279
+ const ms = new MagicString(match);
2280
+ jsTokenUpdater.updateMagicString(ms);
2281
+ return ms.toString();
2282
+ }
2283
+ //#endregion
2284
+ //#region src/wxml/utils/codegen.ts
2285
+ const WRAP_EXPRESSION_HANDLER_OPTIONS = Object.freeze({ wrapExpression: true });
2286
+ function generateCode(match, options = {}) {
2287
+ try {
2288
+ const { jsHandler, runtimeSet, wrapExpression } = options;
2289
+ if (jsHandler && runtimeSet) {
2290
+ const initial = jsHandler(match, runtimeSet, wrapExpression ? WRAP_EXPRESSION_HANDLER_OPTIONS : void 0);
2291
+ if (!initial.error || wrapExpression) return initial.code;
2292
+ return jsHandler(match, runtimeSet, WRAP_EXPRESSION_HANDLER_OPTIONS).code;
2293
+ } else
2294
+ /**
2295
+ * @deprecated
2296
+ */
2297
+ return rewriteLegacyExpression(match, options);
2298
+ } catch {
2299
+ return match;
2300
+ }
2301
+ }
2302
+ //#endregion
2303
+ //#region src/wxml/whitespace.ts
2304
+ const WHITESPACE_CODES = new Set([
2305
+ 9,
2306
+ 10,
2307
+ 11,
2308
+ 12,
2309
+ 13,
2310
+ 32,
2311
+ 160,
2312
+ 65279
2313
+ ]);
2314
+ function isWhitespace(char) {
2315
+ if (char.length === 0) return false;
2316
+ return WHITESPACE_CODES.has(char.charCodeAt(0));
2317
+ }
2318
+ function isAllWhitespace(value) {
2319
+ for (let i = 0; i < value.length; i++) if (!WHITESPACE_CODES.has(value.charCodeAt(i))) return false;
2320
+ return true;
2321
+ }
2322
+ //#endregion
2323
+ //#region src/wxml/Tokenizer.ts
2324
+ var Tokenizer = class {
2325
+ constructor() {
2326
+ this.reset();
2327
+ }
2328
+ processChar(char, index) {
2329
+ switch (this.state) {
2330
+ case 0:
2331
+ if (isWhitespace(char)) {} else if (char === "{") {
2332
+ this.state = 2;
2333
+ this.bufferStartIndex = index;
2334
+ this.buffer += char;
2335
+ this.expressionBuffer = char;
2336
+ this.expressionStartIndex = index;
2337
+ } else {
2338
+ this.state = 1;
2339
+ this.bufferStartIndex = index;
2340
+ this.buffer += char;
2341
+ }
2342
+ break;
2343
+ case 1:
2344
+ if (isWhitespace(char)) {
2345
+ this.tokens.push({
2346
+ start: this.bufferStartIndex,
2347
+ end: index,
2348
+ value: this.buffer,
2349
+ expressions: this.expressions
2350
+ });
2351
+ this.buffer = "";
2352
+ this.expressions = [];
2353
+ this.state = 0;
2354
+ } else if (char === "{") {
2355
+ this.buffer += char;
2356
+ this.expressionBuffer = char;
2357
+ this.expressionStartIndex = index;
2358
+ this.state = 2;
2359
+ } else this.buffer += char;
2360
+ break;
2361
+ case 2:
2362
+ if (char === "}") {
2363
+ this.buffer += char;
2364
+ this.expressionBuffer += char;
2365
+ this.state = 3;
2366
+ } else {
2367
+ this.buffer += char;
2368
+ this.expressionBuffer += char;
2369
+ }
2370
+ break;
2371
+ case 3:
2372
+ if (char === "}") {
2373
+ this.buffer += char;
2374
+ this.expressionBuffer += char;
2375
+ this.expressions.push({
2376
+ start: this.expressionStartIndex,
2377
+ end: index + 1,
2378
+ value: this.expressionBuffer
2379
+ });
2380
+ this.expressionBuffer = "";
2381
+ this.state = 4;
2382
+ } else {
2383
+ this.buffer += char;
2384
+ this.expressionBuffer += char;
2385
+ this.state = 2;
2386
+ }
2387
+ break;
2388
+ case 4:
2389
+ if (isWhitespace(char)) {
2390
+ this.tokens.push({
2391
+ start: this.bufferStartIndex,
2392
+ end: index,
2393
+ value: this.buffer,
2394
+ expressions: this.expressions
2395
+ });
2396
+ this.buffer = "";
2397
+ this.expressions = [];
2398
+ this.state = 0;
2399
+ } else if (char === "{") {
2400
+ this.expressionStartIndex = index;
2401
+ this.expressionBuffer = char;
2402
+ this.buffer += char;
2403
+ this.state = 2;
2404
+ } else {
2405
+ this.buffer += char;
2406
+ this.state = 1;
2407
+ }
2408
+ break;
2409
+ default: throw new Error("Unexpected state");
2410
+ }
2411
+ }
2412
+ run(input) {
2413
+ this.reset();
2414
+ for (let i = 0; i < input.length; i++) {
2415
+ const char = input[i];
2416
+ this.processChar(char, i);
2417
+ }
2418
+ if (this.buffer.length > 0) this.tokens.push({
2419
+ start: this.bufferStartIndex,
2420
+ end: input.length,
2421
+ value: this.buffer,
2422
+ expressions: this.expressions
2423
+ });
2424
+ const tokens = this.tokens;
2425
+ this.reset();
2426
+ return tokens;
2427
+ }
2428
+ reset() {
2429
+ this.state = 0;
2430
+ this.buffer = "";
2431
+ this.tokens = [];
2432
+ this.bufferStartIndex = 0;
2433
+ this.expressionBuffer = "";
2434
+ this.expressionStartIndex = 0;
2435
+ this.expressions = [];
2436
+ }
2437
+ };
2438
+ //#endregion
2439
+ //#region src/wxml/utils/fragment-helpers.ts
2440
+ function updateWhitespaceGap(ms, start, end, options) {
2441
+ const gap = ms.slice(start, end);
2442
+ if (isAllWhitespace(gap)) ms.update(start, end, replaceWxml(gap, {
2443
+ keepEOL: false,
2444
+ escapeMap: options.escapeMap,
2445
+ ignoreHead: true
2446
+ }));
2447
+ }
2448
+ function updateWxmlSegment(ms, start, end, options, keepEOL, ignoreHead) {
2449
+ ms.update(start, end, replaceWxml(ms.slice(start, end), {
2450
+ keepEOL,
2451
+ escapeMap: options.escapeMap,
2452
+ ignoreHead
2453
+ }));
2454
+ }
2455
+ function updateExpressionSegment(ms, exp, options) {
2456
+ const code = `{{${generateCode(exp.value.slice(2, -2), options)}}}`;
2457
+ ms.update(exp.start, exp.end, code);
2458
+ }
2459
+ //#endregion
2460
+ //#region src/wxml/utils/fragment-updater.ts
2461
+ function handleEachClassFragment(ms, tokens, options = {}) {
2462
+ let previousEnd = 0;
2463
+ for (const token of tokens) {
2464
+ if (token.start > previousEnd) updateWhitespaceGap(ms, previousEnd, token.start, options);
2465
+ let p = token.start;
2466
+ if (token.expressions.length > 0) {
2467
+ for (const exp of token.expressions) {
2468
+ if (exp.start > token.start && p < exp.start) updateWxmlSegment(ms, p, exp.start, options, true, p > 0);
2469
+ updateExpressionSegment(ms, exp, options);
2470
+ p = exp.end;
2471
+ }
2472
+ if (token.end > p) updateWxmlSegment(ms, p, token.end, options, false, true);
2473
+ } else updateWxmlSegment(ms, token.start, token.end, options, false, false);
2474
+ previousEnd = token.end;
2475
+ }
2476
+ if (tokens.length > 0) {
2477
+ const lastToken = tokens[tokens.length - 1];
2478
+ if (lastToken.end < ms.original.length) updateWhitespaceGap(ms, lastToken.end, ms.original.length, options);
2479
+ }
2480
+ }
2481
+ //#endregion
2482
+ //#region src/wxml/utils/template-fragments.ts
2483
+ /**
2484
+ * 模块级共享 Tokenizer 实例,避免每次调用都重新创建。
2485
+ * Tokenizer.run() 末尾已调用 reset(),天然支持复用。
2486
+ */
2487
+ const sharedTokenizer = new Tokenizer();
2488
+ function templateReplacer(original, options = {}, tokenizer) {
2489
+ const ms = new MagicString(original);
2490
+ handleEachClassFragment(ms, (tokenizer ?? sharedTokenizer).run(ms.original), options);
2491
+ return ms.toString();
2492
+ }
2493
+ //#endregion
2494
+ //#region src/wxml/utils/custom-template.ts
2495
+ async function customTemplateHandler(rawSource, options, cachedMatcher) {
2496
+ const { customAttributesEntities = [], disabledDefaultTemplateHandler, inlineWxs, runtimeSet, jsHandler } = options ?? {};
2497
+ const matchCustomAttribute = cachedMatcher ?? createAttributeMatcher(customAttributesEntities);
2498
+ const defaultTemplateHandlerEnabled = !disabledDefaultTemplateHandler;
2499
+ let replaceOptions;
2500
+ let cachedQuote;
2501
+ let s;
2502
+ let tag = "";
2503
+ let wxsArray;
2504
+ function getMagicString() {
2505
+ if (!s) s = new MagicString(rawSource);
2506
+ return s;
2507
+ }
2508
+ function getReplaceOptions(quote) {
2509
+ if (!replaceOptions) {
2510
+ replaceOptions = {
2511
+ ...options,
2512
+ quote
2513
+ };
2514
+ cachedQuote = quote;
2515
+ return replaceOptions;
2516
+ }
2517
+ if (cachedQuote !== quote) {
2518
+ replaceOptions.quote = quote;
2519
+ cachedQuote = quote;
2520
+ }
2521
+ return replaceOptions;
2522
+ }
2523
+ function isDefaultTemplateAttribute(name) {
2524
+ if (name === "class" || name === "hover-class" || name === "virtualhostclass") return true;
2525
+ const lowerName = name.toLowerCase();
2526
+ return lowerName === "class" || lowerName === "hover-class" || lowerName === "virtualhostclass";
2527
+ }
2528
+ const parser = new Parser({
2529
+ onopentagname(name) {
2530
+ tag = name;
2531
+ },
2532
+ onattribute(name, value, quote) {
2533
+ if (!value) return;
2534
+ const shouldHandleDefault = defaultTemplateHandlerEnabled && isDefaultTemplateAttribute(name);
2535
+ const shouldHandleCustom = matchCustomAttribute?.(tag, name) ?? false;
2536
+ if (!shouldHandleDefault && !shouldHandleCustom) return;
2537
+ getMagicString().update(parser.startIndex + name.length + 2, parser.endIndex - 1, templateReplacer(value, getReplaceOptions(quote)));
2538
+ },
2539
+ ontext(data) {
2540
+ if (inlineWxs && tag === "wxs") (wxsArray ?? (wxsArray = [])).push({
2541
+ data,
2542
+ endIndex: parser.endIndex + 1,
2543
+ startIndex: parser.startIndex
2544
+ });
2545
+ },
2546
+ onclosetag() {
2547
+ tag = "";
2548
+ }
2549
+ }, { xmlMode: true });
2550
+ parser.write(rawSource);
2551
+ parser.end();
2552
+ for (const { data, endIndex, startIndex } of wxsArray ?? []) {
2553
+ const { code } = await jsHandler(data, runtimeSet);
2554
+ if (code !== data) getMagicString().update(startIndex, endIndex, code);
2555
+ }
2556
+ return s?.toString() ?? rawSource;
2557
+ }
2558
+ //#endregion
2559
+ //#region src/wxml/utils.ts
2560
+ function createTemplateHandler(options = {}) {
2561
+ const cachedMatcher = createAttributeMatcher(options.customAttributesEntities);
2562
+ const defaultOptions = options;
2563
+ let cachedRuntimeSet;
2564
+ let cachedOptionsWithRuntimeSet;
2565
+ return (rawSource, opt) => {
2566
+ const runtimeSet = opt?.runtimeSet;
2567
+ if (runtimeSet === void 0) return customTemplateHandler(rawSource, defaultOptions, cachedMatcher);
2568
+ if (cachedRuntimeSet !== runtimeSet || !cachedOptionsWithRuntimeSet) {
2569
+ cachedRuntimeSet = runtimeSet;
2570
+ cachedOptionsWithRuntimeSet = {
2571
+ ...defaultOptions,
2572
+ runtimeSet
2573
+ };
2574
+ }
2575
+ return customTemplateHandler(rawSource, cachedOptionsWithRuntimeSet, cachedMatcher);
2576
+ };
2577
+ }
2578
+ //#endregion
2579
+ //#region src/context/handlers.ts
2580
+ function resolveRuntimePackageReplacements(option) {
2581
+ if (!option) return;
2582
+ const mapping = option === true ? DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS : option;
2583
+ const normalized = {};
2584
+ for (const [from, to] of Object.entries(mapping)) {
2585
+ if (!from || typeof to !== "string" || to.length === 0) continue;
2586
+ normalized[from] = to;
2587
+ }
2588
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
2589
+ }
2590
+ function createHandlersFromContext(ctx, customAttributesEntities, cssCalcOptions, tailwindcssMajorVersion) {
2591
+ const { cssPreflight, cssPreflightRange, escapeMap, cssChildCombinatorReplaceValue, injectAdditionalCssVarScope, cssSelectorReplacement, rem2rpx, postcssOptions, cssRemoveProperty, cssRemoveHoverPseudoClass, cssPresetEnv, autoprefixer, uniAppX, px2rpx, unitsToPx, arbitraryValues, jsPreserveClass, staleClassNameFallback, jsArbitraryValueFallback, babelParserOptions, ignoreCallExpressionIdentifiers, ignoreTaggedTemplateExpressionIdentifiers, inlineWxs, disabledDefaultTemplateHandler, replaceRuntimePackages } = ctx;
2592
+ const uniAppXEnabled = isUniAppXEnabled(uniAppX);
2593
+ const resolvedUniAppXOptions = resolveUniAppXOptions(uniAppX);
2594
+ const moduleSpecifierReplacements = resolveRuntimePackageReplacements(replaceRuntimePackages);
2595
+ const styleHandler = createStyleHandler({
2596
+ cssPreflight,
2597
+ cssPreflightRange,
2598
+ escapeMap,
2599
+ cssChildCombinatorReplaceValue,
2600
+ injectAdditionalCssVarScope,
2601
+ cssSelectorReplacement,
2602
+ rem2rpx,
2603
+ postcssOptions,
2604
+ cssRemoveProperty,
2605
+ cssRemoveHoverPseudoClass,
2606
+ cssPresetEnv,
2607
+ autoprefixer,
2608
+ uniAppX: uniAppXEnabled,
2609
+ uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
2610
+ cssCalc: cssCalcOptions,
2611
+ px2rpx,
2612
+ unitsToPx,
2613
+ majorVersion: tailwindcssMajorVersion
2614
+ });
2615
+ const jsHandler = createJsHandler({
2616
+ escapeMap,
2617
+ arbitraryValues,
2618
+ jsPreserveClass,
2619
+ staleClassNameFallback,
2620
+ jsArbitraryValueFallback: jsArbitraryValueFallback ?? "auto",
2621
+ tailwindcssMajorVersion,
2622
+ generateMap: true,
2623
+ babelParserOptions,
2624
+ ignoreCallExpressionIdentifiers,
2625
+ ignoreTaggedTemplateExpressionIdentifiers,
2626
+ uniAppX: uniAppXEnabled,
2627
+ moduleSpecifierReplacements
2628
+ });
2629
+ return {
2630
+ styleHandler,
2631
+ jsHandler,
2632
+ templateHandler: createTemplateHandler({
2633
+ customAttributesEntities,
2634
+ escapeMap,
2635
+ inlineWxs,
2636
+ jsHandler,
2637
+ disabledDefaultTemplateHandler
2638
+ })
2639
+ };
2640
+ }
2641
+ //#endregion
2642
+ //#region src/context/logger.ts
2643
+ const loggerLevelMap = {
2644
+ error: 0,
2645
+ warn: 1,
2646
+ info: 3,
2647
+ silent: -999
2648
+ };
2649
+ function applyLoggerLevel(logLevel) {
2650
+ logger.level = loggerLevelMap[logLevel ?? "info"] ?? loggerLevelMap.info;
2651
+ }
2652
+ //#endregion
2653
+ //#region src/context/index.ts
2654
+ async function clearTailwindcssPatcherCache(patcher, options) {
2655
+ if (!patcher) return;
2656
+ const cacheOptions = patcher.options?.cache;
2657
+ if (cacheOptions == null || typeof cacheOptions === "object" && cacheOptions.enabled === false) return;
2658
+ if (typeof patcher.clearCache === "function") try {
2659
+ await patcher.clearCache({ scope: "all" });
2660
+ } catch (error) {
2661
+ logger.debug("failed to clear tailwindcss patcher cache via clearCache(): %O", error);
2662
+ }
2663
+ if (!options?.removeDirectory) return;
2664
+ const cachePaths = /* @__PURE__ */ new Map();
2665
+ const normalizedCacheOptions = typeof cacheOptions === "object" ? cacheOptions : void 0;
2666
+ if (normalizedCacheOptions?.path) cachePaths.set(normalizedCacheOptions.path, false);
2667
+ const privateCachePath = patcher?.cacheStore?.options?.path;
2668
+ if (privateCachePath) cachePaths.set(privateCachePath, false);
2669
+ if (options?.removeDirectory && normalizedCacheOptions?.dir) cachePaths.set(normalizedCacheOptions.dir, true);
2670
+ if (!cachePaths.size) return;
2671
+ for (const [cachePath, recursive] of cachePaths.entries()) try {
2672
+ await rm(cachePath, {
2673
+ force: true,
2674
+ recursive
2675
+ });
2676
+ } catch (error) {
2677
+ const err = error;
2678
+ if (err?.code === "ENOENT") continue;
2679
+ logger.debug("failed to clear tailwindcss patcher cache: %s %O", cachePath, err);
2680
+ }
2681
+ }
2682
+ function createInternalCompilerContext(opts) {
2683
+ const ctx = defuOverrideArray(opts, getDefaultOptions(), {});
2684
+ ctx.escapeMap = ctx.customReplaceDictionary;
2685
+ applyLoggerLevel(ctx.logLevel);
2686
+ const twPatcher = createTailwindcssPatcherFromContext(ctx);
2687
+ logTailwindcssTarget("runtime", twPatcher, ctx.tailwindcssBasedir);
2688
+ logRuntimeTailwindcssVersion(ctx.tailwindcssBasedir, twPatcher.packageInfo?.rootPath, twPatcher.packageInfo?.version);
2689
+ warnMissingCssEntries(ctx, twPatcher);
2690
+ const cssCalcOptions = applyV4CssCalcDefaults(ctx.cssCalc, twPatcher);
2691
+ ctx.cssCalc = cssCalcOptions;
2692
+ const { styleHandler, jsHandler, templateHandler } = createHandlersFromContext(ctx, toCustomAttributesEntities(ctx.customAttributes), cssCalcOptions, twPatcher.majorVersion);
2693
+ ctx.styleHandler = styleHandler;
2694
+ ctx.jsHandler = jsHandler;
2695
+ ctx.templateHandler = templateHandler;
2696
+ ctx.cache = initializeCache(ctx.cache);
2697
+ ctx.twPatcher = twPatcher;
2698
+ const refreshTailwindcssPatcher = async (options) => {
2699
+ const previousPatcher = ctx.twPatcher;
2700
+ if (options?.clearCache !== false) await clearTailwindcssPatcherCache(previousPatcher);
2701
+ invalidateRuntimeClassSet(previousPatcher);
2702
+ const nextPatcher = createTailwindcssPatcherFromContext(ctx);
2703
+ Object.assign(previousPatcher, nextPatcher);
2704
+ ctx.twPatcher = previousPatcher;
2705
+ return previousPatcher;
2706
+ };
2707
+ ctx.refreshTailwindcssPatcher = refreshTailwindcssPatcher;
2708
+ Object.defineProperty(ctx.twPatcher, refreshTailwindcssPatcherSymbol, {
2709
+ value: refreshTailwindcssPatcher,
2710
+ configurable: true
2711
+ });
2712
+ return ctx;
2713
+ }
2714
+ /**
2715
+ * 获取用户定义选项的内部表示,并初始化相关的处理程序和补丁。
2716
+ * @param opts - 用户定义的选项,可选。
2717
+ * @returns 返回一个包含内部用户定义选项的对象,包括样式、JS和模板处理程序,以及Tailwind CSS补丁。
2718
+ */
2719
+ function getCompilerContext(opts) {
2720
+ return withCompilerContextCache(opts, () => createInternalCompilerContext(opts));
2721
+ }
2722
+ //#endregion
2723
+ //#region src/js/precheck.ts
2724
+ /** 用于检测源码中是否包含类名相关模式的正则表达式 */
2725
+ const FAST_JS_TRANSFORM_HINT_RE = /className\b|class\s*=|classList\.|\b(?:twMerge|clsx|classnames|cn|cva)\b|\[["'`]class["'`]\]|text-\[|bg-\[|\b(?:[whpm]|px|py|mx|my|rounded|flex|grid|gap)-/;
2726
+ /** 用于检测源码中是否包含 import/export/require 语句的正则表达式 */
2727
+ const DEPENDENCY_HINT_RE = /\bimport\s*[("'`{*]|\brequire\s*\(|\bexport\s+\*\s+from\s+["'`]|\bexport\s*\{[^}]*\}\s*from\s+["'`]/;
2728
+ /**
2729
+ * 判断是否可以跳过 JS 转换。
2730
+ * 通过正则快速检测源码内容,避免不必要的 Babel AST 解析。
2731
+ *
2732
+ * @param rawSource - 原始 JS 源码字符串
2733
+ * @param options - 可选的 JS 处理器配置选项
2734
+ * @returns 如果可以跳过转换返回 `true`,否则返回 `false`
2735
+ */
2736
+ function shouldSkipJsTransform(rawSource, options) {
2737
+ if (process.env.WEAPP_TW_DISABLE_JS_PRECHECK === "1") return false;
2738
+ if (!rawSource) return true;
2739
+ if (options?.alwaysEscape) return false;
2740
+ if (options?.moduleSpecifierReplacements && Object.keys(options.moduleSpecifierReplacements).length > 0) return false;
2741
+ if (options?.wrapExpression) return false;
2742
+ if (DEPENDENCY_HINT_RE.test(rawSource)) return false;
2743
+ return !FAST_JS_TRANSFORM_HINT_RE.test(rawSource);
2744
+ }
2745
+ //#endregion
2746
+ //#region src/tailwindcss/recorder.ts
2747
+ function setupPatchRecorder(patcher, baseDir, options) {
2748
+ const recorder = createPatchTargetRecorder(baseDir, patcher, options);
2749
+ if (recorder?.message && options?.logMessage !== false) {
2750
+ const prefix = options?.messagePrefix ? `${options.messagePrefix} ` : "";
2751
+ logger$1.info("%s%s", prefix, recorder.message);
2752
+ }
2753
+ const onPatchCompleted = recorder?.onPatched ? async () => {
2754
+ await recorder.onPatched();
2755
+ } : void 0;
2756
+ return {
2757
+ recorder,
2758
+ patchPromise: patcher ? createTailwindPatchPromise(patcher, onPatchCompleted) : Promise.resolve(),
2759
+ onPatchCompleted
2760
+ };
2761
+ }
2762
+ //#endregion
2763
+ export { refreshTailwindRuntimeState as _, createAttributeMatcher as a, isClassContextLiteralPath as c, traverse as d, toCustomAttributesEntities as f, ensureRuntimeClassSet as g, collectRuntimeClassSet as h, generateCode as i, replaceWxml as l, vitePluginName as m, shouldSkipJsTransform as n, analyzeSource as o, pluginName as p, getCompilerContext as r, JsTokenUpdater as s, setupPatchRecorder as t, babelParse as u, createDebug as v };