weapp-tailwindcss 4.12.0-next.0 → 5.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (310) hide show
  1. package/bin/weapp-tailwindcss.js +21 -1
  2. package/dist/babel/index.d.ts +3 -0
  3. package/dist/bundlers/gulp/index.d.ts +7 -0
  4. package/dist/bundlers/shared/cache.d.ts +16 -0
  5. package/dist/bundlers/shared/css-cleanup.d.ts +4 -0
  6. package/dist/bundlers/shared/css-imports.d.ts +8 -0
  7. package/dist/bundlers/shared/generator-candidates.d.ts +5 -0
  8. package/dist/bundlers/shared/generator-css.d.ts +41 -0
  9. package/dist/bundlers/shared/module-graph.d.ts +5 -0
  10. package/dist/bundlers/shared/run-tasks.d.ts +2 -0
  11. package/dist/bundlers/vite/bundle-entries.d.ts +14 -0
  12. package/dist/bundlers/vite/bundle-state.d.ts +43 -0
  13. package/dist/bundlers/vite/css-finalizer.d.ts +19 -0
  14. package/dist/bundlers/vite/generate-bundle.d.ts +20 -0
  15. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +21 -0
  16. package/dist/bundlers/vite/index.d.ts +3 -0
  17. package/dist/bundlers/vite/js-precheck.d.ts +1 -0
  18. package/dist/bundlers/vite/query.d.ts +15 -0
  19. package/dist/bundlers/vite/resolve-app-type.d.ts +2 -0
  20. package/dist/bundlers/vite/rewrite-css-imports.d.ts +11 -0
  21. package/dist/bundlers/vite/runtime-affecting-signature.d.ts +2 -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 +2517 -1544
  65. package/dist/cli.mjs +2493 -1524
  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 +15 -0
  109. package/dist/generator/types.d.ts +19 -0
  110. package/dist/generator-CZ-JXw6T.js +492 -0
  111. package/dist/generator-Dwxgra97.mjs +399 -0
  112. package/dist/generator-css-CnYjiMrD.js +1084 -0
  113. package/dist/generator-css-DhPFjSzK.mjs +1057 -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-DvwgIYdA.mjs +205 -0
  148. package/dist/loader-anchors-cprm4Klq.js +273 -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 +278 -0
  159. package/dist/postcss.mjs +268 -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-B_XyZ576.mjs +2763 -0
  170. package/dist/recorder-rn_2v_nd.js +2878 -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/design-system.d.ts +1 -0
  205. package/dist/tailwindcss/v4-engine/generator.d.ts +2 -0
  206. package/dist/tailwindcss/v4-engine/index.d.ts +5 -0
  207. package/dist/tailwindcss/v4-engine/miniprogram.d.ts +4 -0
  208. package/dist/tailwindcss/v4-engine/source.d.ts +7 -0
  209. package/dist/tailwindcss/v4-engine/types.d.ts +17 -0
  210. package/dist/typedoc.export.d.ts +5 -0
  211. package/dist/types/base.d.ts +1 -0
  212. package/dist/types/disabled-options.d.ts +4 -0
  213. package/dist/types/index.d.ts +104 -0
  214. package/dist/types/shared.d.ts +7 -0
  215. package/dist/types/user-defined-options/general.d.ts +31 -0
  216. package/dist/types/user-defined-options/important.d.ts +37 -0
  217. package/dist/types/user-defined-options/index.d.ts +11 -0
  218. package/dist/types/user-defined-options/lifecycle.d.ts +6 -0
  219. package/dist/types/user-defined-options/matcher.d.ts +9 -0
  220. package/dist/types.d.ts +1 -150
  221. package/dist/types.js +0 -1
  222. package/dist/types.mjs +1 -1
  223. package/dist/uni-app-x/component-local-style.d.ts +19 -0
  224. package/dist/uni-app-x/index.d.ts +2 -0
  225. package/dist/uni-app-x/options.d.ts +12 -0
  226. package/dist/uni-app-x/style-isolation.d.ts +2 -0
  227. package/dist/uni-app-x/transform.d.ts +9 -0
  228. package/dist/uni-app-x/vite.d.ts +36 -0
  229. package/dist/utils/decode.d.ts +2 -0
  230. package/dist/utils/disabled.d.ts +6 -0
  231. package/dist/utils/hbuilderx.d.ts +5 -0
  232. package/dist/utils/index.d.ts +7 -0
  233. package/dist/utils/nameMatcher.d.ts +4 -0
  234. package/dist/utils/resolve-package.d.ts +1 -0
  235. package/dist/utils/uni-platform.d.ts +11 -0
  236. package/dist/utils-7DUGTFED.mjs +48 -0
  237. package/dist/utils-DmC9_In3.js +61 -0
  238. package/dist/vite-BHpAqldo.js +1952 -0
  239. package/dist/vite-C8JlHiyR.mjs +1940 -0
  240. package/dist/vite.d.ts +4 -17
  241. package/dist/vite.js +5 -14
  242. package/dist/vite.mjs +2 -14
  243. package/dist/weapp-tw-css-import-rewrite-loader.js +59 -87
  244. package/dist/weapp-tw-runtime-classset-loader.js +33 -47
  245. package/dist/webpack-CABjKGGQ.mjs +441 -0
  246. package/dist/webpack-DNIJ0ysE.js +456 -0
  247. package/dist/webpack.d.ts +4 -25
  248. package/dist/webpack.js +6 -17
  249. package/dist/webpack.mjs +2 -17
  250. package/dist/webpack4.d.ts +4 -26
  251. package/dist/webpack4.js +379 -481
  252. package/dist/webpack4.mjs +370 -482
  253. package/dist/wxml/Tokenizer.d.ts +15 -0
  254. package/dist/wxml/custom-attributes.d.ts +4 -0
  255. package/dist/wxml/index.d.ts +2 -0
  256. package/dist/wxml/shared.d.ts +2 -0
  257. package/dist/wxml/tokenizer/types.d.ts +18 -0
  258. package/dist/wxml/utils/codegen/legacy-rewriter.d.ts +2 -0
  259. package/dist/wxml/utils/codegen/legacy-visitor.d.ts +8 -0
  260. package/dist/wxml/utils/codegen.d.ts +2 -0
  261. package/dist/wxml/utils/custom-template.d.ts +3 -0
  262. package/dist/wxml/utils/fragment-helpers.d.ts +6 -0
  263. package/dist/wxml/utils/fragment-updater.d.ts +4 -0
  264. package/dist/wxml/utils/template-fragments.d.ts +3 -0
  265. package/dist/wxml/utils.d.ts +8 -0
  266. package/dist/wxml/whitespace.d.ts +2 -0
  267. package/generator-placeholder.css +1 -0
  268. package/package.json +28 -13
  269. package/scripts/postinstall.mjs +59 -0
  270. package/dist/chunk-2LH6PZH3.mjs +0 -51
  271. package/dist/chunk-4AFQP74Z.js +0 -24
  272. package/dist/chunk-5ONE75V7.js +0 -2381
  273. package/dist/chunk-76S2EME4.mjs +0 -34
  274. package/dist/chunk-A5PB4KZT.js +0 -138
  275. package/dist/chunk-AYJ4HLWZ.mjs +0 -1508
  276. package/dist/chunk-DYLQ6UOI.js +0 -71
  277. package/dist/chunk-F2CKKG6Q.mjs +0 -171
  278. package/dist/chunk-F5XJWJYO.mjs +0 -582
  279. package/dist/chunk-FMK6SFQQ.js +0 -276
  280. package/dist/chunk-GC7WXUOW.js +0 -3906
  281. package/dist/chunk-GD4SQMVF.mjs +0 -2378
  282. package/dist/chunk-GMKSBLNY.js +0 -175
  283. package/dist/chunk-HL3US2OT.mjs +0 -10
  284. package/dist/chunk-LVSUBDJC.js +0 -579
  285. package/dist/chunk-NIS74SI6.js +0 -1511
  286. package/dist/chunk-OF6MFURR.js +0 -34
  287. package/dist/chunk-ONLKZIRQ.js +0 -7
  288. package/dist/chunk-OOHJLO5M.mjs +0 -71
  289. package/dist/chunk-OYSABARD.js +0 -51
  290. package/dist/chunk-QNRJCEZN.mjs +0 -3906
  291. package/dist/chunk-UUJWDME4.mjs +0 -276
  292. package/dist/chunk-WSS26HZS.js +0 -292
  293. package/dist/chunk-XAKAD2CR.mjs +0 -138
  294. package/dist/chunk-ZR3KN3FG.mjs +0 -292
  295. package/dist/cli.d.mts +0 -2
  296. package/dist/core.d.mts +0 -26
  297. package/dist/css-macro/postcss.d.mts +0 -7
  298. package/dist/css-macro.d.mts +0 -18
  299. package/dist/defaults.d.mts +0 -11
  300. package/dist/gulp.d.mts +0 -24
  301. package/dist/index-BXrmQelt.d.mts +0 -672
  302. package/dist/index-BXrmQelt.d.ts +0 -672
  303. package/dist/index.d.mts +0 -15
  304. package/dist/postcss-html-transform.d.mts +0 -2
  305. package/dist/presets.d.mts +0 -76
  306. package/dist/reset.d.mts +0 -1
  307. package/dist/types.d.mts +0 -150
  308. package/dist/vite.d.mts +0 -17
  309. package/dist/webpack.d.mts +0 -25
  310. package/dist/webpack4.d.mts +0 -26
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";
1
+ //#region \0rolldown/runtime.js
2
2
  var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -6,1640 +6,2613 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
15
17
  };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
-
25
- // src/cli.ts
26
- var import_node_process18 = __toESM(require("process"));
27
- var import_semver = __toESM(require("semver"));
28
- var import_tailwindcss_patch3 = require("tailwindcss-patch");
29
-
30
- // src/cli/context.ts
31
- var import_node_path12 = __toESM(require("path"));
32
- var import_node_process12 = __toESM(require("process"));
33
-
34
- // src/context/index.ts
35
- var import_promises2 = require("fs/promises");
36
- var import_logger11 = require("@weapp-tailwindcss/logger");
37
-
38
- // src/cache/index.ts
39
- var import_lru_cache = require("lru-cache");
40
-
41
- // src/cache/md5.ts
42
- var import_node = require("@weapp-tailwindcss/shared/node");
43
-
44
- // src/defaults.ts
45
- var import_escape = require("@weapp-core/escape");
46
-
47
- // src/utils/index.ts
48
- var import_shared = require("@weapp-tailwindcss/shared");
49
-
50
- // src/utils/hbuilderx.ts
51
- var import_node_path = __toESM(require("path"));
52
- var import_node_process = __toESM(require("process"));
53
-
54
- // src/utils/uni-platform.ts
55
- var import_node_process2 = __toESM(require("process"));
56
-
57
- // src/debug/index.ts
58
- var import_debug = __toESM(require("debug"));
59
- var _debug = (0, import_debug.default)("weapp-tw");
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ let node_process = require("node:process");
24
+ node_process = __toESM(node_process);
25
+ let semver = require("semver");
26
+ semver = __toESM(semver);
27
+ let tailwindcss_patch = require("tailwindcss-patch");
28
+ let node_path = require("node:path");
29
+ node_path = __toESM(node_path);
30
+ let node_fs_promises = require("node:fs/promises");
31
+ let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
32
+ let lru_cache = require("lru-cache");
33
+ let _weapp_tailwindcss_shared_node = require("@weapp-tailwindcss/shared/node");
34
+ let _weapp_core_escape = require("@weapp-core/escape");
35
+ require("@weapp-tailwindcss/shared");
36
+ let debug = require("debug");
37
+ debug = __toESM(debug);
38
+ let node_fs = require("node:fs");
39
+ let node_module = require("node:module");
40
+ require("@weapp-tailwindcss/postcss");
41
+ let _babel_traverse = require("@babel/traverse");
42
+ _babel_traverse = __toESM(_babel_traverse);
43
+ let _babel_parser = require("@babel/parser");
44
+ let _weapp_core_regex = require("@weapp-core/regex");
45
+ let magic_string = require("magic-string");
46
+ magic_string = __toESM(magic_string);
47
+ let _ast_core_escape = require("@ast-core/escape");
48
+ let _weapp_tailwindcss_shared_extractors = require("@weapp-tailwindcss/shared/extractors");
49
+ require("@babel/types");
50
+ require("htmlparser2");
51
+ let local_pkg = require("local-pkg");
52
+ let fast_glob = require("fast-glob");
53
+ fast_glob = __toESM(fast_glob);
54
+ let yaml = require("yaml");
55
+ //#region src/debug/index.ts
56
+ const _debug = (0, debug.default)("weapp-tw");
60
57
  function createDebug(prefix) {
61
- const debug3 = ((formatter, ...args) => {
62
- return _debug((prefix ?? "") + formatter, ...args);
63
- });
64
- Object.defineProperty(debug3, "enabled", {
65
- enumerable: false,
66
- configurable: false,
67
- get() {
68
- return _debug.enabled;
69
- }
70
- });
71
- return debug3;
72
- }
73
-
74
- // src/tailwindcss/runtime/cache.ts
75
- var import_node_fs = require("fs");
76
-
77
- // src/tailwindcss/runtime.ts
78
- var debug = createDebug("[tailwindcss:runtime] ");
79
-
80
- // src/tailwindcss/runtime-logs.ts
81
- var import_node_process3 = __toESM(require("process"));
82
- var import_logger = require("@weapp-tailwindcss/logger");
83
- var runtimeLogDedupeHolder = globalThis;
84
- var runtimeLogDedupe = runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ ?? (runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ = /* @__PURE__ */ new Set());
58
+ const debug$3 = ((formatter, ...args) => {
59
+ return _debug((prefix ?? "") + formatter, ...args);
60
+ });
61
+ Object.defineProperty(debug$3, "enabled", {
62
+ enumerable: false,
63
+ configurable: false,
64
+ get() {
65
+ return _debug.enabled;
66
+ }
67
+ });
68
+ return debug$3;
69
+ }
70
+ createDebug("[tailwindcss:runtime] ");
71
+ //#endregion
72
+ //#region src/tailwindcss/runtime-logs.ts
73
+ const runtimeLogDedupeHolder = globalThis;
74
+ const runtimeLogDedupe = runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ ?? (runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ = /* @__PURE__ */ new Set());
85
75
  function createRuntimeLogKey(category, baseDir, rootPath, version) {
86
- return JSON.stringify([
87
- category,
88
- baseDir ?? import_node_process3.default.cwd(),
89
- rootPath ?? "",
90
- version ?? ""
91
- ]);
76
+ return JSON.stringify([
77
+ category,
78
+ baseDir ?? node_process.default.cwd(),
79
+ rootPath ?? "",
80
+ version ?? ""
81
+ ]);
92
82
  }
93
83
  function markRuntimeLog(category, baseDir, rootPath, version) {
94
- const key = createRuntimeLogKey(category, baseDir, rootPath, version);
95
- if (runtimeLogDedupe.has(key)) {
96
- return false;
97
- }
98
- runtimeLogDedupe.add(key);
99
- return true;
84
+ const key = createRuntimeLogKey(category, baseDir, rootPath, version);
85
+ if (runtimeLogDedupe.has(key)) return false;
86
+ runtimeLogDedupe.add(key);
87
+ return true;
100
88
  }
101
89
  function logRuntimeTailwindcssTarget(baseDir, rootPath, version) {
102
- if (!markRuntimeLog("target", baseDir, rootPath, version)) {
103
- return;
104
- }
105
- const versionText = version ? ` (v${version})` : "";
106
- import_logger.logger.info("%s \u4F7F\u7528 Tailwind CSS%s", "Weapp-tailwindcss", versionText);
107
- }
108
-
109
- // src/tailwindcss/targets.ts
110
- var import_node_process6 = __toESM(require("process"));
111
- var import_logger3 = require("@weapp-tailwindcss/logger");
112
-
113
- // src/tailwindcss/targets/paths.ts
114
- var import_node_fs3 = require("fs");
115
- var import_node_path3 = __toESM(require("path"));
116
-
117
- // src/context/workspace.ts
118
- var import_node_fs2 = require("fs");
119
- var import_node_path2 = __toESM(require("path"));
90
+ if (!markRuntimeLog("target", baseDir, rootPath, version)) return;
91
+ const versionText = version ? ` (v${version})` : "";
92
+ _weapp_tailwindcss_logger.logger.info("%s 使用 Tailwind CSS%s", "Weapp-tailwindcss", versionText);
93
+ }
94
+ //#endregion
95
+ //#region src/context/workspace.ts
120
96
  function findWorkspaceRoot(startDir) {
121
- if (!startDir) {
122
- return void 0;
123
- }
124
- let current = import_node_path2.default.resolve(startDir);
125
- while (true) {
126
- const workspaceFile = import_node_path2.default.join(current, "pnpm-workspace.yaml");
127
- if ((0, import_node_fs2.existsSync)(workspaceFile)) {
128
- return current;
129
- }
130
- const parent = import_node_path2.default.dirname(current);
131
- if (parent === current) {
132
- return void 0;
133
- }
134
- current = parent;
135
- }
97
+ if (!startDir) return;
98
+ let current = node_path.default.resolve(startDir);
99
+ while (true) {
100
+ if ((0, node_fs.existsSync)(node_path.default.join(current, "pnpm-workspace.yaml"))) return current;
101
+ const parent = node_path.default.dirname(current);
102
+ if (parent === current) return;
103
+ current = parent;
104
+ }
136
105
  }
137
106
  function findNearestPackageRoot(startDir) {
138
- if (!startDir) {
139
- return void 0;
140
- }
141
- let current = import_node_path2.default.resolve(startDir);
142
- while (true) {
143
- const pkgPath = import_node_path2.default.join(current, "package.json");
144
- if ((0, import_node_fs2.existsSync)(pkgPath)) {
145
- return current;
146
- }
147
- const parent = import_node_path2.default.dirname(current);
148
- if (parent === current) {
149
- return void 0;
150
- }
151
- current = parent;
152
- }
153
- }
154
-
155
- // src/tailwindcss/targets/paths.ts
156
- var PATCH_INFO_FILENAME = "tailwindcss-target.json";
157
- var PATCH_INFO_CACHE_RELATIVE_PATH = import_node_path3.default.join("node_modules", ".cache", "weapp-tailwindcss", PATCH_INFO_FILENAME);
158
- var PATCH_INFO_LEGACY_RELATIVE_PATH = import_node_path3.default.join(".tw-patch", PATCH_INFO_FILENAME);
107
+ if (!startDir) return;
108
+ let current = node_path.default.resolve(startDir);
109
+ while (true) {
110
+ if ((0, node_fs.existsSync)(node_path.default.join(current, "package.json"))) return current;
111
+ const parent = node_path.default.dirname(current);
112
+ if (parent === current) return;
113
+ current = parent;
114
+ }
115
+ }
116
+ //#endregion
117
+ //#region src/tailwindcss/targets/paths.ts
118
+ const PATCH_INFO_FILENAME = "tailwindcss-target.json";
119
+ const PATCH_INFO_CACHE_RELATIVE_PATH = node_path.default.join("node_modules", ".cache", "weapp-tailwindcss", PATCH_INFO_FILENAME);
120
+ const PATCH_INFO_LEGACY_RELATIVE_PATH = node_path.default.join(".tw-patch", PATCH_INFO_FILENAME);
121
+ function toDisplayPath(value) {
122
+ return node_path.default.normalize(value).replace(/\\/g, "/");
123
+ }
159
124
  function formatRelativeToBase(targetPath, baseDir) {
160
- if (!baseDir) {
161
- return import_node_path3.default.normalize(targetPath);
162
- }
163
- const relative = import_node_path3.default.relative(baseDir, targetPath);
164
- if (!relative || relative === ".") {
165
- return ".";
166
- }
167
- if (relative.startsWith("..")) {
168
- return import_node_path3.default.normalize(targetPath);
169
- }
170
- return import_node_path3.default.join(".", relative);
125
+ if (!baseDir) return toDisplayPath(targetPath);
126
+ const relative = node_path.default.relative(baseDir, targetPath);
127
+ if (!relative || relative === ".") return ".";
128
+ if (relative.startsWith("..")) return toDisplayPath(targetPath);
129
+ return toDisplayPath(node_path.default.join(".", relative));
171
130
  }
172
131
  function resolveRecordLocation(baseDir) {
173
- const normalizedBase = import_node_path3.default.normalize(baseDir);
174
- const packageRoot = findNearestPackageRoot(normalizedBase) ?? normalizedBase;
175
- const packageJsonPath = import_node_path3.default.join(packageRoot, "package.json");
176
- const hasPackageJson = (0, import_node_fs3.existsSync)(packageJsonPath);
177
- const recordKeySource = hasPackageJson ? packageJsonPath : normalizedBase;
178
- const recordKey = (0, import_node.md5)(import_node_path3.default.normalize(recordKeySource));
179
- const recordDir = import_node_path3.default.join(packageRoot, "node_modules", ".cache", "weapp-tailwindcss", recordKey);
180
- const recordPath = import_node_path3.default.join(recordDir, PATCH_INFO_FILENAME);
181
- return {
182
- normalizedBase,
183
- packageRoot,
184
- recordDir,
185
- recordKey,
186
- recordPath,
187
- packageJsonPath: hasPackageJson ? packageJsonPath : void 0
188
- };
132
+ const normalizedBase = node_path.default.normalize(baseDir);
133
+ const packageRoot = findNearestPackageRoot(normalizedBase) ?? normalizedBase;
134
+ const packageJsonPath = node_path.default.join(packageRoot, "package.json");
135
+ const hasPackageJson = (0, node_fs.existsSync)(packageJsonPath);
136
+ const recordKeySource = hasPackageJson ? packageJsonPath : normalizedBase;
137
+ const recordKey = (0, _weapp_tailwindcss_shared_node.md5)(node_path.default.normalize(recordKeySource));
138
+ const recordDir = node_path.default.join(packageRoot, "node_modules", ".cache", "weapp-tailwindcss", recordKey);
139
+ return {
140
+ normalizedBase,
141
+ packageRoot,
142
+ recordDir,
143
+ recordKey,
144
+ recordPath: node_path.default.join(recordDir, PATCH_INFO_FILENAME),
145
+ packageJsonPath: hasPackageJson ? packageJsonPath : void 0
146
+ };
189
147
  }
