weapp-tailwindcss 5.0.0-next.8 → 5.0.0

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