weapp-tailwindcss 5.0.0-next.24 → 5.0.0-next.26

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