190
148
  function getRecordFileCandidates(baseDir) {
191
- const { normalizedBase, packageRoot, recordPath } = resolveRecordLocation(baseDir);
192
- const candidates = /* @__PURE__ */ new Set([
193
- recordPath,
194
- import_node_path3.default.join(packageRoot, PATCH_INFO_CACHE_RELATIVE_PATH),
195
- import_node_path3.default.join(normalizedBase, PATCH_INFO_CACHE_RELATIVE_PATH),
196
- import_node_path3.default.join(normalizedBase, PATCH_INFO_LEGACY_RELATIVE_PATH)
197
- ]);
198
- return [...candidates];
199
- }
200
-
201
- // src/tailwindcss/targets/record-io.ts
202
- var import_node_fs4 = require("fs");
203
- var import_promises = require("fs/promises");
204
- var import_node_path4 = __toESM(require("path"));
205
- var import_node_process4 = __toESM(require("process"));
206
- var import_logger2 = require("@weapp-tailwindcss/logger");
207
-
208
- // package.json
209
- var package_default = {
210
- name: "weapp-tailwindcss",
211
- version: "4.12.0-next.0",
212
- description: "\u628A tailwindcss \u539F\u5B50\u5316\u6837\u5F0F\u601D\u60F3\uFF0C\u5E26\u7ED9\u5C0F\u7A0B\u5E8F\u5F00\u53D1\u8005\u4EEC! bring tailwindcss to miniprogram developers!",
213
- author: "ice breaker <1324318532@qq.com>",
214
- license: "MIT",
215
- homepage: "https://tw.icebreaker.top",
216
- repository: {
217
- type: "git",
218
- url: "git+https://github.com/sonofmagic/weapp-tailwindcss.git",
219
- directory: "packages/weapp-tailwindcss"
220
- },
221
- bugs: {
222
- url: "https://github.com/sonofmagic/weapp-tailwindcss/issues"
223
- },
224
- keywords: [
225
- "tailwindcss",
226
- "weapp",
227
- "wechat",
228
- "mini",
229
- "miniprogram",
230
- "mini app",
231
- "weapp-tw",
232
- "weapp-tailwindcss",
233
- "taro",
234
- "uni-app",
235
- "remax",
236
- "rax",
237
- "mpx",
238
- "jit",
239
- "mp",
240
- "android",
241
- "ios",
242
- "\u5C0F\u7A0B\u5E8F",
243
- "vite",
244
- "postcss",
245
- "webpack",
246
- "webpack-plugin",
247
- "gulp",
248
- "gulp-plugin"
249
- ],
250
- exports: {
251
- ".": {
252
- style: "./index.css",
253
- types: "./dist/index.d.ts",
254
- import: "./dist/index.mjs",
255
- require: "./dist/index.js"
256
- },
257
- "./escape": {
258
- types: "./dist/escape.d.ts",
259
- import: "./dist/escape.mjs",
260
- require: "./dist/escape.js"
261
- },
262
- "./vite": {
263
- types: "./dist/vite.d.ts",
264
- import: "./dist/vite.mjs",
265
- require: "./dist/vite.js"
266
- },
267
- "./webpack": {
268
- types: "./dist/webpack.d.ts",
269
- import: "./dist/webpack.mjs",
270
- require: "./dist/webpack.js"
271
- },
272
- "./webpack4": {
273
- types: "./dist/webpack4.d.ts",
274
- import: "./dist/webpack4.mjs",
275
- require: "./dist/webpack4.js"
276
- },
277
- "./core": {
278
- types: "./dist/core.d.ts",
279
- import: "./dist/core.mjs",
280
- require: "./dist/core.js"
281
- },
282
- "./gulp": {
283
- types: "./dist/gulp.d.ts",
284
- import: "./dist/gulp.mjs",
285
- require: "./dist/gulp.js"
286
- },
287
- "./defaults": {
288
- types: "./dist/defaults.d.ts",
289
- import: "./dist/defaults.mjs",
290
- require: "./dist/defaults.js"
291
- },
292
- "./presets": {
293
- types: "./dist/presets.d.ts",
294
- import: "./dist/presets.mjs",
295
- require: "./dist/presets.js"
296
- },
297
- "./reset": {
298
- types: "./dist/reset.d.ts",
299
- import: "./dist/reset.mjs",
300
- require: "./dist/reset.js"
301
- },
302
- "./css-macro/postcss": {
303
- types: "./dist/css-macro/postcss.d.ts",
304
- import: "./dist/css-macro/postcss.mjs",
305
- require: "./dist/css-macro/postcss.js"
306
- },
307
- "./css-macro": {
308
- types: "./dist/css-macro.d.ts",
309
- import: "./dist/css-macro.mjs",
310
- require: "./dist/css-macro.js"
311
- },
312
- "./types": {
313
- types: "./dist/types.d.ts",
314
- import: "./dist/types.mjs",
315
- require: "./dist/types.js"
316
- },
317
- "./postcss-html-transform": {
318
- types: "./dist/postcss-html-transform.d.ts",
319
- import: "./dist/postcss-html-transform.mjs",
320
- require: "./dist/postcss-html-transform.js"
321
- },
322
- "./package.json": "./package.json",
323
- "./index.css": "./index.css",
324
- "./index": "./index.css",
325
- "./preflight.css": "./preflight.css",
326
- "./preflight": "./preflight.css",
327
- "./theme.css": "./theme.css",
328
- "./theme": "./theme.css",
329
- "./utilities.css": "./utilities.css",
330
- "./utilities": "./utilities.css",
331
- "./with-layer.css": "./with-layer.css",
332
- "./with-layer": "./with-layer.css",
333
- "./uni-app-x": "./uni-app-x.css",
334
- "./uni-app-x.css": "./uni-app-x.css",
335
- "./css": "./css/index.css",
336
- "./*": "./*"
337
- },
338
- main: "./dist/index.js",
339
- module: "./dist/index.mjs",
340
- types: "./dist/index.d.ts",
341
- style: "index.css",
342
- typesVersions: {
343
- "*": {
344
- "*": [
345
- "./dist/*",
346
- "./dist/index.d.ts"
347
- ]
348
- }
349
- },
350
- bin: {
351
- "weapp-tailwindcss-webpack-plugin": "bin/weapp-tailwindcss.js",
352
- "weapp-tailwindcss": "bin/weapp-tailwindcss.js",
353
- "weapp-tw": "bin/weapp-tailwindcss.js"
354
- },
355
- files: [
356
- "bin",
357
- "css",
358
- "dist",
359
- "index.css",
360
- "preflight.css",
361
- "theme.css",
362
- "uni-app-x.css",
363
- "utilities.css",
364
- "with-layer.css"
365
- ],
366
- engines: {
367
- node: "^18.17.0 || >=20.5.0"
368
- },
369
- scripts: {
370
- dev: "tsup --watch --sourcemap",
371
- build: "tsup && node scripts/ensure-escape-dts.mjs",
372
- "build:tsc": "cross-env NODE_ENV=development tsc --build tsconfig.json",
373
- "build:cli": "cd plugins/cli && pnpm run build",
374
- "build:css": "tsx scripts/build-css.ts",
375
- "build:weapp-theme": "tsx scripts/build-weapp-theme.ts",
376
- test: "npm run postinstall && vitest run",
377
- "test:dev": "vitest",
378
- "test:ui": "vitest --ui",
379
- bench: "vitest bench --config ./vitest.config.ts",
380
- "bench:vite-perf": "tsx scripts/vite-perf-bench.ts",
381
- "bench:vite-perf:summary": "tsx scripts/vite-perf-summary.ts",
382
- "bench:js-handlers": "tsx scripts/js-bench.ts",
383
- "bench:js-diff": "tsx scripts/js-bench-diff.ts",
384
- tsd: "tsd",
385
- clean: "tsx scripts/clean.ts",
386
- "get-decl": "tsx scripts/get-decl.ts",
387
- "ls:pack": "npm pack --dry-run",
388
- "cli:patch": "node bin/weapp-tailwindcss.js patch",
389
- colors: "tsx scripts/colors.ts",
390
- release: "tsx scripts/release.ts",
391
- lint: "eslint .",
392
- "lint:fix": "eslint ./src --fix",
393
- postinstall: "node bin/weapp-tailwindcss.js patch",
394
- "bench:vite-dev-hmr": "tsx scripts/vite-dev-hmr-bench.ts",
395
- "test:watch-hmr": "node --import tsx scripts/watch-hmr-regression/index.ts"
396
- },
397
- publishConfig: {
398
- access: "public",
399
- registry: "https://registry.npmjs.org"
400
- },
401
- dependencies: {
402
- "@ast-core/escape": "~1.0.1",
403
- "@babel/parser": "~7.29.2",
404
- "@babel/traverse": "~7.29.0",
405
- "@babel/types": "~7.29.0",
406
- "@tailwindcss-mangle/config": "^7.0.0",
407
- "@vue/compiler-dom": "catalog:vue3",
408
- "@vue/compiler-sfc": "catalog:vue3",
409
- "@weapp-core/escape": "~7.0.0",
410
- "@weapp-core/regex": "~1.0.1",
411
- "@weapp-tailwindcss/logger": "workspace:*",
412
- "@weapp-tailwindcss/postcss": "workspace:*",
413
- "@weapp-tailwindcss/reset": "workspace:*",
414
- "@weapp-tailwindcss/shared": "workspace:*",
415
- cac: "6.7.14",
416
- "comment-json": "^4.6.2",
417
- debug: "~4.4.3",
418
- "fast-glob": "^3.3.3",
419
- htmlparser2: "10.1.0",
420
- "loader-utils": "2.0.4",
421
- "local-pkg": "^1.1.2",
422
- "lru-cache": "10.4.3",
423
- "magic-string": "0.30.21",
424
- semver: "~7.7.4",
425
- "tailwindcss-patch": "catalog:tailwindcssPatch",
426
- "webpack-sources": "3.3.4",
427
- yaml: "^2.8.3"
428
- },
429
- devDependencies: {
430
- "fast-check": "^4.7.0"
431
- }
432
- };
433
-
434
- // src/constants.ts
435
- var WEAPP_TW_REQUIRED_NODE_VERSION = "18.17.0";
436
- var WEAPP_TW_VERSION = package_default.version;
437
-
438
- // src/tailwindcss/targets/record-io.ts
439
- var loggedInvalidPatchRecords = /* @__PURE__ */ new Set();
149
+ const { normalizedBase, packageRoot, recordPath } = resolveRecordLocation(baseDir);
150
+ return [...new Set([
151
+ recordPath,
152
+ node_path.default.join(packageRoot, PATCH_INFO_CACHE_RELATIVE_PATH),
153
+ node_path.default.join(normalizedBase, PATCH_INFO_CACHE_RELATIVE_PATH),
154
+ node_path.default.join(normalizedBase, PATCH_INFO_LEGACY_RELATIVE_PATH)
155
+ ])];
156
+ }
157
+ //#endregion
158
+ //#region package.json
159
+ var version = "5.0.0-next.1";
160
+ //#endregion
161
+ //#region src/constants.ts
162
+ const WEAPP_TW_REQUIRED_NODE_VERSION_RANGE = "^20.19.0 || >=22.12.0";
163
+ const WEAPP_TW_VERSION = version;
164
+ //#endregion
165
+ //#region src/tailwindcss/targets/record-io.ts
166
+ const loggedInvalidPatchRecords = /* @__PURE__ */ new Set();
440
167
  function warnInvalidPatchTargetRecord(baseDir, recordPath, reason) {
441
- const normalizedPath = import_node_path4.default.normalize(recordPath);
442
- if (loggedInvalidPatchRecords.has(normalizedPath)) {
443
- return;
444
- }
445
- loggedInvalidPatchRecords.add(normalizedPath);
446
- const fileDisplay = formatRelativeToBase(normalizedPath, baseDir);
447
- const baseDisplay = formatRelativeToBase(import_node_path4.default.normalize(baseDir), import_node_process4.default.cwd());
448
- const reasonMessage = reason ? `\uFF1A${reason}` : "";
449
- import_logger2.logger.warn(
450
- `\u68C0\u6D4B\u5230\u635F\u574F\u7684 Tailwind CSS \u76EE\u6807\u8BB0\u5F55 ${fileDisplay}${reasonMessage}\u3002\u8BF7\u5728 ${baseDisplay} \u91CD\u65B0\u6267\u884C "weapp-tw patch --record-target" \u6216\u5220\u9664\u8BE5\u6587\u4EF6\u540E\u518D\u8FD0\u884C\u3002`
451
- );
168
+ const normalizedPath = node_path.default.normalize(recordPath);
169
+ if (loggedInvalidPatchRecords.has(normalizedPath)) return;
170
+ loggedInvalidPatchRecords.add(normalizedPath);
171
+ const fileDisplay = formatRelativeToBase(normalizedPath, baseDir);
172
+ const baseDisplay = formatRelativeToBase(node_path.default.normalize(baseDir), node_process.default.cwd());
173
+ const reasonMessage = reason ? `:${reason}` : "";
174
+ _weapp_tailwindcss_logger.logger.warn(`检测到损坏的 Tailwind CSS 目标记录 ${fileDisplay}${reasonMessage}。请在 ${baseDisplay} 重新执行 "weapp-tw patch --record-target" 或删除该文件后再运行。`);
452
175
  }
453
176
  function readPatchTargetRecord(baseDir) {
454
- if (!baseDir) {
455
- return void 0;
456
- }
457
- const normalizedBase = import_node_path4.default.normalize(baseDir);
458
- for (const recordPath of getRecordFileCandidates(normalizedBase)) {
459
- if (!(0, import_node_fs4.existsSync)(recordPath)) {
460
- continue;
461
- }
462
- try {
463
- const content = (0, import_node_fs4.readFileSync)(recordPath, "utf8");
464
- const parsed = JSON.parse(content);
465
- if (!parsed || typeof parsed.tailwindPackagePath !== "string") {
466
- warnInvalidPatchTargetRecord(normalizedBase, recordPath, "\u7F3A\u5C11 tailwindPackagePath \u5B57\u6BB5");
467
- continue;
468
- }
469
- return {
470
- baseDir: normalizedBase,
471
- path: recordPath,
472
- record: parsed
473
- };
474
- } catch (error) {
475
- const reason = error instanceof Error ? error.message : String(error);
476
- warnInvalidPatchTargetRecord(normalizedBase, recordPath, reason);
477
- continue;
478
- }
479
- }
480
- return void 0;
177
+ if (!baseDir) return;
178
+ const normalizedBase = node_path.default.normalize(baseDir);
179
+ for (const recordPath of getRecordFileCandidates(normalizedBase)) {
180
+ if (!(0, node_fs.existsSync)(recordPath)) continue;
181
+ try {
182
+ const content = (0, node_fs.readFileSync)(recordPath, "utf8");
183
+ const parsed = JSON.parse(content);
184
+ if (!parsed || typeof parsed.tailwindPackagePath !== "string") {
185
+ warnInvalidPatchTargetRecord(normalizedBase, recordPath, "缺少 tailwindPackagePath 字段");
186
+ continue;
187
+ }
188
+ return {
189
+ baseDir: normalizedBase,
190
+ path: recordPath,
191
+ record: parsed
192
+ };
193
+ } catch (error) {
194
+ warnInvalidPatchTargetRecord(normalizedBase, recordPath, error instanceof Error ? error.message : String(error));
195
+ continue;
196
+ }
197
+ }
481
198
  }
482
199
  async function saveCliPatchTargetRecord(baseDir, patcher, options) {
483
- if (!baseDir || !patcher?.packageInfo?.rootPath) {
484
- return void 0;
485
- }
486
- const normalizedBase = import_node_path4.default.normalize(baseDir);
487
- const location = resolveRecordLocation(normalizedBase);
488
- const recordPath = options?.recordPath ? import_node_path4.default.normalize(options.recordPath) : location.recordPath;
489
- const record = {
490
- tailwindPackagePath: import_node_path4.default.normalize(patcher.packageInfo.rootPath),
491
- packageVersion: patcher.packageInfo.version,
492
- recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
493
- source: options?.source ?? "cli",
494
- tailwindcssBasedir: normalizedBase,
495
- cwd: options?.cwd ? import_node_path4.default.normalize(options.cwd) : normalizedBase,
496
- patchVersion: WEAPP_TW_VERSION,
497
- packageJsonPath: options?.packageJsonPath ?? location.packageJsonPath,
498
- recordKey: options?.recordKey ?? location.recordKey
499
- };
500
- try {
501
- await (0, import_promises.mkdir)(import_node_path4.default.dirname(recordPath), { recursive: true });
502
- await (0, import_promises.writeFile)(recordPath, `${JSON.stringify(record, null, 2)}
503
- `, "utf8");
504
- return recordPath;
505
- } catch (error) {
506
- const baseDisplay = formatRelativeToBase(normalizedBase, import_node_process4.default.cwd());
507
- import_logger2.logger.warn(
508
- '\u81EA\u52A8\u66F4\u65B0 Tailwind CSS \u8865\u4E01\u8BB0\u5F55\u5931\u8D25\uFF0C\u8BF7\u5728 %s \u8FD0\u884C "weapp-tw patch --cwd %s"\u3002',
509
- baseDisplay,
510
- normalizedBase
511
- );
512
- import_logger2.logger.debug("failed to persist patch target record %s: %O", recordPath, error);
513
- return void 0;
514
- }
515
- }
516
-
517
- // src/tailwindcss/targets/recorder.ts
518
- var import_node_path5 = __toESM(require("path"));
519
- var import_node_process5 = __toESM(require("process"));
200
+ if (!baseDir || !patcher?.packageInfo?.rootPath) return;
201
+ const normalizedBase = node_path.default.normalize(baseDir);
202
+ const location = resolveRecordLocation(normalizedBase);
203
+ const recordPath = options?.recordPath ? node_path.default.normalize(options.recordPath) : location.recordPath;
204
+ const record = {
205
+ tailwindPackagePath: node_path.default.normalize(patcher.packageInfo.rootPath),
206
+ packageVersion: patcher.packageInfo.version,
207
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
208
+ source: options?.source ?? "cli",
209
+ tailwindcssBasedir: normalizedBase,
210
+ cwd: options?.cwd ? node_path.default.normalize(options.cwd) : normalizedBase,
211
+ patchVersion: WEAPP_TW_VERSION,
212
+ packageJsonPath: options?.packageJsonPath ?? location.packageJsonPath,
213
+ recordKey: options?.recordKey ?? location.recordKey
214
+ };
215
+ try {
216
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(recordPath), { recursive: true });
217
+ await (0, node_fs_promises.writeFile)(recordPath, `${JSON.stringify(record, null, 2)}\n`, "utf8");
218
+ return recordPath;
219
+ } catch (error) {
220
+ const baseDisplay = formatRelativeToBase(normalizedBase, node_process.default.cwd());
221
+ _weapp_tailwindcss_logger.logger.warn("自动更新 Tailwind CSS 补丁记录失败,请在 %s 运行 \"weapp-tw patch --cwd %s\"。", baseDisplay, normalizedBase);
222
+ _weapp_tailwindcss_logger.logger.debug("failed to persist patch target record %s: %O", recordPath, error);
223
+ return;
224
+ }
225
+ }
226
+ //#endregion
227
+ //#region src/tailwindcss/targets/recorder.ts
520
228
  function findPatchTargetRecord(baseDir) {
521
- const visited = /* @__PURE__ */ new Set();
522
- const fallback = baseDir ?? import_node_process5.default.cwd();
523
- let current = import_node_path5.default.resolve(fallback);
524
- while (!visited.has(current)) {
525
- const record = readPatchTargetRecord(current);
526
- if (record) {
527
- return record;
528
- }
529
- const parent = import_node_path5.default.dirname(current);
530
- if (parent === current) {
531
- break;
532
- }
533
- visited.add(current);
534
- current = parent;
535
- }
536
- return void 0;
229
+ const visited = /* @__PURE__ */ new Set();
230
+ const fallback = baseDir ?? node_process.default.cwd();
231
+ let current = node_path.default.resolve(fallback);
232
+ while (!visited.has(current)) {
233
+ const record = readPatchTargetRecord(current);
234
+ if (record) return record;
235
+ const parent = node_path.default.dirname(current);
236
+ if (parent === current) break;
237
+ visited.add(current);
238
+ current = parent;
239
+ }
537
240
  }
538
241
  function createPatchTargetRecorder(baseDir, patcher, options) {
539
- if (!baseDir || !patcher?.packageInfo?.rootPath || options?.recordTarget === false) {
540
- return void 0;
541
- }
542
- const normalizedBase = import_node_path5.default.normalize(baseDir);
543
- const recorded = findPatchTargetRecord(normalizedBase);
544
- const location = resolveRecordLocation(normalizedBase);
545
- const expectedPath = import_node_path5.default.normalize(patcher.packageInfo.rootPath);
546
- let reason;
547
- if (!recorded) {
548
- reason = "missing";
549
- } else {
550
- const normalizedRecorded = import_node_path5.default.normalize(recorded.record.tailwindPackagePath);
551
- if (normalizedRecorded !== expectedPath) {
552
- reason = "mismatch";
553
- } else if (import_node_path5.default.normalize(recorded.path) !== import_node_path5.default.normalize(location.recordPath) || !recorded.record.recordKey || recorded.record.recordKey !== location.recordKey) {
554
- reason = "migrate";
555
- } else if (!recorded.record.patchVersion || recorded.record.patchVersion !== WEAPP_TW_VERSION) {
556
- reason = "stale";
557
- } else if (options?.cwd && recorded.record.cwd && import_node_path5.default.normalize(recorded.record.cwd) !== import_node_path5.default.normalize(options.cwd)) {
558
- reason = "metadata";
559
- } else if (!recorded.record.cwd && options?.cwd) {
560
- reason = "metadata";
561
- }
562
- }
563
- const shouldPersist = options?.alwaysRecord || !recorded || Boolean(reason);
564
- if (!shouldPersist) {
565
- return void 0;
566
- }
567
- let message;
568
- switch (reason) {
569
- case "mismatch":
570
- message = "\u68C0\u6D4B\u5230 Tailwind CSS \u76EE\u6807\u8BB0\u5F55\u4E0E\u5F53\u524D\u89E3\u6790\u7ED3\u679C\u4E0D\u4E00\u81F4\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u65B0 patch \u5E76\u5237\u65B0\u7F13\u5B58\u3002";
571
- break;
572
- case "migrate":
573
- case "stale":
574
- message = "\u6B63\u5728\u5237\u65B0\u5F53\u524D\u5B50\u5305\u7684 Tailwind CSS \u8865\u4E01\u8BB0\u5F55\uFF0C\u786E\u4FDD\u7F13\u5B58\u9694\u79BB\u3002";
575
- break;
576
- case "missing":
577
- message = "\u672A\u627E\u5230\u5F53\u524D\u5B50\u5305\u7684 Tailwind CSS \u76EE\u6807\u8BB0\u5F55\uFF0C\u6B63\u5728\u751F\u6210\u3002";
578
- break;
579
- default:
580
- break;
581
- }
582
- const onPatched = async () => saveCliPatchTargetRecord(normalizedBase, patcher, {
583
- cwd: options?.cwd ?? normalizedBase,
584
- source: options?.source ?? "cli",
585
- recordPath: location.recordPath,
586
- recordKey: location.recordKey,
587
- packageJsonPath: location.packageJsonPath
588
- });
589
- return {
590
- recordPath: location.recordPath,
591
- message,
592
- reason,
593
- onPatched
594
- };
595
- }
596
-
597
- // src/tailwindcss/targets.ts
242
+ if (!baseDir || !patcher?.packageInfo?.rootPath || options?.recordTarget === false) return;
243
+ const normalizedBase = node_path.default.normalize(baseDir);
244
+ const recorded = findPatchTargetRecord(normalizedBase);
245
+ const location = resolveRecordLocation(normalizedBase);
246
+ const expectedPath = node_path.default.normalize(patcher.packageInfo.rootPath);
247
+ let reason;
248
+ if (!recorded) reason = "missing";
249
+ else if (node_path.default.normalize(recorded.record.tailwindPackagePath) !== expectedPath) reason = "mismatch";
250
+ else if (node_path.default.normalize(recorded.path) !== node_path.default.normalize(location.recordPath) || !recorded.record.recordKey || recorded.record.recordKey !== location.recordKey) reason = "migrate";
251
+ else if (!recorded.record.patchVersion || recorded.record.patchVersion !== WEAPP_TW_VERSION) reason = "stale";
252
+ else if (options?.cwd && recorded.record.cwd && node_path.default.normalize(recorded.record.cwd) !== node_path.default.normalize(options.cwd)) reason = "metadata";
253
+ else if (!recorded.record.cwd && options?.cwd) reason = "metadata";
254
+ if (!(options?.alwaysRecord || !recorded || Boolean(reason))) return;
255
+ let message;
256
+ switch (reason) {
257
+ case "mismatch":
258
+ message = "检测到 Tailwind CSS 目标记录与当前解析结果不一致,正在自动重新 patch 并刷新缓存。";
259
+ break;
260
+ case "migrate":
261
+ case "stale":
262
+ message = "正在刷新当前子包的 Tailwind CSS 补丁记录,确保缓存隔离。";
263
+ break;
264
+ case "missing":
265
+ message = "未找到当前子包的 Tailwind CSS 目标记录,正在生成。";
266
+ break;
267
+ default: break;
268
+ }
269
+ const onPatched = async () => saveCliPatchTargetRecord(normalizedBase, patcher, {
270
+ cwd: options?.cwd ?? normalizedBase,
271
+ source: options?.source ?? "cli",
272
+ recordPath: location.recordPath,
273
+ recordKey: location.recordKey,
274
+ packageJsonPath: location.packageJsonPath
275
+ });
276
+ return {
277
+ recordPath: location.recordPath,
278
+ message,
279
+ reason,
280
+ onPatched
281
+ };
282
+ }
283
+ //#endregion
284
+ //#region src/tailwindcss/targets.ts
598
285
  function logTailwindcssTarget(kind, patcher, baseDir) {
599
- const packageInfo = patcher?.packageInfo;
600
- const label = kind === "cli" ? "weapp-tw patch" : "Weapp-tailwindcss";
601
- if (!packageInfo?.rootPath) {
602
- import_logger3.logger.warn(
603
- "%s \u672A\u627E\u5230 Tailwind CSS \u4F9D\u8D56\uFF0C\u8BF7\u68C0\u67E5\u5728 %s \u662F\u5426\u5DF2\u5B89\u88C5 tailwindcss",
604
- label,
605
- baseDir ?? import_node_process6.default.cwd()
606
- );
607
- return;
608
- }
609
- const displayPath = formatRelativeToBase(packageInfo.rootPath, baseDir);
610
- const version = packageInfo.version ? ` (v${packageInfo.version})` : "";
611
- if (kind === "runtime") {
612
- logRuntimeTailwindcssTarget(baseDir, packageInfo.rootPath, packageInfo.version);
613
- return;
614
- }
615
- import_logger3.logger.info("%s \u7ED1\u5B9A Tailwind CSS -> %s%s", label, displayPath, version);
616
- }
617
-
618
- // src/tailwindcss/v4/config.ts
619
- var import_logger4 = require("@weapp-tailwindcss/logger");
620
-
621
- // src/tailwindcss/v4/patcher.ts
622
- var import_logger6 = require("@weapp-tailwindcss/logger");
623
-
624
- // src/tailwindcss/patcher.ts
625
- var import_node_path7 = __toESM(require("path"));
626
- var import_node_process8 = __toESM(require("process"));
627
- var import_logger5 = require("@weapp-tailwindcss/logger");
628
- var import_shared2 = require("@weapp-tailwindcss/shared");
629
- var import_tailwindcss_patch = require("tailwindcss-patch");
630
-
631
- // src/tailwindcss/patcher-resolve.ts
632
- var import_node_fs5 = require("fs");
633
- var import_node_module = require("module");
634
- var import_node_path6 = __toESM(require("path"));
635
- var import_node_process7 = __toESM(require("process"));
636
- var import_node_url = require("url");
637
-
638
- // src/tailwindcss/v4/css-entries.ts
639
- var import_node_path8 = __toESM(require("path"));
640
-
641
- // src/context/compiler-context-cache.ts
642
- var import_node_buffer = require("buffer");
643
- var import_node_path9 = __toESM(require("path"));
644
- var import_node_process9 = __toESM(require("process"));
645
- var import_logger7 = require("@weapp-tailwindcss/logger");
646
- var globalCacheHolder = globalThis;
647
- var compilerContextCache = globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ ?? (globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ = /* @__PURE__ */ new Map());
648
-
649
- // src/context/handlers.ts
650
- var import_postcss = require("@weapp-tailwindcss/postcss");
651
-
652
- // src/js/index.ts
653
- var import_lru_cache3 = require("lru-cache");
654
-
655
- // src/babel/index.ts
656
- var import_traverse = __toESM(require("@babel/traverse"));
657
- var import_parser = require("@babel/parser");
286
+ const packageInfo = patcher?.packageInfo;
287
+ const label = kind === "cli" ? "weapp-tw patch" : "Weapp-tailwindcss";
288
+ if (!packageInfo?.rootPath) {
289
+ _weapp_tailwindcss_logger.logger.warn("%s 未找到 Tailwind CSS 依赖,请检查在 %s 是否已安装 tailwindcss", label, baseDir ?? node_process.default.cwd());
290
+ return;
291
+ }
292
+ const displayPath = formatRelativeToBase(packageInfo.rootPath, baseDir);
293
+ const version = packageInfo.version ? ` (v${packageInfo.version})` : "";
294
+ if (kind === "runtime") {
295
+ logRuntimeTailwindcssTarget(baseDir, packageInfo.rootPath, packageInfo.version);
296
+ return;
297
+ }
298
+ _weapp_tailwindcss_logger.logger.info("%s 绑定 Tailwind CSS -> %s%s", label, displayPath, version);
299
+ }
300
+ //#endregion
301
+ //#region src/context/compiler-context-cache.ts
302
+ const globalCacheHolder = globalThis;
303
+ globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ ?? (globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ = /* @__PURE__ */ new Map());
304
+ //#endregion
305
+ //#region src/babel/index.ts
658
306
  function _interopDefaultCompat(e) {
659
- return e && typeof e === "object" && "default" in e ? e.default : e;
660
- }
661
- var traverse = _interopDefaultCompat(import_traverse.default);
662
-
663
- // src/utils/nameMatcher.ts
664
- var import_regex = require("@weapp-core/regex");
665
-
666
- // src/js/babel/parse.ts
667
- var import_lru_cache2 = require("lru-cache");
668
- var parseCache = new import_lru_cache2.LRUCache(
669
- {
670
- max: 1024
671
- }
672
- );
673
-
674
- // src/js/babel/process.ts
675
- var import_magic_string = __toESM(require("magic-string"));
676
-
677
- // src/js/handlers.ts
678
- var import_escape3 = require("@ast-core/escape");
679
- var import_extractors = require("@weapp-tailwindcss/shared/extractors");
680
-
681
- // src/wxml/shared.ts
682
- var import_escape2 = require("@weapp-core/escape");
683
-
684
- // src/js/handlers.ts
685
- var debug2 = createDebug("[js:handlers] ");
686
-
687
- // src/js/evalTransforms.ts
688
- var import_escape4 = require("@ast-core/escape");
689
-
690
- // src/wxml/utils/codegen/legacy-rewriter.ts
691
- var import_magic_string2 = __toESM(require("magic-string"));
692
-
693
- // src/wxml/utils/codegen/legacy-visitor.ts
694
- var t = __toESM(require("@babel/types"));
695
-
696
- // src/wxml/utils/codegen.ts
697
- var WRAP_EXPRESSION_HANDLER_OPTIONS = Object.freeze({
698
- wrapExpression: true
699
- });
700
-
701
- // src/wxml/utils/custom-template.ts
702
- var import_htmlparser2 = require("htmlparser2");
703
- var import_magic_string4 = __toESM(require("magic-string"));
704
-
705
- // src/wxml/utils/template-fragments.ts
706
- var import_magic_string3 = __toESM(require("magic-string"));
707
-
708
- // src/wxml/whitespace.ts
709
- var WHITESPACE_CODES = /* @__PURE__ */ new Set([
710
- 9,
711
- // 制表符 \t
712
- 10,
713
- // 换行符 \n
714
- 11,
715
- // 垂直制表符 \v
716
- 12,
717
- // 换页符 \f
718
- 13,
719
- // 回车符 \r
720
- 32,
721
- // 空格
722
- 160,
723
- // 不间断空格 \u00A0
724
- 65279
725
- // 零宽无断行空格 \uFEFF
307
+ return e && typeof e === "object" && "default" in e ? e.default : e;
308
+ }
309
+ const traverse = _interopDefaultCompat(_babel_traverse.default);
310
+ //#endregion
311
+ //#region src/utils/nameMatcher.ts
312
+ const NEVER_MATCH_NAME$1 = () => false;
313
+ const GLOBAL_FLAG_REGEXP = /g/g;
314
+ function buildFuzzyMatcher(fuzzyStrings) {
315
+ if (fuzzyStrings.length === 0) return;
316
+ if (fuzzyStrings.length === 1) {
317
+ const [needle] = fuzzyStrings;
318
+ return (value) => value.includes(needle);
319
+ }
320
+ const unique = [...new Set(fuzzyStrings)];
321
+ const pattern = new RegExp(unique.map(_weapp_core_regex.escapeStringRegexp).join("|"));
322
+ return (value) => pattern.test(value);
323
+ }
324
+ function normaliseRegex(regex) {
325
+ const { source, flags } = regex;
326
+ if (!flags.includes("g")) return regex;
327
+ return new RegExp(source, flags.replace(GLOBAL_FLAG_REGEXP, ""));
328
+ }
329
+ function createNameMatcher(list, { exact = false } = {}) {
330
+ if (!list || list.length === 0) return NEVER_MATCH_NAME$1;
331
+ const exactStrings = exact ? /* @__PURE__ */ new Set() : void 0;
332
+ const fuzzyStrings = [];
333
+ const regexList = [];
334
+ for (const item of list) if (typeof item === "string") if (exact) exactStrings.add(item);
335
+ else fuzzyStrings.push(item);
336
+ else regexList.push(normaliseRegex(item));
337
+ if (exact) {
338
+ const exactStringCount = exactStrings?.size ?? 0;
339
+ if (exactStringCount === 1 && regexList.length === 0) {
340
+ const [needle] = exactStrings;
341
+ return (value) => value === needle;
342
+ }
343
+ if (regexList.length === 0) return (value) => exactStrings.has(value);
344
+ if (exactStringCount === 0 && regexList.length === 1) {
345
+ const [regex] = regexList;
346
+ return (value) => regex.test(value);
347
+ }
348
+ return (value) => {
349
+ if (exactStrings?.has(value)) return true;
350
+ return regexList.some((regex) => regex.test(value));
351
+ };
352
+ }
353
+ const fuzzyMatcher = exact ? void 0 : buildFuzzyMatcher(fuzzyStrings);
354
+ const hasRegex = regexList.length > 0;
355
+ if (fuzzyMatcher && !hasRegex) return fuzzyMatcher;
356
+ if (!fuzzyMatcher && regexList.length === 1) {
357
+ const [regex] = regexList;
358
+ return (value) => regex.test(value);
359
+ }
360
+ return (value) => {
361
+ if (fuzzyMatcher?.(value)) return true;
362
+ if (!hasRegex) return false;
363
+ return regexList.some((regex) => regex.test(value));
364
+ };
365
+ }
366
+ //#endregion
367
+ //#region src/js/babel/parse.ts
368
+ const parseCache = new lru_cache.LRUCache({ max: 1024 });
369
+ function genCacheKey(source, options) {
370
+ if (typeof options === "string") return source + options;
371
+ return source + JSON.stringify(options, (_, val) => typeof val === "function" ? val.toString() : val);
372
+ }
373
+ function babelParse(code, opts = {}) {
374
+ const { cache, cacheKey, ...rest } = opts;
375
+ const cacheKeyString = genCacheKey(code, cacheKey ?? rest);
376
+ let result;
377
+ if (cache) result = parseCache.get(cacheKeyString);
378
+ if (!result) {
379
+ const { cache: _cache, cacheKey: _cacheKey, ...parseOptions } = opts;
380
+ result = (0, _babel_parser.parse)(code, parseOptions);
381
+ if (cache) parseCache.set(cacheKeyString, result);
382
+ }
383
+ return result;
384
+ }
385
+ //#endregion
386
+ //#region src/wxml/shared.ts
387
+ const NEWLINE_RE = /[\n\r]+/g;
388
+ function replaceWxml(original, options = {
389
+ keepEOL: false,
390
+ escapeMap: _weapp_core_escape.MappingChars2String
391
+ }) {
392
+ const { keepEOL, escapeMap, ignoreHead } = options;
393
+ let res = original;
394
+ if (!keepEOL) res = res.replaceAll(NEWLINE_RE, "");
395
+ res = (0, _weapp_core_escape.escape)(res, {
396
+ map: escapeMap,
397
+ ignoreHead
398
+ });
399
+ return res;
400
+ }
401
+ //#endregion
402
+ //#region src/shared/classname-transform.ts
403
+ const escapedCandidateCacheByEscapeMap = /* @__PURE__ */ new WeakMap();
404
+ const defaultEscapedCandidateCache = /* @__PURE__ */ new Map();
405
+ let lastEscapedCandidateEscapeMap;
406
+ let lastEscapedCandidateCacheStore;
407
+ function isUrlLikeCandidate(candidate) {
408
+ return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
409
+ }
410
+ function isArbitraryValueCandidate(candidate) {
411
+ let hasOpenBracket = false;
412
+ let hasCloseBracket = false;
413
+ for (let i = 0; i < candidate.length; i++) {
414
+ const char = candidate[i];
415
+ if (char === "[") hasOpenBracket = true;
416
+ else if (char === "]") hasCloseBracket = true;
417
+ if (hasOpenBracket && hasCloseBracket) break;
418
+ }
419
+ if (!hasOpenBracket || !hasCloseBracket) return false;
420
+ if (isUrlLikeCandidate(candidate.trim())) return false;
421
+ return true;
422
+ }
423
+ function shouldEnableArbitraryValueFallbackByInputs(classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion) {
424
+ if (jsArbitraryValueFallback === true) return true;
425
+ if (jsArbitraryValueFallback === false) return false;
426
+ return tailwindcssMajorVersion === 4 && (!classNameSet || classNameSet.size === 0);
427
+ }
428
+ function shouldEnableArbitraryValueFallback({ classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion }) {
429
+ return shouldEnableArbitraryValueFallbackByInputs(classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion);
430
+ }
431
+ const SKIP_RESULT = { decision: "skip" };
432
+ const DIRECT_RESULT = { decision: "direct" };
433
+ const FALLBACK_RESULT = { decision: "fallback" };
434
+ function getEscapedCandidateCacheStore(escapeMap) {
435
+ if (!escapeMap) return defaultEscapedCandidateCache;
436
+ if (escapeMap === lastEscapedCandidateEscapeMap && lastEscapedCandidateCacheStore) return lastEscapedCandidateCacheStore;
437
+ let store = escapedCandidateCacheByEscapeMap.get(escapeMap);
438
+ if (!store) {
439
+ store = /* @__PURE__ */ new Map();
440
+ escapedCandidateCacheByEscapeMap.set(escapeMap, store);
441
+ }
442
+ lastEscapedCandidateEscapeMap = escapeMap;
443
+ lastEscapedCandidateCacheStore = store;
444
+ return store;
445
+ }
446
+ function getEscapedCandidate(candidate, escapeMap, store = getEscapedCandidateCacheStore(escapeMap)) {
447
+ let cached = store.get(candidate);
448
+ if (cached === void 0) {
449
+ cached = replaceWxml(candidate, { escapeMap });
450
+ store.set(candidate, cached);
451
+ }
452
+ return cached;
453
+ }
454
+ /**
455
+ * JS 转译严格遵循 runtime class set:
456
+ * 1. 直接命中 classNameSet 原始值;
457
+ * 2. 兼容命中 classNameSet 中已转义值;
458
+ * 3. 仅在受控条件下允许 class 语义兜底。
459
+ *
460
+ * 返回结构化结果,附带已计算的 escapedValue 以避免下游重复 escape。
461
+ */
462
+ function resolveClassNameTransformWithResult(candidate, { alwaysEscape, classNameSet, escapeMap, jsArbitraryValueFallback, jsPreserveClass, tailwindcssMajorVersion, classContext }) {
463
+ if (alwaysEscape) return DIRECT_RESULT;
464
+ if (jsPreserveClass?.(candidate)) return SKIP_RESULT;
465
+ if (classNameSet?.has(candidate)) return DIRECT_RESULT;
466
+ if (classNameSet && classNameSet.size > 0) {
467
+ const escapedCandidate = getEscapedCandidate(candidate, escapeMap);
468
+ if (escapedCandidate !== candidate && classNameSet.has(escapedCandidate)) return {
469
+ decision: "escaped",
470
+ escapedValue: escapedCandidate
471
+ };
472
+ }
473
+ if (classContext && shouldEnableArbitraryValueFallbackByInputs(classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion) && isArbitraryValueCandidate(candidate)) return FALLBACK_RESULT;
474
+ return SKIP_RESULT;
475
+ }
476
+ //#endregion
477
+ //#region src/utils/decode.ts
478
+ const unicodeEscapeRE = /\\u([\dA-Fa-f]{4})/g;
479
+ const unicodeEscapeTestRE = /\\u[\dA-Fa-f]{4}/;
480
+ function decodeUnicode(value) {
481
+ if (!unicodeEscapeTestRE.test(value)) return value;
482
+ return value.replace(unicodeEscapeRE, (_match, hex) => {
483
+ const codePoint = Number.parseInt(hex, 16);
484
+ return Number.isNaN(codePoint) ? _match : String.fromCharCode(codePoint);
485
+ });
486
+ }
487
+ function decodeUnicode2(input) {
488
+ if (!unicodeEscapeTestRE.test(input)) return input;
489
+ try {
490
+ return JSON.parse(`"${input}"`);
491
+ } catch (_error) {
492
+ return decodeUnicode(input);
493
+ }
494
+ }
495
+ //#endregion
496
+ //#region src/js/class-context.ts
497
+ const CLASS_LIKE_KEYWORDS = new Set([
498
+ "class",
499
+ "classname",
500
+ "hoverclass",
501
+ "virtualhostclass",
502
+ "rootclass"
503
+ ]);
504
+ const CLASS_HELPER_IDENTIFIERS = new Set([
505
+ "cn",
506
+ "clsx",
507
+ "classnames",
508
+ "twmerge",
509
+ "cva",
510
+ "tv",
511
+ "cx",
512
+ "r"
513
+ ]);
514
+ const DASH_CODE = 45;
515
+ const COLON_CODE = 58;
516
+ const UPPERCASE_A_CODE = 65;
517
+ const UPPERCASE_Z_CODE = 90;
518
+ const UNDERSCORE_CODE = 95;
519
+ const ASCII_MAX_CODE = 127;
520
+ const NORMALIZE_KEYWORD_REGEXP = /[-_:]/g;
521
+ function normalizeKeyword(name) {
522
+ const length = name.length;
523
+ let firstNormalizedIndex = -1;
524
+ for (let i = 0; i < length; i++) {
525
+ const code = name.charCodeAt(i);
526
+ if (code === DASH_CODE || code === UNDERSCORE_CODE || code === COLON_CODE || code >= UPPERCASE_A_CODE && code <= UPPERCASE_Z_CODE) {
527
+ firstNormalizedIndex = i;
528
+ break;
529
+ }
530
+ if (code > ASCII_MAX_CODE) return name.replace(NORMALIZE_KEYWORD_REGEXP, "").toLowerCase();
531
+ }
532
+ if (firstNormalizedIndex === -1) return name;
533
+ let normalized = name.slice(0, firstNormalizedIndex);
534
+ for (let i = firstNormalizedIndex; i < length; i++) {
535
+ const code = name.charCodeAt(i);
536
+ if (code === DASH_CODE || code === UNDERSCORE_CODE || code === COLON_CODE) continue;
537
+ if (code >= UPPERCASE_A_CODE && code <= UPPERCASE_Z_CODE) {
538
+ normalized += String.fromCharCode(code + 32);
539
+ continue;
540
+ }
541
+ if (code > ASCII_MAX_CODE) return name.replace(NORMALIZE_KEYWORD_REGEXP, "").toLowerCase();
542
+ normalized += name[i];
543
+ }
544
+ return normalized;
545
+ }
546
+ function readObjectKeyName(path) {
547
+ if (path.isIdentifier()) return path.node.name;
548
+ if (path.isStringLiteral()) return path.node.value;
549
+ if (path.isTemplateLiteral() && path.node.expressions.length === 0) return path.node.quasis[0]?.value.cooked ?? path.node.quasis[0]?.value.raw;
550
+ }
551
+ function isClassLikeObjectProperty(path, valuePath) {
552
+ if (!path.isObjectProperty()) return false;
553
+ if (path.get("value") !== valuePath) return false;
554
+ const keyName = readObjectKeyName(path.get("key"));
555
+ if (!keyName) return false;
556
+ return CLASS_LIKE_KEYWORDS.has(normalizeKeyword(keyName));
557
+ }
558
+ function isClassLikeJsxAttribute(path) {
559
+ if (!path.isJSXAttribute()) return false;
560
+ const namePath = path.get("name");
561
+ if (!namePath.isJSXIdentifier()) return false;
562
+ return CLASS_LIKE_KEYWORDS.has(normalizeKeyword(namePath.node.name));
563
+ }
564
+ function readCallHelperName(calleePath) {
565
+ if (calleePath.isIdentifier()) return calleePath.node.name;
566
+ if (calleePath.isMemberExpression()) {
567
+ const propertyPath = calleePath.get("property");
568
+ if (propertyPath.isIdentifier()) return propertyPath.node.name;
569
+ if (propertyPath.isStringLiteral()) return propertyPath.node.value;
570
+ }
571
+ }
572
+ function isClassLikeCallExpression(path, valuePath) {
573
+ if (!path.isCallExpression()) return false;
574
+ const helperName = readCallHelperName(path.get("callee"));
575
+ if (!helperName || !CLASS_HELPER_IDENTIFIERS.has(normalizeKeyword(helperName))) return false;
576
+ return path.get("arguments").some((argumentPath) => argumentPath.node === valuePath.node);
577
+ }
578
+ /**
579
+ * 判断字符串字面量是否处于 class 语义上下文。
580
+ * 仅用于受控兜底场景,避免将普通业务文本误判为 class。
581
+ */
582
+ function isClassContextLiteralPath(path) {
583
+ let current = path;
584
+ while (current.parentPath) {
585
+ const parent = current.parentPath;
586
+ if (isClassLikeObjectProperty(parent, current)) return true;
587
+ if (isClassLikeJsxAttribute(parent)) return true;
588
+ if (isClassLikeCallExpression(parent, current)) return true;
589
+ current = parent;
590
+ }
591
+ return false;
592
+ }
593
+ //#endregion
594
+ //#region src/js/handlers.ts
595
+ const debug$1 = createDebug("[js:handlers] ");
596
+ const replacementCacheByEscapeMap = /* @__PURE__ */ new WeakMap();
597
+ const defaultReplacementCache = /* @__PURE__ */ new Map();
598
+ const WEAPP_TW_IGNORE_MARKER = "weapp-tw";
599
+ const IGNORE_MARKER = "ignore";
600
+ function getReplacementCacheStore(escapeMap) {
601
+ if (!escapeMap) return defaultReplacementCache;
602
+ let store = replacementCacheByEscapeMap.get(escapeMap);
603
+ if (!store) {
604
+ store = /* @__PURE__ */ new Map();
605
+ replacementCacheByEscapeMap.set(escapeMap, store);
606
+ }
607
+ return store;
608
+ }
609
+ function getReplacement(candidate, escapeMap, store = getReplacementCacheStore(escapeMap)) {
610
+ let cached = store.get(candidate);
611
+ if (cached === void 0) {
612
+ cached = replaceWxml(candidate, { escapeMap });
613
+ store.set(candidate, cached);
614
+ }
615
+ return cached;
616
+ }
617
+ function hasIgnoreComment(node) {
618
+ const { leadingComments } = node;
619
+ if (!Array.isArray(leadingComments) || leadingComments.length === 0) return false;
620
+ for (const comment of leadingComments) {
621
+ const { value } = comment;
622
+ if (value.includes(WEAPP_TW_IGNORE_MARKER) && value.includes(IGNORE_MARKER)) return true;
623
+ }
624
+ return false;
625
+ }
626
+ function extractLiteralValue(path, { unescapeUnicode, arbitraryValues }) {
627
+ const allowDoubleQuotes = arbitraryValues?.allowDoubleQuotes;
628
+ const { node } = path;
629
+ let offset = 0;
630
+ let original;
631
+ if (node.type === "StringLiteral") {
632
+ offset = 1;
633
+ original = node.value;
634
+ } else if (node.type === "TemplateElement") original = node.value.raw;
635
+ else original = "";
636
+ let literal = original;
637
+ if (unescapeUnicode && original.includes("\\u")) literal = decodeUnicode2(original);
638
+ return {
639
+ allowDoubleQuotes,
640
+ literal,
641
+ offset,
642
+ original
643
+ };
644
+ }
645
+ function createCandidatePlanResolver(options, classContext) {
646
+ const { escapeMap } = options;
647
+ const replacementCache = getReplacementCacheStore(escapeMap);
648
+ const transformOptions = classContext ? {
649
+ ...options,
650
+ classContext
651
+ } : options;
652
+ let firstCandidate = "";
653
+ let firstPlan;
654
+ let cache;
655
+ const buildCandidatePlan = (candidate) => {
656
+ const result = resolveClassNameTransformWithResult(candidate, transformOptions);
657
+ if (result.decision === "skip") return { result };
658
+ let replacement;
659
+ if (result.decision === "escaped" && result.escapedValue) {
660
+ replacement = result.escapedValue;
661
+ replacementCache.set(candidate, replacement);
662
+ } else replacement = getReplacement(candidate, escapeMap, replacementCache);
663
+ return {
664
+ result,
665
+ replacement
666
+ };
667
+ };
668
+ return (candidate) => {
669
+ if (cache) {
670
+ const cached = cache.get(candidate);
671
+ if (cached) return cached;
672
+ } else if (firstPlan && candidate === firstCandidate) return firstPlan;
673
+ const plan = buildCandidatePlan(candidate);
674
+ if (!firstPlan) {
675
+ firstCandidate = candidate;
676
+ firstPlan = plan;
677
+ return plan;
678
+ }
679
+ if (!cache) {
680
+ cache = /* @__PURE__ */ new Map();
681
+ cache.set(firstCandidate, firstPlan);
682
+ }
683
+ cache.set(candidate, plan);
684
+ return plan;
685
+ };
686
+ }
687
+ function replaceHandleValue(path, options) {
688
+ const { needEscaped = false } = options;
689
+ const { classNameSet, alwaysEscape } = options;
690
+ const fallbackEnabled = shouldEnableArbitraryValueFallback(options);
691
+ if (!alwaysEscape && !fallbackEnabled && (!classNameSet || classNameSet.size === 0)) return;
692
+ if (hasIgnoreComment(path.node)) return;
693
+ const { literal, original, allowDoubleQuotes, offset } = extractLiteralValue(path, options);
694
+ const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
695
+ if (candidates.length === 0) return;
696
+ const debugEnabled = debug$1.enabled;
697
+ const classContext = options.wrapExpression || isClassContextLiteralPath(path);
698
+ let transformed = literal;
699
+ let mutated = false;
700
+ let matchedCandidateCount = 0;
701
+ let escapedDecisionCount = 0;
702
+ let fallbackDecisionCount = 0;
703
+ let escapedSamples;
704
+ let skippedSamples;
705
+ const resolveCandidatePlan = createCandidatePlanResolver(options, classContext);
706
+ for (const candidate of candidates) {
707
+ const plan = resolveCandidatePlan(candidate);
708
+ if (plan.result.decision === "skip") {
709
+ if (debugEnabled) {
710
+ if (!skippedSamples) skippedSamples = [];
711
+ if (skippedSamples.length < 6) skippedSamples.push(candidate);
712
+ }
713
+ continue;
714
+ }
715
+ if (debugEnabled) {
716
+ matchedCandidateCount += 1;
717
+ if (plan.result.decision === "escaped") {
718
+ escapedDecisionCount += 1;
719
+ if (!escapedSamples) escapedSamples = [];
720
+ if (escapedSamples.length < 6) escapedSamples.push(candidate);
721
+ }
722
+ if (plan.result.decision === "fallback") fallbackDecisionCount += 1;
723
+ }
724
+ const replaced = transformed.replace(candidate, plan.replacement);
725
+ if (replaced !== transformed) {
726
+ transformed = replaced;
727
+ mutated = true;
728
+ }
729
+ }
730
+ const node = path.node;
731
+ if (!mutated || typeof node.start !== "number" || typeof node.end !== "number") return;
732
+ if (debugEnabled) debug$1("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(",") || "-");
733
+ const start = node.start + offset;
734
+ const end = node.end - offset;
735
+ if (start >= end || transformed === original) return;
736
+ return {
737
+ start,
738
+ end,
739
+ value: needEscaped ? (0, _ast_core_escape.jsStringEscape)(transformed) : transformed,
740
+ path
741
+ };
742
+ }
743
+ //#endregion
744
+ //#region src/js/sourceAnalysis.ts
745
+ function hasReplacementEntries(replacements) {
746
+ for (const key in replacements) if (Object.hasOwn(replacements, key)) return true;
747
+ return false;
748
+ }
749
+ function createModuleSpecifierReplacementToken(path, replacement) {
750
+ const node = path.node;
751
+ if (node.value === replacement) return;
752
+ if (typeof node.start !== "number" || typeof node.end !== "number") return;
753
+ const start = node.start + 1;
754
+ const end = node.end - 1;
755
+ if (start >= end) return;
756
+ return {
757
+ start,
758
+ end,
759
+ value: replacement,
760
+ path
761
+ };
762
+ }
763
+ function collectModuleSpecifierReplacementTokens(analysis, replacements) {
764
+ if (!hasReplacementEntries(replacements)) return [];
765
+ if (analysis.importDeclarations.size === 0 && analysis.exportDeclarations.size === 0 && analysis.requireCallPaths.length === 0 && analysis.walker.imports.size === 0) return [];
766
+ const tokens = [];
767
+ const applyReplacement = (path) => {
768
+ const replacement = replacements[path.node.value];
769
+ if (!replacement) return;
770
+ const token = createModuleSpecifierReplacementToken(path, replacement);
771
+ if (token) tokens.push(token);
772
+ };
773
+ for (const importPath of analysis.importDeclarations) {
774
+ const source = importPath.get("source");
775
+ if (source.isStringLiteral()) applyReplacement(source);
776
+ }
777
+ for (const exportPath of analysis.exportDeclarations) if (exportPath.isExportNamedDeclaration() || exportPath.isExportAllDeclaration()) {
778
+ const source = exportPath.get("source");
779
+ if (source && !Array.isArray(source) && source.isStringLiteral()) applyReplacement(source);
780
+ }
781
+ for (const literalPath of analysis.requireCallPaths) applyReplacement(literalPath);
782
+ for (const token of analysis.walker.imports) {
783
+ const replacement = replacements[token.source];
784
+ if (replacement) token.source = replacement;
785
+ }
786
+ return tokens;
787
+ }
788
+ //#endregion
789
+ //#region src/js/babel/process.ts
790
+ const optionVariantsCache = /* @__PURE__ */ new WeakMap();
791
+ function getNeedEscapedOptions(options, needEscaped) {
792
+ if (options.needEscaped === needEscaped) return options;
793
+ let cached = optionVariantsCache.get(options);
794
+ if (!cached) {
795
+ cached = {};
796
+ optionVariantsCache.set(options, cached);
797
+ }
798
+ if (needEscaped) {
799
+ if (!cached.stringLiteralOptions) cached.stringLiteralOptions = {
800
+ ...options,
801
+ needEscaped: true
802
+ };
803
+ return cached.stringLiteralOptions;
804
+ }
805
+ if (!cached.templateLiteralOptions) cached.templateLiteralOptions = {
806
+ ...options,
807
+ needEscaped: false
808
+ };
809
+ return cached.templateLiteralOptions;
810
+ }
811
+ function processUpdatedSource(rawSource, options, analysis) {
812
+ const { targetPaths, jsTokenUpdater, ignoredPaths } = analysis;
813
+ if (targetPaths.length === 0 && !options.moduleSpecifierReplacements && jsTokenUpdater.length === 0) return new magic_string.default(rawSource);
814
+ const replacementTokens = [];
815
+ for (const path of targetPaths) {
816
+ if (ignoredPaths.has(path)) continue;
817
+ const token = replaceHandleValue(path, path.isStringLiteral() ? getNeedEscapedOptions(options, true) : getNeedEscapedOptions(options, false));
818
+ if (token) replacementTokens.push(token);
819
+ }
820
+ if (options.moduleSpecifierReplacements) replacementTokens.push(...collectModuleSpecifierReplacementTokens(analysis, options.moduleSpecifierReplacements));
821
+ if (jsTokenUpdater.length + replacementTokens.length === 0) return new magic_string.default(rawSource);
822
+ const ms = new magic_string.default(rawSource);
823
+ jsTokenUpdater.push(...replacementTokens).filter((token) => !ignoredPaths.has(token.path)).updateMagicString(ms);
824
+ return ms;
825
+ }
826
+ //#endregion
827
+ //#region src/js/evalTransforms.ts
828
+ const evalHandlerOptionsCache = /* @__PURE__ */ new WeakMap();
829
+ const EVAL_SCOPE_ERROR_REGEXP = /pass a scope and parentPath|traversing a Program\/File/i;
830
+ function isEvalPath(path) {
831
+ if (path.isCallExpression()) return path.get("callee").isIdentifier({ name: "eval" });
832
+ return false;
833
+ }
834
+ function createEvalReplacementToken(path, updated) {
835
+ const node = path.node;
836
+ let offset = 0;
837
+ let original;
838
+ if (path.isStringLiteral()) {
839
+ offset = 1;
840
+ original = path.node.value;
841
+ } else if (path.isTemplateElement()) original = path.node.value.raw;
842
+ else original = "";
843
+ if (typeof node.start !== "number" || typeof node.end !== "number") return;
844
+ const start = node.start + offset;
845
+ const end = node.end - offset;
846
+ if (start >= end) return;
847
+ if (original === updated) return;
848
+ return {
849
+ start,
850
+ end,
851
+ value: path.isStringLiteral() ? (0, _ast_core_escape.jsStringEscape)(updated) : updated,
852
+ path
853
+ };
854
+ }
855
+ function handleEvalStringLiteral(path, handlerOptions, updater, handler) {
856
+ const { code } = handler(path.node.value, handlerOptions);
857
+ if (!code) return;
858
+ const token = createEvalReplacementToken(path, code);
859
+ if (token) updater.addToken(token);
860
+ }
861
+ function handleEvalTemplateElement(path, handlerOptions, updater, handler) {
862
+ const { code } = handler(path.node.value.raw, handlerOptions);
863
+ if (!code) return;
864
+ const token = createEvalReplacementToken(path, code);
865
+ if (token) updater.addToken(token);
866
+ }
867
+ function getEvalStringHandlerOptions(options) {
868
+ if (options.needEscaped === false && options.generateMap === false) return options;
869
+ let cached = evalHandlerOptionsCache.get(options);
870
+ if (!cached) {
871
+ cached = {};
872
+ evalHandlerOptionsCache.set(options, cached);
873
+ }
874
+ if (!cached.stringLiteralOptions) cached.stringLiteralOptions = {
875
+ ...options,
876
+ needEscaped: false,
877
+ generateMap: false
878
+ };
879
+ return cached.stringLiteralOptions;
880
+ }
881
+ function getEvalTemplateHandlerOptions(options) {
882
+ if (options.generateMap === false) return options;
883
+ let cached = evalHandlerOptionsCache.get(options);
884
+ if (!cached) {
885
+ cached = {};
886
+ evalHandlerOptionsCache.set(options, cached);
887
+ }
888
+ if (!cached.templateLiteralOptions) cached.templateLiteralOptions = {
889
+ ...options,
890
+ generateMap: false
891
+ };
892
+ return cached.templateLiteralOptions;
893
+ }
894
+ function walkEvalExpression(path, options, updater, handler) {
895
+ const stringHandlerOptions = getEvalStringHandlerOptions(options);
896
+ const templateHandlerOptions = getEvalTemplateHandlerOptions(options);
897
+ const maybeTraverse = path?.traverse;
898
+ if (typeof maybeTraverse === "function") try {
899
+ return maybeTraverse.call(path, {
900
+ StringLiteral(innerPath) {
901
+ handleEvalStringLiteral(innerPath, stringHandlerOptions, updater, handler);
902
+ },
903
+ TemplateElement(innerPath) {
904
+ handleEvalTemplateElement(innerPath, templateHandlerOptions, updater, handler);
905
+ }
906
+ });
907
+ } catch (error) {
908
+ const msg = error?.message ?? "";
909
+ if (!EVAL_SCOPE_ERROR_REGEXP.test(msg)) throw error;
910
+ }
911
+ const getArgs = path?.get?.("arguments");
912
+ if (Array.isArray(getArgs)) {
913
+ for (const arg of getArgs) {
914
+ if (arg?.isStringLiteral?.()) {
915
+ handleEvalStringLiteral(arg, stringHandlerOptions, updater, handler);
916
+ continue;
917
+ }
918
+ if (arg?.isTemplateLiteral?.()) for (const quasi of arg.get("quasis")) handleEvalTemplateElement(quasi, templateHandlerOptions, updater, handler);
919
+ }
920
+ return;
921
+ }
922
+ const nodeArgs = path?.node?.arguments;
923
+ if (Array.isArray(nodeArgs)) {
924
+ for (const n of nodeArgs) if (n?.type === "StringLiteral") handleEvalStringLiteral({
925
+ node: n,
926
+ isStringLiteral: () => true
927
+ }, stringHandlerOptions, updater, handler);
928
+ else if (n?.type === "TemplateLiteral" && Array.isArray(n.quasis)) for (const q of n.quasis) handleEvalTemplateElement({
929
+ node: q,
930
+ isStringLiteral: () => false,
931
+ isTemplateElement: () => true
932
+ }, templateHandlerOptions, updater, handler);
933
+ }
934
+ }
935
+ //#endregion
936
+ //#region src/js/JsTokenUpdater.ts
937
+ /**
938
+ * Lightweight helper that batches updates to {@link MagicString}.
939
+ * It keeps the transformation logic out of the traversal code and makes
940
+ * it easier to reason about the order in which tokens are written back.
941
+ */
942
+ var JsTokenUpdater = class {
943
+ constructor({ value } = {}) {
944
+ this.tokens = value ? [...value] : [];
945
+ }
946
+ addToken(token) {
947
+ if (token) this.tokens.push(token);
948
+ }
949
+ push(...args) {
950
+ this.tokens.push(...args);
951
+ return this;
952
+ }
953
+ /**
954
+ * 待写入的 token 数量。
955
+ */
956
+ get length() {
957
+ return this.tokens.length;
958
+ }
959
+ map(callbackfn) {
960
+ this.tokens = this.tokens.map(callbackfn);
961
+ return this;
962
+ }
963
+ filter(callbackfn) {
964
+ this.tokens = this.tokens.filter(callbackfn);
965
+ return this;
966
+ }
967
+ updateMagicString(ms) {
968
+ for (const { start, end, value } of this.tokens) ms.update(start, end, value);
969
+ return ms;
970
+ }
971
+ };
972
+ //#endregion
973
+ //#region src/js/module-graph/ignored-exports.ts
974
+ var IgnoredExportsTracker = class {
975
+ constructor(options) {
976
+ this.options = options;
977
+ this.ignoredExportNames = /* @__PURE__ */ new Map();
978
+ }
979
+ addIgnoredExport(filename, exportName) {
980
+ if (!exportName) return;
981
+ let pending = this.ignoredExportNames.get(filename);
982
+ if (!pending) {
983
+ pending = /* @__PURE__ */ new Set();
984
+ this.ignoredExportNames.set(filename, pending);
985
+ }
986
+ if (pending.has(exportName)) return;
987
+ pending.add(exportName);
988
+ const existing = this.options.modules.get(filename);
989
+ if (existing) this.applyIgnoredExportsToAnalysis(filename, existing.analysis);
990
+ }
991
+ registerIgnoredExportsFromTokens(resolved, tokens) {
992
+ for (const token of tokens) if (token.type === "ImportSpecifier") this.addIgnoredExport(resolved, token.imported);
993
+ else if (token.type === "ImportDefaultSpecifier") this.addIgnoredExport(resolved, "default");
994
+ }
995
+ applyIgnoredExportsToAnalysis(filename, analysis) {
996
+ const pending = this.ignoredExportNames.get(filename);
997
+ if (!pending || pending.size === 0) return;
998
+ const names = new Set(pending);
999
+ pending.clear();
1000
+ const propagate = [];
1001
+ for (const exportPath of analysis.exportDeclarations) {
1002
+ if (names.size === 0) break;
1003
+ if (exportPath.isExportDefaultDeclaration()) {
1004
+ if (names.has("default")) {
1005
+ analysis.walker.walkExportDefaultDeclaration(exportPath);
1006
+ names.delete("default");
1007
+ }
1008
+ continue;
1009
+ }
1010
+ if (exportPath.isExportNamedDeclaration()) {
1011
+ const source = exportPath.node.source?.value;
1012
+ if (typeof source === "string") {
1013
+ for (const spec of exportPath.get("specifiers")) {
1014
+ if (!spec.isExportSpecifier()) continue;
1015
+ const exported = spec.get("exported");
1016
+ let exportedName;
1017
+ if (exported.isIdentifier()) exportedName = exported.node.name;
1018
+ else if (exported.isStringLiteral()) exportedName = exported.node.value;
1019
+ if (!exportedName || !names.has(exportedName)) continue;
1020
+ const local = spec.get("local");
1021
+ if (local.isIdentifier()) {
1022
+ propagate.push({
1023
+ specifier: source,
1024
+ exportName: local.node.name
1025
+ });
1026
+ names.delete(exportedName);
1027
+ } else if (local.isStringLiteral()) {
1028
+ propagate.push({
1029
+ specifier: source,
1030
+ exportName: local.node.value
1031
+ });
1032
+ names.delete(exportedName);
1033
+ }
1034
+ }
1035
+ continue;
1036
+ }
1037
+ const declaration = exportPath.get("declaration");
1038
+ if (declaration.isVariableDeclaration()) for (const decl of declaration.get("declarations")) {
1039
+ const id = decl.get("id");
1040
+ if (id.isIdentifier()) {
1041
+ const exportName = id.node.name;
1042
+ if (names.has(exportName)) {
1043
+ analysis.walker.walkVariableDeclarator(decl);
1044
+ names.delete(exportName);
1045
+ }
1046
+ }
1047
+ }
1048
+ for (const spec of exportPath.get("specifiers")) {
1049
+ if (!spec.isExportSpecifier()) continue;
1050
+ const exported = spec.get("exported");
1051
+ let exportedName;
1052
+ if (exported.isIdentifier()) exportedName = exported.node.name;
1053
+ else if (exported.isStringLiteral()) exportedName = exported.node.value;
1054
+ if (!exportedName || !names.has(exportedName)) continue;
1055
+ const local = spec.get("local");
1056
+ analysis.walker.walkNode(local);
1057
+ names.delete(exportedName);
1058
+ }
1059
+ continue;
1060
+ }
1061
+ if (exportPath.isExportAllDeclaration()) {
1062
+ const source = exportPath.node.source?.value;
1063
+ if (typeof source === "string") {
1064
+ for (const exportName of names) propagate.push({
1065
+ specifier: source,
1066
+ exportName
1067
+ });
1068
+ names.clear();
1069
+ }
1070
+ }
1071
+ }
1072
+ for (const { specifier, exportName } of propagate) {
1073
+ let resolved;
1074
+ try {
1075
+ resolved = this.options.resolve(specifier, filename);
1076
+ } catch {
1077
+ resolved = void 0;
1078
+ }
1079
+ if (!resolved) {
1080
+ pending.add(exportName);
1081
+ continue;
1082
+ }
1083
+ if (this.options.filter && !this.options.filter(resolved, specifier, filename)) {
1084
+ pending.add(exportName);
1085
+ continue;
1086
+ }
1087
+ this.addIgnoredExport(resolved, exportName);
1088
+ }
1089
+ for (const name of names) pending.add(name);
1090
+ }
1091
+ };
1092
+ //#endregion
1093
+ //#region src/js/ModuleGraph.ts
1094
+ var JsModuleGraph = class {
1095
+ constructor(entry, graphOptions) {
1096
+ this.modules = /* @__PURE__ */ new Map();
1097
+ this.queue = [];
1098
+ this.resolve = graphOptions.resolve;
1099
+ this.load = graphOptions.load;
1100
+ this.filter = graphOptions.filter;
1101
+ this.maxDepth = graphOptions.maxDepth ?? Number.POSITIVE_INFINITY;
1102
+ const { moduleGraph: _moduleGraph, filename: _ignoredFilename, ...rest } = entry.handlerOptions;
1103
+ this.baseOptions = {
1104
+ ...rest,
1105
+ filename: entry.filename
1106
+ };
1107
+ this.parserOptions = entry.handlerOptions.babelParserOptions;
1108
+ this.rootFilename = entry.filename;
1109
+ this.ignoredExports = new IgnoredExportsTracker({
1110
+ resolve: this.resolve,
1111
+ filter: this.filter,
1112
+ modules: this.modules
1113
+ });
1114
+ this.modules.set(entry.filename, {
1115
+ filename: entry.filename,
1116
+ source: entry.source,
1117
+ analysis: entry.analysis
1118
+ });
1119
+ this.queue.push({
1120
+ filename: entry.filename,
1121
+ depth: 0
1122
+ });
1123
+ }
1124
+ build() {
1125
+ this.collectDependencies();
1126
+ let linked;
1127
+ for (const [filename, state] of this.modules) {
1128
+ if (filename === this.rootFilename) continue;
1129
+ const childOptions = {
1130
+ ...this.baseOptions,
1131
+ filename
1132
+ };
1133
+ const code = processUpdatedSource(state.source, childOptions, state.analysis).toString();
1134
+ if (code !== state.source) {
1135
+ if (!linked) linked = {};
1136
+ linked[filename] = { code };
1137
+ }
1138
+ }
1139
+ return linked;
1140
+ }
1141
+ collectDependencies() {
1142
+ while (this.queue.length > 0) {
1143
+ const { filename, depth } = this.queue.shift();
1144
+ if (depth >= this.maxDepth) continue;
1145
+ const state = this.modules.get(filename);
1146
+ if (!state) continue;
1147
+ const dependencySpecifiers = /* @__PURE__ */ new Map();
1148
+ for (const token of state.analysis.walker.imports) {
1149
+ if (!dependencySpecifiers.has(token.source)) dependencySpecifiers.set(token.source, []);
1150
+ dependencySpecifiers.get(token.source).push(token);
1151
+ }
1152
+ for (const exportPath of state.analysis.exportDeclarations) if (exportPath.isExportAllDeclaration() || exportPath.isExportNamedDeclaration()) {
1153
+ const source = exportPath.node.source?.value;
1154
+ if (typeof source === "string" && !dependencySpecifiers.has(source)) dependencySpecifiers.set(source, []);
1155
+ }
1156
+ for (const [specifier, tokens] of dependencySpecifiers) {
1157
+ let resolved;
1158
+ try {
1159
+ resolved = this.resolve(specifier, filename);
1160
+ } catch {
1161
+ continue;
1162
+ }
1163
+ if (!resolved) continue;
1164
+ if (this.filter && !this.filter(resolved, specifier, filename)) continue;
1165
+ if (tokens.length > 0) this.ignoredExports.registerIgnoredExportsFromTokens(resolved, tokens);
1166
+ if (this.modules.has(resolved)) continue;
1167
+ let source;
1168
+ try {
1169
+ source = this.load(resolved);
1170
+ } catch {
1171
+ continue;
1172
+ }
1173
+ if (typeof source !== "string") continue;
1174
+ let analysis;
1175
+ try {
1176
+ analysis = analyzeSource(babelParse(source, {
1177
+ ...this.parserOptions,
1178
+ sourceFilename: resolved
1179
+ }), {
1180
+ ...this.baseOptions,
1181
+ filename: resolved
1182
+ });
1183
+ this.ignoredExports.applyIgnoredExportsToAnalysis(resolved, analysis);
1184
+ } catch {
1185
+ continue;
1186
+ }
1187
+ this.modules.set(resolved, {
1188
+ filename: resolved,
1189
+ source,
1190
+ analysis
1191
+ });
1192
+ this.queue.push({
1193
+ filename: resolved,
1194
+ depth: depth + 1
1195
+ });
1196
+ }
1197
+ }
1198
+ }
1199
+ };
1200
+ //#endregion
1201
+ //#region src/js/node-path-walker/export-handlers.ts
1202
+ function walkExportDeclaration(ctx, path) {
1203
+ if (path.isExportDeclaration()) {
1204
+ if (path.isExportNamedDeclaration()) walkExportNamedDeclaration(ctx, path);
1205
+ else if (path.isExportDefaultDeclaration()) walkExportDefaultDeclaration(ctx, path);
1206
+ else if (path.isExportAllDeclaration()) walkExportAllDeclaration(ctx, path);
1207
+ }
1208
+ }
1209
+ function walkExportNamedDeclaration(ctx, path) {
1210
+ const declaration = path.get("declaration");
1211
+ if (declaration.isVariableDeclaration()) for (const decl of declaration.get("declarations")) ctx.walkNode(decl);
1212
+ const specifiers = path.get("specifiers");
1213
+ for (const spec of specifiers) if (spec.isExportSpecifier()) {
1214
+ const local = spec.get("local");
1215
+ if (local.isIdentifier()) ctx.walkNode(local);
1216
+ }
1217
+ }
1218
+ function walkExportDefaultDeclaration(ctx, path) {
1219
+ const decl = path.get("declaration");
1220
+ if (decl.isIdentifier()) ctx.walkNode(decl);
1221
+ else ctx.walkNode(decl);
1222
+ }
1223
+ function walkExportAllDeclaration(ctx, path) {
1224
+ const source = path.get("source");
1225
+ if (source.isStringLiteral()) ctx.addImportToken({
1226
+ declaration: path,
1227
+ source: source.node.value,
1228
+ type: "ExportAllDeclaration"
1229
+ });
1230
+ }
1231
+ //#endregion
1232
+ //#region src/js/node-path-walker/import-tokens.ts
1233
+ function maybeAddImportToken(imports, arg) {
1234
+ if (!(arg.isImportSpecifier() && arg.node.importKind !== "type" || arg.isImportDefaultSpecifier())) return false;
1235
+ const importDeclaration = arg.parentPath;
1236
+ if (!importDeclaration.isImportDeclaration() || importDeclaration.node.importKind === "type") return false;
1237
+ if (arg.isImportSpecifier()) {
1238
+ const imported = arg.get("imported");
1239
+ if (imported.isIdentifier()) imports.add({
1240
+ declaration: importDeclaration,
1241
+ specifier: arg,
1242
+ imported: imported.node.name,
1243
+ local: arg.node.local.name,
1244
+ source: importDeclaration.node.source.value,
1245
+ type: "ImportSpecifier"
1246
+ });
1247
+ return true;
1248
+ }
1249
+ imports.add({
1250
+ declaration: importDeclaration,
1251
+ specifier: arg,
1252
+ local: arg.node.local.name,
1253
+ source: importDeclaration.node.source.value,
1254
+ type: "ImportDefaultSpecifier"
1255
+ });
1256
+ return true;
1257
+ }
1258
+ //#endregion
1259
+ //#region src/js/NodePathWalker.ts
1260
+ const EMPTY_IGNORE_CALL_EXPRESSION_IDENTIFIERS = [];
1261
+ const EMPTY_IMPORT_TOKENS = /* @__PURE__ */ new Set();
1262
+ function NOOP_STRING_PATH_CALLBACK() {}
1263
+ const NEVER_MATCH_NAME = () => false;
1264
+ /**
1265
+ * 遍历我们关注的调用表达式所关联的绑定,收集后续需要转换的字符串节点。
1266
+ */
1267
+ var NodePathWalker = class {
1268
+ constructor({ ignoreCallExpressionIdentifiers, callback } = {}) {
1269
+ this.hasIgnoredCallIdentifiers = Boolean(ignoreCallExpressionIdentifiers && ignoreCallExpressionIdentifiers.length > 0);
1270
+ this.ignoreCallExpressionIdentifiers = ignoreCallExpressionIdentifiers ?? EMPTY_IGNORE_CALL_EXPRESSION_IDENTIFIERS;
1271
+ this.callback = callback ?? NOOP_STRING_PATH_CALLBACK;
1272
+ this.isIgnoredCallIdentifier = this.hasIgnoredCallIdentifiers ? createNameMatcher(this.ignoreCallExpressionIdentifiers, { exact: true }) : NEVER_MATCH_NAME;
1273
+ }
1274
+ get imports() {
1275
+ return this.importsStore ?? EMPTY_IMPORT_TOKENS;
1276
+ }
1277
+ getWritableImports() {
1278
+ if (!this.importsStore) this.importsStore = /* @__PURE__ */ new Set();
1279
+ return this.importsStore;
1280
+ }
1281
+ addImportToken(token) {
1282
+ this.getWritableImports().add(token);
1283
+ }
1284
+ getVisited() {
1285
+ if (!this.visitedStore) this.visitedStore = /* @__PURE__ */ new WeakSet();
1286
+ return this.visitedStore;
1287
+ }
1288
+ walkVariableDeclarator(path) {
1289
+ const init = path.get("init");
1290
+ this.walkNode(init);
1291
+ }
1292
+ walkTemplateLiteral(path) {
1293
+ for (const exp of path.get("expressions")) this.walkNode(exp);
1294
+ for (const quasis of path.get("quasis")) this.callback(quasis);
1295
+ }
1296
+ walkStringLiteral(path) {
1297
+ this.callback(path);
1298
+ }
1299
+ walkBinaryExpression(path) {
1300
+ const left = path.get("left");
1301
+ this.walkNode(left);
1302
+ const right = path.get("right");
1303
+ this.walkNode(right);
1304
+ }
1305
+ walkLogicalExpression(path) {
1306
+ const left = path.get("left");
1307
+ this.walkNode(left);
1308
+ const right = path.get("right");
1309
+ this.walkNode(right);
1310
+ }
1311
+ walkObjectExpression(path) {
1312
+ const props = path.get("properties");
1313
+ for (const prop of props) if (prop.isObjectProperty()) {
1314
+ const key = prop.get("key");
1315
+ this.walkNode(key);
1316
+ const value = prop.get("value");
1317
+ this.walkNode(value);
1318
+ }
1319
+ }
1320
+ walkArrayExpression(path) {
1321
+ const elements = path.get("elements");
1322
+ for (const element of elements) this.walkNode(element);
1323
+ }
1324
+ walkNode(arg) {
1325
+ const visited = this.getVisited();
1326
+ if (visited.has(arg)) return;
1327
+ visited.add(arg);
1328
+ if (arg.isIdentifier()) {
1329
+ const binding = arg?.scope?.getBinding?.(arg.node.name);
1330
+ if (binding) this.walkNode(binding.path);
1331
+ } else if (arg.isMemberExpression()) {
1332
+ const objectPath = arg.get("object");
1333
+ if (objectPath.isIdentifier()) {
1334
+ const binding = arg?.scope?.getBinding?.(objectPath.node.name);
1335
+ if (binding) {
1336
+ if (binding.path.isVariableDeclarator()) this.walkVariableDeclarator(binding.path);
1337
+ }
1338
+ }
1339
+ } else if (arg.isTemplateLiteral()) this.walkTemplateLiteral(arg);
1340
+ else if (arg.isStringLiteral()) this.walkStringLiteral(arg);
1341
+ else if (arg.isBinaryExpression()) this.walkBinaryExpression(arg);
1342
+ else if (arg.isLogicalExpression()) this.walkLogicalExpression(arg);
1343
+ else if (arg.isObjectExpression()) this.walkObjectExpression(arg);
1344
+ else if (arg.isArrayExpression()) this.walkArrayExpression(arg);
1345
+ else if (arg.isVariableDeclarator()) this.walkVariableDeclarator(arg);
1346
+ else if (maybeAddImportToken(this.getWritableImports(), arg)) {}
1347
+ }
1348
+ /**
1349
+ * Walk the arguments of a desired call expression so their bindings can be analysed.
1350
+ */
1351
+ walkCallExpression(path) {
1352
+ if (!this.hasIgnoredCallIdentifiers) return;
1353
+ const calleePath = path.get("callee");
1354
+ if (calleePath.isIdentifier() && this.isIgnoredCallIdentifier(calleePath.node.name)) for (const arg of path.get("arguments")) this.walkNode(arg);
1355
+ }
1356
+ walkExportDeclaration(path) {
1357
+ walkExportDeclaration(this, path);
1358
+ }
1359
+ walkExportNamedDeclaration(path) {
1360
+ walkExportNamedDeclaration(this, path);
1361
+ }
1362
+ walkExportDefaultDeclaration(path) {
1363
+ walkExportDefaultDeclaration(this, path);
1364
+ }
1365
+ walkExportAllDeclaration(path) {
1366
+ walkExportAllDeclaration(this, path);
1367
+ }
1368
+ };
1369
+ //#endregion
1370
+ //#region src/js/taggedTemplateIgnore.ts
1371
+ function createTaggedTemplateIgnore({ matcher, names }) {
1372
+ const bindingIgnoreCache = /* @__PURE__ */ new Map();
1373
+ const taggedTemplateIgnoreCache = /* @__PURE__ */ new WeakMap();
1374
+ const seenBindings = /* @__PURE__ */ new Set();
1375
+ let singleCanonicalIgnoreName;
1376
+ let canonicalIgnoreNames;
1377
+ for (const item of names ?? []) {
1378
+ if (typeof item !== "string") continue;
1379
+ if (singleCanonicalIgnoreName === void 0) {
1380
+ singleCanonicalIgnoreName = item;
1381
+ continue;
1382
+ }
1383
+ if (item === singleCanonicalIgnoreName) continue;
1384
+ if (!canonicalIgnoreNames) {
1385
+ canonicalIgnoreNames = new Set([singleCanonicalIgnoreName, item]);
1386
+ continue;
1387
+ }
1388
+ canonicalIgnoreNames.add(item);
1389
+ }
1390
+ const hasCanonicalIgnoreNames = singleCanonicalIgnoreName !== void 0;
1391
+ const matchesIgnoreName = (value) => {
1392
+ if (hasCanonicalIgnoreNames) {
1393
+ if (canonicalIgnoreNames) {
1394
+ if (canonicalIgnoreNames.has(value)) return true;
1395
+ } else if (value === singleCanonicalIgnoreName) return true;
1396
+ }
1397
+ return matcher(value);
1398
+ };
1399
+ const propertyMatches = (propertyPath) => {
1400
+ if (!propertyPath) return false;
1401
+ if (propertyPath.isIdentifier()) return matchesIgnoreName(propertyPath.node.name);
1402
+ if (propertyPath.isStringLiteral()) return matchesIgnoreName(propertyPath.node.value);
1403
+ return false;
1404
+ };
1405
+ const resolvesMemberExpressionToIgnore = (path, seen) => {
1406
+ if (propertyMatches(path.get("property"))) return true;
1407
+ const objectPath = path.get("object");
1408
+ if (objectPath.isIdentifier()) {
1409
+ const binding = (objectPath?.scope)?.getBinding?.(objectPath.node.name);
1410
+ if (binding) return resolvesToWeappTwIgnore(binding, seen);
1411
+ }
1412
+ return false;
1413
+ };
1414
+ const resolvesToWeappTwIgnore = (binding, seen) => {
1415
+ const cached = bindingIgnoreCache.get(binding);
1416
+ if (cached !== void 0) return cached;
1417
+ if (seen.has(binding)) return false;
1418
+ seen.add(binding);
1419
+ let result = false;
1420
+ const bindingPath = binding.path;
1421
+ if (bindingPath.isImportSpecifier()) {
1422
+ const imported = bindingPath.node.imported;
1423
+ if (imported.type === "Identifier" && matchesIgnoreName(imported.name)) result = true;
1424
+ else if (imported.type === "StringLiteral" && matchesIgnoreName(imported.value)) result = true;
1425
+ } else if (bindingPath.isVariableDeclarator()) {
1426
+ const init = bindingPath.get("init");
1427
+ if (init && init.node) {
1428
+ if (init.isIdentifier()) {
1429
+ const target = binding?.scope?.getBinding?.(init.node.name);
1430
+ if (target) result = resolvesToWeappTwIgnore(target, seen);
1431
+ } else if (init.isMemberExpression()) result = resolvesMemberExpressionToIgnore(init, seen);
1432
+ }
1433
+ }
1434
+ bindingIgnoreCache.set(binding, result);
1435
+ seen.delete(binding);
1436
+ return result;
1437
+ };
1438
+ const getEffectiveTagPath = (tagPath) => {
1439
+ let current = tagPath;
1440
+ while (true) {
1441
+ if (current.isParenthesizedExpression?.() || current.node.type === "ParenthesizedExpression") {
1442
+ current = current.get("expression");
1443
+ continue;
1444
+ }
1445
+ if (current.isTSAsExpression() || current.isTSTypeAssertion()) {
1446
+ current = current.get("expression");
1447
+ continue;
1448
+ }
1449
+ if (current.isTSNonNullExpression()) {
1450
+ current = current.get("expression");
1451
+ continue;
1452
+ }
1453
+ if (current.isTypeCastExpression?.()) {
1454
+ current = current.get("expression");
1455
+ continue;
1456
+ }
1457
+ if (current.isSequenceExpression()) {
1458
+ const last = current.get("expressions").at(-1);
1459
+ if (last) {
1460
+ current = last;
1461
+ continue;
1462
+ }
1463
+ }
1464
+ if (current.isCallExpression?.() || current.node.type === "CallExpression") {
1465
+ current = current.get("callee");
1466
+ continue;
1467
+ }
1468
+ break;
1469
+ }
1470
+ return current;
1471
+ };
1472
+ const evaluateTagPath = (tagPath, seen) => {
1473
+ if (tagPath.isCallExpression?.() || tagPath.node.type === "CallExpression") return evaluateTagPath(tagPath.get("callee"), seen);
1474
+ if (tagPath.isIdentifier()) {
1475
+ if (matchesIgnoreName(tagPath.node.name)) return true;
1476
+ const binding = tagPath?.scope?.getBinding?.(tagPath.node.name);
1477
+ if (binding) return resolvesToWeappTwIgnore(binding, seen);
1478
+ return false;
1479
+ }
1480
+ if (tagPath.isMemberExpression()) return resolvesMemberExpressionToIgnore(tagPath, seen);
1481
+ return false;
1482
+ };
1483
+ const computeIgnore = (tagPath) => {
1484
+ const cached = taggedTemplateIgnoreCache.get(tagPath.node);
1485
+ if (cached !== void 0) return cached;
1486
+ const effectiveTagPath = getEffectiveTagPath(tagPath);
1487
+ const effectiveCached = taggedTemplateIgnoreCache.get(effectiveTagPath.node);
1488
+ if (effectiveCached !== void 0) {
1489
+ taggedTemplateIgnoreCache.set(tagPath.node, effectiveCached);
1490
+ return effectiveCached;
1491
+ }
1492
+ seenBindings.clear();
1493
+ const result = evaluateTagPath(effectiveTagPath, seenBindings);
1494
+ taggedTemplateIgnoreCache.set(effectiveTagPath.node, result);
1495
+ taggedTemplateIgnoreCache.set(tagPath.node, result);
1496
+ return result;
1497
+ };
1498
+ return {
1499
+ shouldIgnore(tagPath) {
1500
+ return computeIgnore(tagPath);
1501
+ },
1502
+ getEffectiveTagPath
1503
+ };
1504
+ }
1505
+ //#endregion
1506
+ //#region src/js/babel.ts
1507
+ const EXPRESSION_WRAPPER_PREFIX = "(\n";
1508
+ const EXPRESSION_WRAPPER_SUFFIX = "\n)";
1509
+ const EMPTY_IGNORED_PATHS = /* @__PURE__ */ new WeakSet();
1510
+ const EMPTY_IMPORT_DECLARATIONS = /* @__PURE__ */ new Set();
1511
+ const EMPTY_EXPORT_DECLARATIONS = /* @__PURE__ */ new Set();
1512
+ const EMPTY_REQUIRE_CALL_PATHS = [];
1513
+ const ignoredTaggedTemplateMatcherCache = /* @__PURE__ */ new WeakMap();
1514
+ let defaultEvalHandler;
1515
+ function getIgnoredTaggedTemplateMatcher(options) {
1516
+ const cached = ignoredTaggedTemplateMatcherCache.get(options);
1517
+ if (cached) return cached;
1518
+ const created = createNameMatcher(options.ignoreTaggedTemplateExpressionIdentifiers, { exact: true });
1519
+ ignoredTaggedTemplateMatcherCache.set(options, created);
1520
+ return created;
1521
+ }
1522
+ function getDefaultEvalHandler() {
1523
+ if (!defaultEvalHandler) throw new Error("Default JS eval handler is not initialized.");
1524
+ return defaultEvalHandler;
1525
+ }
1526
+ function analyzeSource(ast, options, handler, collectModuleMetadata = true) {
1527
+ const jsTokenUpdater = new JsTokenUpdater();
1528
+ const needScope = Boolean(options.ignoreCallExpressionIdentifiers && options.ignoreCallExpressionIdentifiers.length > 0);
1529
+ const ignoredPaths = needScope ? /* @__PURE__ */ new WeakSet() : EMPTY_IGNORED_PATHS;
1530
+ const walker = needScope ? new NodePathWalker({
1531
+ ignoreCallExpressionIdentifiers: options.ignoreCallExpressionIdentifiers,
1532
+ callback(path) {
1533
+ ignoredPaths.add(path);
1534
+ }
1535
+ }) : new NodePathWalker();
1536
+ let taggedTemplateIgnore;
1537
+ const hasTaggedTemplateIgnoreIdentifiers = Boolean(options.ignoreTaggedTemplateExpressionIdentifiers && options.ignoreTaggedTemplateExpressionIdentifiers.length > 0);
1538
+ function getTaggedTemplateIgnore() {
1539
+ if (!taggedTemplateIgnore) taggedTemplateIgnore = createTaggedTemplateIgnore({
1540
+ matcher: getIgnoredTaggedTemplateMatcher(options),
1541
+ names: options.ignoreTaggedTemplateExpressionIdentifiers
1542
+ });
1543
+ return taggedTemplateIgnore;
1544
+ }
1545
+ const targetPaths = [];
1546
+ const importDeclarations = collectModuleMetadata ? /* @__PURE__ */ new Set() : EMPTY_IMPORT_DECLARATIONS;
1547
+ const exportDeclarations = collectModuleMetadata ? /* @__PURE__ */ new Set() : EMPTY_EXPORT_DECLARATIONS;
1548
+ const requireCallPaths = collectModuleMetadata ? [] : EMPTY_REQUIRE_CALL_PATHS;
1549
+ const evalHandler = handler ?? getDefaultEvalHandler();
1550
+ traverse(ast, {
1551
+ StringLiteral: { enter(p) {
1552
+ if (isEvalPath(p.parentPath)) return;
1553
+ targetPaths.push(p);
1554
+ } },
1555
+ TemplateElement: { enter: hasTaggedTemplateIgnoreIdentifiers ? (p) => {
1556
+ const pp = p.parentPath;
1557
+ if (pp.isTemplateLiteral()) {
1558
+ const ppp = pp.parentPath;
1559
+ if (isEvalPath(ppp)) return;
1560
+ if (ppp.isTaggedTemplateExpression()) {
1561
+ const tagPath = ppp.get("tag");
1562
+ if (getTaggedTemplateIgnore().shouldIgnore(tagPath)) return;
1563
+ }
1564
+ }
1565
+ targetPaths.push(p);
1566
+ } : (p) => {
1567
+ const pp = p.parentPath;
1568
+ if (pp.isTemplateLiteral()) {
1569
+ const ppp = pp.parentPath;
1570
+ if (isEvalPath(ppp)) return;
1571
+ }
1572
+ targetPaths.push(p);
1573
+ } },
1574
+ CallExpression: { enter: !collectModuleMetadata && !needScope ? (p) => {
1575
+ if (isEvalPath(p)) walkEvalExpression(p, options, jsTokenUpdater, evalHandler);
1576
+ } : (p) => {
1577
+ if (isEvalPath(p)) {
1578
+ walkEvalExpression(p, options, jsTokenUpdater, evalHandler);
1579
+ return;
1580
+ }
1581
+ const calleePath = p.get("callee");
1582
+ if (collectModuleMetadata && calleePath.isIdentifier({ name: "require" }) && !p?.scope?.hasBinding?.("require")) {
1583
+ const args = p.get("arguments");
1584
+ if (Array.isArray(args) && args.length > 0) {
1585
+ const first = args[0];
1586
+ if (first?.isStringLiteral()) requireCallPaths.push(first);
1587
+ }
1588
+ }
1589
+ if (needScope) walker.walkCallExpression(p);
1590
+ } },
1591
+ ...collectModuleMetadata ? {
1592
+ ImportDeclaration: { enter(p) {
1593
+ importDeclarations.add(p);
1594
+ } },
1595
+ ExportDeclaration: { enter(p) {
1596
+ exportDeclarations.add(p);
1597
+ } }
1598
+ } : {},
1599
+ noScope: !needScope
1600
+ });
1601
+ return {
1602
+ walker,
1603
+ jsTokenUpdater,
1604
+ ast,
1605
+ targetPaths,
1606
+ importDeclarations,
1607
+ exportDeclarations,
1608
+ requireCallPaths,
1609
+ ignoredPaths
1610
+ };
1611
+ }
1612
+ function jsHandler(rawSource, options) {
1613
+ const shouldWrapExpression = Boolean(options.wrapExpression);
1614
+ const source = shouldWrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
1615
+ let ast;
1616
+ try {
1617
+ ast = babelParse(source, options.babelParserOptions);
1618
+ } catch (error) {
1619
+ return {
1620
+ code: rawSource,
1621
+ error
1622
+ };
1623
+ }
1624
+ const needsModuleMetadata = Boolean(options.moduleSpecifierReplacements || options.moduleGraph && options.filename);
1625
+ const analysis = analyzeSource(ast, options, jsHandler, needsModuleMetadata);
1626
+ const ms = processUpdatedSource(source, options, analysis);
1627
+ if (shouldWrapExpression) {
1628
+ const start = 0;
1629
+ const end = source.length;
1630
+ const prefixLength = 2;
1631
+ const suffixLength = 2;
1632
+ ms.remove(start, start + prefixLength);
1633
+ ms.remove(end - suffixLength, end);
1634
+ }
1635
+ const result = { code: ms.toString() };
1636
+ if (options.generateMap) Object.defineProperty(result, "map", {
1637
+ configurable: true,
1638
+ enumerable: true,
1639
+ get() {
1640
+ return ms.generateMap();
1641
+ }
1642
+ });
1643
+ if (options.moduleGraph && options.filename) {
1644
+ const linked = new JsModuleGraph({
1645
+ filename: options.filename,
1646
+ source: rawSource,
1647
+ analysis,
1648
+ handlerOptions: options
1649
+ }, options.moduleGraph).build();
1650
+ if (linked) result.linked = linked;
1651
+ }
1652
+ return result;
1653
+ }
1654
+ defaultEvalHandler = jsHandler;
1655
+ Object.freeze({ wrapExpression: true });
1656
+ //#endregion
1657
+ //#region src/wxml/whitespace.ts
1658
+ const WHITESPACE_CODES = new Set([
1659
+ 9,
1660
+ 10,
1661
+ 11,
1662
+ 12,
1663
+ 13,
1664
+ 32,
1665
+ 160,
1666
+ 65279
726
1667
  ]);
727
1668
  function isWhitespace(char) {
728
- if (char.length === 0) {
729
- return false;
730
- }
731
- return WHITESPACE_CODES.has(char.charCodeAt(0));
1669
+ if (char.length === 0) return false;
1670
+ return WHITESPACE_CODES.has(char.charCodeAt(0));
732
1671
  }
733
-
734
- // src/wxml/Tokenizer.ts
1672
+ //#endregion
1673
+ //#region src/wxml/Tokenizer.ts
735
1674
  var Tokenizer = class {
736
- constructor() {
737
- this.reset();
738
- }
739
- processChar(char, index) {
740
- switch (this.state) {
741
- case 0 /* START */:
742
- if (isWhitespace(char)) {
743
- } else if (char === "{") {
744
- this.state = 2 /* OPEN_BRACE */;
745
- this.bufferStartIndex = index;
746
- this.buffer += char;
747
- this.expressionBuffer = char;
748
- this.expressionStartIndex = index;
749
- } else {
750
- this.state = 1 /* TEXT */;
751
- this.bufferStartIndex = index;
752
- this.buffer += char;
753
- }
754
- break;
755
- case 1 /* TEXT */:
756
- if (isWhitespace(char)) {
757
- this.tokens.push({ start: this.bufferStartIndex, end: index, value: this.buffer, expressions: this.expressions });
758
- this.buffer = "";
759
- this.expressions = [];
760
- this.state = 0 /* START */;
761
- } else if (char === "{") {
762
- this.buffer += char;
763
- this.expressionBuffer = char;
764
- this.expressionStartIndex = index;
765
- this.state = 2 /* OPEN_BRACE */;
766
- } else {
767
- this.buffer += char;
768
- }
769
- break;
770
- case 2 /* OPEN_BRACE */:
771
- if (char === "}") {
772
- this.buffer += char;
773
- this.expressionBuffer += char;
774
- this.state = 3 /* POTENTIAL_CLOSE */;
775
- } else {
776
- this.buffer += char;
777
- this.expressionBuffer += char;
778
- }
779
- break;
780
- case 3 /* POTENTIAL_CLOSE */:
781
- if (char === "}") {
782
- this.buffer += char;
783
- this.expressionBuffer += char;
784
- this.expressions.push({
785
- start: this.expressionStartIndex,
786
- end: index + 1,
787
- value: this.expressionBuffer
788
- });
789
- this.expressionBuffer = "";
790
- this.state = 4 /* BRACES_COMPLETE */;
791
- } else {
792
- this.buffer += char;
793
- this.expressionBuffer += char;
794
- this.state = 2 /* OPEN_BRACE */;
795
- }
796
- break;
797
- case 4 /* BRACES_COMPLETE */:
798
- if (isWhitespace(char)) {
799
- this.tokens.push({
800
- start: this.bufferStartIndex,
801
- end: index,
802
- value: this.buffer,
803
- expressions: this.expressions
804
- });
805
- this.buffer = "";
806
- this.expressions = [];
807
- this.state = 0 /* START */;
808
- } else if (char === "{") {
809
- this.expressionStartIndex = index;
810
- this.expressionBuffer = char;
811
- this.buffer += char;
812
- this.state = 2 /* OPEN_BRACE */;
813
- } else {
814
- this.buffer += char;
815
- this.state = 1 /* TEXT */;
816
- }
817
- break;
818
- default:
819
- throw new Error("Unexpected state");
820
- }
821
- }
822
- run(input) {
823
- this.reset();
824
- for (let i = 0; i < input.length; i++) {
825
- const char = input[i];
826
- this.processChar(char, i);
827
- }
828
- if (this.buffer.length > 0) {
829
- this.tokens.push({
830
- start: this.bufferStartIndex,
831
- end: input.length,
832
- value: this.buffer,
833
- expressions: this.expressions
834
- });
835
- }
836
- const tokens = this.tokens;
837
- this.reset();
838
- return tokens;
839
- }
840
- reset() {
841
- this.state = 0 /* START */;
842
- this.buffer = "";
843
- this.tokens = [];
844
- this.bufferStartIndex = 0;
845
- this.expressionBuffer = "";
846
- this.expressionStartIndex = 0;
847
- this.expressions = [];
848
- }
1675
+ constructor() {
1676
+ this.reset();
1677
+ }
1678
+ processChar(char, index) {
1679
+ switch (this.state) {
1680
+ case 0:
1681
+ if (isWhitespace(char)) {} else if (char === "{") {
1682
+ this.state = 2;
1683
+ this.bufferStartIndex = index;
1684
+ this.buffer += char;
1685
+ this.expressionBuffer = char;
1686
+ this.expressionStartIndex = index;
1687
+ } else {
1688
+ this.state = 1;
1689
+ this.bufferStartIndex = index;
1690
+ this.buffer += char;
1691
+ }
1692
+ break;
1693
+ case 1:
1694
+ if (isWhitespace(char)) {
1695
+ this.tokens.push({
1696
+ start: this.bufferStartIndex,
1697
+ end: index,
1698
+ value: this.buffer,
1699
+ expressions: this.expressions
1700
+ });
1701
+ this.buffer = "";
1702
+ this.expressions = [];
1703
+ this.state = 0;
1704
+ } else if (char === "{") {
1705
+ this.buffer += char;
1706
+ this.expressionBuffer = char;
1707
+ this.expressionStartIndex = index;
1708
+ this.state = 2;
1709
+ } else this.buffer += char;
1710
+ break;
1711
+ case 2:
1712
+ if (char === "}") {
1713
+ this.buffer += char;
1714
+ this.expressionBuffer += char;
1715
+ this.state = 3;
1716
+ } else {
1717
+ this.buffer += char;
1718
+ this.expressionBuffer += char;
1719
+ }
1720
+ break;
1721
+ case 3:
1722
+ if (char === "}") {
1723
+ this.buffer += char;
1724
+ this.expressionBuffer += char;
1725
+ this.expressions.push({
1726
+ start: this.expressionStartIndex,
1727
+ end: index + 1,
1728
+ value: this.expressionBuffer
1729
+ });
1730
+ this.expressionBuffer = "";
1731
+ this.state = 4;
1732
+ } else {
1733
+ this.buffer += char;
1734
+ this.expressionBuffer += char;
1735
+ this.state = 2;
1736
+ }
1737
+ break;
1738
+ case 4:
1739
+ if (isWhitespace(char)) {
1740
+ this.tokens.push({
1741
+ start: this.bufferStartIndex,
1742
+ end: index,
1743
+ value: this.buffer,
1744
+ expressions: this.expressions
1745
+ });
1746
+ this.buffer = "";
1747
+ this.expressions = [];
1748
+ this.state = 0;
1749
+ } else if (char === "{") {
1750
+ this.expressionStartIndex = index;
1751
+ this.expressionBuffer = char;
1752
+ this.buffer += char;
1753
+ this.state = 2;
1754
+ } else {
1755
+ this.buffer += char;
1756
+ this.state = 1;
1757
+ }
1758
+ break;
1759
+ default: throw new Error("Unexpected state");
1760
+ }
1761
+ }
1762
+ run(input) {
1763
+ this.reset();
1764
+ for (let i = 0; i < input.length; i++) {
1765
+ const char = input[i];
1766
+ this.processChar(char, i);
1767
+ }
1768
+ if (this.buffer.length > 0) this.tokens.push({
1769
+ start: this.bufferStartIndex,
1770
+ end: input.length,
1771
+ value: this.buffer,
1772
+ expressions: this.expressions
1773
+ });
1774
+ const tokens = this.tokens;
1775
+ this.reset();
1776
+ return tokens;
1777
+ }
1778
+ reset() {
1779
+ this.state = 0;
1780
+ this.buffer = "";
1781
+ this.tokens = [];
1782
+ this.bufferStartIndex = 0;
1783
+ this.expressionBuffer = "";
1784
+ this.expressionStartIndex = 0;
1785
+ this.expressions = [];
1786
+ }
849
1787
  };
850
-
851
- // src/wxml/utils/template-fragments.ts
852
- var sharedTokenizer = new Tokenizer();
853
-
854
- // src/context/logger.ts
855
- var import_logger8 = require("@weapp-tailwindcss/logger");
856
-
857
- // src/context/tailwindcss.ts
858
- var import_logger10 = require("@weapp-tailwindcss/logger");
859
-
860
- // src/context/tailwindcss/basedir.ts
861
- var import_node_module2 = require("module");
862
- var import_node_path10 = __toESM(require("path"));
863
- var import_node_process10 = __toESM(require("process"));
864
- var import_node_url2 = require("url");
865
- var import_logger9 = require("@weapp-tailwindcss/logger");
866
-
867
- // src/context/tailwindcss/rax.ts
868
- var import_node_fs6 = require("fs");
869
- var import_node_path11 = __toESM(require("path"));
870
- var import_node_process11 = __toESM(require("process"));
871
-
872
- // src/context/index.ts
1788
+ new Tokenizer();
1789
+ //#endregion
1790
+ //#region src/context/index.ts
873
1791
  async function clearTailwindcssPatcherCache(patcher, options) {
874
- if (!patcher) {
875
- return;
876
- }
877
- const cacheOptions = patcher.options?.cache;
878
- if (cacheOptions == null || typeof cacheOptions === "object" && cacheOptions.enabled === false) {
879
- return;
880
- }
881
- if (typeof patcher.clearCache === "function") {
882
- try {
883
- await patcher.clearCache({ scope: "all" });
884
- } catch (error) {
885
- import_logger11.logger.debug("failed to clear tailwindcss patcher cache via clearCache(): %O", error);
886
- }
887
- }
888
- if (!options?.removeDirectory) {
889
- return;
890
- }
891
- const cachePaths = /* @__PURE__ */ new Map();
892
- const normalizedCacheOptions = typeof cacheOptions === "object" ? cacheOptions : void 0;
893
- if (normalizedCacheOptions?.path) {
894
- cachePaths.set(normalizedCacheOptions.path, false);
895
- }
896
- const privateCachePath = patcher?.cacheStore?.options?.path;
897
- if (privateCachePath) {
898
- cachePaths.set(privateCachePath, false);
899
- }
900
- if (options?.removeDirectory && normalizedCacheOptions?.dir) {
901
- cachePaths.set(normalizedCacheOptions.dir, true);
902
- }
903
- if (!cachePaths.size) {
904
- return;
905
- }
906
- for (const [cachePath, recursive] of cachePaths.entries()) {
907
- try {
908
- await (0, import_promises2.rm)(cachePath, { force: true, recursive });
909
- } catch (error) {
910
- const err = error;
911
- if (err?.code === "ENOENT") {
912
- continue;
913
- }
914
- import_logger11.logger.debug("failed to clear tailwindcss patcher cache: %s %O", cachePath, err);
915
- }
916
- }
917
- }
918
-
919
- // src/cli/context.ts
1792
+ if (!patcher) return;
1793
+ const cacheOptions = patcher.options?.cache;
1794
+ if (cacheOptions == null || typeof cacheOptions === "object" && cacheOptions.enabled === false) return;
1795
+ if (typeof patcher.clearCache === "function") try {
1796
+ await patcher.clearCache({ scope: "all" });
1797
+ } catch (error) {
1798
+ _weapp_tailwindcss_logger.logger.debug("failed to clear tailwindcss patcher cache via clearCache(): %O", error);
1799
+ }
1800
+ if (!options?.removeDirectory) return;
1801
+ const cachePaths = /* @__PURE__ */ new Map();
1802
+ const normalizedCacheOptions = typeof cacheOptions === "object" ? cacheOptions : void 0;
1803
+ if (normalizedCacheOptions?.path) cachePaths.set(normalizedCacheOptions.path, false);
1804
+ const privateCachePath = patcher?.cacheStore?.options?.path;
1805
+ if (privateCachePath) cachePaths.set(privateCachePath, false);
1806
+ if (options?.removeDirectory && normalizedCacheOptions?.dir) cachePaths.set(normalizedCacheOptions.dir, true);
1807
+ if (!cachePaths.size) return;
1808
+ for (const [cachePath, recursive] of cachePaths.entries()) try {
1809
+ await (0, node_fs_promises.rm)(cachePath, {
1810
+ force: true,
1811
+ recursive
1812
+ });
1813
+ } catch (error) {
1814
+ const err = error;
1815
+ if (err?.code === "ENOENT") continue;
1816
+ _weapp_tailwindcss_logger.logger.debug("failed to clear tailwindcss patcher cache: %s %O", cachePath, err);
1817
+ }
1818
+ }
1819
+ //#endregion
1820
+ //#region src/cli/context.ts
920
1821
  function formatOutputPath(target, baseDir) {
921
- const root = baseDir ?? import_node_process12.default.cwd();
922
- const relative = import_node_path12.default.relative(root, target);
923
- if (!relative) {
924
- return ".";
925
- }
926
- if (relative.startsWith("..")) {
927
- return import_node_path12.default.normalize(target);
928
- }
929
- return relative.startsWith(".") ? relative : `.${import_node_path12.default.sep}${relative}`;
930
- }
931
-
932
- // src/cli/helpers.ts
933
- var import_promises3 = require("fs/promises");
934
- var import_node_process15 = __toESM(require("process"));
935
-
936
- // src/logger/index.ts
937
- var import_logger13 = require("@weapp-tailwindcss/logger");
938
-
939
- // src/cli/helpers/options/parse.ts
1822
+ const root = baseDir ?? node_process.default.cwd();
1823
+ const relative = node_path.default.relative(root, target);
1824
+ if (!relative) return ".";
1825
+ if (relative.startsWith("..")) return node_path.default.normalize(target);
1826
+ return relative.startsWith(".") ? relative : `.${node_path.default.sep}${relative}`;
1827
+ }
1828
+ //#endregion
1829
+ //#region src/cli/doctor/constants.ts
1830
+ const CONFIG_FILES = {
1831
+ tailwind: [
1832
+ "tailwind.config.js",
1833
+ "tailwind.config.cjs",
1834
+ "tailwind.config.mjs",
1835
+ "tailwind.config.ts"
1836
+ ],
1837
+ postcss: [
1838
+ "postcss.config.js",
1839
+ "postcss.config.cjs",
1840
+ "postcss.config.mjs",
1841
+ "postcss.config.ts"
1842
+ ],
1843
+ vite: [
1844
+ "vite.config.js",
1845
+ "vite.config.mjs",
1846
+ "vite.config.ts"
1847
+ ],
1848
+ webpack: [
1849
+ "webpack.config.js",
1850
+ "webpack.config.cjs",
1851
+ "webpack.config.ts"
1852
+ ]
1853
+ };
1854
+ const FRAMEWORK_DEPS = [
1855
+ ["@tarojs/taro", "Taro"],
1856
+ ["@dcloudio/uni-app", "uni-app"],
1857
+ ["@mpxjs/core", "MPX"],
1858
+ ["remax", "Remax"],
1859
+ ["rax", "Rax"]
1860
+ ];
1861
+ //#endregion
1862
+ //#region src/cli/doctor.ts
1863
+ function tryReadJson$1(file) {
1864
+ try {
1865
+ return JSON.parse((0, node_fs.readFileSync)(file, "utf8"));
1866
+ } catch {
1867
+ return;
1868
+ }
1869
+ }
1870
+ function findFirstExisting(cwd, files) {
1871
+ return files.find((file) => (0, node_fs.existsSync)(node_path.default.join(cwd, file)));
1872
+ }
1873
+ function readProjectPackageJson(cwd) {
1874
+ return tryReadJson$1(node_path.default.join(cwd, "package.json"));
1875
+ }
1876
+ function readDependencyVersion(cwd, packageName) {
1877
+ try {
1878
+ return tryReadJson$1((0, node_module.createRequire)(node_path.default.join(cwd, "package.json")).resolve(`${packageName}/package.json`))?.version;
1879
+ } catch {
1880
+ return;
1881
+ }
1882
+ }
1883
+ function collectDependencySpecs(pkg) {
1884
+ return {
1885
+ ...pkg?.dependencies ?? {},
1886
+ ...pkg?.devDependencies ?? {},
1887
+ ...pkg?.optionalDependencies ?? {},
1888
+ ...pkg?.peerDependencies ?? {}
1889
+ };
1890
+ }
1891
+ function detectPackageManager(cwd, pkg) {
1892
+ if (pkg?.packageManager) return pkg.packageManager;
1893
+ if ((0, node_fs.existsSync)(node_path.default.join(cwd, "pnpm-lock.yaml"))) return "pnpm";
1894
+ if ((0, node_fs.existsSync)(node_path.default.join(cwd, "package-lock.json"))) return "npm";
1895
+ if ((0, node_fs.existsSync)(node_path.default.join(cwd, "yarn.lock"))) return "yarn";
1896
+ }
1897
+ function detectFrameworks(deps) {
1898
+ return FRAMEWORK_DEPS.filter(([dependency]) => dependency in deps).map(([, label]) => label);
1899
+ }
1900
+ function addCheck(checks, check) {
1901
+ checks.push(check);
1902
+ }
1903
+ function summarizeChecks(checks) {
1904
+ return checks.reduce((summary, check) => {
1905
+ summary[check.status] += 1;
1906
+ return summary;
1907
+ }, {
1908
+ ok: 0,
1909
+ warn: 0,
1910
+ error: 0,
1911
+ info: 0
1912
+ });
1913
+ }
1914
+ function hasDependency(deps, packageName) {
1915
+ return packageName in deps;
1916
+ }
1917
+ function getMajorVersion(version) {
1918
+ if (!version) return;
1919
+ return semver.default.parse(version)?.major;
1920
+ }
1921
+ function getDependencyMajor(deps, packageName) {
1922
+ const spec = deps[packageName];
1923
+ return spec ? semver.default.minVersion(spec)?.major : void 0;
1924
+ }
1925
+ function createDoctorReport(options = {}) {
1926
+ const cwd = node_path.default.resolve(options.cwd ?? node_process.default.cwd());
1927
+ const nodeVersion = options.nodeVersion ?? node_process.default.versions.node;
1928
+ const pkg = readProjectPackageJson(cwd);
1929
+ const deps = collectDependencySpecs(pkg);
1930
+ const checks = [];
1931
+ const packageManager = detectPackageManager(cwd, pkg);
1932
+ const frameworks = detectFrameworks(deps);
1933
+ const tailwindcssVersion = readDependencyVersion(cwd, "tailwindcss");
1934
+ const weappTailwindcssVersion = readDependencyVersion(cwd, "weapp-tailwindcss");
1935
+ const tailwindMajor = getMajorVersion(tailwindcssVersion) ?? getDependencyMajor(deps, "tailwindcss");
1936
+ const tailwindConfig = findFirstExisting(cwd, CONFIG_FILES.tailwind);
1937
+ const postcssConfig = findFirstExisting(cwd, CONFIG_FILES.postcss);
1938
+ const viteConfig = findFirstExisting(cwd, CONFIG_FILES.vite);
1939
+ const webpackConfig = findFirstExisting(cwd, CONFIG_FILES.webpack);
1940
+ addCheck(checks, pkg ? {
1941
+ id: "package-json",
1942
+ title: "package.json",
1943
+ status: "ok",
1944
+ message: "已找到项目 package.json。"
1945
+ } : {
1946
+ id: "package-json",
1947
+ title: "package.json",
1948
+ status: "error",
1949
+ message: "当前目录没有 package.json。",
1950
+ suggestion: "请在项目根目录运行 doctor,或通过 --cwd 指向项目根目录。"
1951
+ });
1952
+ addCheck(checks, semver.default.satisfies(nodeVersion, "^20.19.0 || >=22.12.0") ? {
1953
+ id: "node-version",
1954
+ title: "Node.js",
1955
+ status: "ok",
1956
+ message: `当前 Node.js ${nodeVersion} 满足版本要求 ${WEAPP_TW_REQUIRED_NODE_VERSION_RANGE}。`
1957
+ } : {
1958
+ id: "node-version",
1959
+ title: "Node.js",
1960
+ status: "error",
1961
+ message: `当前 Node.js ${nodeVersion} 不满足版本要求 ${WEAPP_TW_REQUIRED_NODE_VERSION_RANGE}。`,
1962
+ suggestion: "请升级 Node.js 后再安装或构建 weapp-tailwindcss 项目。"
1963
+ });
1964
+ addCheck(checks, packageManager ? {
1965
+ id: "package-manager",
1966
+ title: "包管理器",
1967
+ status: packageManager.startsWith("pnpm") ? "ok" : "info",
1968
+ message: `检测到 ${packageManager}。`
1969
+ } : {
1970
+ id: "package-manager",
1971
+ title: "包管理器",
1972
+ status: "info",
1973
+ message: "未检测到 lockfile 或 packageManager 字段。"
1974
+ });
1975
+ addCheck(checks, hasDependency(deps, "weapp-tailwindcss") || Boolean(weappTailwindcssVersion) ? {
1976
+ id: "weapp-tailwindcss",
1977
+ title: "weapp-tailwindcss",
1978
+ status: "ok",
1979
+ message: `检测到 weapp-tailwindcss${weappTailwindcssVersion ? `@${weappTailwindcssVersion}` : ""}。`
1980
+ } : {
1981
+ id: "weapp-tailwindcss",
1982
+ title: "weapp-tailwindcss",
1983
+ status: "warn",
1984
+ message: "未在当前项目依赖中检测到 weapp-tailwindcss。",
1985
+ suggestion: "如果这是业务项目,请安装 weapp-tailwindcss 并确认命令运行在项目根目录。"
1986
+ });
1987
+ addCheck(checks, hasDependency(deps, "tailwindcss") || Boolean(tailwindcssVersion) ? {
1988
+ id: "tailwindcss",
1989
+ title: "Tailwind CSS",
1990
+ status: "ok",
1991
+ message: `检测到 tailwindcss${tailwindcssVersion ? `@${tailwindcssVersion}` : ""}。`
1992
+ } : {
1993
+ id: "tailwindcss",
1994
+ title: "Tailwind CSS",
1995
+ status: "error",
1996
+ message: "未检测到 tailwindcss。",
1997
+ suggestion: "请安装 tailwindcss,并确认依赖可以从当前项目解析。"
1998
+ });
1999
+ addCheck(checks, tailwindConfig ? {
2000
+ id: "tailwind-config",
2001
+ title: "Tailwind 配置",
2002
+ status: "ok",
2003
+ message: `检测到 ${tailwindConfig}。`
2004
+ } : {
2005
+ id: "tailwind-config",
2006
+ title: "Tailwind 配置",
2007
+ status: tailwindMajor === 4 ? "info" : "warn",
2008
+ message: "未检测到 tailwind.config.*。",
2009
+ suggestion: tailwindMajor === 4 ? "Tailwind CSS v4 可以采用 CSS-first 配置;如果使用 v3 或复杂 content/source,请补充配置文件。" : "请确认 Tailwind content/source 配置能够覆盖小程序页面、组件和脚本文件。"
2010
+ });
2011
+ addCheck(checks, postcssConfig ? {
2012
+ id: "postcss-config",
2013
+ title: "PostCSS 配置",
2014
+ status: "ok",
2015
+ message: `检测到 ${postcssConfig}。`
2016
+ } : {
2017
+ id: "postcss-config",
2018
+ title: "PostCSS 配置",
2019
+ status: viteConfig ? "info" : "warn",
2020
+ message: "未检测到 postcss.config.*。",
2021
+ suggestion: "如果通过 PostCSS 接入,请补充 postcss.config.*;如果通过 Vite/Taro 插件接入,可忽略此项。"
2022
+ });
2023
+ if (tailwindMajor === 4 && postcssConfig && !hasDependency(deps, "@tailwindcss/postcss")) addCheck(checks, {
2024
+ id: "tailwindcss-v4-postcss",
2025
+ title: "Tailwind v4 PostCSS",
2026
+ status: "warn",
2027
+ message: "Tailwind CSS v4 项目存在 PostCSS 配置,但未检测到 @tailwindcss/postcss。",
2028
+ suggestion: "如果 PostCSS 配置中仍直接使用 tailwindcss,请迁移到 @tailwindcss/postcss。"
2029
+ });
2030
+ addCheck(checks, frameworks.length > 0 ? {
2031
+ id: "framework",
2032
+ title: "框架识别",
2033
+ status: "ok",
2034
+ message: `检测到 ${frameworks.join(", ")}。`
2035
+ } : {
2036
+ id: "framework",
2037
+ title: "框架识别",
2038
+ status: "info",
2039
+ message: "未从依赖中识别出 Taro、uni-app、MPX、Remax 或 Rax。"
2040
+ });
2041
+ addCheck(checks, viteConfig || webpackConfig ? {
2042
+ id: "bundler-config",
2043
+ title: "构建器配置",
2044
+ status: "ok",
2045
+ message: `检测到 ${[viteConfig, webpackConfig].filter(Boolean).join(", ")}。`
2046
+ } : {
2047
+ id: "bundler-config",
2048
+ title: "构建器配置",
2049
+ status: "info",
2050
+ message: "未检测到 vite.config.* 或 webpack.config.*。"
2051
+ });
2052
+ return {
2053
+ cwd,
2054
+ nodeVersion,
2055
+ detected: {
2056
+ packageManager,
2057
+ frameworks,
2058
+ tailwindcssVersion,
2059
+ weappTailwindcssVersion
2060
+ },
2061
+ summary: summarizeChecks(checks),
2062
+ checks
2063
+ };
2064
+ }
2065
+ function hasDoctorFailure(report, strict = false) {
2066
+ return report.summary.error > 0 || strict && report.summary.warn > 0;
2067
+ }
2068
+ function formatDoctorReport(report) {
2069
+ const lines = [
2070
+ `weapp-tailwindcss doctor`,
2071
+ `cwd: ${report.cwd}`,
2072
+ `summary: ${report.summary.error} error, ${report.summary.warn} warn, ${report.summary.ok} ok, ${report.summary.info} info`,
2073
+ ""
2074
+ ];
2075
+ for (const check of report.checks) {
2076
+ lines.push(`[${check.status}] ${check.title}: ${check.message}`);
2077
+ if (check.suggestion) lines.push(` -> ${check.suggestion}`);
2078
+ }
2079
+ return lines.join("\n");
2080
+ }
2081
+ //#endregion
2082
+ //#region src/cli/helpers/options/parse.ts
940
2083
  function readStringOption(flag, value) {
941
- if (value == null) {
942
- return void 0;
943
- }
944
- if (typeof value !== "string") {
945
- throw new TypeError(`Option "--${flag}" expects a string value.`);
946
- }
947
- const trimmed = value.trim();
948
- if (trimmed.length === 0) {
949
- throw new TypeError(`Option "--${flag}" expects a non-empty value.`);
950
- }
951
- return trimmed;
2084
+ if (value == null) return;
2085
+ if (typeof value !== "string") throw new TypeError(`Option "--${flag}" expects a string value.`);
2086
+ const trimmed = value.trim();
2087
+ if (trimmed.length === 0) throw new TypeError(`Option "--${flag}" expects a non-empty value.`);
2088
+ return trimmed;
952
2089
  }
953
2090
  function readStringArrayOption(flag, value) {
954
- if (value == null) {
955
- return void 0;
956
- }
957
- if (Array.isArray(value)) {
958
- const normalized2 = value.filter((entry) => entry != null).map((entry) => {
959
- if (typeof entry !== "string") {
960
- throw new TypeError(`Option "--${flag}" expects string values.`);
961
- }
962
- const trimmed = entry.trim();
963
- if (!trimmed) {
964
- throw new TypeError(`Option "--${flag}" expects non-empty values.`);
965
- }
966
- return trimmed;
967
- });
968
- return normalized2.length > 0 ? normalized2 : void 0;
969
- }
970
- const normalized = readStringOption(flag, value);
971
- return normalized ? [normalized] : void 0;
2091
+ if (value == null) return;
2092
+ if (Array.isArray(value)) {
2093
+ const normalized = value.filter((entry) => entry != null).map((entry) => {
2094
+ if (typeof entry !== "string") throw new TypeError(`Option "--${flag}" expects string values.`);
2095
+ const trimmed = entry.trim();
2096
+ if (!trimmed) throw new TypeError(`Option "--${flag}" expects non-empty values.`);
2097
+ return trimmed;
2098
+ });
2099
+ return normalized.length > 0 ? normalized : void 0;
2100
+ }
2101
+ const normalized = readStringOption(flag, value);
2102
+ return normalized ? [normalized] : void 0;
972
2103
  }
973
2104
  function toBoolean(value, fallback) {
974
- if (typeof value === "boolean") {
975
- return value;
976
- }
977
- if (typeof value === "string") {
978
- if (value === "true") {
979
- return true;
980
- }
981
- if (value === "false") {
982
- return false;
983
- }
984
- }
985
- if (value == null) {
986
- return fallback;
987
- }
988
- return Boolean(value);
989
- }
990
-
991
- // src/cli/helpers/options/resolve.ts
992
- var import_node_path13 = __toESM(require("path"));
993
- var import_node_process13 = __toESM(require("process"));
2105
+ if (typeof value === "boolean") return value;
2106
+ if (typeof value === "string") {
2107
+ if (value === "true") return true;
2108
+ if (value === "false") return false;
2109
+ }
2110
+ if (value == null) return fallback;
2111
+ return Boolean(value);
2112
+ }
2113
+ //#endregion
2114
+ //#region src/cli/helpers/options/resolve.ts
994
2115
  function resolveCliCwd(value) {
995
- const raw = readStringOption("cwd", value);
996
- if (!raw) {
997
- return void 0;
998
- }
999
- return import_node_path13.default.isAbsolute(raw) ? import_node_path13.default.normalize(raw) : import_node_path13.default.resolve(import_node_process13.default.cwd(), raw);
1000
- }
1001
-
1002
- // src/cli/helpers/patch-cwd.ts
1003
- var import_node_path14 = __toESM(require("path"));
1004
- var import_node_process14 = __toESM(require("process"));
1005
-
1006
- // src/tailwindcss/index.ts
1007
- var import_local_pkg = require("local-pkg");
2116
+ const raw = readStringOption("cwd", value);
2117
+ if (!raw) return;
2118
+ return node_path.default.isAbsolute(raw) ? node_path.default.normalize(raw) : node_path.default.resolve(node_process.default.cwd(), raw);
2119
+ }
2120
+ //#endregion
2121
+ //#region src/tailwindcss/index.ts
1008
2122
  function getTailwindcssPackageInfo(options) {
1009
- return (0, import_local_pkg.getPackageInfoSync)("tailwindcss", options);
2123
+ return (0, local_pkg.getPackageInfoSync)("tailwindcss", options);
1010
2124
  }
1011
-
1012
- // src/cli/helpers/patch-cwd.ts
2125
+ //#endregion
2126
+ //#region src/cli/helpers/patch-cwd.ts
2127
+ /**
2128
+ * Resolve default working directory for `weapp-tw patch`.
2129
+ * Prefer explicit env overrides to avoid cross-package INIT_CWD pollution.
2130
+ */
1013
2131
  function normalizeCandidatePath(baseDir, candidate) {
1014
- if (!candidate) {
1015
- return void 0;
1016
- }
1017
- return import_node_path14.default.isAbsolute(candidate) ? import_node_path14.default.normalize(candidate) : import_node_path14.default.resolve(baseDir, candidate);
2132
+ if (!candidate) return;
2133
+ return node_path.default.isAbsolute(candidate) ? node_path.default.normalize(candidate) : node_path.default.resolve(baseDir, candidate);
1018
2134
  }
1019
2135
  function detectTailwindWorkspace(paths) {
1020
- for (const candidate of paths) {
1021
- try {
1022
- const info = getTailwindcssPackageInfo({ paths: [candidate] });
1023
- if (info?.rootPath) {
1024
- return candidate;
1025
- }
1026
- } catch {
1027
- }
1028
- }
1029
- return void 0;
1030
- }
1031
- function resolvePatchDefaultCwd(currentCwd = import_node_process14.default.cwd()) {
1032
- const baseDir = import_node_path14.default.normalize(currentCwd);
1033
- const explicitCwd = normalizeCandidatePath(baseDir, import_node_process14.default.env.WEAPP_TW_PATCH_CWD);
1034
- if (explicitCwd) {
1035
- return explicitCwd;
1036
- }
1037
- const workspaceRoot = findWorkspaceRoot(baseDir);
1038
- const initCwd = normalizeCandidatePath(baseDir, import_node_process14.default.env.INIT_CWD);
1039
- const localPrefix = normalizeCandidatePath(baseDir, import_node_process14.default.env.npm_config_local_prefix);
1040
- const candidates = [
1041
- baseDir,
1042
- workspaceRoot,
1043
- initCwd,
1044
- localPrefix
1045
- ].filter(Boolean);
1046
- const detected = detectTailwindWorkspace([...new Set(candidates)]);
1047
- if (detected) {
1048
- return detected;
1049
- }
1050
- return initCwd ?? localPrefix ?? workspaceRoot ?? baseDir;
1051
- }
1052
-
1053
- // src/cli/helpers.ts
2136
+ for (const candidate of paths) try {
2137
+ if (getTailwindcssPackageInfo({ paths: [candidate] })?.rootPath) return candidate;
2138
+ } catch {}
2139
+ }
2140
+ function resolvePatchDefaultCwd(currentCwd = node_process.default.cwd()) {
2141
+ const baseDir = node_path.default.normalize(currentCwd);
2142
+ const explicitCwd = normalizeCandidatePath(baseDir, node_process.default.env.WEAPP_TW_PATCH_CWD);
2143
+ if (explicitCwd) return explicitCwd;
2144
+ const workspaceRoot = findWorkspaceRoot(baseDir);
2145
+ const initCwd = normalizeCandidatePath(baseDir, node_process.default.env.INIT_CWD);
2146
+ const localPrefix = normalizeCandidatePath(baseDir, node_process.default.env.npm_config_local_prefix);
2147
+ const candidates = [
2148
+ baseDir,
2149
+ workspaceRoot,
2150
+ initCwd,
2151
+ localPrefix
2152
+ ].filter(Boolean);
2153
+ const detected = detectTailwindWorkspace([...new Set(candidates)]);
2154
+ if (detected) return detected;
2155
+ return initCwd ?? localPrefix ?? workspaceRoot ?? baseDir;
2156
+ }
2157
+ //#endregion
2158
+ //#region src/cli/helpers.ts
1054
2159
  async function ensureDir(dir) {
1055
- await (0, import_promises3.mkdir)(dir, { recursive: true });
2160
+ await (0, node_fs_promises.mkdir)(dir, { recursive: true });
1056
2161
  }
1057
- function handleCliError(error) {
1058
- if (error instanceof Error) {
1059
- import_logger13.logger.error(error.message);
1060
- if (error.stack && import_node_process15.default.env.WEAPP_TW_DEBUG === "1") {
1061
- import_logger13.logger.error(error.stack);
1062
- }
1063
- } else {
1064
- import_logger13.logger.error(String(error));
1065
- }
2162
+ function handleCliError$1(error) {
2163
+ if (error instanceof Error) {
2164
+ _weapp_tailwindcss_logger.logger.error(error.message);
2165
+ if (error.stack && node_process.default.env.WEAPP_TW_DEBUG === "1") _weapp_tailwindcss_logger.logger.error(error.stack);
2166
+ } else _weapp_tailwindcss_logger.logger.error(String(error));
1066
2167
  }
1067
2168
  function commandAction(handler) {
1068
- return async (...args) => {
1069
- try {
1070
- await handler(...args);
1071
- } catch (error) {
1072
- handleCliError(error);
1073
- import_node_process15.default.exitCode = 1;
1074
- }
1075
- };
1076
- }
1077
-
1078
- // src/cli/mount-options.ts
1079
- var import_node_process17 = __toESM(require("process"));
1080
-
1081
- // src/cli/mount-options/patch-status.ts
2169
+ return async (...args) => {
2170
+ try {
2171
+ await handler(...args);
2172
+ } catch (error) {
2173
+ handleCliError$1(error);
2174
+ node_process.default.exitCode = 1;
2175
+ }
2176
+ };
2177
+ }
2178
+ //#endregion
2179
+ //#region src/cli/mount-options/patch-status.ts
1082
2180
  function formatStatusFilesHint(files) {
1083
- if (!files?.length) {
1084
- return "";
1085
- }
1086
- return ` (${files.join(", ")})`;
2181
+ if (!files?.length) return "";
2182
+ return ` (${files.join(", ")})`;
1087
2183
  }
1088
2184
  function logPatchStatusReport(report) {
1089
- const applied = report.entries.filter((entry) => entry.status === "applied");
1090
- const pending = report.entries.filter((entry) => entry.status === "not-applied");
1091
- const skipped = report.entries.filter(
1092
- (entry) => entry.status === "skipped" || entry.status === "unsupported"
1093
- );
1094
- const packageLabel = `${report.package.name ?? "tailwindcss"}@${report.package.version ?? "unknown"}`;
1095
- import_logger13.logger.info(`Patch status for ${packageLabel} (v${report.majorVersion})`);
1096
- if (applied.length) {
1097
- import_logger13.logger.success("Applied:");
1098
- applied.forEach((entry) => {
1099
- import_logger13.logger.success(` - ${entry.name}${formatStatusFilesHint(entry.files)}`);
1100
- });
1101
- }
1102
- if (pending.length) {
1103
- import_logger13.logger.warn("Needs attention:");
1104
- pending.forEach((entry) => {
1105
- const details = entry.reason ? ` - ${entry.reason}` : "";
1106
- import_logger13.logger.warn(` - ${entry.name}${formatStatusFilesHint(entry.files)}${details}`);
1107
- });
1108
- } else {
1109
- import_logger13.logger.success("All applicable patches are applied.");
1110
- }
1111
- if (skipped.length) {
1112
- import_logger13.logger.info("Skipped:");
1113
- skipped.forEach((entry) => {
1114
- const details = entry.reason ? ` - ${entry.reason}` : "";
1115
- import_logger13.logger.info(` - ${entry.name}${details}`);
1116
- });
1117
- }
1118
- }
1119
-
1120
- // src/cli/patch-options.ts
1121
- var DEFAULT_EXTEND_LENGTH_UNITS_FEATURE = {
1122
- enabled: true,
1123
- units: ["rpx"],
1124
- overwrite: true
2185
+ const applied = report.entries.filter((entry) => entry.status === "applied");
2186
+ const pending = report.entries.filter((entry) => entry.status === "not-applied");
2187
+ const skipped = report.entries.filter((entry) => entry.status === "skipped" || entry.status === "unsupported");
2188
+ const packageLabel = `${report.package.name ?? "tailwindcss"}@${report.package.version ?? "unknown"}`;
2189
+ _weapp_tailwindcss_logger.logger.info(`Patch status for ${packageLabel} (v${report.majorVersion})`);
2190
+ if (applied.length) {
2191
+ _weapp_tailwindcss_logger.logger.success("Applied:");
2192
+ applied.forEach((entry) => {
2193
+ _weapp_tailwindcss_logger.logger.success(` - ${entry.name}${formatStatusFilesHint(entry.files)}`);
2194
+ });
2195
+ }
2196
+ if (pending.length) {
2197
+ _weapp_tailwindcss_logger.logger.warn("Needs attention:");
2198
+ pending.forEach((entry) => {
2199
+ const details = entry.reason ? ` - ${entry.reason}` : "";
2200
+ _weapp_tailwindcss_logger.logger.warn(` - ${entry.name}${formatStatusFilesHint(entry.files)}${details}`);
2201
+ });
2202
+ } else _weapp_tailwindcss_logger.logger.success("All applicable patches are applied.");
2203
+ if (skipped.length) {
2204
+ _weapp_tailwindcss_logger.logger.info("Skipped:");
2205
+ skipped.forEach((entry) => {
2206
+ const details = entry.reason ? ` - ${entry.reason}` : "";
2207
+ _weapp_tailwindcss_logger.logger.info(` - ${entry.name}${details}`);
2208
+ });
2209
+ }
2210
+ }
2211
+ //#endregion
2212
+ //#region src/cli/patch-options.ts
2213
+ const DEFAULT_EXTEND_LENGTH_UNITS_FEATURE = {
2214
+ enabled: true,
2215
+ units: ["rpx"],
2216
+ overwrite: true
1125
2217
  };
1126
2218
  function withDefaultExtendLengthUnits(options) {
1127
- const normalized = options ?? {};
1128
- const extendLengthUnits = normalized.apply?.extendLengthUnits;
1129
- if (extendLengthUnits == null) {
1130
- return {
1131
- ...normalized,
1132
- apply: {
1133
- ...normalized.apply ?? {},
1134
- extendLengthUnits: DEFAULT_EXTEND_LENGTH_UNITS_FEATURE
1135
- }
1136
- };
1137
- }
1138
- return normalized;
2219
+ const normalized = options ?? {};
2220
+ if (normalized.apply?.extendLengthUnits == null) return {
2221
+ ...normalized,
2222
+ apply: {
2223
+ ...normalized.apply ?? {},
2224
+ extendLengthUnits: DEFAULT_EXTEND_LENGTH_UNITS_FEATURE
2225
+ }
2226
+ };
2227
+ return normalized;
1139
2228
  }
1140
2229
  function buildExtendLengthUnitsOverride(options) {
1141
- const extendLengthUnits = options?.apply?.extendLengthUnits;
1142
- if (extendLengthUnits == null) {
1143
- return {
1144
- apply: {
1145
- ...options?.apply ?? {},
1146
- extendLengthUnits: DEFAULT_EXTEND_LENGTH_UNITS_FEATURE
1147
- }
1148
- };
1149
- }
1150
- return void 0;
1151
- }
1152
-
1153
- // src/cli/workspace.ts
1154
- var import_node_path19 = __toESM(require("path"));
1155
- var import_node_process16 = __toESM(require("process"));
1156
-
1157
- // src/cli/workspace/package-dirs.ts
1158
- var import_node_fs10 = require("fs");
1159
- var import_node_path17 = __toESM(require("path"));
1160
- var import_fast_glob = __toESM(require("fast-glob"));
1161
-
1162
- // src/cli/workspace/workspace-globs.ts
1163
- var import_node_fs8 = require("fs");
1164
- var import_node_path15 = __toESM(require("path"));
1165
- var import_yaml = require("yaml");
1166
-
1167
- // src/cli/workspace/workspace-io.ts
1168
- var import_node_fs7 = require("fs");
2230
+ if (options?.apply?.extendLengthUnits == null) return { apply: {
2231
+ ...options?.apply ?? {},
2232
+ extendLengthUnits: DEFAULT_EXTEND_LENGTH_UNITS_FEATURE
2233
+ } };
2234
+ }
2235
+ //#endregion
2236
+ //#region src/cli/workspace/workspace-io.ts
1169
2237
  function tryReadJson(file) {
1170
- try {
1171
- const content = (0, import_node_fs7.readFileSync)(file, "utf8");
1172
- return JSON.parse(content);
1173
- } catch {
1174
- return void 0;
1175
- }
1176
- }
1177
-
1178
- // src/cli/workspace/workspace-globs.ts
2238
+ try {
2239
+ const content = (0, node_fs.readFileSync)(file, "utf8");
2240
+ return JSON.parse(content);
2241
+ } catch {
2242
+ return;
2243
+ }
2244
+ }
2245
+ //#endregion
2246
+ //#region src/cli/workspace/workspace-globs.ts
1179
2247
  function parseWorkspaceGlobsFromPackageJson(workspaceRoot) {
1180
- const pkgJsonPath = import_node_path15.default.join(workspaceRoot, "package.json");
1181
- const pkg = tryReadJson(pkgJsonPath);
1182
- if (!pkg?.workspaces) {
1183
- return [];
1184
- }
1185
- if (Array.isArray(pkg.workspaces)) {
1186
- return pkg.workspaces.filter(Boolean);
1187
- }
1188
- if (Array.isArray(pkg.workspaces.packages)) {
1189
- return pkg.workspaces.packages.filter(Boolean);
1190
- }
1191
- return [];
2248
+ const pkg = tryReadJson(node_path.default.join(workspaceRoot, "package.json"));
2249
+ if (!pkg?.workspaces) return [];
2250
+ if (Array.isArray(pkg.workspaces)) return pkg.workspaces.filter(Boolean);
2251
+ if (Array.isArray(pkg.workspaces.packages)) return pkg.workspaces.packages.filter(Boolean);
2252
+ return [];
1192
2253
  }
1193
2254
  function parseWorkspaceGlobsFromWorkspaceFile(workspaceRoot) {
1194
- const workspaceFile = import_node_path15.default.join(workspaceRoot, "pnpm-workspace.yaml");
1195
- if (!(0, import_node_fs8.existsSync)(workspaceFile)) {
1196
- return [];
1197
- }
1198
- try {
1199
- const parsed = (0, import_yaml.parse)((0, import_node_fs8.readFileSync)(workspaceFile, "utf8"));
1200
- return Array.isArray(parsed?.packages) ? parsed.packages.filter(Boolean) : [];
1201
- } catch {
1202
- return [];
1203
- }
1204
- }
1205
-
1206
- // src/cli/workspace/workspace-lock.ts
1207
- var import_node_fs9 = require("fs");
1208
- var import_node_path16 = __toESM(require("path"));
1209
- var import_yaml2 = require("yaml");
2255
+ const workspaceFile = node_path.default.join(workspaceRoot, "pnpm-workspace.yaml");
2256
+ if (!(0, node_fs.existsSync)(workspaceFile)) return [];
2257
+ try {
2258
+ const parsed = (0, yaml.parse)((0, node_fs.readFileSync)(workspaceFile, "utf8"));
2259
+ return Array.isArray(parsed?.packages) ? parsed.packages.filter(Boolean) : [];
2260
+ } catch {
2261
+ return [];
2262
+ }
2263
+ }
2264
+ //#endregion
2265
+ //#region src/cli/workspace/workspace-lock.ts
1210
2266
  function parseImportersFromLock(workspaceRoot) {
1211
- const lockPath = import_node_path16.default.join(workspaceRoot, "pnpm-lock.yaml");
1212
- if (!(0, import_node_fs9.existsSync)(lockPath)) {
1213
- return [];
1214
- }
1215
- try {
1216
- const parsed = (0, import_yaml2.parse)((0, import_node_fs9.readFileSync)(lockPath, "utf8"));
1217
- const importers = parsed?.importers;
1218
- if (!importers) {
1219
- return [];
1220
- }
1221
- return Object.keys(importers).map((key) => {
1222
- if (!key || key === ".") {
1223
- return workspaceRoot;
1224
- }
1225
- return import_node_path16.default.join(workspaceRoot, key);
1226
- });
1227
- } catch {
1228
- return [];
1229
- }
1230
- }
1231
-
1232
- // src/cli/workspace/package-dirs.ts
1233
- var BACKSLASH_RE = /\\/g;
1234
- var TRAILING_SLASH_RE = /\/+$/;
2267
+ const lockPath = node_path.default.join(workspaceRoot, "pnpm-lock.yaml");
2268
+ if (!(0, node_fs.existsSync)(lockPath)) return [];
2269
+ try {
2270
+ const importers = (0, yaml.parse)((0, node_fs.readFileSync)(lockPath, "utf8"))?.importers;
2271
+ if (!importers) return [];
2272
+ return Object.keys(importers).map((key) => {
2273
+ if (!key || key === ".") return workspaceRoot;
2274
+ return node_path.default.join(workspaceRoot, key);
2275
+ });
2276
+ } catch {
2277
+ return [];
2278
+ }
2279
+ }
2280
+ //#endregion
2281
+ //#region src/cli/workspace/package-dirs.ts
2282
+ const BACKSLASH_RE$1 = /\\/g;
2283
+ const TRAILING_SLASH_RE = /\/+$/;
1235
2284
  async function resolveWorkspacePackageDirs(workspaceRoot) {
1236
- const dirs = /* @__PURE__ */ new Set();
1237
- for (const importerDir of parseImportersFromLock(workspaceRoot)) {
1238
- dirs.add(import_node_path17.default.normalize(importerDir));
1239
- }
1240
- if (!dirs.size) {
1241
- let globs = parseWorkspaceGlobsFromWorkspaceFile(workspaceRoot);
1242
- if (!globs.length) {
1243
- globs = parseWorkspaceGlobsFromPackageJson(workspaceRoot);
1244
- }
1245
- if (globs.length > 0) {
1246
- const patterns = globs.map((pattern) => {
1247
- const normalized = pattern.replace(BACKSLASH_RE, "/").replace(TRAILING_SLASH_RE, "");
1248
- return normalized.endsWith("package.json") ? normalized : `${normalized}/package.json`;
1249
- });
1250
- const packageJsonFiles = await (0, import_fast_glob.default)(patterns, {
1251
- cwd: workspaceRoot,
1252
- absolute: true,
1253
- onlyFiles: true,
1254
- unique: true,
1255
- ignore: ["**/node_modules/**", "**/.git/**"]
1256
- });
1257
- for (const file of packageJsonFiles) {
1258
- dirs.add(import_node_path17.default.normalize(import_node_path17.default.dirname(file)));
1259
- }
1260
- }
1261
- }
1262
- const rootPkg = import_node_path17.default.join(workspaceRoot, "package.json");
1263
- if ((0, import_node_fs10.existsSync)(rootPkg)) {
1264
- dirs.add(import_node_path17.default.normalize(workspaceRoot));
1265
- }
1266
- return [...dirs];
1267
- }
1268
-
1269
- // src/cli/workspace/patch-package.ts
1270
- var import_tailwindcss_patch2 = require("tailwindcss-patch");
1271
-
1272
- // src/cli/workspace/patch-utils.ts
1273
- var import_node_path18 = __toESM(require("path"));
2285
+ const dirs = /* @__PURE__ */ new Set();
2286
+ for (const importerDir of parseImportersFromLock(workspaceRoot)) dirs.add(node_path.default.normalize(importerDir));
2287
+ if (!dirs.size) {
2288
+ let globs = parseWorkspaceGlobsFromWorkspaceFile(workspaceRoot);
2289
+ if (!globs.length) globs = parseWorkspaceGlobsFromPackageJson(workspaceRoot);
2290
+ if (globs.length > 0) {
2291
+ const packageJsonFiles = await (0, fast_glob.default)(globs.map((pattern) => {
2292
+ const normalized = pattern.replace(BACKSLASH_RE$1, "/").replace(TRAILING_SLASH_RE, "");
2293
+ return normalized.endsWith("package.json") ? normalized : `${normalized}/package.json`;
2294
+ }), {
2295
+ cwd: workspaceRoot,
2296
+ absolute: true,
2297
+ onlyFiles: true,
2298
+ unique: true,
2299
+ ignore: ["**/node_modules/**", "**/.git/**"]
2300
+ });
2301
+ for (const file of packageJsonFiles) dirs.add(node_path.default.normalize(node_path.default.dirname(file)));
2302
+ }
2303
+ }
2304
+ if ((0, node_fs.existsSync)(node_path.default.join(workspaceRoot, "package.json"))) dirs.add(node_path.default.normalize(workspaceRoot));
2305
+ return [...dirs];
2306
+ }
2307
+ //#endregion
2308
+ //#region src/cli/workspace/patch-utils.ts
1274
2309
  function formatDisplayName(workspaceRoot, dir, name) {
1275
- const relative = import_node_path18.default.relative(workspaceRoot, dir) || ".";
1276
- return name ? `${name} (${relative})` : relative;
2310
+ const relative = node_path.default.relative(workspaceRoot, dir) || ".";
2311
+ return name ? `${name} (${relative})` : relative;
1277
2312
  }
1278
2313
  function summarizeWorkspaceResults(results) {
1279
- const patched = results.filter((result) => result.status === "patched").length;
1280
- const skipped = results.filter((result) => result.status === "skipped").length;
1281
- const failed = results.filter((result) => result.status === "failed").length;
1282
- import_logger13.logger.info("[workspace] \u6C47\u603B\uFF1A\u5DF2\u8865\u4E01 %d\uFF0C\u8DF3\u8FC7 %d\uFF0C\u5931\u8D25 %d", patched, skipped, failed);
2314
+ const patched = results.filter((result) => result.status === "patched").length;
2315
+ const skipped = results.filter((result) => result.status === "skipped").length;
2316
+ const failed = results.filter((result) => result.status === "failed").length;
2317
+ _weapp_tailwindcss_logger.logger.info("[workspace] 汇总:已补丁 %d,跳过 %d,失败 %d", patched, skipped, failed);
1283
2318
  }
1284
-
1285
- // src/cli/workspace/patch-package.ts
2319
+ //#endregion
2320
+ //#region src/cli/workspace/patch-package.ts
1286
2321
  function createWorkspacePatcher(cwd) {
1287
- const normalized = (0, import_tailwindcss_patch2.normalizeOptions)(
1288
- withDefaultExtendLengthUnits({
1289
- projectRoot: cwd
1290
- })
1291
- );
1292
- return new import_tailwindcss_patch2.TailwindcssPatcher(normalized);
2322
+ return new tailwindcss_patch.TailwindcssPatcher((0, tailwindcss_patch.normalizeOptions)(withDefaultExtendLengthUnits({ projectRoot: cwd })));
1293
2323
  }
1294
2324
  async function patchWorkspacePackage(workspaceRoot, dir, pkgName, options) {
1295
- const displayName = formatDisplayName(workspaceRoot, dir, pkgName);
1296
- const tailwindInfo = getTailwindcssPackageInfo({ paths: [dir] });
1297
- if (!tailwindInfo?.rootPath) {
1298
- import_logger13.logger.info("[workspace] \u8DF3\u8FC7 %s\uFF08tailwindcss \u672A\u5B89\u88C5\uFF09\u3002", displayName);
1299
- return {
1300
- dir,
1301
- name: pkgName,
1302
- status: "skipped",
1303
- message: "tailwindcss \u672A\u5B89\u88C5\uFF0C\u5DF2\u8DF3\u8FC7\u3002"
1304
- };
1305
- }
1306
- try {
1307
- const patcher = createWorkspacePatcher(dir);
1308
- if (options.clearCache) {
1309
- await clearTailwindcssPatcherCache(patcher, { removeDirectory: true });
1310
- }
1311
- const recorder = createPatchTargetRecorder(dir, patcher, {
1312
- source: "cli",
1313
- cwd: dir,
1314
- recordTarget: options.recordTarget !== false,
1315
- alwaysRecord: true
1316
- });
1317
- if (recorder?.message) {
1318
- import_logger13.logger.info("[workspace] %s %s", displayName, recorder.message);
1319
- }
1320
- logTailwindcssTarget("cli", patcher, dir);
1321
- await patcher.patch();
1322
- if (recorder?.onPatched) {
1323
- await recorder.onPatched();
1324
- }
1325
- import_logger13.logger.success("[workspace] \u5DF2\u8865\u4E01 %s", displayName);
1326
- return {
1327
- dir,
1328
- name: pkgName,
1329
- status: "patched",
1330
- message: "\u5DF2\u5B8C\u6210 patch\u3002"
1331
- };
1332
- } catch (error) {
1333
- const reason = error instanceof Error ? error.message : String(error);
1334
- const suggestion = `\u8BF7\u5728 ${dir} \u8FD0\u884C "weapp-tw patch --cwd ${dir}".`;
1335
- const message = `${reason}\uFF0C${suggestion}`;
1336
- import_logger13.logger.error("[workspace] \u8865\u4E01\u5931\u8D25 %s\uFF1A%s", displayName, message);
1337
- return {
1338
- dir,
1339
- name: pkgName,
1340
- status: "failed",
1341
- message
1342
- };
1343
- }
1344
- }
1345
-
1346
- // src/cli/workspace.ts
2325
+ const displayName = formatDisplayName(workspaceRoot, dir, pkgName);
2326
+ if (!getTailwindcssPackageInfo({ paths: [dir] })?.rootPath) {
2327
+ _weapp_tailwindcss_logger.logger.info("[workspace] 跳过 %s(tailwindcss 未安装)。", displayName);
2328
+ return {
2329
+ dir,
2330
+ name: pkgName,
2331
+ status: "skipped",
2332
+ message: "tailwindcss 未安装,已跳过。"
2333
+ };
2334
+ }
2335
+ try {
2336
+ const patcher = createWorkspacePatcher(dir);
2337
+ if (options.clearCache) await clearTailwindcssPatcherCache(patcher, { removeDirectory: true });
2338
+ const recorder = createPatchTargetRecorder(dir, patcher, {
2339
+ source: "cli",
2340
+ cwd: dir,
2341
+ recordTarget: options.recordTarget !== false,
2342
+ alwaysRecord: true
2343
+ });
2344
+ if (recorder?.message) _weapp_tailwindcss_logger.logger.info("[workspace] %s %s", displayName, recorder.message);
2345
+ logTailwindcssTarget("cli", patcher, dir);
2346
+ await patcher.patch();
2347
+ if (recorder?.onPatched) await recorder.onPatched();
2348
+ _weapp_tailwindcss_logger.logger.success("[workspace] 已补丁 %s", displayName);
2349
+ return {
2350
+ dir,
2351
+ name: pkgName,
2352
+ status: "patched",
2353
+ message: "已完成 patch。"
2354
+ };
2355
+ } catch (error) {
2356
+ const message = `${error instanceof Error ? error.message : String(error)},${`请在 ${dir} 运行 "weapp-tw patch --cwd ${dir}".`}`;
2357
+ _weapp_tailwindcss_logger.logger.error("[workspace] 补丁失败 %s:%s", displayName, message);
2358
+ return {
2359
+ dir,
2360
+ name: pkgName,
2361
+ status: "failed",
2362
+ message
2363
+ };
2364
+ }
2365
+ }
2366
+ //#endregion
2367
+ //#region src/cli/workspace.ts
1347
2368
  async function patchWorkspace(options) {
1348
- const cwd = options.cwd ?? import_node_process16.default.cwd();
1349
- const workspaceRoot = findWorkspaceRoot(cwd) ?? cwd;
1350
- const packageDirs = await resolveWorkspacePackageDirs(workspaceRoot);
1351
- if (packageDirs.length === 0) {
1352
- import_logger13.logger.warn("\u672A\u5728 %s \u68C0\u6D4B\u5230 workspace \u5305\uFF0C\u5DF2\u8DF3\u8FC7\u6279\u91CF patch\u3002", workspaceRoot);
1353
- return;
1354
- }
1355
- const results = [];
1356
- for (const dir of packageDirs) {
1357
- const pkgJsonPath = import_node_path19.default.join(dir, "package.json");
1358
- const pkgJson = tryReadJson(pkgJsonPath);
1359
- results.push(await patchWorkspacePackage(workspaceRoot, dir, pkgJson?.name, options));
1360
- }
1361
- summarizeWorkspaceResults(results);
1362
- }
1363
-
1364
- // src/cli/mount-options.ts
1365
- function handleCliError2(error) {
1366
- if (error instanceof Error) {
1367
- import_logger13.logger.error(error.message);
1368
- if (error.stack && import_node_process17.default.env.WEAPP_TW_DEBUG === "1") {
1369
- import_logger13.logger.error(error.stack);
1370
- }
1371
- } else {
1372
- import_logger13.logger.error(String(error));
1373
- }
2369
+ const cwd = options.cwd ?? node_process.default.cwd();
2370
+ const workspaceRoot = findWorkspaceRoot(cwd) ?? cwd;
2371
+ const packageDirs = await resolveWorkspacePackageDirs(workspaceRoot);
2372
+ if (packageDirs.length === 0) {
2373
+ _weapp_tailwindcss_logger.logger.warn("未在 %s 检测到 workspace 包,已跳过批量 patch", workspaceRoot);
2374
+ return;
2375
+ }
2376
+ const results = [];
2377
+ for (const dir of packageDirs) {
2378
+ const pkgJson = tryReadJson(node_path.default.join(dir, "package.json"));
2379
+ results.push(await patchWorkspacePackage(workspaceRoot, dir, pkgJson?.name, options));
2380
+ }
2381
+ summarizeWorkspaceResults(results);
2382
+ }
2383
+ //#endregion
2384
+ //#region src/cli/mount-options.ts
2385
+ function handleCliError(error) {
2386
+ if (error instanceof Error) {
2387
+ _weapp_tailwindcss_logger.logger.error(error.message);
2388
+ if (error.stack && node_process.default.env.WEAPP_TW_DEBUG === "1") _weapp_tailwindcss_logger.logger.error(error.stack);
2389
+ } else _weapp_tailwindcss_logger.logger.error(String(error));
1374
2390
  }
1375
2391
  function withCommandErrorHandling(handler) {
1376
- return (async (ctx, next) => {
1377
- try {
1378
- return await handler(ctx, next);
1379
- } catch (error) {
1380
- handleCliError2(error);
1381
- import_node_process17.default.exitCode = 1;
1382
- return void 0;
1383
- }
1384
- });
2392
+ return (async (ctx, next) => {
2393
+ try {
2394
+ return await handler(ctx, next);
2395
+ } catch (error) {
2396
+ handleCliError(error);
2397
+ node_process.default.exitCode = 1;
2398
+ return;
2399
+ }
2400
+ });
1385
2401
  }
1386
2402
  async function createPatcherWithDefaultExtendLengthUnits(ctx) {
1387
- const patchOptions = await ctx.loadPatchOptions();
1388
- const extendLengthUnitsOverride = buildExtendLengthUnitsOverride(patchOptions);
1389
- if (extendLengthUnitsOverride) {
1390
- return ctx.createPatcher(extendLengthUnitsOverride);
1391
- }
1392
- return ctx.createPatcher();
1393
- }
1394
- var mountOptions = {
1395
- commandOptions: {
1396
- install: {
1397
- name: "patch",
1398
- aliases: ["install"],
1399
- appendDefaultOptions: false,
1400
- optionDefs: [
1401
- {
1402
- flags: "--cwd <dir>",
1403
- description: "Working directory",
1404
- config: { default: resolvePatchDefaultCwd() }
1405
- },
1406
- {
1407
- flags: "--record-target",
1408
- description: 'Write tailwindcss target metadata (node_modules/.cache/weapp-tailwindcss/tailwindcss-target.json). Pass "--record-target false" to skip.',
1409
- config: { default: true }
1410
- },
1411
- {
1412
- flags: "--clear-cache",
1413
- description: "Clear tailwindcss-patch cache before patch (opt-in)"
1414
- },
1415
- {
1416
- flags: "--workspace",
1417
- description: "Scan pnpm workspace packages and patch each Tailwind CSS dependency"
1418
- }
1419
- ]
1420
- },
1421
- status: {
1422
- appendDefaultOptions: false,
1423
- optionDefs: [
1424
- {
1425
- flags: "--cwd <dir>",
1426
- description: "Working directory",
1427
- config: { default: resolvePatchDefaultCwd() }
1428
- },
1429
- {
1430
- flags: "--json",
1431
- description: "Print a JSON report of patch status"
1432
- }
1433
- ]
1434
- }
1435
- },
1436
- commandHandlers: {
1437
- install: withCommandErrorHandling(async (ctx) => {
1438
- const shouldClearCache = toBoolean(ctx.args.clearCache, false);
1439
- const shouldRecordTarget = toBoolean(ctx.args.recordTarget, true);
1440
- const runWorkspace = toBoolean(ctx.args.workspace, false);
1441
- if (runWorkspace) {
1442
- await patchWorkspace({
1443
- cwd: ctx.cwd,
1444
- clearCache: shouldClearCache,
1445
- recordTarget: shouldRecordTarget
1446
- });
1447
- return;
1448
- }
1449
- const patcher = await createPatcherWithDefaultExtendLengthUnits(ctx);
1450
- if (shouldClearCache) {
1451
- await clearTailwindcssPatcherCache(patcher, { removeDirectory: true });
1452
- }
1453
- const recorder = createPatchTargetRecorder(ctx.cwd, patcher, {
1454
- source: "cli",
1455
- cwd: ctx.cwd,
1456
- recordTarget: shouldRecordTarget,
1457
- alwaysRecord: true
1458
- });
1459
- if (recorder?.message) {
1460
- import_logger13.logger.info(recorder.message);
1461
- }
1462
- logTailwindcssTarget("cli", patcher, ctx.cwd);
1463
- await patcher.patch();
1464
- if (recorder?.onPatched) {
1465
- const recordPath = await recorder.onPatched();
1466
- if (recordPath) {
1467
- import_logger13.logger.info(`\u8BB0\u5F55 weapp-tw patch \u76EE\u6807 -> ${formatOutputPath(recordPath, ctx.cwd)}`);
1468
- }
1469
- }
1470
- import_logger13.logger.success("Tailwind CSS \u8FD0\u884C\u65F6\u8865\u4E01\u5DF2\u5B8C\u6210\u3002");
1471
- }),
1472
- extract: withCommandErrorHandling(async (_ctx, next) => next()),
1473
- tokens: withCommandErrorHandling(async (_ctx, next) => next()),
1474
- init: withCommandErrorHandling(async (_ctx, next) => next()),
1475
- status: withCommandErrorHandling(async (ctx) => {
1476
- const patcher = await createPatcherWithDefaultExtendLengthUnits(ctx);
1477
- const report = await patcher.getPatchStatus();
1478
- if (ctx.args.json) {
1479
- import_logger13.logger.log(JSON.stringify(report, null, 2));
1480
- return report;
1481
- }
1482
- logPatchStatusReport(report);
1483
- return report;
1484
- })
1485
- }
2403
+ const extendLengthUnitsOverride = buildExtendLengthUnitsOverride(await ctx.loadPatchOptions());
2404
+ if (extendLengthUnitsOverride) return ctx.createPatcher(extendLengthUnitsOverride);
2405
+ return ctx.createPatcher();
2406
+ }
2407
+ const mountOptions = {
2408
+ commandOptions: {
2409
+ install: {
2410
+ name: "patch",
2411
+ aliases: ["install"],
2412
+ appendDefaultOptions: false,
2413
+ optionDefs: [
2414
+ {
2415
+ flags: "--cwd <dir>",
2416
+ description: "Working directory",
2417
+ config: { default: resolvePatchDefaultCwd() }
2418
+ },
2419
+ {
2420
+ flags: "--record-target",
2421
+ description: "Write tailwindcss target metadata (node_modules/.cache/weapp-tailwindcss/tailwindcss-target.json). Pass \"--record-target false\" to skip.",
2422
+ config: { default: true }
2423
+ },
2424
+ {
2425
+ flags: "--clear-cache",
2426
+ description: "Clear tailwindcss-patch cache before patch (opt-in)"
2427
+ },
2428
+ {
2429
+ flags: "--workspace",
2430
+ description: "Scan pnpm workspace packages and patch each Tailwind CSS dependency"
2431
+ }
2432
+ ]
2433
+ },
2434
+ status: {
2435
+ appendDefaultOptions: false,
2436
+ optionDefs: [{
2437
+ flags: "--cwd <dir>",
2438
+ description: "Working directory",
2439
+ config: { default: resolvePatchDefaultCwd() }
2440
+ }, {
2441
+ flags: "--json",
2442
+ description: "Print a JSON report of patch status"
2443
+ }]
2444
+ }
2445
+ },
2446
+ commandHandlers: {
2447
+ install: withCommandErrorHandling(async (ctx) => {
2448
+ const shouldClearCache = toBoolean(ctx.args.clearCache, false);
2449
+ const shouldRecordTarget = toBoolean(ctx.args.recordTarget, true);
2450
+ if (toBoolean(ctx.args.workspace, false)) {
2451
+ await patchWorkspace({
2452
+ cwd: ctx.cwd,
2453
+ clearCache: shouldClearCache,
2454
+ recordTarget: shouldRecordTarget
2455
+ });
2456
+ return;
2457
+ }
2458
+ const patcher = await createPatcherWithDefaultExtendLengthUnits(ctx);
2459
+ if (shouldClearCache) await clearTailwindcssPatcherCache(patcher, { removeDirectory: true });
2460
+ const recorder = createPatchTargetRecorder(ctx.cwd, patcher, {
2461
+ source: "cli",
2462
+ cwd: ctx.cwd,
2463
+ recordTarget: shouldRecordTarget,
2464
+ alwaysRecord: true
2465
+ });
2466
+ if (recorder?.message) _weapp_tailwindcss_logger.logger.info(recorder.message);
2467
+ logTailwindcssTarget("cli", patcher, ctx.cwd);
2468
+ await patcher.patch();
2469
+ if (recorder?.onPatched) {
2470
+ const recordPath = await recorder.onPatched();
2471
+ if (recordPath) _weapp_tailwindcss_logger.logger.info(`记录 weapp-tw patch 目标 -> ${formatOutputPath(recordPath, ctx.cwd)}`);
2472
+ }
2473
+ _weapp_tailwindcss_logger.logger.success("Tailwind CSS 运行时补丁已完成。");
2474
+ }),
2475
+ extract: withCommandErrorHandling(async (_ctx, next) => next()),
2476
+ tokens: withCommandErrorHandling(async (_ctx, next) => next()),
2477
+ init: withCommandErrorHandling(async (_ctx, next) => next()),
2478
+ status: withCommandErrorHandling(async (ctx) => {
2479
+ const report = await (await createPatcherWithDefaultExtendLengthUnits(ctx)).getPatchStatus();
2480
+ if (ctx.args.json) {
2481
+ _weapp_tailwindcss_logger.logger.log(JSON.stringify(report, null, 2));
2482
+ return report;
2483
+ }
2484
+ logPatchStatusReport(report);
2485
+ return report;
2486
+ })
2487
+ }
1486
2488
  };
1487
-
1488
- // src/cli/vscode-entry.ts
1489
- var import_node_fs11 = require("fs");
1490
- var import_promises4 = require("fs/promises");
1491
- var import_node_path20 = __toESM(require("path"));
1492
- var DEFAULT_VSCODE_ENTRY_OUTPUT = ".vscode/weapp-tailwindcss.intellisense.css";
1493
- var DEFAULT_VSCODE_SOURCES = [
1494
- 'not "./dist"',
1495
- 'not "./unpackage"',
1496
- "./src/**/*.{wxml,axml,swan,qml,ttml,ux,uts}",
1497
- "./src/**/*.{js,jsx,ts,tsx}",
1498
- "./src/**/*.{vue,svelte,html,md,mdx}"
2489
+ //#endregion
2490
+ //#region src/cli/vscode-entry.ts
2491
+ const DEFAULT_VSCODE_ENTRY_OUTPUT = ".vscode/weapp-tailwindcss.intellisense.css";
2492
+ const DEFAULT_VSCODE_SOURCES = [
2493
+ "not \"./dist\"",
2494
+ "not \"./unpackage\"",
2495
+ "./src/**/*.{wxml,axml,swan,qml,ttml,ux,uts}",
2496
+ "./src/**/*.{js,jsx,ts,tsx,mjs,cjs,wxs,sjs}",
2497
+ "./src/**/*.{vue,svelte,mpx,html,md,mdx}"
1499
2498
  ];
1500
- var SINGLE_QUOTE = "'";
1501
- var DOUBLE_QUOTE = '"';
1502
- var BACKSLASH_RE2 = /\\/g;
2499
+ const SINGLE_QUOTE = "'";
2500
+ const DOUBLE_QUOTE = "\"";
2501
+ const BACKSLASH_RE = /\\/g;
1503
2502
  function toPosixPath(filepath) {
1504
- return filepath.replace(BACKSLASH_RE2, "/");
2503
+ return filepath.replace(BACKSLASH_RE, "/");
1505
2504
  }
1506
2505
  async function assertFileExists(filepath) {
1507
- try {
1508
- await (0, import_promises4.access)(filepath, import_node_fs11.constants.F_OK);
1509
- } catch (error) {
1510
- const err = error;
1511
- if (err?.code === "ENOENT") {
1512
- throw new Error(`CSS entry file not found: ${filepath}`);
1513
- }
1514
- throw err;
1515
- }
2506
+ try {
2507
+ await (0, node_fs_promises.access)(filepath, node_fs.constants.F_OK);
2508
+ } catch (error) {
2509
+ const err = error;
2510
+ if (err?.code === "ENOENT") throw new Error(`CSS entry file not found: ${filepath}`);
2511
+ throw err;
2512
+ }
1516
2513
  }
1517
2514
  async function assertCanWrite(filepath, force) {
1518
- try {
1519
- await (0, import_promises4.access)(filepath, import_node_fs11.constants.F_OK);
1520
- if (!force) {
1521
- throw new Error(
1522
- `VS Code helper already exists at ${filepath}. Re-run with --force to overwrite it.`
1523
- );
1524
- }
1525
- } catch (error) {
1526
- const err = error;
1527
- if (err?.code === "ENOENT") {
1528
- return;
1529
- }
1530
- throw err;
1531
- }
2515
+ try {
2516
+ await (0, node_fs_promises.access)(filepath, node_fs.constants.F_OK);
2517
+ if (!force) throw new Error(`VS Code helper already exists at ${filepath}. Re-run with --force to overwrite it.`);
2518
+ } catch (error) {
2519
+ const err = error;
2520
+ if (err?.code === "ENOENT") return;
2521
+ throw err;
2522
+ }
1532
2523
  }
1533
2524
  function toCssLiteral(value) {
1534
- const normalized = toPosixPath(value);
1535
- return JSON.stringify(normalized);
2525
+ const normalized = toPosixPath(value);
2526
+ return JSON.stringify(normalized);
1536
2527
  }
1537
2528
  function formatSource(pattern) {
1538
- const trimmed = pattern.trim();
1539
- if (!trimmed) {
1540
- return null;
1541
- }
1542
- if (trimmed.startsWith("@source ")) {
1543
- return trimmed.endsWith(";") ? trimmed : `${trimmed};`;
1544
- }
1545
- let body = trimmed;
1546
- let keyword = "";
1547
- if (body.startsWith("not ")) {
1548
- keyword = "not ";
1549
- body = body.slice(4).trim();
1550
- } else if (body.startsWith("!")) {
1551
- keyword = "not ";
1552
- body = body.slice(1).trim();
1553
- }
1554
- if (!body) {
1555
- throw new Error("Invalid @source pattern: empty body.");
1556
- }
1557
- if (!body.startsWith(SINGLE_QUOTE) && !body.startsWith(DOUBLE_QUOTE)) {
1558
- body = toCssLiteral(body);
1559
- }
1560
- return `@source ${keyword}${body};`;
2529
+ const trimmed = pattern.trim();
2530
+ if (!trimmed) return null;
2531
+ if (trimmed.startsWith("@source ")) return trimmed.endsWith(";") ? trimmed : `${trimmed};`;
2532
+ let body = trimmed;
2533
+ let keyword = "";
2534
+ if (body.startsWith("not ")) {
2535
+ keyword = "not ";
2536
+ body = body.slice(4).trim();
2537
+ } else if (body.startsWith("!")) {
2538
+ keyword = "not ";
2539
+ body = body.slice(1).trim();
2540
+ }
2541
+ if (!body) throw new Error("Invalid @source pattern: empty body.");
2542
+ if (!body.startsWith(SINGLE_QUOTE) && !body.startsWith(DOUBLE_QUOTE)) body = toCssLiteral(body);
2543
+ return `@source ${keyword}${body};`;
1561
2544
  }
1562
2545
  function resolveOutputPath(baseDir, output) {
1563
- const target = output ?? DEFAULT_VSCODE_ENTRY_OUTPUT;
1564
- return import_node_path20.default.isAbsolute(target) ? import_node_path20.default.normalize(target) : import_node_path20.default.resolve(baseDir, target);
2546
+ const target = output ?? ".vscode/weapp-tailwindcss.intellisense.css";
2547
+ return node_path.default.isAbsolute(target) ? node_path.default.normalize(target) : node_path.default.resolve(baseDir, target);
1565
2548
  }
1566
2549
  function resolveCssEntry(baseDir, entry) {
1567
- return import_node_path20.default.isAbsolute(entry) ? import_node_path20.default.normalize(entry) : import_node_path20.default.resolve(baseDir, entry);
2550
+ return node_path.default.isAbsolute(entry) ? node_path.default.normalize(entry) : node_path.default.resolve(baseDir, entry);
1568
2551
  }
1569
2552
  function toRelativeImport(fromFile, targetFile) {
1570
- const fromDir = import_node_path20.default.dirname(fromFile);
1571
- let relative = import_node_path20.default.relative(fromDir, targetFile);
1572
- if (!relative) {
1573
- relative = import_node_path20.default.basename(targetFile);
1574
- }
1575
- if (!relative.startsWith(".")) {
1576
- relative = `./${relative}`;
1577
- }
1578
- return toPosixPath(relative);
2553
+ const fromDir = node_path.default.dirname(fromFile);
2554
+ let relative = node_path.default.relative(fromDir, targetFile);
2555
+ if (!relative) relative = node_path.default.basename(targetFile);
2556
+ if (!relative.startsWith(".")) relative = `./${relative}`;
2557
+ return toPosixPath(relative);
1579
2558
  }
1580
2559
  async function generateVscodeIntellisenseEntry(options) {
1581
- const baseDir = options.baseDir;
1582
- const cssEntryPath = resolveCssEntry(baseDir, options.cssEntry);
1583
- await assertFileExists(cssEntryPath);
1584
- const outputPath = resolveOutputPath(baseDir, options.output);
1585
- await ensureDir(import_node_path20.default.dirname(outputPath));
1586
- await assertCanWrite(outputPath, options.force);
1587
- const sources = options.sources && options.sources.length > 0 ? options.sources : DEFAULT_VSCODE_SOURCES;
1588
- const formattedSources = sources.map(formatSource).filter((statement) => Boolean(statement));
1589
- const cssImport = toRelativeImport(outputPath, cssEntryPath);
1590
- const separator = formattedSources.length > 0 ? [""] : [];
1591
- const content = [
1592
- "/*",
1593
- " * Auto-generated by weapp-tailwindcss.",
1594
- " * This file exists solely to activate Tailwind CSS IntelliSense in VS Code.",
1595
- " * Do not import it in your actual mini-program bundles.",
1596
- " */",
1597
- "@import 'tailwindcss';",
1598
- "",
1599
- ...formattedSources,
1600
- ...separator,
1601
- `@import '${cssImport}';`,
1602
- ""
1603
- ].filter((line, idx, arr) => !(line === "" && arr[idx - 1] === "")).join("\n");
1604
- await (0, import_promises4.writeFile)(outputPath, `${content}
1605
- `, "utf8");
1606
- return { outputPath, cssEntryPath };
1607
- }
1608
-
1609
- // src/cli.ts
1610
- import_node_process18.default.title = "node (weapp-tailwindcss)";
1611
- if (import_semver.default.lt(import_node_process18.default.versions.node, WEAPP_TW_REQUIRED_NODE_VERSION)) {
1612
- import_logger13.logger.warn(
1613
- `You are using Node.js ${import_node_process18.default.versions.node}. For weapp-tailwindcss, Node.js version >= v${WEAPP_TW_REQUIRED_NODE_VERSION} is required.`
1614
- );
1615
- }
1616
- var cli = (0, import_tailwindcss_patch3.createTailwindcssPatchCli)({
1617
- name: "weapp-tailwindcss",
1618
- mountOptions
2560
+ const baseDir = options.baseDir;
2561
+ const cssEntryPath = resolveCssEntry(baseDir, options.cssEntry);
2562
+ await assertFileExists(cssEntryPath);
2563
+ const outputPath = resolveOutputPath(baseDir, options.output);
2564
+ await ensureDir(node_path.default.dirname(outputPath));
2565
+ await assertCanWrite(outputPath, options.force);
2566
+ const formattedSources = (options.sources && options.sources.length > 0 ? options.sources : DEFAULT_VSCODE_SOURCES).map(formatSource).filter((statement) => Boolean(statement));
2567
+ const cssImport = toRelativeImport(outputPath, cssEntryPath);
2568
+ const separator = formattedSources.length > 0 ? [""] : [];
2569
+ await (0, node_fs_promises.writeFile)(outputPath, `${[
2570
+ "/*",
2571
+ " * Auto-generated by weapp-tailwindcss.",
2572
+ " * This file exists solely to activate Tailwind CSS IntelliSense in VS Code.",
2573
+ " * Do not import it in your actual mini-program bundles.",
2574
+ " */",
2575
+ "@import 'tailwindcss';",
2576
+ "",
2577
+ ...formattedSources,
2578
+ ...separator,
2579
+ `@import '${cssImport}';`,
2580
+ ""
2581
+ ].filter((line, idx, arr) => !(line === "" && arr[idx - 1] === "")).join("\n")}\n`, "utf8");
2582
+ return {
2583
+ outputPath,
2584
+ cssEntryPath
2585
+ };
2586
+ }
2587
+ //#endregion
2588
+ //#region src/cli.ts
2589
+ node_process.default.title = "node (weapp-tailwindcss)";
2590
+ if (!semver.default.satisfies(node_process.default.versions.node, "^20.19.0 || >=22.12.0")) _weapp_tailwindcss_logger.logger.warn(`You are using Node.js ${node_process.default.versions.node}. For weapp-tailwindcss, Node.js version ${WEAPP_TW_REQUIRED_NODE_VERSION_RANGE} is required.`);
2591
+ const cli = (0, tailwindcss_patch.createTailwindcssPatchCli)({
2592
+ name: "weapp-tailwindcss",
2593
+ mountOptions
1619
2594
  });
1620
- cli.command("vscode-entry", "Generate a VS Code helper CSS for Tailwind IntelliSense").option("--cwd <dir>", "Working directory").option("--css <file>", "Path to the CSS file that imports weapp-tailwindcss (required)").option("--output <file>", `Helper output path. Defaults to ${DEFAULT_VSCODE_ENTRY_OUTPUT}`).option("--source <pattern>", "Additional @source glob (can be repeated)").option("--force", "Overwrite the helper file when it already exists").action(
1621
- commandAction(async (options) => {
1622
- const resolvedCwd = resolveCliCwd(options.cwd);
1623
- const baseDir = resolvedCwd ?? import_node_process18.default.cwd();
1624
- const cssEntry = readStringOption("css", options.css);
1625
- if (!cssEntry) {
1626
- throw new Error('Option "--css" is required.');
1627
- }
1628
- const output = readStringOption("output", options.output);
1629
- const sources = readStringArrayOption("source", options.source);
1630
- const force = toBoolean(options.force, false);
1631
- const result = await generateVscodeIntellisenseEntry({
1632
- baseDir,
1633
- cssEntry,
1634
- output,
1635
- sources,
1636
- force
1637
- });
1638
- import_logger13.logger.success(
1639
- `VS Code helper generated -> ${formatOutputPath(result.outputPath, resolvedCwd)}`
1640
- );
1641
- })
1642
- );
2595
+ cli.command("vscode-entry", "Generate a VS Code helper CSS for Tailwind IntelliSense").option("--cwd <dir>", "Working directory").option("--css <file>", "Path to the CSS file that imports weapp-tailwindcss (required)").option("--output <file>", `Helper output path. Defaults to ${DEFAULT_VSCODE_ENTRY_OUTPUT}`).option("--source <pattern>", "Additional @source glob (can be repeated)").option("--force", "Overwrite the helper file when it already exists").action(commandAction(async (options) => {
2596
+ const resolvedCwd = resolveCliCwd(options.cwd);
2597
+ const baseDir = resolvedCwd ?? node_process.default.cwd();
2598
+ const cssEntry = readStringOption("css", options.css);
2599
+ if (!cssEntry) throw new Error("Option \"--css\" is required.");
2600
+ const result = await generateVscodeIntellisenseEntry({
2601
+ baseDir,
2602
+ cssEntry,
2603
+ output: readStringOption("output", options.output),
2604
+ sources: readStringArrayOption("source", options.source),
2605
+ force: toBoolean(options.force, false)
2606
+ });
2607
+ _weapp_tailwindcss_logger.logger.success(`VS Code helper generated -> ${formatOutputPath(result.outputPath, resolvedCwd)}`);
2608
+ }));
2609
+ cli.command("doctor", "Check project setup for weapp-tailwindcss").option("--cwd <dir>", "Working directory").option("--json", "Print a JSON report").option("--strict", "Exit with code 1 when warnings are found").action(commandAction(async (options) => {
2610
+ const report = createDoctorReport({ cwd: resolveCliCwd(options.cwd) });
2611
+ if (toBoolean(options.json, false)) _weapp_tailwindcss_logger.logger.log(JSON.stringify(report, null, 2));
2612
+ else _weapp_tailwindcss_logger.logger.log(formatDoctorReport(report));
2613
+ if (hasDoctorFailure(report, toBoolean(options.strict, false))) node_process.default.exitCode = 1;
2614
+ }));
1643
2615
  cli.help();
1644
- cli.version(import_node_process18.default.env.npm_package_version ?? "0.0.0");
2616
+ cli.version(node_process.default.env.npm_package_version ?? "0.0.0");
1645
2617
  cli.parse();
2618
+ //#endregion