weapp-tailwindcss 5.4.2 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +13 -1
  2. package/README.zh-CN.md +13 -1
  3. package/dist/bundlers/shared/v4-generation-core.d.ts +1 -0
  4. package/dist/bundlers/vite/capability-profile.d.ts +1 -0
  5. package/dist/bundlers/vite/css-finalizer/web-plugin.d.ts +3 -0
  6. package/dist/bundlers/vite/css-handler-options.d.ts +32 -0
  7. package/dist/bundlers/vite/{generate-bundle/css-output.d.ts → css-output.d.ts} +1 -1
  8. package/dist/bundlers/vite/frameworks/generic/web.d.ts +2 -0
  9. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +2 -32
  10. package/dist/bundlers/vite/generate-bundle/finalize/root-import-shell.d.ts +1 -1
  11. package/dist/bundlers/vite/generate-bundle/remembered-css-replay.d.ts +2 -2
  12. package/dist/bundlers/vite/generate-bundle/runtime.d.ts +1 -1
  13. package/dist/bundlers/vite/generate-bundle/uni-app-x-postprocess.d.ts +1 -1
  14. package/dist/bundlers/vite/generate-bundle.d.ts +1 -1
  15. package/dist/bundlers/vite/runtime-class-set.d.ts +1 -5
  16. package/dist/bundlers/vite/shared/create-css-only-plugins-runtime.d.ts +3 -0
  17. package/dist/cache-CBJFB1HN.cjs +223 -0
  18. package/dist/compiler/events.d.ts +32 -0
  19. package/dist/compiler/host.d.ts +13 -0
  20. package/dist/compiler/index.d.ts +3 -0
  21. package/dist/compiler/runtime-state.d.ts +17 -0
  22. package/dist/compiler-B0YSc0DY.js +4877 -0
  23. package/dist/{wxml-o-CUulAM.cjs → compiler-SwMb3lOX.cjs} +3649 -283
  24. package/dist/core.cjs +6 -3
  25. package/dist/core.d.ts +2 -0
  26. package/dist/core.js +4 -4
  27. package/dist/defaults-B5ep0ojb.js +120 -0
  28. package/dist/defaults-BI9j1znS.cjs +156 -0
  29. package/dist/defaults.cjs +5 -121
  30. package/dist/defaults.js +1 -116
  31. package/dist/final-css-cleanup-BMlUDzik.cjs +112 -0
  32. package/dist/final-css-cleanup-CmVYbXPr.js +282 -0
  33. package/dist/{generator-WlhrtNa3.cjs → generator-DsrQ9txU.cjs} +62 -5
  34. package/dist/{generator-BjK5PRR-.js → generator-DyXTBPmE.js} +47 -2
  35. package/dist/generator.cjs +1 -1
  36. package/dist/generator.js +1 -1
  37. package/dist/{gulp-D6LcfRz_.js → gulp-CVUiPXPy.js} +7 -7
  38. package/dist/{gulp-ChecVI6A.cjs → gulp-Dtc01FdI.cjs} +30 -28
  39. package/dist/gulp.cjs +1 -1
  40. package/dist/gulp.js +1 -1
  41. package/dist/{hmr-timing-afnWvy7u.cjs → hmr-timing-3SdRVfZx.cjs} +6 -229
  42. package/dist/{hmr-timing-CqDfjvqE.js → hmr-timing-DNxQm-bN.js} +6 -1258
  43. package/dist/index.cjs +4 -4
  44. package/dist/index.js +4 -4
  45. package/dist/{pipeline-helpers-DxPFMGxz.cjs → pipeline-helpers-DVrgv1HS.cjs} +6 -5
  46. package/dist/postcss.cjs +1 -1
  47. package/dist/postcss.js +1 -1
  48. package/dist/presets.cjs +4 -4
  49. package/dist/presets.js +2 -2
  50. package/dist/rspack.cjs +2 -2
  51. package/dist/rspack.js +2 -2
  52. package/dist/runtime-state-BBQcA0n5.cjs +54 -0
  53. package/dist/{source-candidate-scan-signature-FywFU3Rg.cjs → scoped-generator-B7thnzzm.cjs} +5 -123
  54. package/dist/{source-candidate-scan-signature-BVScymyM.js → scoped-generator-kRj_5Axx.js} +4 -92
  55. package/dist/source-candidate-scan-signature-B7cUxqqX.cjs +129 -0
  56. package/dist/source-candidate-scan-signature-CsP4BQNa.js +92 -0
  57. package/dist/style-injector/internal.d.ts +1 -1
  58. package/dist/style-injector/vite-web.d.ts +3 -0
  59. package/dist/{tailwindcss-9xmoCkaR.js → tailwindcss-BK9S7zuq.js} +1 -2
  60. package/dist/{tailwindcss-D3jltF7M.cjs → tailwindcss-C-jBBQfw.cjs} +8 -9
  61. package/dist/{transform-DQhgAarN.js → transform-C0rWZblB.js} +3 -3
  62. package/dist/{transform-C6k9zTQR.cjs → transform-C7QxW-fV.cjs} +27 -27
  63. package/dist/{v4-generation-core-CPKNwzjz.cjs → v4-generation-core-DuIVZvRz.cjs} +29 -1172
  64. package/dist/vite/web.cjs +27 -0
  65. package/dist/vite/web.d.ts +1 -0
  66. package/dist/vite/web.js +25 -0
  67. package/dist/{vite-D3aCtpmv.js → vite-0PsttwuR.js} +241 -3581
  68. package/dist/{vite-D-gmOkPN.cjs → vite-CJbO-7AQ.cjs} +494 -3794
  69. package/dist/vite-web.d.ts +4 -0
  70. package/dist/vite.cjs +1 -1
  71. package/dist/vite.js +1 -1
  72. package/dist/weapp-tw-css-generation-loader.cjs +1 -1
  73. package/dist/weapp-tw-css-import-rewrite-loader.cjs +5 -5
  74. package/dist/web-BFOkkJ-8.cjs +4357 -0
  75. package/dist/web-D8HSs56R.js +3792 -0
  76. package/dist/{webpack-yAne9ZYu.cjs → webpack-BWknqSDV.cjs} +51 -49
  77. package/dist/{webpack-B-6a8Z8F.js → webpack-DVtKeBq1.js} +13 -12
  78. package/dist/webpack.cjs +1 -1
  79. package/dist/webpack.js +1 -1
  80. package/package.json +12 -3
  81. package/dist/cache-options-DavPxrhC.cjs +0 -16
  82. package/dist/cache-options-DwBtLwQe.js +0 -5
  83. package/dist/compiler-B-m9VGqj.cjs +0 -2316
  84. package/dist/compiler-BgMj2E5l.js +0 -2051
  85. package/dist/local-style-matcher-DRpFEu1s.cjs +0 -34
  86. package/dist/local-style-matcher-DsiI2wIc.js +0 -17
  87. package/dist/object-B-8IHefx.js +0 -47
  88. package/dist/object-DbHtAXRk.cjs +0 -58
  89. package/dist/wxml-CvKyV69S.js +0 -1822
@@ -0,0 +1,4877 @@
1
+ import { resolveMpxPlatform } from "./framework.js";
2
+ import { A as resolveBooleanObjectOption, Bt as resolveValidTailwindV4Candidates$1, Ft as resolveCssMacroTailwindV4Source, Mt as _defineProperty, Rt as shouldUseUniAppWebRpxCompatibility, T as omitUndefined, Tt as isFileMatchedByTailwindSourceEntries, a as resolveGeneratorRuntimeBranch, bt as createTailwindV4Engine$1, d as resolveTailwindV4SourceFromRuntime, i as normalizeWeappTailwindcssGeneratorOptions, t as createWeappTailwindcssGenerator, u as resolveTailwindV4Source$1, zt as loadTailwindV4DesignSystem } from "./generator-DyXTBPmE.js";
3
+ import { c as getRuntimeClassSetCacheEntry, d as invalidateRuntimeClassSet, i as resolveUniAppXOptions, o as applyV4CssCalcDefaults, s as warnMissingCssEntries, t as createTailwindcssRuntimeFromContext, u as getRuntimeClassSetSignatureWithSources } from "./tailwindcss-BK9S7zuq.js";
4
+ import { i as isMap, n as defuOverrideArray$1 } from "./utils-MVwpU07P.js";
5
+ import { a as DEFAULT_PARSE_CACHE_MAX_SOURCE_LENGTH, i as resolveDefaultCssPreflight, o as HARD_PARSE_CACHE_MAX_ENTRIES, r as getDefaultOptions } from "./defaults-B5ep0ojb.js";
6
+ import { createRequire } from "node:module";
7
+ import path from "node:path";
8
+ import process from "node:process";
9
+ import { splitCandidateTokens } from "@tailwindcss-mangle/engine";
10
+ import { createStyleHandler, finalizeMiniProgramCss, finalizeMiniProgramCssRoot, postcss } from "@weapp-tailwindcss/postcss";
11
+ import { LRUCache } from "lru-cache";
12
+ import { rm } from "node:fs/promises";
13
+ import { defuOverrideArray } from "@weapp-tailwindcss/shared";
14
+ import { md5 as md5Hash } from "@weapp-tailwindcss/shared/node";
15
+ import { Parser } from "htmlparser2";
16
+ import _babelTraverse from "@babel/traverse";
17
+ import { parse, parseExpression } from "@babel/parser";
18
+ import MagicString from "magic-string";
19
+ import _createDebug from "debug";
20
+ import { MappingChars2String, escape } from "@weapp-core/escape";
21
+ import { Buffer } from "node:buffer";
22
+ import { logger, pc } from "@weapp-tailwindcss/logger";
23
+ import { walk } from "oxc-walker";
24
+ import * as t from "@babel/types";
25
+ //#region src/babel/index.ts
26
+ function _interopDefaultCompat(e) {
27
+ return e && typeof e === "object" && "default" in e ? e.default : e;
28
+ }
29
+ const traverse = _interopDefaultCompat(_babelTraverse);
30
+ //#endregion
31
+ //#region src/utils/regex.ts
32
+ function escapeStringRegexp(str) {
33
+ if (typeof str !== "string") throw new TypeError("Expected a string");
34
+ return str.replaceAll(/[$()*+.?[\\\]^{|}]/g, "\\$&").replaceAll("-", "\\x2d");
35
+ }
36
+ //#endregion
37
+ //#region src/utils/nameMatcher.ts
38
+ const NEVER_MATCH_NAME$1 = () => false;
39
+ const GLOBAL_FLAG_REGEXP = /g/g;
40
+ function buildFuzzyMatcher(fuzzyStrings) {
41
+ if (fuzzyStrings.length === 0) return;
42
+ if (fuzzyStrings.length === 1) {
43
+ const [needle] = fuzzyStrings;
44
+ if (needle === void 0) return;
45
+ return (value) => value.includes(needle);
46
+ }
47
+ const unique = [...new Set(fuzzyStrings)];
48
+ const pattern = new RegExp(unique.map(escapeStringRegexp).join("|"));
49
+ return (value) => pattern.test(value);
50
+ }
51
+ function normaliseRegex(regex) {
52
+ const { source, flags } = regex;
53
+ if (!flags.includes("g")) return regex;
54
+ return new RegExp(source, flags.replace(GLOBAL_FLAG_REGEXP, ""));
55
+ }
56
+ function createNameMatcher(list, { exact = false } = {}) {
57
+ if (!list || list.length === 0) return NEVER_MATCH_NAME$1;
58
+ const exactStrings = exact ? /* @__PURE__ */ new Set() : void 0;
59
+ const fuzzyStrings = [];
60
+ const regexList = [];
61
+ for (const item of list) if (typeof item === "string") {
62
+ if (exact) exactStrings.add(item);
63
+ else fuzzyStrings.push(item);
64
+ } else regexList.push(normaliseRegex(item));
65
+ if (exact) {
66
+ const exactStringCount = exactStrings?.size ?? 0;
67
+ if (exactStringCount === 1 && regexList.length === 0) {
68
+ const [needle] = exactStrings;
69
+ if (needle === void 0) return NEVER_MATCH_NAME$1;
70
+ return (value) => value === needle;
71
+ }
72
+ if (regexList.length === 0) return (value) => exactStrings.has(value);
73
+ if (exactStringCount === 0 && regexList.length === 1) {
74
+ const [regex] = regexList;
75
+ if (!regex) return NEVER_MATCH_NAME$1;
76
+ return (value) => regex.test(value);
77
+ }
78
+ return (value) => {
79
+ if (exactStrings?.has(value)) return true;
80
+ return regexList.some((regex) => regex.test(value));
81
+ };
82
+ }
83
+ const fuzzyMatcher = exact ? void 0 : buildFuzzyMatcher(fuzzyStrings);
84
+ const hasRegex = regexList.length > 0;
85
+ if (fuzzyMatcher && !hasRegex) return fuzzyMatcher;
86
+ if (!fuzzyMatcher && regexList.length === 1) {
87
+ const [regex] = regexList;
88
+ if (!regex) return NEVER_MATCH_NAME$1;
89
+ return (value) => regex.test(value);
90
+ }
91
+ return (value) => {
92
+ if (fuzzyMatcher?.(value)) return true;
93
+ if (!hasRegex) return false;
94
+ return regexList.some((regex) => regex.test(value));
95
+ };
96
+ }
97
+ //#endregion
98
+ //#region src/js/babel/parse.ts
99
+ const parseCache = new LRUCache({ max: HARD_PARSE_CACHE_MAX_ENTRIES });
100
+ function genCacheKey(source, options) {
101
+ if (typeof options === "string") return `${md5Hash(source)}:${options}`;
102
+ return `${md5Hash(source)}:${JSON.stringify(options, (_, val) => typeof val === "function" ? val.toString() : val)}`;
103
+ }
104
+ function normalizeCacheMaxEntries(value) {
105
+ if (typeof value !== "number" || !Number.isFinite(value)) return 128;
106
+ return Math.min(Math.max(Math.floor(value), 0), HARD_PARSE_CACHE_MAX_ENTRIES);
107
+ }
108
+ function normalizeCacheMaxSourceLength(value) {
109
+ if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_PARSE_CACHE_MAX_SOURCE_LENGTH;
110
+ return Math.max(Math.floor(value), 0);
111
+ }
112
+ function trimParseCache(maxEntries) {
113
+ while (parseCache.size > maxEntries) parseCache.pop();
114
+ }
115
+ function babelParse(code, opts = {}) {
116
+ const { cache, cacheKey, cacheMaxEntries, cacheMaxSourceLength, ...rest } = opts;
117
+ const maxEntries = normalizeCacheMaxEntries(cacheMaxEntries);
118
+ const maxSourceLength = normalizeCacheMaxSourceLength(cacheMaxSourceLength);
119
+ const shouldCache = cache === true && maxEntries > 0 && code.length <= maxSourceLength;
120
+ const cacheKeyString = shouldCache ? genCacheKey(code, cacheKey ?? rest) : void 0;
121
+ let result;
122
+ if (shouldCache) {
123
+ trimParseCache(maxEntries);
124
+ result = parseCache.get(cacheKeyString);
125
+ }
126
+ if (!result) {
127
+ const { cache: _cache, cacheKey: _cacheKey, cacheMaxEntries: _cacheMaxEntries, cacheMaxSourceLength: _cacheMaxSourceLength, ...parseOptions } = opts;
128
+ result = parse(code, parseOptions);
129
+ if (shouldCache) {
130
+ parseCache.set(cacheKeyString, result);
131
+ trimParseCache(maxEntries);
132
+ }
133
+ }
134
+ return result;
135
+ }
136
+ //#endregion
137
+ //#region src/debug/index.ts
138
+ const _debug = _createDebug("weapp-tw");
139
+ function createDebug(prefix) {
140
+ const debug = ((formatter, ...args) => {
141
+ return _debug((prefix ?? "") + formatter, ...args);
142
+ });
143
+ Object.defineProperty(debug, "enabled", {
144
+ enumerable: false,
145
+ configurable: false,
146
+ get() {
147
+ return _debug.enabled;
148
+ }
149
+ });
150
+ return debug;
151
+ }
152
+ //#endregion
153
+ //#region src/wxml/shared.ts
154
+ const NEWLINE_RE = /[\n\r]+/g;
155
+ function replaceWxml(original, options = {
156
+ keepEOL: false,
157
+ escapeMap: MappingChars2String
158
+ }) {
159
+ const { keepEOL, escapeMap, ignoreHead } = options;
160
+ let res = original;
161
+ if (!keepEOL) res = res.replaceAll(NEWLINE_RE, "");
162
+ res = escape(res, omitUndefined({
163
+ map: escapeMap,
164
+ ignoreHead
165
+ }));
166
+ return res;
167
+ }
168
+ //#endregion
169
+ //#region src/shared/classname-transform.ts
170
+ const escapedCandidateCacheByEscapeMap = /* @__PURE__ */ new WeakMap();
171
+ const defaultEscapedCandidateCache = /* @__PURE__ */ new Map();
172
+ let lastEscapedCandidateEscapeMap;
173
+ let lastEscapedCandidateCacheStore;
174
+ function isUrlLikeCandidate(candidate) {
175
+ return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
176
+ }
177
+ function isPlainSlashPathCandidate(candidate) {
178
+ const slashIndex = candidate.indexOf("/");
179
+ if (slashIndex <= 0) return false;
180
+ if (isUrlLikeCandidate(candidate)) return true;
181
+ if (candidate.includes("[") || candidate.includes("]") || candidate.includes(":")) return false;
182
+ return !candidate.slice(0, slashIndex).includes("-");
183
+ }
184
+ const SKIP_RESULT = { decision: "skip" };
185
+ const DIRECT_RESULT = { decision: "direct" };
186
+ function getEscapedCandidateCacheStore(escapeMap) {
187
+ if (!escapeMap) return defaultEscapedCandidateCache;
188
+ if (escapeMap === lastEscapedCandidateEscapeMap && lastEscapedCandidateCacheStore) return lastEscapedCandidateCacheStore;
189
+ let store = escapedCandidateCacheByEscapeMap.get(escapeMap);
190
+ if (!store) {
191
+ store = /* @__PURE__ */ new Map();
192
+ escapedCandidateCacheByEscapeMap.set(escapeMap, store);
193
+ }
194
+ lastEscapedCandidateEscapeMap = escapeMap;
195
+ lastEscapedCandidateCacheStore = store;
196
+ return store;
197
+ }
198
+ function getEscapedCandidate(candidate, escapeMap, store = getEscapedCandidateCacheStore(escapeMap)) {
199
+ let cached = store.get(candidate);
200
+ if (cached === void 0) {
201
+ cached = replaceWxml(candidate, { escapeMap });
202
+ store.set(candidate, cached);
203
+ }
204
+ return cached;
205
+ }
206
+ /**
207
+ * JS 转译严格遵循 runtime class set:
208
+ * 1. 直接命中 classNameSet 原始值;
209
+ * 2. 兼容命中 classNameSet 中已转义值;
210
+ * 3. 除显式 alwaysEscape 外,不允许绕过 classNameSet。
211
+ *
212
+ * 返回结构化结果,附带已计算的 escapedValue 以避免下游重复 escape。
213
+ */
214
+ function resolveClassNameTransformWithResult(candidate, { alwaysEscape, classNameSet, escapeMap, jsPreserveClass, classContext }) {
215
+ if (jsPreserveClass?.(candidate)) return SKIP_RESULT;
216
+ if (alwaysEscape) return DIRECT_RESULT;
217
+ if (!classContext && isPlainSlashPathCandidate(candidate)) return SKIP_RESULT;
218
+ if (classNameSet?.has(candidate)) return DIRECT_RESULT;
219
+ if (classNameSet && classNameSet.size > 0) {
220
+ const escapedCandidate = getEscapedCandidate(candidate, escapeMap);
221
+ if (escapedCandidate !== candidate && classNameSet.has(escapedCandidate)) return {
222
+ decision: "escaped",
223
+ escapedValue: escapedCandidate
224
+ };
225
+ }
226
+ return SKIP_RESULT;
227
+ }
228
+ //#endregion
229
+ //#region src/utils/decode.ts
230
+ const unicodeEscapeRE = /\\u([\dA-Fa-f]{4})/g;
231
+ const unicodeEscapeTestRE = /\\u[\dA-Fa-f]{4}/;
232
+ function decodeUnicode(value) {
233
+ if (!unicodeEscapeTestRE.test(value)) return value;
234
+ return value.replace(unicodeEscapeRE, (_match, hex) => {
235
+ const codePoint = Number.parseInt(hex, 16);
236
+ return Number.isNaN(codePoint) ? _match : String.fromCharCode(codePoint);
237
+ });
238
+ }
239
+ function decodeUnicode2(input) {
240
+ if (!unicodeEscapeTestRE.test(input)) return input;
241
+ try {
242
+ return JSON.parse(`"${input}"`);
243
+ } catch (_error) {
244
+ return decodeUnicode(input);
245
+ }
246
+ }
247
+ //#endregion
248
+ //#region src/js/class-context.ts
249
+ const CLASS_LIKE_KEYWORDS = /* @__PURE__ */ new Set([
250
+ "class",
251
+ "classname",
252
+ "hoverclass",
253
+ "virtualhostclass",
254
+ "rootclass"
255
+ ]);
256
+ const CLASS_HELPER_IDENTIFIERS = /* @__PURE__ */ new Set([
257
+ "cn",
258
+ "clsx",
259
+ "classnames",
260
+ "twmerge",
261
+ "cva",
262
+ "tv",
263
+ "cx",
264
+ "r"
265
+ ]);
266
+ const DASH_CODE = 45;
267
+ const COLON_CODE = 58;
268
+ const UPPERCASE_A_CODE = 65;
269
+ const UPPERCASE_Z_CODE = 90;
270
+ const UNDERSCORE_CODE = 95;
271
+ const ASCII_MAX_CODE = 127;
272
+ const NORMALIZE_KEYWORD_REGEXP = /[-_:]/g;
273
+ function normalizeKeyword(name) {
274
+ const length = name.length;
275
+ let firstNormalizedIndex = -1;
276
+ for (let i = 0; i < length; i++) {
277
+ const code = name.charCodeAt(i);
278
+ if (code === DASH_CODE || code === UNDERSCORE_CODE || code === COLON_CODE || code >= UPPERCASE_A_CODE && code <= UPPERCASE_Z_CODE) {
279
+ firstNormalizedIndex = i;
280
+ break;
281
+ }
282
+ if (code > ASCII_MAX_CODE) return name.replace(NORMALIZE_KEYWORD_REGEXP, "").toLowerCase();
283
+ }
284
+ if (firstNormalizedIndex === -1) return name;
285
+ let normalized = name.slice(0, firstNormalizedIndex);
286
+ for (let i = firstNormalizedIndex; i < length; i++) {
287
+ const code = name.charCodeAt(i);
288
+ if (code === DASH_CODE || code === UNDERSCORE_CODE || code === COLON_CODE) continue;
289
+ if (code >= UPPERCASE_A_CODE && code <= UPPERCASE_Z_CODE) {
290
+ normalized += String.fromCharCode(code + 32);
291
+ continue;
292
+ }
293
+ if (code > ASCII_MAX_CODE) return name.replace(NORMALIZE_KEYWORD_REGEXP, "").toLowerCase();
294
+ normalized += name[i];
295
+ }
296
+ return normalized;
297
+ }
298
+ function readObjectKeyName(path) {
299
+ if (path.isIdentifier()) return path.node.name;
300
+ if (path.isStringLiteral()) return path.node.value;
301
+ if (path.isTemplateLiteral() && path.node.expressions.length === 0) return path.node.quasis[0]?.value.cooked ?? path.node.quasis[0]?.value.raw;
302
+ }
303
+ function isClassLikeObjectProperty(path, valuePath) {
304
+ if (!path.isObjectProperty()) return false;
305
+ if (path.get("value") !== valuePath) return false;
306
+ const keyName = readObjectKeyName(path.get("key"));
307
+ if (!keyName) return false;
308
+ return CLASS_LIKE_KEYWORDS.has(normalizeKeyword(keyName));
309
+ }
310
+ function isClassLikeJsxAttribute(path) {
311
+ if (!path.isJSXAttribute()) return false;
312
+ const namePath = path.get("name");
313
+ if (!namePath.isJSXIdentifier()) return false;
314
+ return CLASS_LIKE_KEYWORDS.has(normalizeKeyword(namePath.node.name));
315
+ }
316
+ function readCallHelperName(calleePath) {
317
+ if (calleePath.isIdentifier()) return calleePath.node.name;
318
+ if (calleePath.isMemberExpression()) {
319
+ const propertyPath = calleePath.get("property");
320
+ if (propertyPath.isIdentifier()) return propertyPath.node.name;
321
+ if (propertyPath.isStringLiteral()) return propertyPath.node.value;
322
+ }
323
+ }
324
+ function isClassLikeCallExpression(path, valuePath) {
325
+ if (!path.isCallExpression()) return false;
326
+ const helperName = readCallHelperName(path.get("callee"));
327
+ if (!helperName || !CLASS_HELPER_IDENTIFIERS.has(normalizeKeyword(helperName))) return false;
328
+ return path.get("arguments").some((argumentPath) => argumentPath.node === valuePath.node);
329
+ }
330
+ /**
331
+ * 判断字符串字面量是否处于 class 语义上下文。
332
+ * 仅用于受控兜底场景,避免将普通业务文本误判为 class。
333
+ */
334
+ function isClassContextLiteralPath(path) {
335
+ let current = path;
336
+ while (current.parentPath) {
337
+ const parent = current.parentPath;
338
+ if (isClassLikeObjectProperty(parent, current)) return true;
339
+ if (isClassLikeJsxAttribute(parent)) return true;
340
+ if (isClassLikeCallExpression(parent, current)) return true;
341
+ current = parent;
342
+ }
343
+ return false;
344
+ }
345
+ //#endregion
346
+ //#region src/js/js-string-escape.ts
347
+ function jsStringEscape(value) {
348
+ return String(value).replaceAll(/[\n\r"'\\\u2028\u2029]/g, (character) => {
349
+ switch (character) {
350
+ case "\"":
351
+ case "'":
352
+ case "\\": return `\\${character}`;
353
+ case "\n": return "\\n";
354
+ case "\r": return "\\r";
355
+ case "\u2028": return "\\u2028";
356
+ case "\u2029": return "\\u2029";
357
+ default: return character;
358
+ }
359
+ });
360
+ }
361
+ //#endregion
362
+ //#region src/js/replacement-cache.ts
363
+ const replacementCacheByEscapeMap = /* @__PURE__ */ new WeakMap();
364
+ const defaultReplacementCache = /* @__PURE__ */ new Map();
365
+ function getReplacementCacheStore(escapeMap) {
366
+ if (!escapeMap) return defaultReplacementCache;
367
+ let store = replacementCacheByEscapeMap.get(escapeMap);
368
+ if (!store) {
369
+ store = /* @__PURE__ */ new Map();
370
+ replacementCacheByEscapeMap.set(escapeMap, store);
371
+ }
372
+ return store;
373
+ }
374
+ function getReplacement(candidate, escapeMap, store = getReplacementCacheStore(escapeMap)) {
375
+ let cached = store.get(candidate);
376
+ if (cached === void 0) {
377
+ cached = replaceWxml(candidate, { escapeMap });
378
+ store.set(candidate, cached);
379
+ }
380
+ return cached;
381
+ }
382
+ //#endregion
383
+ //#region src/js/handlers.ts
384
+ const debug$1 = createDebug("[js:handlers] ");
385
+ const WEAPP_TW_IGNORE_MARKER = "weapp-tw";
386
+ const IGNORE_MARKER = "ignore";
387
+ function hasIgnoreComment(node) {
388
+ const { leadingComments } = node;
389
+ if (!Array.isArray(leadingComments) || leadingComments.length === 0) return false;
390
+ for (const comment of leadingComments) {
391
+ const { value } = comment;
392
+ if (value.includes(WEAPP_TW_IGNORE_MARKER) && value.includes(IGNORE_MARKER)) return true;
393
+ }
394
+ return false;
395
+ }
396
+ function isConditionTestLiteral(path) {
397
+ let current = path;
398
+ while (current?.parentPath) {
399
+ const parent = current.parentPath;
400
+ if (parent.isConditionalExpression()) return parent.node.test === current.node;
401
+ if (parent.isBinaryExpression() || parent.isCallExpression() || parent.isLogicalExpression() || parent.isMemberExpression() || parent.isUnaryExpression()) {
402
+ current = parent;
403
+ continue;
404
+ }
405
+ return false;
406
+ }
407
+ return false;
408
+ }
409
+ function extractLiteralValue(path, { unescapeUnicode }) {
410
+ const { node } = path;
411
+ let offset = 0;
412
+ let original;
413
+ if (node.type === "StringLiteral") {
414
+ offset = 1;
415
+ original = node.value;
416
+ } else if (node.type === "TemplateElement") original = node.value.raw;
417
+ else original = "";
418
+ let literal = original;
419
+ if (unescapeUnicode && original.includes("\\u")) literal = decodeUnicode2(original);
420
+ return {
421
+ literal,
422
+ offset,
423
+ original
424
+ };
425
+ }
426
+ function createCandidatePlanResolver(options, classContext) {
427
+ const { escapeMap } = options;
428
+ const replacementCache = getReplacementCacheStore(escapeMap);
429
+ const transformOptions = classContext ? {
430
+ ...options,
431
+ classContext
432
+ } : options;
433
+ let firstCandidate = "";
434
+ let firstPlan;
435
+ let cache;
436
+ const buildCandidatePlan = (candidate) => {
437
+ const result = resolveClassNameTransformWithResult(candidate, transformOptions);
438
+ if (result.decision === "skip") return { result };
439
+ let replacement;
440
+ if (result.decision === "escaped" && result.escapedValue) {
441
+ replacement = result.escapedValue;
442
+ replacementCache.set(candidate, replacement);
443
+ } else replacement = getReplacement(candidate, escapeMap, replacementCache);
444
+ return {
445
+ result,
446
+ replacement
447
+ };
448
+ };
449
+ return (candidate) => {
450
+ if (cache) {
451
+ const cached = cache.get(candidate);
452
+ if (cached) return cached;
453
+ } else if (firstPlan && candidate === firstCandidate) return firstPlan;
454
+ const plan = buildCandidatePlan(candidate);
455
+ if (!firstPlan) {
456
+ firstCandidate = candidate;
457
+ firstPlan = plan;
458
+ return plan;
459
+ }
460
+ if (!cache) {
461
+ cache = /* @__PURE__ */ new Map();
462
+ cache.set(firstCandidate, firstPlan);
463
+ }
464
+ cache.set(candidate, plan);
465
+ return plan;
466
+ };
467
+ }
468
+ function replaceHandleValue(path, options) {
469
+ const { needEscaped = false } = options;
470
+ const { classNameSet, alwaysEscape } = options;
471
+ if (!alwaysEscape && (!classNameSet || classNameSet.size === 0)) return;
472
+ if (hasIgnoreComment(path.node)) return;
473
+ if (isConditionTestLiteral(path)) return;
474
+ const { literal, original, offset } = extractLiteralValue(path, options);
475
+ const candidates = splitCandidateTokens(literal);
476
+ if (candidates.length === 0) return;
477
+ const debugEnabled = debug$1.enabled;
478
+ const classContext = options.wrapExpression || isClassContextLiteralPath(path);
479
+ let transformed = literal;
480
+ let mutated = false;
481
+ let matchedCandidateCount = 0;
482
+ let escapedDecisionCount = 0;
483
+ let escapedSamples;
484
+ let skippedSamples;
485
+ const resolveCandidatePlan = createCandidatePlanResolver(options, classContext);
486
+ for (const candidate of candidates) {
487
+ const plan = resolveCandidatePlan(candidate);
488
+ if (plan.result.decision === "skip") {
489
+ if (debugEnabled) {
490
+ if (!skippedSamples) skippedSamples = [];
491
+ if (skippedSamples.length < 6) skippedSamples.push(candidate);
492
+ }
493
+ continue;
494
+ }
495
+ if (debugEnabled) {
496
+ matchedCandidateCount += 1;
497
+ if (plan.result.decision === "escaped") {
498
+ escapedDecisionCount += 1;
499
+ if (!escapedSamples) escapedSamples = [];
500
+ if (escapedSamples.length < 6) escapedSamples.push(candidate);
501
+ }
502
+ }
503
+ const replaced = transformed.replace(candidate, plan.replacement);
504
+ if (replaced !== transformed) {
505
+ transformed = replaced;
506
+ mutated = true;
507
+ }
508
+ }
509
+ const node = path.node;
510
+ if (!mutated || typeof node.start !== "number" || typeof node.end !== "number") return;
511
+ if (debugEnabled) debug$1("runtimeSet size=%d candidates=%d matched=%d escapedHits=%d skipped=%d file=%s escapedSamples=%s skippedSamples=%s", classNameSet?.size ?? 0, candidates.length, matchedCandidateCount, escapedDecisionCount, skippedSamples?.length ?? 0, options.filename ?? "unknown", escapedSamples?.join(",") || "-", skippedSamples?.join(",") || "-");
512
+ const start = node.start + offset;
513
+ const end = node.end - offset;
514
+ if (start >= end || transformed === original) return;
515
+ return {
516
+ start,
517
+ end,
518
+ value: needEscaped ? jsStringEscape(transformed) : transformed,
519
+ path
520
+ };
521
+ }
522
+ //#endregion
523
+ //#region src/js/sourceAnalysis.ts
524
+ function hasReplacementEntries(replacements) {
525
+ for (const key in replacements) if (Object.hasOwn(replacements, key)) return true;
526
+ return false;
527
+ }
528
+ function createModuleSpecifierReplacementToken(path, replacement) {
529
+ const node = path.node;
530
+ if (node.value === replacement) return;
531
+ if (typeof node.start !== "number" || typeof node.end !== "number") return;
532
+ const start = node.start + 1;
533
+ const end = node.end - 1;
534
+ if (start >= end) return;
535
+ return {
536
+ start,
537
+ end,
538
+ value: replacement,
539
+ path
540
+ };
541
+ }
542
+ function collectModuleSpecifierReplacementTokens(analysis, replacements) {
543
+ if (!hasReplacementEntries(replacements)) return [];
544
+ if (analysis.importDeclarations.size === 0 && analysis.exportDeclarations.size === 0 && analysis.requireCallPaths.length === 0 && analysis.walker.imports.size === 0) return [];
545
+ const tokens = [];
546
+ const applyReplacement = (path) => {
547
+ const replacement = replacements[path.node.value];
548
+ if (!replacement) return;
549
+ const token = createModuleSpecifierReplacementToken(path, replacement);
550
+ if (token) tokens.push(token);
551
+ };
552
+ for (const importPath of analysis.importDeclarations) {
553
+ const source = importPath.get("source");
554
+ if (source.isStringLiteral()) applyReplacement(source);
555
+ }
556
+ for (const exportPath of analysis.exportDeclarations) if (exportPath.isExportNamedDeclaration() || exportPath.isExportAllDeclaration()) {
557
+ const source = exportPath.get("source");
558
+ if (source && !Array.isArray(source) && source.isStringLiteral()) applyReplacement(source);
559
+ }
560
+ for (const literalPath of analysis.requireCallPaths) applyReplacement(literalPath);
561
+ for (const token of analysis.walker.imports) {
562
+ const replacement = replacements[token.source];
563
+ if (replacement) token.source = replacement;
564
+ }
565
+ return tokens;
566
+ }
567
+ //#endregion
568
+ //#region src/js/babel/process.ts
569
+ const optionVariantsCache = /* @__PURE__ */ new WeakMap();
570
+ function getNeedEscapedOptions(options, needEscaped) {
571
+ if (options.needEscaped === needEscaped) return options;
572
+ let cached = optionVariantsCache.get(options);
573
+ if (!cached) {
574
+ cached = {};
575
+ optionVariantsCache.set(options, cached);
576
+ }
577
+ if (needEscaped) {
578
+ if (!cached.stringLiteralOptions) cached.stringLiteralOptions = {
579
+ ...options,
580
+ needEscaped: true
581
+ };
582
+ return cached.stringLiteralOptions;
583
+ }
584
+ if (!cached.templateLiteralOptions) cached.templateLiteralOptions = {
585
+ ...options,
586
+ needEscaped: false
587
+ };
588
+ return cached.templateLiteralOptions;
589
+ }
590
+ function processUpdatedSource(rawSource, options, analysis) {
591
+ const { targetPaths, jsTokenUpdater, ignoredPaths } = analysis;
592
+ if (targetPaths.length === 0 && !options.moduleSpecifierReplacements && jsTokenUpdater.length === 0) return new MagicString(rawSource);
593
+ const replacementTokens = [];
594
+ for (const path of targetPaths) {
595
+ if (ignoredPaths.has(path)) continue;
596
+ const token = replaceHandleValue(path, path.isStringLiteral() ? getNeedEscapedOptions(options, true) : getNeedEscapedOptions(options, false));
597
+ if (token) replacementTokens.push(token);
598
+ }
599
+ if (options.moduleSpecifierReplacements) replacementTokens.push(...collectModuleSpecifierReplacementTokens(analysis, options.moduleSpecifierReplacements));
600
+ if (jsTokenUpdater.length + replacementTokens.length === 0) return new MagicString(rawSource);
601
+ const ms = new MagicString(rawSource);
602
+ jsTokenUpdater.push(...replacementTokens).filter((token) => !ignoredPaths.has(token.path)).updateMagicString(ms);
603
+ return ms;
604
+ }
605
+ //#endregion
606
+ //#region src/js/evalTransforms.ts
607
+ const evalHandlerOptionsCache = /* @__PURE__ */ new WeakMap();
608
+ const EVAL_SCOPE_ERROR_REGEXP = /pass a scope and parentPath|traversing a Program\/File/i;
609
+ function isEvalPath(path) {
610
+ if (path.isCallExpression()) return path.get("callee").isIdentifier({ name: "eval" });
611
+ return false;
612
+ }
613
+ function createEvalReplacementToken(path, updated) {
614
+ const node = path.node;
615
+ let offset = 0;
616
+ let original;
617
+ if (path.isStringLiteral()) {
618
+ offset = 1;
619
+ original = path.node.value;
620
+ } else if (path.isTemplateElement()) original = path.node.value.raw;
621
+ else original = "";
622
+ if (typeof node.start !== "number" || typeof node.end !== "number") return;
623
+ const start = node.start + offset;
624
+ const end = node.end - offset;
625
+ if (start >= end) return;
626
+ if (original === updated) return;
627
+ return {
628
+ start,
629
+ end,
630
+ value: path.isStringLiteral() ? jsStringEscape(updated) : updated,
631
+ path
632
+ };
633
+ }
634
+ function handleEvalStringLiteral(path, handlerOptions, updater, handler) {
635
+ const { code } = handler(path.node.value, handlerOptions);
636
+ if (!code) return;
637
+ const token = createEvalReplacementToken(path, code);
638
+ if (token) updater.addToken(token);
639
+ }
640
+ function handleEvalTemplateElement(path, handlerOptions, updater, handler) {
641
+ const { code } = handler(path.node.value.raw, handlerOptions);
642
+ if (!code) return;
643
+ const token = createEvalReplacementToken(path, code);
644
+ if (token) updater.addToken(token);
645
+ }
646
+ function getEvalStringHandlerOptions(options) {
647
+ if (options.needEscaped === false && options.generateMap === false) return options;
648
+ let cached = evalHandlerOptionsCache.get(options);
649
+ if (!cached) {
650
+ cached = {};
651
+ evalHandlerOptionsCache.set(options, cached);
652
+ }
653
+ if (!cached.stringLiteralOptions) cached.stringLiteralOptions = {
654
+ ...options,
655
+ needEscaped: false,
656
+ generateMap: false
657
+ };
658
+ return cached.stringLiteralOptions;
659
+ }
660
+ function getEvalTemplateHandlerOptions(options) {
661
+ if (options.generateMap === false) return options;
662
+ let cached = evalHandlerOptionsCache.get(options);
663
+ if (!cached) {
664
+ cached = {};
665
+ evalHandlerOptionsCache.set(options, cached);
666
+ }
667
+ if (!cached.templateLiteralOptions) cached.templateLiteralOptions = {
668
+ ...options,
669
+ generateMap: false
670
+ };
671
+ return cached.templateLiteralOptions;
672
+ }
673
+ function walkEvalExpression(path, options, updater, handler) {
674
+ const stringHandlerOptions = getEvalStringHandlerOptions(options);
675
+ const templateHandlerOptions = getEvalTemplateHandlerOptions(options);
676
+ const maybeTraverse = path?.traverse;
677
+ if (typeof maybeTraverse === "function") try {
678
+ return maybeTraverse.call(path, {
679
+ StringLiteral(innerPath) {
680
+ handleEvalStringLiteral(innerPath, stringHandlerOptions, updater, handler);
681
+ },
682
+ TemplateElement(innerPath) {
683
+ handleEvalTemplateElement(innerPath, templateHandlerOptions, updater, handler);
684
+ }
685
+ });
686
+ } catch (error) {
687
+ const msg = error?.message ?? "";
688
+ if (!EVAL_SCOPE_ERROR_REGEXP.test(msg)) throw error;
689
+ }
690
+ const getArgs = path?.get?.("arguments");
691
+ if (Array.isArray(getArgs)) {
692
+ for (const arg of getArgs) {
693
+ if (arg?.isStringLiteral?.()) {
694
+ handleEvalStringLiteral(arg, stringHandlerOptions, updater, handler);
695
+ continue;
696
+ }
697
+ if (arg?.isTemplateLiteral?.()) for (const quasi of arg.get("quasis")) handleEvalTemplateElement(quasi, templateHandlerOptions, updater, handler);
698
+ }
699
+ return;
700
+ }
701
+ const nodeArgs = path?.node?.arguments;
702
+ if (Array.isArray(nodeArgs)) {
703
+ for (const n of nodeArgs) if (n?.type === "StringLiteral") handleEvalStringLiteral({
704
+ node: n,
705
+ isStringLiteral: () => true
706
+ }, stringHandlerOptions, updater, handler);
707
+ else if (n?.type === "TemplateLiteral" && Array.isArray(n.quasis)) for (const q of n.quasis) handleEvalTemplateElement({
708
+ node: q,
709
+ isStringLiteral: () => false,
710
+ isTemplateElement: () => true
711
+ }, templateHandlerOptions, updater, handler);
712
+ }
713
+ }
714
+ //#endregion
715
+ //#region src/js/JsTokenUpdater.ts
716
+ /**
717
+ * Lightweight helper that batches updates to {@link MagicString}.
718
+ * It keeps the transformation logic out of the traversal code and makes
719
+ * it easier to reason about the order in which tokens are written back.
720
+ */
721
+ var JsTokenUpdater = class {
722
+ constructor({ value } = {}) {
723
+ _defineProperty(this, "tokens", void 0);
724
+ this.tokens = value ? [...value] : [];
725
+ }
726
+ addToken(token) {
727
+ if (token) this.tokens.push(token);
728
+ }
729
+ push(...args) {
730
+ this.tokens.push(...args);
731
+ return this;
732
+ }
733
+ /**
734
+ * 待写入的 token 数量。
735
+ */
736
+ get length() {
737
+ return this.tokens.length;
738
+ }
739
+ map(callbackfn) {
740
+ this.tokens = this.tokens.map(callbackfn);
741
+ return this;
742
+ }
743
+ filter(callbackfn) {
744
+ this.tokens = this.tokens.filter(callbackfn);
745
+ return this;
746
+ }
747
+ updateMagicString(ms) {
748
+ for (const { start, end, value } of this.tokens) ms.update(start, end, value);
749
+ return ms;
750
+ }
751
+ };
752
+ //#endregion
753
+ //#region src/js/module-graph/ignored-exports.ts
754
+ var IgnoredExportsTracker = class {
755
+ constructor(options) {
756
+ this.options = options;
757
+ _defineProperty(this, "ignoredExportNames", /* @__PURE__ */ new Map());
758
+ }
759
+ addIgnoredExport(filename, exportName) {
760
+ if (!exportName) return;
761
+ let pending = this.ignoredExportNames.get(filename);
762
+ if (!pending) {
763
+ pending = /* @__PURE__ */ new Set();
764
+ this.ignoredExportNames.set(filename, pending);
765
+ }
766
+ if (pending.has(exportName)) return;
767
+ pending.add(exportName);
768
+ const existing = this.options.modules.get(filename);
769
+ if (existing) this.applyIgnoredExportsToAnalysis(filename, existing.analysis);
770
+ }
771
+ registerIgnoredExportsFromTokens(resolved, tokens) {
772
+ for (const token of tokens) if (token.type === "ImportSpecifier") this.addIgnoredExport(resolved, token.imported);
773
+ else if (token.type === "ImportDefaultSpecifier") this.addIgnoredExport(resolved, "default");
774
+ }
775
+ applyIgnoredExportsToAnalysis(filename, analysis) {
776
+ const pending = this.ignoredExportNames.get(filename);
777
+ if (!pending || pending.size === 0) return;
778
+ const names = new Set(pending);
779
+ pending.clear();
780
+ const propagate = [];
781
+ for (const exportPath of analysis.exportDeclarations) {
782
+ if (names.size === 0) break;
783
+ if (exportPath.isExportDefaultDeclaration()) {
784
+ if (names.has("default")) {
785
+ analysis.walker.walkExportDefaultDeclaration(exportPath);
786
+ names.delete("default");
787
+ }
788
+ continue;
789
+ }
790
+ if (exportPath.isExportNamedDeclaration()) {
791
+ const source = exportPath.node.source?.value;
792
+ if (typeof source === "string") {
793
+ for (const spec of exportPath.get("specifiers")) {
794
+ if (!spec.isExportSpecifier()) continue;
795
+ const exported = spec.get("exported");
796
+ let exportedName;
797
+ if (exported.isIdentifier()) exportedName = exported.node.name;
798
+ else if (exported.isStringLiteral()) exportedName = exported.node.value;
799
+ if (!exportedName || !names.has(exportedName)) continue;
800
+ const local = spec.get("local");
801
+ if (local.isIdentifier()) {
802
+ propagate.push({
803
+ specifier: source,
804
+ exportName: local.node.name
805
+ });
806
+ names.delete(exportedName);
807
+ } else if (local.isStringLiteral()) {
808
+ propagate.push({
809
+ specifier: source,
810
+ exportName: local.node.value
811
+ });
812
+ names.delete(exportedName);
813
+ }
814
+ }
815
+ continue;
816
+ }
817
+ const declaration = exportPath.get("declaration");
818
+ if (declaration.isVariableDeclaration()) for (const decl of declaration.get("declarations")) {
819
+ const id = decl.get("id");
820
+ if (id.isIdentifier()) {
821
+ const exportName = id.node.name;
822
+ if (names.has(exportName)) {
823
+ analysis.walker.walkVariableDeclarator(decl);
824
+ names.delete(exportName);
825
+ }
826
+ }
827
+ }
828
+ for (const spec of exportPath.get("specifiers")) {
829
+ if (!spec.isExportSpecifier()) continue;
830
+ const exported = spec.get("exported");
831
+ let exportedName;
832
+ if (exported.isIdentifier()) exportedName = exported.node.name;
833
+ else if (exported.isStringLiteral()) exportedName = exported.node.value;
834
+ if (!exportedName || !names.has(exportedName)) continue;
835
+ const local = spec.get("local");
836
+ analysis.walker.walkNode(local);
837
+ names.delete(exportedName);
838
+ }
839
+ continue;
840
+ }
841
+ if (exportPath.isExportAllDeclaration()) {
842
+ const source = exportPath.node.source?.value;
843
+ if (typeof source === "string") {
844
+ for (const exportName of names) propagate.push({
845
+ specifier: source,
846
+ exportName
847
+ });
848
+ names.clear();
849
+ }
850
+ }
851
+ }
852
+ for (const { specifier, exportName } of propagate) {
853
+ let resolved;
854
+ try {
855
+ resolved = this.options.resolve(specifier, filename);
856
+ } catch {
857
+ resolved = void 0;
858
+ }
859
+ if (!resolved) {
860
+ pending.add(exportName);
861
+ continue;
862
+ }
863
+ if (this.options.filter && !this.options.filter(resolved, specifier, filename)) {
864
+ pending.add(exportName);
865
+ continue;
866
+ }
867
+ this.addIgnoredExport(resolved, exportName);
868
+ }
869
+ for (const name of names) pending.add(name);
870
+ }
871
+ };
872
+ //#endregion
873
+ //#region src/js/ModuleGraph.ts
874
+ var JsModuleGraph = class {
875
+ constructor(entry, graphOptions) {
876
+ _defineProperty(this, "modules", /* @__PURE__ */ new Map());
877
+ _defineProperty(this, "queue", []);
878
+ _defineProperty(this, "resolve", void 0);
879
+ _defineProperty(this, "load", void 0);
880
+ _defineProperty(this, "filter", void 0);
881
+ _defineProperty(this, "maxDepth", void 0);
882
+ _defineProperty(this, "baseOptions", void 0);
883
+ _defineProperty(this, "parserOptions", void 0);
884
+ _defineProperty(this, "rootFilename", void 0);
885
+ _defineProperty(this, "ignoredExports", void 0);
886
+ this.resolve = graphOptions.resolve;
887
+ this.load = graphOptions.load;
888
+ this.filter = graphOptions.filter;
889
+ this.maxDepth = graphOptions.maxDepth ?? Number.POSITIVE_INFINITY;
890
+ const { moduleGraph: _moduleGraph, filename: _ignoredFilename, ...rest } = entry.handlerOptions;
891
+ this.baseOptions = {
892
+ ...rest,
893
+ filename: entry.filename
894
+ };
895
+ this.parserOptions = entry.handlerOptions.babelParserOptions;
896
+ this.rootFilename = entry.filename;
897
+ this.ignoredExports = new IgnoredExportsTracker({
898
+ resolve: this.resolve,
899
+ filter: this.filter,
900
+ modules: this.modules
901
+ });
902
+ this.modules.set(entry.filename, {
903
+ filename: entry.filename,
904
+ source: entry.source,
905
+ analysis: entry.analysis
906
+ });
907
+ this.queue.push({
908
+ filename: entry.filename,
909
+ depth: 0
910
+ });
911
+ }
912
+ build() {
913
+ this.collectDependencies();
914
+ let linked;
915
+ for (const [filename, state] of this.modules) {
916
+ if (filename === this.rootFilename) continue;
917
+ const childOptions = {
918
+ ...this.baseOptions,
919
+ filename
920
+ };
921
+ const code = processUpdatedSource(state.source, childOptions, state.analysis).toString();
922
+ if (code !== state.source) {
923
+ if (!linked) linked = {};
924
+ linked[filename] = { code };
925
+ }
926
+ }
927
+ return linked;
928
+ }
929
+ collectDependencies() {
930
+ while (this.queue.length > 0) {
931
+ const { filename, depth } = this.queue.shift();
932
+ if (depth >= this.maxDepth) continue;
933
+ const state = this.modules.get(filename);
934
+ if (!state) continue;
935
+ const dependencySpecifiers = /* @__PURE__ */ new Map();
936
+ for (const token of state.analysis.walker.imports) {
937
+ if (!dependencySpecifiers.has(token.source)) dependencySpecifiers.set(token.source, []);
938
+ dependencySpecifiers.get(token.source).push(token);
939
+ }
940
+ for (const exportPath of state.analysis.exportDeclarations) if (exportPath.isExportAllDeclaration() || exportPath.isExportNamedDeclaration()) {
941
+ const source = exportPath.node.source?.value;
942
+ if (typeof source === "string" && !dependencySpecifiers.has(source)) dependencySpecifiers.set(source, []);
943
+ }
944
+ for (const [specifier, tokens] of dependencySpecifiers) {
945
+ let resolved;
946
+ try {
947
+ resolved = this.resolve(specifier, filename);
948
+ } catch {
949
+ continue;
950
+ }
951
+ if (!resolved) continue;
952
+ if (this.filter && !this.filter(resolved, specifier, filename)) continue;
953
+ if (tokens.length > 0) this.ignoredExports.registerIgnoredExportsFromTokens(resolved, tokens);
954
+ if (this.modules.has(resolved)) continue;
955
+ let source;
956
+ try {
957
+ source = this.load(resolved);
958
+ } catch {
959
+ continue;
960
+ }
961
+ if (typeof source !== "string") continue;
962
+ let analysis;
963
+ try {
964
+ analysis = analyzeSource(babelParse(source, {
965
+ ...this.parserOptions,
966
+ sourceFilename: resolved
967
+ }), {
968
+ ...this.baseOptions,
969
+ filename: resolved
970
+ });
971
+ this.ignoredExports.applyIgnoredExportsToAnalysis(resolved, analysis);
972
+ } catch {
973
+ continue;
974
+ }
975
+ this.modules.set(resolved, {
976
+ filename: resolved,
977
+ source,
978
+ analysis
979
+ });
980
+ this.queue.push({
981
+ filename: resolved,
982
+ depth: depth + 1
983
+ });
984
+ }
985
+ }
986
+ }
987
+ };
988
+ //#endregion
989
+ //#region src/js/node-path-walker/export-handlers.ts
990
+ function walkExportDeclaration(ctx, path) {
991
+ if (path.isExportDeclaration()) {
992
+ if (path.isExportNamedDeclaration()) walkExportNamedDeclaration(ctx, path);
993
+ else if (path.isExportDefaultDeclaration()) walkExportDefaultDeclaration(ctx, path);
994
+ else if (path.isExportAllDeclaration()) walkExportAllDeclaration(ctx, path);
995
+ }
996
+ }
997
+ function walkExportNamedDeclaration(ctx, path) {
998
+ const declaration = path.get("declaration");
999
+ if (declaration.isVariableDeclaration()) for (const decl of declaration.get("declarations")) ctx.walkNode(decl);
1000
+ const specifiers = path.get("specifiers");
1001
+ for (const spec of specifiers) if (spec.isExportSpecifier()) {
1002
+ const local = spec.get("local");
1003
+ if (local.isIdentifier()) ctx.walkNode(local);
1004
+ }
1005
+ }
1006
+ function walkExportDefaultDeclaration(ctx, path) {
1007
+ const decl = path.get("declaration");
1008
+ if (decl.isIdentifier()) ctx.walkNode(decl);
1009
+ else ctx.walkNode(decl);
1010
+ }
1011
+ function walkExportAllDeclaration(ctx, path) {
1012
+ const source = path.get("source");
1013
+ if (source.isStringLiteral()) ctx.addImportToken({
1014
+ declaration: path,
1015
+ source: source.node.value,
1016
+ type: "ExportAllDeclaration"
1017
+ });
1018
+ }
1019
+ //#endregion
1020
+ //#region src/js/node-path-walker/import-tokens.ts
1021
+ function maybeAddImportToken(imports, arg) {
1022
+ if (!(arg.isImportSpecifier() && arg.node.importKind !== "type" || arg.isImportDefaultSpecifier())) return false;
1023
+ const importDeclaration = arg.parentPath;
1024
+ if (!importDeclaration.isImportDeclaration() || importDeclaration.node.importKind === "type") return false;
1025
+ if (arg.isImportSpecifier()) {
1026
+ const imported = arg.get("imported");
1027
+ if (imported.isIdentifier()) imports.add({
1028
+ declaration: importDeclaration,
1029
+ specifier: arg,
1030
+ imported: imported.node.name,
1031
+ local: arg.node.local.name,
1032
+ source: importDeclaration.node.source.value,
1033
+ type: "ImportSpecifier"
1034
+ });
1035
+ return true;
1036
+ }
1037
+ imports.add({
1038
+ declaration: importDeclaration,
1039
+ specifier: arg,
1040
+ local: arg.node.local.name,
1041
+ source: importDeclaration.node.source.value,
1042
+ type: "ImportDefaultSpecifier"
1043
+ });
1044
+ return true;
1045
+ }
1046
+ //#endregion
1047
+ //#region src/js/NodePathWalker.ts
1048
+ const EMPTY_IGNORE_CALL_EXPRESSION_IDENTIFIERS = [];
1049
+ const EMPTY_IMPORT_TOKENS = /* @__PURE__ */ new Set();
1050
+ function NOOP_STRING_PATH_CALLBACK() {}
1051
+ const NEVER_MATCH_NAME = () => false;
1052
+ /**
1053
+ * 遍历我们关注的调用表达式所关联的绑定,收集后续需要转换的字符串节点。
1054
+ */
1055
+ var NodePathWalker = class {
1056
+ constructor({ ignoreCallExpressionIdentifiers, callback } = {}) {
1057
+ _defineProperty(this, "ignoreCallExpressionIdentifiers", void 0);
1058
+ _defineProperty(this, "callback", void 0);
1059
+ _defineProperty(this, "isIgnoredCallIdentifier", void 0);
1060
+ _defineProperty(this, "hasIgnoredCallIdentifiers", void 0);
1061
+ _defineProperty(this, "importsStore", void 0);
1062
+ _defineProperty(this, "visitedStore", void 0);
1063
+ this.hasIgnoredCallIdentifiers = Boolean(ignoreCallExpressionIdentifiers && ignoreCallExpressionIdentifiers.length > 0);
1064
+ this.ignoreCallExpressionIdentifiers = ignoreCallExpressionIdentifiers ?? EMPTY_IGNORE_CALL_EXPRESSION_IDENTIFIERS;
1065
+ this.callback = callback ?? NOOP_STRING_PATH_CALLBACK;
1066
+ this.isIgnoredCallIdentifier = this.hasIgnoredCallIdentifiers ? createNameMatcher(this.ignoreCallExpressionIdentifiers, { exact: true }) : NEVER_MATCH_NAME;
1067
+ }
1068
+ get imports() {
1069
+ return this.importsStore ?? EMPTY_IMPORT_TOKENS;
1070
+ }
1071
+ getWritableImports() {
1072
+ if (!this.importsStore) this.importsStore = /* @__PURE__ */ new Set();
1073
+ return this.importsStore;
1074
+ }
1075
+ addImportToken(token) {
1076
+ this.getWritableImports().add(token);
1077
+ }
1078
+ getVisited() {
1079
+ if (!this.visitedStore) this.visitedStore = /* @__PURE__ */ new WeakSet();
1080
+ return this.visitedStore;
1081
+ }
1082
+ walkVariableDeclarator(path) {
1083
+ const init = path.get("init");
1084
+ this.walkNode(init);
1085
+ }
1086
+ walkTemplateLiteral(path) {
1087
+ for (const exp of path.get("expressions")) this.walkNode(exp);
1088
+ for (const quasis of path.get("quasis")) this.callback(quasis);
1089
+ }
1090
+ walkStringLiteral(path) {
1091
+ this.callback(path);
1092
+ }
1093
+ walkBinaryExpression(path) {
1094
+ const left = path.get("left");
1095
+ this.walkNode(left);
1096
+ const right = path.get("right");
1097
+ this.walkNode(right);
1098
+ }
1099
+ walkLogicalExpression(path) {
1100
+ const left = path.get("left");
1101
+ this.walkNode(left);
1102
+ const right = path.get("right");
1103
+ this.walkNode(right);
1104
+ }
1105
+ walkObjectExpression(path) {
1106
+ const props = path.get("properties");
1107
+ for (const prop of props) if (prop.isObjectProperty()) {
1108
+ const key = prop.get("key");
1109
+ this.walkNode(key);
1110
+ const value = prop.get("value");
1111
+ this.walkNode(value);
1112
+ }
1113
+ }
1114
+ walkArrayExpression(path) {
1115
+ const elements = path.get("elements");
1116
+ for (const element of elements) this.walkNode(element);
1117
+ }
1118
+ walkNode(arg) {
1119
+ const visited = this.getVisited();
1120
+ if (visited.has(arg)) return;
1121
+ visited.add(arg);
1122
+ if (arg.isIdentifier()) {
1123
+ const binding = arg?.scope?.getBinding?.(arg.node.name);
1124
+ if (binding) this.walkNode(binding.path);
1125
+ } else if (arg.isMemberExpression()) {
1126
+ const objectPath = arg.get("object");
1127
+ if (objectPath.isIdentifier()) {
1128
+ const binding = arg?.scope?.getBinding?.(objectPath.node.name);
1129
+ if (binding) {
1130
+ if (binding.path.isVariableDeclarator()) this.walkVariableDeclarator(binding.path);
1131
+ }
1132
+ }
1133
+ } else if (arg.isTemplateLiteral()) this.walkTemplateLiteral(arg);
1134
+ else if (arg.isStringLiteral()) this.walkStringLiteral(arg);
1135
+ else if (arg.isBinaryExpression()) this.walkBinaryExpression(arg);
1136
+ else if (arg.isLogicalExpression()) this.walkLogicalExpression(arg);
1137
+ else if (arg.isObjectExpression()) this.walkObjectExpression(arg);
1138
+ else if (arg.isArrayExpression()) this.walkArrayExpression(arg);
1139
+ else if (arg.isVariableDeclarator()) this.walkVariableDeclarator(arg);
1140
+ else if (maybeAddImportToken(this.getWritableImports(), arg)) {}
1141
+ }
1142
+ /**
1143
+ * Walk the arguments of a desired call expression so their bindings can be analysed.
1144
+ */
1145
+ walkCallExpression(path) {
1146
+ if (!this.hasIgnoredCallIdentifiers) return;
1147
+ const calleePath = path.get("callee");
1148
+ if (calleePath.isIdentifier() && this.isIgnoredCallIdentifier(calleePath.node.name)) for (const arg of path.get("arguments")) this.walkNode(arg);
1149
+ }
1150
+ walkExportDeclaration(path) {
1151
+ walkExportDeclaration(this, path);
1152
+ }
1153
+ walkExportNamedDeclaration(path) {
1154
+ walkExportNamedDeclaration(this, path);
1155
+ }
1156
+ walkExportDefaultDeclaration(path) {
1157
+ walkExportDefaultDeclaration(this, path);
1158
+ }
1159
+ walkExportAllDeclaration(path) {
1160
+ walkExportAllDeclaration(this, path);
1161
+ }
1162
+ };
1163
+ //#endregion
1164
+ //#region src/js/taggedTemplateIgnore.ts
1165
+ function createTaggedTemplateIgnore({ matcher, names }) {
1166
+ const bindingIgnoreCache = /* @__PURE__ */ new Map();
1167
+ const taggedTemplateIgnoreCache = /* @__PURE__ */ new WeakMap();
1168
+ const seenBindings = /* @__PURE__ */ new Set();
1169
+ let singleCanonicalIgnoreName;
1170
+ let canonicalIgnoreNames;
1171
+ for (const item of names ?? []) {
1172
+ if (typeof item !== "string") continue;
1173
+ if (singleCanonicalIgnoreName === void 0) {
1174
+ singleCanonicalIgnoreName = item;
1175
+ continue;
1176
+ }
1177
+ if (item === singleCanonicalIgnoreName) continue;
1178
+ if (!canonicalIgnoreNames) {
1179
+ canonicalIgnoreNames = /* @__PURE__ */ new Set([singleCanonicalIgnoreName, item]);
1180
+ continue;
1181
+ }
1182
+ canonicalIgnoreNames.add(item);
1183
+ }
1184
+ const hasCanonicalIgnoreNames = singleCanonicalIgnoreName !== void 0;
1185
+ const matchesIgnoreName = (value) => {
1186
+ if (hasCanonicalIgnoreNames) {
1187
+ if (canonicalIgnoreNames) {
1188
+ if (canonicalIgnoreNames.has(value)) return true;
1189
+ } else if (value === singleCanonicalIgnoreName) return true;
1190
+ }
1191
+ return matcher(value);
1192
+ };
1193
+ const propertyMatches = (propertyPath) => {
1194
+ if (!propertyPath) return false;
1195
+ if (propertyPath.isIdentifier()) return matchesIgnoreName(propertyPath.node.name);
1196
+ if (propertyPath.isStringLiteral()) return matchesIgnoreName(propertyPath.node.value);
1197
+ return false;
1198
+ };
1199
+ const resolvesMemberExpressionToIgnore = (path, seen) => {
1200
+ const propertyPath = path.get("property");
1201
+ if (propertyMatches(propertyPath)) return true;
1202
+ const objectPath = path.get("object");
1203
+ if (objectPath.isIdentifier()) {
1204
+ const binding = (objectPath?.scope)?.getBinding?.(objectPath.node.name);
1205
+ if (binding) return resolvesToWeappTwIgnore(binding, seen);
1206
+ }
1207
+ return false;
1208
+ };
1209
+ const resolvesToWeappTwIgnore = (binding, seen) => {
1210
+ const cached = bindingIgnoreCache.get(binding);
1211
+ if (cached !== void 0) return cached;
1212
+ if (seen.has(binding)) return false;
1213
+ seen.add(binding);
1214
+ let result = false;
1215
+ const bindingPath = binding.path;
1216
+ if (bindingPath.isImportSpecifier()) {
1217
+ const imported = bindingPath.node.imported;
1218
+ if (imported.type === "Identifier" && matchesIgnoreName(imported.name)) result = true;
1219
+ else if (imported.type === "StringLiteral" && matchesIgnoreName(imported.value)) result = true;
1220
+ } else if (bindingPath.isVariableDeclarator()) {
1221
+ const init = bindingPath.get("init");
1222
+ if (init && init.node) {
1223
+ if (init.isIdentifier()) {
1224
+ const target = binding?.scope?.getBinding?.(init.node.name);
1225
+ if (target) result = resolvesToWeappTwIgnore(target, seen);
1226
+ } else if (init.isMemberExpression()) result = resolvesMemberExpressionToIgnore(init, seen);
1227
+ }
1228
+ }
1229
+ bindingIgnoreCache.set(binding, result);
1230
+ seen.delete(binding);
1231
+ return result;
1232
+ };
1233
+ const getEffectiveTagPath = (tagPath) => {
1234
+ let current = tagPath;
1235
+ while (true) {
1236
+ if (current.isParenthesizedExpression?.() || current.node.type === "ParenthesizedExpression") {
1237
+ current = current.get("expression");
1238
+ continue;
1239
+ }
1240
+ if (current.isTSAsExpression() || current.isTSTypeAssertion()) {
1241
+ current = current.get("expression");
1242
+ continue;
1243
+ }
1244
+ if (current.isTSNonNullExpression()) {
1245
+ current = current.get("expression");
1246
+ continue;
1247
+ }
1248
+ if (current.isTypeCastExpression?.()) {
1249
+ current = current.get("expression");
1250
+ continue;
1251
+ }
1252
+ if (current.isSequenceExpression()) {
1253
+ const last = current.get("expressions").at(-1);
1254
+ if (last) {
1255
+ current = last;
1256
+ continue;
1257
+ }
1258
+ }
1259
+ if (current.isCallExpression?.() || current.node.type === "CallExpression") {
1260
+ current = current.get("callee");
1261
+ continue;
1262
+ }
1263
+ break;
1264
+ }
1265
+ return current;
1266
+ };
1267
+ const evaluateTagPath = (tagPath, seen) => {
1268
+ if (tagPath.isCallExpression?.() || tagPath.node.type === "CallExpression") {
1269
+ const calleePath = tagPath.get("callee");
1270
+ return evaluateTagPath(calleePath, seen);
1271
+ }
1272
+ if (tagPath.isIdentifier()) {
1273
+ if (matchesIgnoreName(tagPath.node.name)) return true;
1274
+ const binding = tagPath?.scope?.getBinding?.(tagPath.node.name);
1275
+ if (binding) return resolvesToWeappTwIgnore(binding, seen);
1276
+ return false;
1277
+ }
1278
+ if (tagPath.isMemberExpression()) return resolvesMemberExpressionToIgnore(tagPath, seen);
1279
+ return false;
1280
+ };
1281
+ const computeIgnore = (tagPath) => {
1282
+ const cached = taggedTemplateIgnoreCache.get(tagPath.node);
1283
+ if (cached !== void 0) return cached;
1284
+ const effectiveTagPath = getEffectiveTagPath(tagPath);
1285
+ const effectiveCached = taggedTemplateIgnoreCache.get(effectiveTagPath.node);
1286
+ if (effectiveCached !== void 0) {
1287
+ taggedTemplateIgnoreCache.set(tagPath.node, effectiveCached);
1288
+ return effectiveCached;
1289
+ }
1290
+ seenBindings.clear();
1291
+ const result = evaluateTagPath(effectiveTagPath, seenBindings);
1292
+ taggedTemplateIgnoreCache.set(effectiveTagPath.node, result);
1293
+ taggedTemplateIgnoreCache.set(tagPath.node, result);
1294
+ return result;
1295
+ };
1296
+ return {
1297
+ shouldIgnore(tagPath) {
1298
+ return computeIgnore(tagPath);
1299
+ },
1300
+ getEffectiveTagPath
1301
+ };
1302
+ }
1303
+ //#endregion
1304
+ //#region src/js/babel.ts
1305
+ const EXPRESSION_WRAPPER_PREFIX = "(\n";
1306
+ const EXPRESSION_WRAPPER_SUFFIX = "\n)";
1307
+ const EMPTY_IGNORED_PATHS = /* @__PURE__ */ new WeakSet();
1308
+ const EMPTY_IMPORT_DECLARATIONS = /* @__PURE__ */ new Set();
1309
+ const EMPTY_EXPORT_DECLARATIONS = /* @__PURE__ */ new Set();
1310
+ const EMPTY_REQUIRE_CALL_PATHS = [];
1311
+ const ignoredTaggedTemplateMatcherCache = /* @__PURE__ */ new WeakMap();
1312
+ let defaultEvalHandler;
1313
+ function getIgnoredTaggedTemplateMatcher(options) {
1314
+ const cached = ignoredTaggedTemplateMatcherCache.get(options);
1315
+ if (cached) return cached;
1316
+ const created = createNameMatcher(options.ignoreTaggedTemplateExpressionIdentifiers, { exact: true });
1317
+ ignoredTaggedTemplateMatcherCache.set(options, created);
1318
+ return created;
1319
+ }
1320
+ function getDefaultEvalHandler() {
1321
+ if (!defaultEvalHandler) throw new Error("Default JS eval handler is not initialized.");
1322
+ return defaultEvalHandler;
1323
+ }
1324
+ function analyzeSource(ast, options, handler, collectModuleMetadata = true) {
1325
+ const jsTokenUpdater = new JsTokenUpdater();
1326
+ const needScope = Boolean(options.ignoreCallExpressionIdentifiers && options.ignoreCallExpressionIdentifiers.length > 0);
1327
+ const ignoredPaths = needScope ? /* @__PURE__ */ new WeakSet() : EMPTY_IGNORED_PATHS;
1328
+ const walker = needScope ? new NodePathWalker({
1329
+ ...options.ignoreCallExpressionIdentifiers === void 0 ? {} : { ignoreCallExpressionIdentifiers: options.ignoreCallExpressionIdentifiers },
1330
+ callback(path) {
1331
+ ignoredPaths.add(path);
1332
+ }
1333
+ }) : new NodePathWalker();
1334
+ let taggedTemplateIgnore;
1335
+ const hasTaggedTemplateIgnoreIdentifiers = Boolean(options.ignoreTaggedTemplateExpressionIdentifiers && options.ignoreTaggedTemplateExpressionIdentifiers.length > 0);
1336
+ function getTaggedTemplateIgnore() {
1337
+ if (!taggedTemplateIgnore) taggedTemplateIgnore = createTaggedTemplateIgnore({
1338
+ matcher: getIgnoredTaggedTemplateMatcher(options),
1339
+ ...options.ignoreTaggedTemplateExpressionIdentifiers === void 0 ? {} : { names: options.ignoreTaggedTemplateExpressionIdentifiers }
1340
+ });
1341
+ return taggedTemplateIgnore;
1342
+ }
1343
+ const targetPaths = [];
1344
+ const importDeclarations = collectModuleMetadata ? /* @__PURE__ */ new Set() : EMPTY_IMPORT_DECLARATIONS;
1345
+ const exportDeclarations = collectModuleMetadata ? /* @__PURE__ */ new Set() : EMPTY_EXPORT_DECLARATIONS;
1346
+ const requireCallPaths = collectModuleMetadata ? [] : EMPTY_REQUIRE_CALL_PATHS;
1347
+ const evalHandler = handler ?? getDefaultEvalHandler();
1348
+ const traverseOptions = {
1349
+ StringLiteral: { enter(p) {
1350
+ if (isEvalPath(p.parentPath)) return;
1351
+ targetPaths.push(p);
1352
+ } },
1353
+ TemplateElement: { enter: hasTaggedTemplateIgnoreIdentifiers ? (p) => {
1354
+ const pp = p.parentPath;
1355
+ if (pp.isTemplateLiteral()) {
1356
+ const ppp = pp.parentPath;
1357
+ if (isEvalPath(ppp)) return;
1358
+ if (ppp.isTaggedTemplateExpression()) {
1359
+ const tagPath = ppp.get("tag");
1360
+ if (getTaggedTemplateIgnore().shouldIgnore(tagPath)) return;
1361
+ }
1362
+ }
1363
+ targetPaths.push(p);
1364
+ } : (p) => {
1365
+ const pp = p.parentPath;
1366
+ if (pp.isTemplateLiteral()) {
1367
+ const ppp = pp.parentPath;
1368
+ if (isEvalPath(ppp)) return;
1369
+ }
1370
+ targetPaths.push(p);
1371
+ } },
1372
+ CallExpression: { enter: !collectModuleMetadata && !needScope ? (p) => {
1373
+ if (isEvalPath(p)) walkEvalExpression(p, options, jsTokenUpdater, evalHandler);
1374
+ } : (p) => {
1375
+ if (isEvalPath(p)) {
1376
+ walkEvalExpression(p, options, jsTokenUpdater, evalHandler);
1377
+ return;
1378
+ }
1379
+ const calleePath = p.get("callee");
1380
+ if (collectModuleMetadata && calleePath.isIdentifier({ name: "require" }) && !p?.scope?.hasBinding?.("require")) {
1381
+ const args = p.get("arguments");
1382
+ if (Array.isArray(args) && args.length > 0) {
1383
+ const first = args[0];
1384
+ if (first?.isStringLiteral()) requireCallPaths.push(first);
1385
+ }
1386
+ }
1387
+ if (needScope) walker.walkCallExpression(p);
1388
+ } },
1389
+ ...collectModuleMetadata ? {
1390
+ ImportDeclaration: { enter(p) {
1391
+ importDeclarations.add(p);
1392
+ } },
1393
+ ExportDeclaration: { enter(p) {
1394
+ exportDeclarations.add(p);
1395
+ } }
1396
+ } : {}
1397
+ };
1398
+ traverse(ast, {
1399
+ ...traverseOptions,
1400
+ noScope: !needScope
1401
+ });
1402
+ return {
1403
+ walker,
1404
+ jsTokenUpdater,
1405
+ ast,
1406
+ targetPaths,
1407
+ importDeclarations,
1408
+ exportDeclarations,
1409
+ requireCallPaths,
1410
+ ignoredPaths
1411
+ };
1412
+ }
1413
+ function jsHandler(rawSource, options) {
1414
+ const shouldWrapExpression = Boolean(options.wrapExpression);
1415
+ const source = shouldWrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
1416
+ let ast;
1417
+ try {
1418
+ ast = babelParse(source, options.babelParserOptions);
1419
+ } catch (error) {
1420
+ return {
1421
+ code: rawSource,
1422
+ error
1423
+ };
1424
+ }
1425
+ const needsModuleMetadata = Boolean(options.moduleSpecifierReplacements || options.moduleGraph && options.filename);
1426
+ const analysis = analyzeSource(ast, options, jsHandler, needsModuleMetadata);
1427
+ const ms = processUpdatedSource(source, options, analysis);
1428
+ if (shouldWrapExpression) {
1429
+ const start = 0;
1430
+ const end = source.length;
1431
+ const suffixLength = 2;
1432
+ ms.remove(start, 2);
1433
+ ms.remove(end - suffixLength, end);
1434
+ }
1435
+ const result = { code: ms.toString() };
1436
+ if (options.generateMap) Object.defineProperty(result, "map", {
1437
+ configurable: true,
1438
+ enumerable: true,
1439
+ get() {
1440
+ return ms.generateMap();
1441
+ }
1442
+ });
1443
+ if (options.moduleGraph && options.filename) {
1444
+ const linked = new JsModuleGraph({
1445
+ filename: options.filename,
1446
+ source: rawSource,
1447
+ analysis,
1448
+ handlerOptions: options
1449
+ }, options.moduleGraph).build();
1450
+ if (linked) result.linked = linked;
1451
+ }
1452
+ return result;
1453
+ }
1454
+ defaultEvalHandler = jsHandler;
1455
+ //#endregion
1456
+ //#region src/wxml/custom-attributes.ts
1457
+ function regTest(reg, str) {
1458
+ reg.lastIndex = 0;
1459
+ return reg.test(str);
1460
+ }
1461
+ function isPropsMatch(props, attr) {
1462
+ if (Array.isArray(props)) {
1463
+ let lowerAttr;
1464
+ for (const prop of props) if (typeof prop === "string") {
1465
+ lowerAttr ?? (lowerAttr = attr.toLowerCase());
1466
+ if (prop.toLowerCase() === lowerAttr) return true;
1467
+ } else if (regTest(prop, attr)) return true;
1468
+ return false;
1469
+ } else if (typeof props === "string") return props === attr;
1470
+ else return regTest(props, attr);
1471
+ }
1472
+ function createAttributeMatcher(entities) {
1473
+ if (!entities || entities.length === 0) return;
1474
+ const wildcardAttributeRules = [];
1475
+ const tagAttributeRuleMap = /* @__PURE__ */ new Map();
1476
+ const regexpAttributeRules = [];
1477
+ for (const [selector, props] of entities) if (selector === "*") wildcardAttributeRules.push(props);
1478
+ else if (typeof selector === "string") {
1479
+ const list = tagAttributeRuleMap.get(selector);
1480
+ if (list) list.push(props);
1481
+ else tagAttributeRuleMap.set(selector, [props]);
1482
+ } else regexpAttributeRules.push([selector, props]);
1483
+ return (tag, attr) => {
1484
+ for (const props of wildcardAttributeRules) if (isPropsMatch(props, attr)) return true;
1485
+ const tagRules = tagAttributeRuleMap.get(tag);
1486
+ if (tagRules) {
1487
+ for (const props of tagRules) if (isPropsMatch(props, attr)) return true;
1488
+ }
1489
+ for (const [selector, props] of regexpAttributeRules) if (regTest(selector, tag) && isPropsMatch(props, attr)) return true;
1490
+ return false;
1491
+ };
1492
+ }
1493
+ //#endregion
1494
+ //#region src/compiler/artifact.ts
1495
+ function createCssFragment(options) {
1496
+ return {
1497
+ id: options.id,
1498
+ kind: options.kind,
1499
+ root: postcss.parse(options.css, { from: options.sourceId }),
1500
+ sourceId: options.sourceId,
1501
+ scope: options.scope,
1502
+ order: options.order ?? 0,
1503
+ stage: options.stage ?? "raw"
1504
+ };
1505
+ }
1506
+ function cloneCssFragment(fragment) {
1507
+ return {
1508
+ ...fragment,
1509
+ root: fragment.root.clone(),
1510
+ scope: { ...fragment.scope }
1511
+ };
1512
+ }
1513
+ function cloneGenerationArtifact(artifact) {
1514
+ return {
1515
+ fragments: artifact.fragments.map(cloneCssFragment),
1516
+ classSet: new Set(artifact.classSet),
1517
+ rawCandidates: new Set(artifact.rawCandidates),
1518
+ dependencies: [...artifact.dependencies],
1519
+ sourceEntries: [...artifact.sourceEntries],
1520
+ ...artifact.revision === void 0 ? {} : { revision: artifact.revision }
1521
+ };
1522
+ }
1523
+ function createGenerationArtifact(fragments, options) {
1524
+ return cloneGenerationArtifact({
1525
+ fragments,
1526
+ ...options
1527
+ });
1528
+ }
1529
+ //#endregion
1530
+ //#region src/compiler/candidate-index.ts
1531
+ var CandidateIndex = class {
1532
+ constructor() {
1533
+ _defineProperty(this, "candidatesBySource", /* @__PURE__ */ new Map());
1534
+ }
1535
+ sync(sourceId, candidates) {
1536
+ const previous = this.candidatesBySource.get(sourceId) ?? /* @__PURE__ */ new Set();
1537
+ const next = new Set(candidates);
1538
+ const addedCandidates = new Set([...next].filter((candidate) => !previous.has(candidate)));
1539
+ const removedCandidates = new Set([...previous].filter((candidate) => !next.has(candidate)));
1540
+ this.candidatesBySource.set(sourceId, next);
1541
+ return {
1542
+ sourceId,
1543
+ addedCandidates,
1544
+ removedCandidates
1545
+ };
1546
+ }
1547
+ remove(sourceId) {
1548
+ const previous = this.candidatesBySource.get(sourceId) ?? /* @__PURE__ */ new Set();
1549
+ this.candidatesBySource.delete(sourceId);
1550
+ return {
1551
+ sourceId,
1552
+ addedCandidates: /* @__PURE__ */ new Set(),
1553
+ removedCandidates: new Set(previous)
1554
+ };
1555
+ }
1556
+ values() {
1557
+ const values = /* @__PURE__ */ new Set();
1558
+ for (const candidates of this.candidatesBySource.values()) for (const candidate of candidates) values.add(candidate);
1559
+ return values;
1560
+ }
1561
+ get(sourceId) {
1562
+ return new Set(this.candidatesBySource.get(sourceId) ?? []);
1563
+ }
1564
+ entries() {
1565
+ return new Map([...this.candidatesBySource].map(([sourceId, candidates]) => [sourceId, new Set(candidates)]));
1566
+ }
1567
+ clear() {
1568
+ this.candidatesBySource.clear();
1569
+ }
1570
+ };
1571
+ //#endregion
1572
+ //#region src/compiler/compilation-scope-graph.ts
1573
+ function sourceNodeId(sourceId) {
1574
+ return `source:${sourceId}`;
1575
+ }
1576
+ function dependencyNodeId(dependencyId) {
1577
+ return `dependency:${dependencyId}`;
1578
+ }
1579
+ function createCompilationDependencyChanges(dependencyIds, type = "dependency-changed") {
1580
+ return [...new Set(dependencyIds)].map((id) => ({
1581
+ id,
1582
+ type
1583
+ }));
1584
+ }
1585
+ function mergeCompilationDependencyChanges(...groups) {
1586
+ const changes = /* @__PURE__ */ new Map();
1587
+ for (const group of groups) for (const change of group ?? []) {
1588
+ const previous = changes.get(change.id);
1589
+ changes.set(change.id, {
1590
+ id: change.id,
1591
+ type: previous?.type === "config-changed" ? previous.type : change.type
1592
+ });
1593
+ }
1594
+ return [...changes.values()];
1595
+ }
1596
+ function mergeCompilationScopeDependencies(...groups) {
1597
+ const dependencies = /* @__PURE__ */ new Map();
1598
+ for (const group of groups) for (const dependency of group ?? []) {
1599
+ const previous = dependencies.get(dependency.id);
1600
+ if (previous && previous.kind !== dependency.kind) throw new Error(`同一个依赖不能对应不同类型:${dependency.id}`);
1601
+ dependencies.set(dependency.id, { ...dependency });
1602
+ }
1603
+ return [...dependencies.values()];
1604
+ }
1605
+ function dependencySignature(source) {
1606
+ return mergeCompilationScopeDependencies(source.dependencies).map((dependency) => `${dependency.kind}\0${dependency.id}`).sort().join("\0");
1607
+ }
1608
+ function createCompilationScopeGraph(scope, outputId, sources) {
1609
+ const normalizedSources = [...sources].map((source) => ({
1610
+ ...source,
1611
+ dependencies: mergeCompilationScopeDependencies(source.dependencies)
1612
+ }));
1613
+ const dependencies = mergeCompilationScopeDependencies(...normalizedSources.map((source) => source.dependencies));
1614
+ const outputNodeId = `asset:${outputId}`;
1615
+ return {
1616
+ nodes: [
1617
+ ...normalizedSources.map((source) => ({
1618
+ id: sourceNodeId(source.id),
1619
+ kind: source.kind,
1620
+ scope: { ...scope },
1621
+ ...source.content === void 0 ? {} : { content: source.content }
1622
+ })),
1623
+ ...dependencies.map((dependency) => ({
1624
+ id: dependencyNodeId(dependency.id),
1625
+ kind: dependency.kind,
1626
+ scope: { ...scope }
1627
+ })),
1628
+ {
1629
+ id: outputNodeId,
1630
+ kind: "asset",
1631
+ scope: { ...scope }
1632
+ }
1633
+ ],
1634
+ edges: normalizedSources.flatMap((source) => [{
1635
+ from: sourceNodeId(source.id),
1636
+ to: outputNodeId,
1637
+ kind: "emits-to"
1638
+ }, ...source.dependencies.map((dependency) => ({
1639
+ from: sourceNodeId(source.id),
1640
+ to: dependencyNodeId(dependency.id),
1641
+ kind: "depends-on"
1642
+ }))])
1643
+ };
1644
+ }
1645
+ function createCompilationScopeSnapshot(scope, outputId, sources, options = {}) {
1646
+ const normalizedSources = [...sources];
1647
+ return {
1648
+ ...createCompilationScopeGraph(scope, outputId, normalizedSources),
1649
+ candidatesBySource: normalizedSources.map((source) => [sourceNodeId(source.id), source.candidates]),
1650
+ ...options.changes === void 0 ? {} : { changes: options.changes },
1651
+ ...options.preserveDeletedCss === void 0 ? {} : { preserveDeletedCss: options.preserveDeletedCss },
1652
+ ...options.validatedClassSet === void 0 ? {} : { validatedClassSet: options.validatedClassSet }
1653
+ };
1654
+ }
1655
+ //#endregion
1656
+ //#region src/compiler/compilation-dependency-state.ts
1657
+ var CompilationDependencyState = class {
1658
+ constructor() {
1659
+ _defineProperty(this, "revisions", /* @__PURE__ */ new Map());
1660
+ }
1661
+ getAffectedScopes(entries, changes) {
1662
+ return new Set(this.getAffectedScopeChanges(entries, changes).keys());
1663
+ }
1664
+ getAffectedScopeChanges(entries, changes) {
1665
+ const changesByNodeId = new Map([...changes].map((change) => [dependencyNodeId(change.id), change]));
1666
+ const affectedScopeChanges = /* @__PURE__ */ new Map();
1667
+ for (const entry of entries) {
1668
+ const scopeChanges = entry.latest?.graphNodes.map((node) => changesByNodeId.get(node.id)).filter((change) => change !== void 0);
1669
+ if (scopeChanges && scopeChanges.length > 0) affectedScopeChanges.set(entry.scope.id, scopeChanges.map((change) => ({ ...change })));
1670
+ }
1671
+ return affectedScopeChanges;
1672
+ }
1673
+ record(entries, changes) {
1674
+ const affectedScopes = this.getAffectedScopes(entries, changes);
1675
+ this.recordScopes(affectedScopes);
1676
+ return affectedScopes;
1677
+ }
1678
+ recordScopes(scopeIds) {
1679
+ for (const scopeId of scopeIds) this.revisions.set(scopeId, (this.revisions.get(scopeId) ?? 0) + 1);
1680
+ }
1681
+ getRevision(scopeId) {
1682
+ return this.revisions.get(scopeId) ?? 0;
1683
+ }
1684
+ delete(scopeId) {
1685
+ this.revisions.delete(scopeId);
1686
+ }
1687
+ clear() {
1688
+ this.revisions.clear();
1689
+ }
1690
+ };
1691
+ //#endregion
1692
+ //#region src/compiler/compiler-owner-state.ts
1693
+ const compilerOwnerDisposals = /* @__PURE__ */ new WeakMap();
1694
+ const compilerOwnerActivities = /* @__PURE__ */ new WeakMap();
1695
+ function ensureCompilerOwnerActive(owner) {
1696
+ if (compilerOwnerDisposals.has(owner)) throw new Error("Compiler owner 正在释放,不能创建新的编译状态。");
1697
+ }
1698
+ function acquireCompilerOwnerActivity(owner) {
1699
+ const currentDisposal = compilerOwnerDisposals.get(owner);
1700
+ if (currentDisposal) return currentDisposal.then(() => acquireCompilerOwnerActivity(owner));
1701
+ let state = compilerOwnerActivities.get(owner);
1702
+ if (!state) {
1703
+ state = {
1704
+ active: 0,
1705
+ idleWaiters: /* @__PURE__ */ new Set()
1706
+ };
1707
+ compilerOwnerActivities.set(owner, state);
1708
+ }
1709
+ state.active += 1;
1710
+ let released = false;
1711
+ return () => {
1712
+ if (released) return;
1713
+ released = true;
1714
+ state.active -= 1;
1715
+ if (state.active > 0) return;
1716
+ compilerOwnerActivities.delete(owner);
1717
+ for (const resolve of state.idleWaiters) resolve();
1718
+ state.idleWaiters.clear();
1719
+ };
1720
+ }
1721
+ function waitForCompilerOwnerIdle(owner) {
1722
+ const state = compilerOwnerActivities.get(owner);
1723
+ if (!state || state.active === 0) return Promise.resolve();
1724
+ return new Promise((resolve) => {
1725
+ state.idleWaiters.add(resolve);
1726
+ });
1727
+ }
1728
+ function runCompilerOwnerActivity(owner, activity) {
1729
+ const acquired = acquireCompilerOwnerActivity(owner);
1730
+ if (typeof acquired !== "function") return acquired.then((release) => runCompilerOwnerActivityWithRelease(activity, release));
1731
+ return runCompilerOwnerActivityWithRelease(activity, acquired);
1732
+ }
1733
+ function runCompilerOwnerActivityWithRelease(activity, release) {
1734
+ try {
1735
+ return Promise.resolve(activity()).finally(release);
1736
+ } catch (error) {
1737
+ release();
1738
+ return Promise.reject(error);
1739
+ }
1740
+ }
1741
+ function runCompilerOwnerDisposal(owner, dispose) {
1742
+ const currentDisposal = compilerOwnerDisposals.get(owner);
1743
+ if (currentDisposal) return currentDisposal;
1744
+ const disposal = Promise.resolve().then(async () => {
1745
+ await waitForCompilerOwnerIdle(owner);
1746
+ await dispose();
1747
+ }).finally(() => {
1748
+ if (compilerOwnerDisposals.get(owner) === disposal) compilerOwnerDisposals.delete(owner);
1749
+ });
1750
+ compilerOwnerDisposals.set(owner, disposal);
1751
+ return disposal;
1752
+ }
1753
+ //#endregion
1754
+ //#region src/compiler/invalidation.ts
1755
+ function resolveInvalidatedScopes(graph, changes) {
1756
+ const invalidatedScopes = /* @__PURE__ */ new Set();
1757
+ const visit = (sourceId, visited) => {
1758
+ if (visited.has(sourceId)) return;
1759
+ visited.add(sourceId);
1760
+ const node = graph.getNode(sourceId);
1761
+ if (node) invalidatedScopes.add(node.scope.id);
1762
+ for (const dependent of graph.getDependents(sourceId)) visit(dependent, visited);
1763
+ };
1764
+ for (const change of changes) visit(change.sourceId, /* @__PURE__ */ new Set());
1765
+ return invalidatedScopes;
1766
+ }
1767
+ //#endregion
1768
+ //#region src/compiler/source-graph.ts
1769
+ var SourceGraph = class {
1770
+ constructor() {
1771
+ _defineProperty(this, "edges", /* @__PURE__ */ new Map());
1772
+ _defineProperty(this, "nodes", /* @__PURE__ */ new Map());
1773
+ }
1774
+ replace(nodes, edges) {
1775
+ this.clear();
1776
+ for (const node of nodes) this.nodes.set(node.id, {
1777
+ ...node,
1778
+ scope: { ...node.scope }
1779
+ });
1780
+ for (const edge of edges) {
1781
+ if (!this.nodes.has(edge.from) || !this.nodes.has(edge.to)) throw new Error(`编译图边引用了不存在的节点:${edge.from} -> ${edge.to}`);
1782
+ this.edges.set(this.edgeKey(edge), { ...edge });
1783
+ }
1784
+ }
1785
+ getNode(id) {
1786
+ const node = this.nodes.get(id);
1787
+ return node ? {
1788
+ ...node,
1789
+ scope: { ...node.scope }
1790
+ } : void 0;
1791
+ }
1792
+ getNodes() {
1793
+ return [...this.nodes.values()].map((node) => ({
1794
+ ...node,
1795
+ scope: { ...node.scope }
1796
+ }));
1797
+ }
1798
+ getEdges() {
1799
+ return [...this.edges.values()].map((edge) => ({ ...edge }));
1800
+ }
1801
+ getDependents(id) {
1802
+ return this.getEdges().filter((edge) => edge.to === id).map((edge) => edge.from);
1803
+ }
1804
+ clear() {
1805
+ this.edges.clear();
1806
+ this.nodes.clear();
1807
+ }
1808
+ edgeKey(edge) {
1809
+ return `${edge.kind}\0${edge.from}\0${edge.to}`;
1810
+ }
1811
+ };
1812
+ //#endregion
1813
+ //#region src/compiler/session.ts
1814
+ var DefaultCompilationSession = class {
1815
+ constructor() {
1816
+ _defineProperty(this, "candidateIndex", new CandidateIndex());
1817
+ _defineProperty(this, "graph", new SourceGraph());
1818
+ _defineProperty(this, "retainedCandidates", /* @__PURE__ */ new Set());
1819
+ _defineProperty(this, "validatedClassSet", /* @__PURE__ */ new Set());
1820
+ _defineProperty(this, "invalidatedScopes", /* @__PURE__ */ new Set());
1821
+ _defineProperty(this, "revision", 0);
1822
+ }
1823
+ update(snapshot) {
1824
+ const changes = [...snapshot.changes ?? []];
1825
+ const invalidatedScopes = resolveInvalidatedScopes(this.graph, changes);
1826
+ this.graph.replace(snapshot.nodes, snapshot.edges);
1827
+ for (const [sourceId, candidates] of snapshot.candidatesBySource ?? []) {
1828
+ const change = this.candidateIndex.sync(sourceId, candidates);
1829
+ if (change.addedCandidates.size > 0 || change.removedCandidates.size > 0) changes.push(change);
1830
+ }
1831
+ for (const change of changes) if ("type" in change && change.type === "source-removed") this.candidateIndex.remove(change.sourceId);
1832
+ const currentCandidates = this.candidateIndex.values();
1833
+ if (snapshot.preserveDeletedCss) for (const candidate of currentCandidates) this.retainedCandidates.add(candidate);
1834
+ else {
1835
+ this.retainedCandidates.clear();
1836
+ for (const candidate of currentCandidates) this.retainedCandidates.add(candidate);
1837
+ }
1838
+ if (snapshot.validatedClassSet !== void 0) this.validatedClassSet = new Set(snapshot.validatedClassSet);
1839
+ else if (!snapshot.preserveDeletedCss) this.validatedClassSet = new Set([...this.validatedClassSet].filter((candidate) => this.retainedCandidates.has(candidate)));
1840
+ this.revision += 1;
1841
+ for (const scopeId of resolveInvalidatedScopes(this.graph, changes)) invalidatedScopes.add(scopeId);
1842
+ this.invalidatedScopes = invalidatedScopes;
1843
+ return this.createResult();
1844
+ }
1845
+ commitValidation(revision, validatedClassSet, graph) {
1846
+ if (revision !== this.revision) throw new Error(`不能向编译 revision ${this.revision} 提交 revision ${revision} 的 classSet。`);
1847
+ if (graph) this.graph.replace(graph.nodes, graph.edges);
1848
+ this.validatedClassSet = new Set(validatedClassSet);
1849
+ return this.createResult();
1850
+ }
1851
+ createResult() {
1852
+ return {
1853
+ revision: this.revision,
1854
+ candidates: new Set(this.retainedCandidates),
1855
+ candidatesBySource: this.candidateIndex.entries(),
1856
+ validatedClassSet: new Set(this.validatedClassSet),
1857
+ invalidatedScopes: new Set(this.invalidatedScopes),
1858
+ graphEdges: this.graph.getEdges(),
1859
+ graphNodes: this.graph.getNodes()
1860
+ };
1861
+ }
1862
+ dispose() {
1863
+ this.candidateIndex.clear();
1864
+ this.graph.clear();
1865
+ this.retainedCandidates.clear();
1866
+ this.validatedClassSet.clear();
1867
+ this.invalidatedScopes.clear();
1868
+ this.revision = 0;
1869
+ }
1870
+ };
1871
+ //#endregion
1872
+ //#region src/compiler/compilation-session-pool.ts
1873
+ const COMPILATION_SCOPE_CACHE_MAX = 128;
1874
+ function cloneScopeSource(source) {
1875
+ return {
1876
+ ...source,
1877
+ candidates: new Set(source.candidates),
1878
+ dependencies: source.dependencies?.map((dependency) => ({ ...dependency }))
1879
+ };
1880
+ }
1881
+ var CompilationSessionPool = class {
1882
+ constructor() {
1883
+ _defineProperty(this, "dependencyState", new CompilationDependencyState());
1884
+ _defineProperty(this, "entries", /* @__PURE__ */ new Map());
1885
+ _defineProperty(this, "disposed", false);
1886
+ }
1887
+ run(request, compile) {
1888
+ const entry = this.getEntry(request.scope);
1889
+ const execution = this.runEntry(entry, request, compile);
1890
+ entry.executions.add(execution);
1891
+ execution.then(() => entry.executions.delete(execution), () => entry.executions.delete(execution));
1892
+ return execution;
1893
+ }
1894
+ invalidateScope(scopeId) {
1895
+ const entry = this.entries.get(scopeId);
1896
+ if (!entry) return;
1897
+ entry.active = false;
1898
+ this.disposeEntry(entry);
1899
+ this.entries.delete(scopeId);
1900
+ this.dependencyState.delete(scopeId);
1901
+ }
1902
+ dispose() {
1903
+ if (this.disposed) return Promise.resolve();
1904
+ this.disposed = true;
1905
+ const entries = [...this.entries.values()];
1906
+ for (const entry of entries) entry.active = false;
1907
+ this.entries.clear();
1908
+ this.dependencyState.clear();
1909
+ return Promise.all(entries.map((entry) => this.disposeEntry(entry))).then(() => void 0);
1910
+ }
1911
+ get size() {
1912
+ return this.entries.size;
1913
+ }
1914
+ getAffectedScopes(changes) {
1915
+ return this.dependencyState.getAffectedScopes(this.entries.values(), changes);
1916
+ }
1917
+ getAffectedScopeChanges(changes) {
1918
+ return this.dependencyState.getAffectedScopeChanges(this.entries.values(), changes);
1919
+ }
1920
+ recordDependencyChanges(changes) {
1921
+ return this.dependencyState.record(this.entries.values(), changes);
1922
+ }
1923
+ recordAffectedScopes(scopeIds) {
1924
+ this.dependencyState.recordScopes(scopeIds);
1925
+ }
1926
+ getScopeDependencyRevision(scopeId) {
1927
+ return this.dependencyState.getRevision(scopeId);
1928
+ }
1929
+ getEntry(scope) {
1930
+ if (this.disposed) throw new Error("CompilationSessionPool 已释放。");
1931
+ const cached = this.entries.get(scope.id);
1932
+ if (cached) {
1933
+ if (cached.scope.kind !== scope.kind) throw new Error(`同一个 scope id 不能对应不同类型:${scope.id}`);
1934
+ this.entries.delete(scope.id);
1935
+ this.entries.set(scope.id, cached);
1936
+ return cached;
1937
+ }
1938
+ const entry = {
1939
+ active: true,
1940
+ executions: /* @__PURE__ */ new Set(),
1941
+ pending: Promise.resolve(),
1942
+ scope: { ...scope },
1943
+ session: new DefaultCompilationSession(),
1944
+ generatedDependencies: /* @__PURE__ */ new Map(),
1945
+ sources: /* @__PURE__ */ new Map()
1946
+ };
1947
+ this.entries.set(scope.id, entry);
1948
+ while (this.entries.size > COMPILATION_SCOPE_CACHE_MAX) {
1949
+ const oldestScopeId = this.entries.keys().next().value;
1950
+ if (oldestScopeId === void 0 || oldestScopeId === scope.id) break;
1951
+ this.invalidateScope(oldestScopeId);
1952
+ }
1953
+ return entry;
1954
+ }
1955
+ async disposeEntry(entry) {
1956
+ await Promise.allSettled([...entry.executions]);
1957
+ await entry.pending;
1958
+ entry.session.dispose();
1959
+ }
1960
+ async runEntry(entry, request, compile) {
1961
+ const prepared = await this.enqueue(entry, () => this.prepareEntry(entry, request));
1962
+ const value = await compile(prepared.compilation);
1963
+ const validatedClassSet = request.preserveDeletedCss ? /* @__PURE__ */ new Set([...prepared.compilation.validatedClassSet, ...value?.classSet ?? []]) : new Set(value?.classSet ?? []);
1964
+ const generatedDependencies = value?.dependenciesBySource === void 0 ? void 0 : this.normalizeGeneratedDependencies(value.dependenciesBySource, prepared.sources);
1965
+ let committed = false;
1966
+ let committedCompilation;
1967
+ await this.enqueue(entry, () => {
1968
+ if (!entry.active || entry.latest?.revision !== prepared.compilation.revision) return;
1969
+ if (generatedDependencies) entry.generatedDependencies = generatedDependencies;
1970
+ entry.latest = entry.session.commitValidation(prepared.compilation.revision, validatedClassSet, createCompilationScopeGraph(request.scope, request.outputId, this.createGraphSources(prepared.sources, entry.generatedDependencies)));
1971
+ committedCompilation = this.toScopeState(entry.latest, prepared.sources);
1972
+ committed = true;
1973
+ });
1974
+ const compilation = committedCompilation ?? {
1975
+ ...prepared.compilation,
1976
+ validatedClassSet
1977
+ };
1978
+ return committed ? {
1979
+ committed,
1980
+ compilation,
1981
+ value
1982
+ } : {
1983
+ committed,
1984
+ compilation
1985
+ };
1986
+ }
1987
+ prepareEntry(entry, request) {
1988
+ const nextSources = new Map(request.sources.map((source) => [source.id, cloneScopeSource(source)]));
1989
+ const changes = [...request.changes ?? []].map((change) => ({
1990
+ sourceId: dependencyNodeId(change.id),
1991
+ type: change.type
1992
+ }));
1993
+ for (const sourceId of entry.sources.keys()) if (!nextSources.has(sourceId)) changes.push({
1994
+ sourceId: sourceNodeId(sourceId),
1995
+ type: "source-removed"
1996
+ });
1997
+ for (const [sourceId, source] of nextSources) {
1998
+ const previous = entry.sources.get(sourceId);
1999
+ if (previous && (previous.content !== source.content || dependencySignature(previous) !== dependencySignature(source))) changes.push({
2000
+ sourceId: sourceNodeId(sourceId),
2001
+ type: "dependency-changed"
2002
+ });
2003
+ }
2004
+ entry.sources = nextSources;
2005
+ entry.generatedDependencies = new Map([...entry.generatedDependencies].filter(([sourceId]) => nextSources.has(sourceId)));
2006
+ entry.latest = entry.session.update(createCompilationScopeSnapshot(request.scope, request.outputId, this.createGraphSources(nextSources, entry.generatedDependencies), {
2007
+ changes,
2008
+ preserveDeletedCss: request.preserveDeletedCss
2009
+ }));
2010
+ return {
2011
+ compilation: this.toScopeState(entry.latest, nextSources),
2012
+ sources: nextSources
2013
+ };
2014
+ }
2015
+ createGraphSources(sources, generatedDependencies) {
2016
+ return [...sources.values()].map((source) => ({
2017
+ ...source,
2018
+ dependencies: mergeCompilationScopeDependencies(source.dependencies, generatedDependencies.get(source.id))
2019
+ }));
2020
+ }
2021
+ normalizeGeneratedDependencies(dependenciesBySource, sources) {
2022
+ const normalized = /* @__PURE__ */ new Map();
2023
+ for (const [sourceId, dependencies] of dependenciesBySource) {
2024
+ if (!sources.has(sourceId)) throw new Error(`生成结果引用了未知 source:${sourceId}`);
2025
+ normalized.set(sourceId, mergeCompilationScopeDependencies(normalized.get(sourceId), dependencies));
2026
+ }
2027
+ return normalized;
2028
+ }
2029
+ enqueue(entry, task) {
2030
+ const execution = entry.pending.then(task);
2031
+ entry.pending = execution.then(() => void 0, () => void 0);
2032
+ return execution;
2033
+ }
2034
+ toScopeState(compilation, sources) {
2035
+ return {
2036
+ ...compilation,
2037
+ candidatesBySource: new Map([...sources.keys()].map((sourceId) => [sourceId, compilation.candidatesBySource.get(sourceNodeId(sourceId)) ?? /* @__PURE__ */ new Set()]))
2038
+ };
2039
+ }
2040
+ };
2041
+ const compilationSessionPools = /* @__PURE__ */ new WeakMap();
2042
+ function getCompilationSessionPool(owner) {
2043
+ ensureCompilerOwnerActive(owner);
2044
+ let pool = compilationSessionPools.get(owner);
2045
+ if (!pool) {
2046
+ pool = new CompilationSessionPool();
2047
+ compilationSessionPools.set(owner, pool);
2048
+ }
2049
+ return pool;
2050
+ }
2051
+ function disposeCompilationSessionPool(owner) {
2052
+ const pool = compilationSessionPools.get(owner);
2053
+ if (!pool) return Promise.resolve();
2054
+ compilationSessionPools.delete(owner);
2055
+ return pool.dispose();
2056
+ }
2057
+ //#endregion
2058
+ //#region src/compiler/tailwind-generation-session-pool.ts
2059
+ const SESSION_ENGINE_CACHE_MAX = 32;
2060
+ function createSourceKey(source) {
2061
+ return md5Hash([
2062
+ source.projectRoot,
2063
+ source.base,
2064
+ source.baseFallbacks.join("\0"),
2065
+ source.css,
2066
+ source.dependencies.join("\0")
2067
+ ].join("\0"));
2068
+ }
2069
+ function disposeGenerator$1(generator) {
2070
+ generator?.dispose?.();
2071
+ }
2072
+ var TailwindGenerationSessionPool = class {
2073
+ constructor() {
2074
+ _defineProperty(this, "generators", /* @__PURE__ */ new Map());
2075
+ _defineProperty(this, "disposed", false);
2076
+ }
2077
+ async generate(source, options) {
2078
+ return this.getGenerator(source).generate(options);
2079
+ }
2080
+ async validateCandidates(source, candidates) {
2081
+ return this.getGenerator(source).validateCandidates(candidates);
2082
+ }
2083
+ invalidate(change) {
2084
+ if (change.type === "all" || change.type === "dependencies") {
2085
+ for (const generator of this.generators.values()) disposeGenerator$1(generator);
2086
+ this.generators.clear();
2087
+ return;
2088
+ }
2089
+ const key = createSourceKey(change.source);
2090
+ disposeGenerator$1(this.generators.get(key));
2091
+ this.generators.delete(key);
2092
+ }
2093
+ dispose() {
2094
+ for (const generator of this.generators.values()) disposeGenerator$1(generator);
2095
+ this.generators.clear();
2096
+ this.disposed = true;
2097
+ }
2098
+ get size() {
2099
+ return this.generators.size;
2100
+ }
2101
+ getGenerator(source) {
2102
+ if (this.disposed) throw new Error("TailwindGenerationSessionPool 已释放。");
2103
+ const key = createSourceKey(source);
2104
+ const cached = this.generators.get(key);
2105
+ if (cached) {
2106
+ this.generators.delete(key);
2107
+ this.generators.set(key, cached);
2108
+ return cached;
2109
+ }
2110
+ const generator = createWeappTailwindcssGenerator(source);
2111
+ this.generators.set(key, generator);
2112
+ while (this.generators.size > SESSION_ENGINE_CACHE_MAX) {
2113
+ const oldest = this.generators.keys().next().value;
2114
+ if (oldest === void 0) break;
2115
+ disposeGenerator$1(this.generators.get(oldest));
2116
+ this.generators.delete(oldest);
2117
+ }
2118
+ return generator;
2119
+ }
2120
+ };
2121
+ const sessionPools = /* @__PURE__ */ new WeakMap();
2122
+ function getTailwindGenerationSessionPool(owner) {
2123
+ ensureCompilerOwnerActive(owner);
2124
+ let pool = sessionPools.get(owner);
2125
+ if (!pool) {
2126
+ pool = new TailwindGenerationSessionPool();
2127
+ sessionPools.set(owner, pool);
2128
+ }
2129
+ return pool;
2130
+ }
2131
+ function disposeTailwindGenerationSessionPool(owner) {
2132
+ const pool = sessionPools.get(owner);
2133
+ if (!pool) return;
2134
+ sessionPools.delete(owner);
2135
+ pool.dispose();
2136
+ }
2137
+ //#endregion
2138
+ //#region src/compiler/compilation-change-coordinator.ts
2139
+ var CompilationChangeCoordinator = class {
2140
+ constructor(compilationPool, generationPool) {
2141
+ this.compilationPool = compilationPool;
2142
+ this.generationPool = generationPool;
2143
+ _defineProperty(this, "pendingChangesByScope", /* @__PURE__ */ new Map());
2144
+ _defineProperty(this, "disposed", false);
2145
+ }
2146
+ record(changes) {
2147
+ this.ensureActive();
2148
+ const normalizedChanges = mergeCompilationDependencyChanges(changes);
2149
+ if (normalizedChanges.length === 0) return /* @__PURE__ */ new Set();
2150
+ const affectedScopeChanges = this.compilationPool.getAffectedScopeChanges(normalizedChanges);
2151
+ const affectedScopes = new Set(affectedScopeChanges.keys());
2152
+ const newlyPendingScopes = /* @__PURE__ */ new Set();
2153
+ const invalidatedPaths = /* @__PURE__ */ new Set();
2154
+ for (const [scopeId, scopeChanges] of affectedScopeChanges) {
2155
+ let pendingChanges = this.pendingChangesByScope.get(scopeId);
2156
+ if (!pendingChanges) {
2157
+ pendingChanges = /* @__PURE__ */ new Map();
2158
+ this.pendingChangesByScope.set(scopeId, pendingChanges);
2159
+ newlyPendingScopes.add(scopeId);
2160
+ }
2161
+ for (const change of scopeChanges) {
2162
+ const previous = pendingChanges.get(change.id);
2163
+ const mergedChange = mergeCompilationDependencyChanges(previous ? [previous] : void 0, [change])[0];
2164
+ if (!previous || previous.type !== mergedChange.type) {
2165
+ pendingChanges.set(change.id, mergedChange);
2166
+ invalidatedPaths.add(change.id);
2167
+ }
2168
+ }
2169
+ }
2170
+ if (newlyPendingScopes.size > 0) this.compilationPool.recordAffectedScopes(newlyPendingScopes);
2171
+ if (invalidatedPaths.size > 0) this.generationPool.invalidate({
2172
+ type: "dependencies",
2173
+ paths: invalidatedPaths
2174
+ });
2175
+ return affectedScopes;
2176
+ }
2177
+ consume(scopeId) {
2178
+ this.ensureActive();
2179
+ const pendingChanges = this.pendingChangesByScope.get(scopeId);
2180
+ if (!pendingChanges) return;
2181
+ this.pendingChangesByScope.delete(scopeId);
2182
+ return [...pendingChanges.values()].map((change) => ({ ...change }));
2183
+ }
2184
+ invalidateScope(scopeId) {
2185
+ this.ensureActive();
2186
+ this.pendingChangesByScope.delete(scopeId);
2187
+ this.compilationPool.invalidateScope(scopeId);
2188
+ }
2189
+ getScopeDependencyRevision(scopeId) {
2190
+ this.ensureActive();
2191
+ return this.compilationPool.getScopeDependencyRevision(scopeId);
2192
+ }
2193
+ dispose() {
2194
+ this.pendingChangesByScope.clear();
2195
+ this.disposed = true;
2196
+ }
2197
+ ensureActive() {
2198
+ if (this.disposed) throw new Error("CompilationChangeCoordinator 已释放。");
2199
+ }
2200
+ };
2201
+ const compilationChangeCoordinators = /* @__PURE__ */ new WeakMap();
2202
+ function getCompilationChangeCoordinator(owner) {
2203
+ ensureCompilerOwnerActive(owner);
2204
+ let coordinator = compilationChangeCoordinators.get(owner);
2205
+ if (!coordinator) {
2206
+ coordinator = new CompilationChangeCoordinator(getCompilationSessionPool(owner), getTailwindGenerationSessionPool(owner));
2207
+ compilationChangeCoordinators.set(owner, coordinator);
2208
+ }
2209
+ return coordinator;
2210
+ }
2211
+ function recordCompilationDependencyChanges(owner, changes) {
2212
+ return getCompilationChangeCoordinator(owner).record(changes);
2213
+ }
2214
+ function consumeCompilationScopeChanges(owner, scopeId) {
2215
+ return getCompilationChangeCoordinator(owner).consume(scopeId);
2216
+ }
2217
+ function getCompilationScopeDependencyRevision(owner, scopeId) {
2218
+ return getCompilationChangeCoordinator(owner).getScopeDependencyRevision(scopeId);
2219
+ }
2220
+ function invalidateCompilationScope(owner, scopeId) {
2221
+ getCompilationChangeCoordinator(owner).invalidateScope(scopeId);
2222
+ }
2223
+ function disposeCompilationChangeCoordinator(owner) {
2224
+ const coordinator = compilationChangeCoordinators.get(owner);
2225
+ if (!coordinator) return;
2226
+ compilationChangeCoordinators.delete(owner);
2227
+ coordinator.dispose();
2228
+ }
2229
+ //#endregion
2230
+ //#region src/compiler/composition.ts
2231
+ function orderCssFragments(fragments) {
2232
+ return [...fragments].sort((left, right) => left.order - right.order || left.id.localeCompare(right.id));
2233
+ }
2234
+ function composeGenerationArtifact(artifact) {
2235
+ const cloned = cloneGenerationArtifact(artifact);
2236
+ const root = postcss.root();
2237
+ for (const fragment of orderCssFragments(cloned.fragments)) root.append(fragment.root.nodes.map((node) => node.clone()));
2238
+ return {
2239
+ artifact: cloned,
2240
+ root,
2241
+ css: root.toString()
2242
+ };
2243
+ }
2244
+ //#endregion
2245
+ //#region src/compiler/emission-plan.ts
2246
+ var AssetEmissionPlan = class {
2247
+ constructor() {
2248
+ _defineProperty(this, "emissions", /* @__PURE__ */ new Map());
2249
+ _defineProperty(this, "assetOperations", []);
2250
+ }
2251
+ upsert(assetId, artifact) {
2252
+ this.emissions.set(assetId, cloneGenerationArtifact(artifact));
2253
+ }
2254
+ get(assetId) {
2255
+ const artifact = this.emissions.get(assetId);
2256
+ return artifact ? cloneGenerationArtifact(artifact) : void 0;
2257
+ }
2258
+ entries() {
2259
+ return [...this.emissions].map(([assetId, artifact]) => ({
2260
+ assetId,
2261
+ artifact: cloneGenerationArtifact(artifact)
2262
+ }));
2263
+ }
2264
+ write(assetId, source) {
2265
+ this.assetOperations.push({
2266
+ assetId,
2267
+ kind: "write",
2268
+ source
2269
+ });
2270
+ }
2271
+ remove(assetId) {
2272
+ this.assetOperations.push({
2273
+ assetId,
2274
+ kind: "delete"
2275
+ });
2276
+ }
2277
+ operations() {
2278
+ return this.assetOperations.map((operation) => ({ ...operation }));
2279
+ }
2280
+ clear() {
2281
+ this.emissions.clear();
2282
+ this.assetOperations.length = 0;
2283
+ }
2284
+ };
2285
+ //#endregion
2286
+ //#region src/compiler/events.ts
2287
+ /** 创建跨 bundler 共用的生命周期事件总线。 */
2288
+ function createCompilationEventBus() {
2289
+ const listeners = /* @__PURE__ */ new Set();
2290
+ let revision = 0;
2291
+ return {
2292
+ get revision() {
2293
+ return revision;
2294
+ },
2295
+ async emit(event) {
2296
+ revision += 1;
2297
+ for (const listener of [...listeners]) await listener(event);
2298
+ return revision;
2299
+ },
2300
+ subscribe(listener) {
2301
+ listeners.add(listener);
2302
+ return () => listeners.delete(listener);
2303
+ },
2304
+ clear() {
2305
+ listeners.clear();
2306
+ }
2307
+ };
2308
+ }
2309
+ //#endregion
2310
+ //#region src/core/compiler/source-fingerprint.ts
2311
+ function stableSerialize(value, stack = /* @__PURE__ */ new WeakSet()) {
2312
+ if (value == null || typeof value === "number" || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
2313
+ if (typeof value === "function") return `[Function:${value.name}]`;
2314
+ if (typeof value !== "object") return String(value);
2315
+ if (stack.has(value)) return "[Circular]";
2316
+ stack.add(value);
2317
+ const serialized = Array.isArray(value) ? `[${value.map((item) => stableSerialize(item, stack)).join(",")}]` : `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableSerialize(value[key], stack)}`).join(",")}}`;
2318
+ stack.delete(value);
2319
+ return serialized;
2320
+ }
2321
+ function createSourceFingerprint(source) {
2322
+ return createCompilerValueFingerprint(source);
2323
+ }
2324
+ function createCompilerValueFingerprint(value) {
2325
+ return md5Hash(stableSerialize(value));
2326
+ }
2327
+ //#endregion
2328
+ //#region src/core/compiler/generation-cache.ts
2329
+ function createCompilerGenerationCacheKey(request, candidates, target) {
2330
+ return {
2331
+ bareArbitraryValues: request.bareArbitraryValues,
2332
+ candidateSignature: [...candidates].sort().join("\0"),
2333
+ incrementalCache: request.incrementalCache,
2334
+ scanSources: request.scanSources,
2335
+ sourcesFingerprint: request.sources === void 0 ? void 0 : createCompilerValueFingerprint(request.sources),
2336
+ styleOptionsFingerprint: request.styleOptions === void 0 ? void 0 : createCompilerValueFingerprint(request.styleOptions),
2337
+ target
2338
+ };
2339
+ }
2340
+ function isSameCompilerGenerationCacheKey(left, right) {
2341
+ return left.bareArbitraryValues === right.bareArbitraryValues && left.candidateSignature === right.candidateSignature && left.incrementalCache === right.incrementalCache && left.scanSources === right.scanSources && left.sourcesFingerprint === right.sourcesFingerprint && left.styleOptionsFingerprint === right.styleOptionsFingerprint && left.target === right.target;
2342
+ }
2343
+ function reuseCompilerGenerationResult(result) {
2344
+ return {
2345
+ ...result,
2346
+ incrementalCss: "",
2347
+ incrementalRawCss: ""
2348
+ };
2349
+ }
2350
+ //#endregion
2351
+ //#region src/core/compiler/generation-state.ts
2352
+ function createGenerationGraph(rootId, source, dependencies) {
2353
+ const scope = {
2354
+ id: rootId,
2355
+ kind: "global"
2356
+ };
2357
+ const dependencyIds = [...new Set(dependencies)].filter((id) => id !== rootId).sort();
2358
+ const nodes = [{
2359
+ content: source.css,
2360
+ id: rootId,
2361
+ kind: "css",
2362
+ scope
2363
+ }, ...dependencyIds.map((id) => ({
2364
+ id,
2365
+ kind: "config",
2366
+ scope
2367
+ }))];
2368
+ return {
2369
+ edges: dependencyIds.map((id) => ({
2370
+ from: rootId,
2371
+ kind: "depends-on",
2372
+ to: id
2373
+ })),
2374
+ nodes
2375
+ };
2376
+ }
2377
+ function prepareCompilerGeneration(entry, request, source, sourceChanged) {
2378
+ const explicitCandidates = request.candidates !== void 0;
2379
+ const candidates = explicitCandidates ? [...request.candidates] : [];
2380
+ const candidateSignature = [...candidates].sort().join("\0");
2381
+ if (!sourceChanged && entry.compilationCache?.candidateSignature === candidateSignature && entry.compilationCache.compilation.revision === entry.compilationRevision) return {
2382
+ ...entry.compilationCache,
2383
+ explicitCandidates
2384
+ };
2385
+ const graph = createGenerationGraph(entry.id, source, source.dependencies);
2386
+ const compilation = entry.compilation.update({
2387
+ ...graph,
2388
+ candidatesBySource: [[entry.id, candidates]],
2389
+ changes: sourceChanged ? [{
2390
+ sourceId: entry.id,
2391
+ type: "dependency-changed"
2392
+ }] : void 0
2393
+ });
2394
+ entry.compilationRevision = compilation.revision;
2395
+ return {
2396
+ candidateSignature,
2397
+ compilation,
2398
+ explicitCandidates,
2399
+ graph
2400
+ };
2401
+ }
2402
+ function commitCompilerGeneration(entry, prepared, source, dependencies, classSet) {
2403
+ const graph = createGenerationGraph(entry.id, source, dependencies);
2404
+ const compilation = entry.compilation.commitValidation(prepared.compilation.revision, classSet, graph);
2405
+ entry.compilationCache = {
2406
+ candidateSignature: prepared.candidateSignature,
2407
+ compilation,
2408
+ graph
2409
+ };
2410
+ }
2411
+ //#endregion
2412
+ //#region src/core/compiler/root-store.ts
2413
+ function disposeGenerator(generator) {
2414
+ generator?.dispose?.();
2415
+ }
2416
+ var CompilerRootStore = class {
2417
+ constructor(maxRoots, onRootEvicted) {
2418
+ this.maxRoots = maxRoots;
2419
+ this.onRootEvicted = onRootEvicted;
2420
+ _defineProperty(this, "dependencyRoots", /* @__PURE__ */ new Map());
2421
+ _defineProperty(this, "releasing", /* @__PURE__ */ new Map());
2422
+ _defineProperty(this, "roots", /* @__PURE__ */ new Map());
2423
+ }
2424
+ get(id) {
2425
+ if (!id) throw new Error("Compiler root id 不能为空。");
2426
+ if (this.releasing.has(id)) throw new Error(`Compiler root 正在移除:${id}`);
2427
+ const cached = this.roots.get(id);
2428
+ if (cached) {
2429
+ if (!cached.accepting) throw new Error(`Compiler root 正在移除:${id}`);
2430
+ this.roots.delete(id);
2431
+ this.roots.set(id, cached);
2432
+ return cached;
2433
+ }
2434
+ if (this.roots.size >= this.maxRoots) {
2435
+ const oldest = [...this.roots.values()].find((entry) => entry.pendingCount === 0);
2436
+ if (oldest) this.remove(oldest.id, true);
2437
+ }
2438
+ const entry = {
2439
+ accepting: true,
2440
+ active: true,
2441
+ appliedInvalidation: 0,
2442
+ compilation: new DefaultCompilationSession(),
2443
+ compilationRevision: 0,
2444
+ dependencies: /* @__PURE__ */ new Set(),
2445
+ id,
2446
+ invalidation: 0,
2447
+ pending: Promise.resolve(),
2448
+ pendingCount: 0,
2449
+ sources: []
2450
+ };
2451
+ this.roots.set(id, entry);
2452
+ return entry;
2453
+ }
2454
+ attachDependencies(entry, dependencies) {
2455
+ this.detachDependencies(entry);
2456
+ if (!entry.accepting) return;
2457
+ for (const dependency of dependencies) {
2458
+ entry.dependencies.add(dependency);
2459
+ let owners = this.dependencyRoots.get(dependency);
2460
+ if (!owners) {
2461
+ owners = /* @__PURE__ */ new Set();
2462
+ this.dependencyRoots.set(dependency, owners);
2463
+ }
2464
+ owners.add(entry.id);
2465
+ }
2466
+ }
2467
+ attachSources(entry, sources) {
2468
+ entry.sources = [...sources];
2469
+ }
2470
+ invalidate(ids) {
2471
+ const affected = /* @__PURE__ */ new Set();
2472
+ for (const id of ids) {
2473
+ const root = this.roots.get(id);
2474
+ if (root?.accepting) affected.add(root.id);
2475
+ for (const rootId of this.dependencyRoots.get(id) ?? []) affected.add(rootId);
2476
+ const sourcePath = stripSourceQuery(id);
2477
+ for (const sourceRoot of this.roots.values()) if (sourceRoot.accepting && sourceRoot.sources.length > 0 && isFileMatchedByTailwindSourceEntries(sourcePath, sourceRoot.sources)) affected.add(sourceRoot.id);
2478
+ }
2479
+ for (const rootId of affected) {
2480
+ const entry = this.roots.get(rootId);
2481
+ if (entry?.accepting) entry.invalidation += 1;
2482
+ }
2483
+ return Object.freeze([...affected].sort());
2484
+ }
2485
+ trim() {
2486
+ while (this.roots.size > this.maxRoots) {
2487
+ const oldest = [...this.roots.values()].find((entry) => entry.pendingCount === 0);
2488
+ if (!oldest) return;
2489
+ this.remove(oldest.id, true);
2490
+ }
2491
+ }
2492
+ remove(id, notifyEvicted = false) {
2493
+ const pendingRelease = this.releasing.get(id);
2494
+ if (pendingRelease) return pendingRelease;
2495
+ const entry = this.roots.get(id);
2496
+ if (!entry) return Promise.resolve();
2497
+ entry.accepting = false;
2498
+ this.roots.delete(id);
2499
+ this.detachDependencies(entry);
2500
+ const release = entry.pending.then(() => {
2501
+ entry.active = false;
2502
+ entry.compilation.dispose();
2503
+ entry.compilationCache = void 0;
2504
+ disposeGenerator(entry.generator);
2505
+ entry.generator = void 0;
2506
+ entry.generationCache = void 0;
2507
+ entry.latestSnapshot = void 0;
2508
+ entry.source = void 0;
2509
+ entry.sourceInput = void 0;
2510
+ entry.sourceFingerprint = void 0;
2511
+ entry.sources = [];
2512
+ if (notifyEvicted) this.onRootEvicted?.(id);
2513
+ }).finally(() => {
2514
+ this.releasing.delete(id);
2515
+ });
2516
+ this.releasing.set(id, release);
2517
+ return release;
2518
+ }
2519
+ async dispose() {
2520
+ await Promise.all([...[...this.roots.keys()].map((id) => this.remove(id)), ...this.releasing.values()]);
2521
+ this.dependencyRoots.clear();
2522
+ }
2523
+ detachDependencies(entry) {
2524
+ for (const dependency of entry.dependencies) {
2525
+ const owners = this.dependencyRoots.get(dependency);
2526
+ owners?.delete(entry.id);
2527
+ if (owners?.size === 0) this.dependencyRoots.delete(dependency);
2528
+ }
2529
+ entry.dependencies.clear();
2530
+ }
2531
+ };
2532
+ function stripSourceQuery(id) {
2533
+ return id.replace(/[?#].*$/, "");
2534
+ }
2535
+ //#endregion
2536
+ //#region src/core/compiler/snapshot.ts
2537
+ const readonlySetValues = /* @__PURE__ */ new WeakMap();
2538
+ const snapshotRegistry = /* @__PURE__ */ new WeakMap();
2539
+ var ImmutableSetView = class {
2540
+ constructor(values) {
2541
+ readonlySetValues.set(this, new Set(values));
2542
+ Object.freeze(this);
2543
+ }
2544
+ get size() {
2545
+ return this.valuesSet.size;
2546
+ }
2547
+ get [Symbol.toStringTag]() {
2548
+ return "Set";
2549
+ }
2550
+ has(value) {
2551
+ return this.valuesSet.has(value);
2552
+ }
2553
+ entries() {
2554
+ return this.valuesSet.entries();
2555
+ }
2556
+ keys() {
2557
+ return this.valuesSet.keys();
2558
+ }
2559
+ values() {
2560
+ return this.valuesSet.values();
2561
+ }
2562
+ forEach(callbackfn, thisArg) {
2563
+ for (const value of this.valuesSet) callbackfn.call(thisArg, value, value, this);
2564
+ }
2565
+ [Symbol.iterator]() {
2566
+ return this.values();
2567
+ }
2568
+ get valuesSet() {
2569
+ return readonlySetValues.get(this);
2570
+ }
2571
+ };
2572
+ function uniqueSorted(values) {
2573
+ return Object.freeze([...new Set(values)].sort());
2574
+ }
2575
+ function sourceKey(source) {
2576
+ return `${source.base}\0${source.pattern}\0${source.negated ? "1" : "0"}`;
2577
+ }
2578
+ function uniqueSortedSources(sources) {
2579
+ const values = /* @__PURE__ */ new Map();
2580
+ for (const source of sources) {
2581
+ const cloned = Object.freeze({ ...source });
2582
+ values.set(sourceKey(cloned), cloned);
2583
+ }
2584
+ return Object.freeze([...values.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([, value]) => value));
2585
+ }
2586
+ function createRootFingerprint(root, target, classSet, dependencies, sources) {
2587
+ return [
2588
+ root.id,
2589
+ String(root.revision),
2590
+ target,
2591
+ ...[...classSet].sort(),
2592
+ ...dependencies,
2593
+ ...[...sources].map(sourceKey)
2594
+ ].join("\0");
2595
+ }
2596
+ function createSnapshotFromState(state, reusableClassSet, reusableClassSetView) {
2597
+ const roots = Object.freeze([...state.roots.values()].sort((left, right) => left.id.localeCompare(right.id)).map(({ id, revision }) => Object.freeze({
2598
+ id,
2599
+ revision
2600
+ })));
2601
+ const classSet = reusableClassSet ?? new Set(state.classSet);
2602
+ const fingerprint = [
2603
+ state.target,
2604
+ ...[...state.roots.values()].map((root) => `${root.id}\0${root.revision}\0${root.fingerprint}`).sort(),
2605
+ ...[...classSet].sort(),
2606
+ ...state.dependencies,
2607
+ ...state.sources.map(sourceKey)
2608
+ ].join("\0");
2609
+ const snapshot = Object.freeze({
2610
+ classSet: reusableClassSetView ?? new ImmutableSetView(classSet),
2611
+ dependencies: state.dependencies,
2612
+ roots,
2613
+ sources: state.sources,
2614
+ target: state.target
2615
+ });
2616
+ snapshotRegistry.set(snapshot, {
2617
+ ...state,
2618
+ classSet,
2619
+ fingerprint
2620
+ });
2621
+ return snapshot;
2622
+ }
2623
+ function createRegisteredCompilerSnapshot(request, reusableClassSet, reusableClassSetView) {
2624
+ if (!request.id) throw new Error("Compiler snapshot 的 root id 不能为空。");
2625
+ const revision = request.revision ?? 0;
2626
+ if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`Compiler snapshot revision 必须是非负安全整数:${revision}`);
2627
+ const target = request.target ?? "weapp";
2628
+ const classSet = new Set(request.classSet);
2629
+ const dependencies = uniqueSorted(request.dependencies ?? []);
2630
+ const sources = uniqueSortedSources(request.sources ?? []);
2631
+ const root = {
2632
+ id: request.id,
2633
+ revision
2634
+ };
2635
+ const internalRoot = {
2636
+ ...root,
2637
+ fingerprint: createRootFingerprint(root, target, classSet, dependencies, sources)
2638
+ };
2639
+ return createSnapshotFromState({
2640
+ classSet,
2641
+ dependencies,
2642
+ roots: /* @__PURE__ */ new Map([[root.id, internalRoot]]),
2643
+ sources,
2644
+ target
2645
+ }, reusableClassSet, reusableClassSetView);
2646
+ }
2647
+ function getInternalCompilerSnapshot(snapshot) {
2648
+ const state = snapshotRegistry.get(snapshot);
2649
+ if (!state) throw new Error("Compiler snapshot 必须由 createSnapshot()、generate() 或 mergeSnapshots() 创建。");
2650
+ return state;
2651
+ }
2652
+ function mergeRegisteredCompilerSnapshots(snapshots) {
2653
+ const states = [...snapshots].map(getInternalCompilerSnapshot);
2654
+ if (states.length === 0) throw new Error("mergeSnapshots() 至少需要一个 snapshot。");
2655
+ const target = states[0].target;
2656
+ const roots = /* @__PURE__ */ new Map();
2657
+ const classSet = /* @__PURE__ */ new Set();
2658
+ const dependencies = [];
2659
+ const sources = [];
2660
+ for (const state of states) {
2661
+ if (state.target !== target) throw new Error(`不能合并不同 target 的 snapshot:${target} 与 ${state.target}`);
2662
+ for (const root of state.roots.values()) {
2663
+ const current = roots.get(root.id);
2664
+ if (current && current.revision !== root.revision) throw new Error(`同一 root 不能合并不同 revision:${root.id} (${current.revision} / ${root.revision})`);
2665
+ if (current && current.fingerprint !== root.fingerprint) throw new Error(`同一 root revision 的 snapshot 内容冲突:${root.id}@${root.revision}`);
2666
+ roots.set(root.id, root);
2667
+ }
2668
+ for (const candidate of state.classSet) classSet.add(candidate);
2669
+ dependencies.push(...state.dependencies);
2670
+ sources.push(...state.sources);
2671
+ }
2672
+ return createSnapshotFromState({
2673
+ classSet: new Set([...classSet].sort()),
2674
+ dependencies: uniqueSorted(dependencies),
2675
+ roots,
2676
+ sources: uniqueSortedSources(sources),
2677
+ target
2678
+ });
2679
+ }
2680
+ function createImmutableSet(values) {
2681
+ return new ImmutableSetView(values);
2682
+ }
2683
+ //#endregion
2684
+ //#region src/cache/index.ts
2685
+ function isProcessResult(value) {
2686
+ return typeof value === "object" && value !== null && "result" in value;
2687
+ }
2688
+ function createCache(options) {
2689
+ const disabled = options === false;
2690
+ const hashMap = /* @__PURE__ */ new Map();
2691
+ const instance = new LRUCache({
2692
+ max: 1024,
2693
+ ttl: 0,
2694
+ ttlAutopurge: false
2695
+ });
2696
+ const cache = {
2697
+ hashMap,
2698
+ instance,
2699
+ hasHashKey(key) {
2700
+ return hashMap.has(key);
2701
+ },
2702
+ getHashValue(key) {
2703
+ return hashMap.get(key);
2704
+ },
2705
+ setHashValue(key, value) {
2706
+ return hashMap.set(key, value);
2707
+ },
2708
+ get(key) {
2709
+ return instance.get(key);
2710
+ },
2711
+ set(key, value) {
2712
+ return instance.set(key, value);
2713
+ },
2714
+ computeHash(message) {
2715
+ return md5Hash(message);
2716
+ },
2717
+ calcHashValueChanged(key, hash) {
2718
+ const hit = hashMap.get(key);
2719
+ if (hit) hashMap.set(key, {
2720
+ changed: hash !== hit.hash,
2721
+ hash
2722
+ });
2723
+ else hashMap.set(key, {
2724
+ changed: true,
2725
+ hash
2726
+ });
2727
+ return cache;
2728
+ },
2729
+ pruneHashKeys(hashKeys) {
2730
+ const activeHashKeys = new Set(hashKeys);
2731
+ for (const key of hashMap.keys()) if (!activeHashKeys.has(key)) hashMap.delete(key);
2732
+ },
2733
+ prune(options) {
2734
+ if (options.cacheKeys) {
2735
+ const cacheKeys = new Set(options.cacheKeys);
2736
+ for (const key of instance.keys()) if (!cacheKeys.has(key)) instance.delete(key);
2737
+ }
2738
+ if (options.hashKeys) cache.pruneHashKeys?.(options.hashKeys);
2739
+ },
2740
+ has(key) {
2741
+ return instance.has(key);
2742
+ },
2743
+ async process({ key, hashKey, rawSource, hash, resolveCache, transform, onCacheHit }) {
2744
+ if (disabled) {
2745
+ const value = await transform();
2746
+ return isProcessResult(value) ? value.result : value;
2747
+ }
2748
+ const cacheHashKey = hashKey ?? key;
2749
+ let hasChanged = true;
2750
+ if (hash != null || rawSource != null) {
2751
+ const nextHash = hash ?? cache.computeHash(rawSource);
2752
+ cache.calcHashValueChanged(cacheHashKey, nextHash);
2753
+ hasChanged = cache.getHashValue(cacheHashKey)?.changed ?? true;
2754
+ }
2755
+ const readCache = resolveCache ?? (() => cache.get(key));
2756
+ if (!hasChanged) {
2757
+ const cached = readCache();
2758
+ if (cached !== void 0) {
2759
+ await onCacheHit?.(cached);
2760
+ return cached;
2761
+ }
2762
+ }
2763
+ const value = await transform();
2764
+ const normalized = isProcessResult(value) ? value : { result: value };
2765
+ const stored = normalized.cacheValue ?? normalized.result;
2766
+ cache.set(key, stored);
2767
+ return normalized.result;
2768
+ }
2769
+ };
2770
+ return cache;
2771
+ }
2772
+ function initializeCache(cacheConfig) {
2773
+ if (typeof cacheConfig === "boolean" || cacheConfig === void 0) return createCache(cacheConfig);
2774
+ return cacheConfig;
2775
+ }
2776
+ //#endregion
2777
+ //#region src/framework/platform.ts
2778
+ const MPX_TO_UNI_PLATFORM = {
2779
+ ali: "mp-alipay",
2780
+ dd: "mp-dingtalk",
2781
+ jd: "mp-jd",
2782
+ qq: "mp-qq",
2783
+ swan: "mp-baidu",
2784
+ tt: "mp-toutiao",
2785
+ wx: "mp-weixin"
2786
+ };
2787
+ function normalizeFrameworkStylePlatform(platform, appType) {
2788
+ const normalized = platform?.trim().toLowerCase();
2789
+ if (!normalized) return;
2790
+ if (appType === "mpx") return MPX_TO_UNI_PLATFORM[normalized] ?? normalized;
2791
+ return normalized;
2792
+ }
2793
+ //#endregion
2794
+ //#region src/tailwindcss/runtime.ts
2795
+ const debug = createDebug("[tailwindcss:runtime] ");
2796
+ const refreshTailwindcssRuntimeSymbol = Symbol.for("weapp-tailwindcss.refreshTailwindcssRuntime");
2797
+ function createTailwindRuntimeReadyPromise(tailwindRuntime) {
2798
+ return Promise.resolve().then(async () => {
2799
+ invalidateRuntimeClassSet(tailwindRuntime);
2800
+ });
2801
+ }
2802
+ const runtimeClassSetStateCache = /* @__PURE__ */ new WeakMap();
2803
+ function getRuntimeClassSetStateEntry(state) {
2804
+ let entry = runtimeClassSetStateCache.get(state);
2805
+ if (!entry) {
2806
+ entry = {};
2807
+ runtimeClassSetStateCache.set(state, entry);
2808
+ }
2809
+ return entry;
2810
+ }
2811
+ function getTailwindRuntime(state) {
2812
+ return state.tailwindRuntime;
2813
+ }
2814
+ function setTailwindRuntime(state, runtime) {
2815
+ state.tailwindRuntime = runtime;
2816
+ }
2817
+ function getRefreshTailwindRuntime(state) {
2818
+ return state.refreshTailwindcssRuntime;
2819
+ }
2820
+ async function refreshTailwindRuntimeState(state, forceOrOptions) {
2821
+ const normalizedOptions = typeof forceOrOptions === "boolean" ? { force: forceOrOptions } : forceOrOptions;
2822
+ const force = normalizedOptions.force;
2823
+ const clearCache = normalizedOptions.clearCache === true;
2824
+ if (!force) return false;
2825
+ const currentRuntime = getTailwindRuntime(state);
2826
+ debug("refresh runtime state start, clearCache=%s major=%s", clearCache, currentRuntime.majorVersion ?? "unknown");
2827
+ await state.readyPromise;
2828
+ let refreshed = false;
2829
+ const refreshTailwindRuntime = getRefreshTailwindRuntime(state);
2830
+ if (typeof refreshTailwindRuntime === "function") {
2831
+ const next = await refreshTailwindRuntime({ clearCache });
2832
+ if (next !== getTailwindRuntime(state)) setTailwindRuntime(state, next);
2833
+ refreshed = true;
2834
+ }
2835
+ if (refreshed) state.readyPromise = createTailwindRuntimeReadyPromise(getTailwindRuntime(state));
2836
+ debug("refresh runtime state end, refreshed=%s major=%s", refreshed, getTailwindRuntime(state).majorVersion ?? "unknown");
2837
+ return refreshed;
2838
+ }
2839
+ async function ensureRuntimeClassSet(state, options = {}) {
2840
+ const forceRefresh = options.forceRefresh === true;
2841
+ const forceCollect = options.forceCollect === true;
2842
+ const clearCache = options.clearCache === true;
2843
+ const allowEmpty = options.allowEmpty === true;
2844
+ if (forceRefresh) await refreshTailwindRuntimeState(state, {
2845
+ force: true,
2846
+ clearCache
2847
+ });
2848
+ await state.readyPromise;
2849
+ const entry = getRuntimeClassSetStateEntry(state);
2850
+ const signature = await getRuntimeClassSetSignatureWithSources(getTailwindRuntime(state));
2851
+ const signatureChanged = entry.signature !== signature;
2852
+ const shouldForceCollect = forceCollect || forceRefresh || signatureChanged;
2853
+ if (!shouldForceCollect) {
2854
+ if (entry.value && (allowEmpty || entry.value.size > 0)) return entry.value;
2855
+ if (entry.promise) return entry.promise;
2856
+ }
2857
+ const task = (async () => {
2858
+ const collected = await collectRuntimeClassSet(getTailwindRuntime(state), {
2859
+ force: shouldForceCollect,
2860
+ skipRefresh: true,
2861
+ clearCache
2862
+ });
2863
+ if (allowEmpty || collected.size > 0) return collected;
2864
+ await refreshTailwindRuntimeState(state, {
2865
+ force: true,
2866
+ clearCache: true
2867
+ });
2868
+ await state.readyPromise;
2869
+ return collectRuntimeClassSet(getTailwindRuntime(state), {
2870
+ force: true,
2871
+ skipRefresh: true,
2872
+ clearCache: true
2873
+ });
2874
+ })();
2875
+ entry.promise = task;
2876
+ try {
2877
+ const runtimeSet = await task;
2878
+ entry.value = runtimeSet;
2879
+ entry.signature = await getRuntimeClassSetSignatureWithSources(getTailwindRuntime(state));
2880
+ return runtimeSet;
2881
+ } finally {
2882
+ if (entry.promise === task) entry.promise = void 0;
2883
+ }
2884
+ }
2885
+ function tryGetRuntimeClassSetSync(tailwindRuntime) {
2886
+ if (typeof tailwindRuntime.getClassSetSync !== "function") return;
2887
+ try {
2888
+ const set = tailwindRuntime.getClassSetSync();
2889
+ if (set && set.size === 0) return;
2890
+ return set;
2891
+ } catch (error) {
2892
+ debug("getClassSetSync() unavailable for tailwindcss v4, fallback to async getClassSet(): %O", error);
2893
+ return;
2894
+ }
2895
+ }
2896
+ async function collectTailwindV4GeneratorClassSet(tailwindRuntime) {
2897
+ if (typeof tailwindRuntime.collectContentTokens !== "function") return;
2898
+ try {
2899
+ const source = resolveCssMacroTailwindV4Source(await resolveTailwindV4SourceFromRuntime(tailwindRuntime));
2900
+ const generated = await createTailwindV4Engine$1(source).generate({
2901
+ scanSources: true,
2902
+ target: "web"
2903
+ });
2904
+ const designSystem = await loadTailwindV4DesignSystem(source);
2905
+ const classSet = resolveValidTailwindV4Candidates$1(designSystem, generated.classSet, { ...source.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: source.bareArbitraryValues } });
2906
+ debug("runtime class set resolved via tailwindcss v4 generator source scan, raw=%d valid=%d", generated.classSet.size, classSet.size);
2907
+ return classSet;
2908
+ } catch (error) {
2909
+ debug("tailwindcss v4 generator source scan failed, continuing fallback chain: %O", error);
2910
+ return;
2911
+ }
2912
+ }
2913
+ async function mergeTailwindV4GeneratorClassSet(tailwindRuntime, classSet) {
2914
+ const generatorClassSet = await collectTailwindV4GeneratorClassSet(tailwindRuntime).catch(() => void 0);
2915
+ if (!generatorClassSet || generatorClassSet.size === 0) return classSet;
2916
+ return /* @__PURE__ */ new Set([...classSet, ...generatorClassSet]);
2917
+ }
2918
+ async function collectRuntimeClassSet(tailwindRuntime, options = {}) {
2919
+ let activeRuntime = tailwindRuntime;
2920
+ if (options.force && !options.skipRefresh) {
2921
+ const refresh = activeRuntime[refreshTailwindcssRuntimeSymbol];
2922
+ if (typeof refresh === "function") try {
2923
+ const refreshed = await refresh({ clearCache: options.clearCache === true });
2924
+ if (refreshed) activeRuntime = refreshed;
2925
+ } catch (error) {
2926
+ debug("refreshTailwindcssRuntime failed, continuing with existing runtime: %O", error);
2927
+ }
2928
+ }
2929
+ const entry = getRuntimeClassSetCacheEntry(activeRuntime);
2930
+ const signature = await getRuntimeClassSetSignatureWithSources(activeRuntime);
2931
+ if (!options.force) {
2932
+ if (entry.value && entry.signature === signature) return entry.value;
2933
+ if (entry.promise) return entry.promise;
2934
+ } else entry.value = void 0;
2935
+ const task = (async () => {
2936
+ const preferExtract = options.force === true;
2937
+ try {
2938
+ const result = await activeRuntime.extract({ write: false });
2939
+ if (result?.classSet) {
2940
+ if (result.classSet.size > 0) {
2941
+ const merged = await mergeTailwindV4GeneratorClassSet(activeRuntime, result.classSet);
2942
+ debug("runtime class set resolved via extract() + tailwindcss v4 source scan, extract=%d merged=%d", result.classSet.size, merged.size);
2943
+ return merged;
2944
+ }
2945
+ if (preferExtract) debug("runtime class set from extract() is empty on force collect, fallback to generator/sync/async class set");
2946
+ else debug("runtime class set from extract() is empty, fallback to sync/async class set");
2947
+ }
2948
+ } catch (error) {
2949
+ debug("extract() failed, fallback to getClassSet(): %O", error);
2950
+ }
2951
+ const generatorClassSet = await collectTailwindV4GeneratorClassSet(activeRuntime);
2952
+ if (generatorClassSet && generatorClassSet.size > 0) return generatorClassSet;
2953
+ const syncSet = tryGetRuntimeClassSetSync(activeRuntime);
2954
+ if (syncSet) {
2955
+ debug("runtime class set resolved via getClassSetSync(), size=%d", syncSet.size);
2956
+ return syncSet;
2957
+ }
2958
+ try {
2959
+ const fallbackSet = await Promise.resolve(activeRuntime.getClassSet());
2960
+ if (fallbackSet) {
2961
+ debug("runtime class set resolved via getClassSet(), size=%d", fallbackSet.size);
2962
+ return fallbackSet;
2963
+ }
2964
+ } catch (error) {
2965
+ debug("getClassSet() failed, returning empty set: %O", error);
2966
+ }
2967
+ return /* @__PURE__ */ new Set();
2968
+ })();
2969
+ entry.promise = task;
2970
+ entry.signature = signature;
2971
+ try {
2972
+ const resolved = await task;
2973
+ entry.value = resolved;
2974
+ entry.promise = void 0;
2975
+ entry.signature = signature;
2976
+ return resolved;
2977
+ } catch (error) {
2978
+ entry.promise = void 0;
2979
+ throw error;
2980
+ }
2981
+ }
2982
+ //#endregion
2983
+ //#region src/tailwindcss/runtime-logs.ts
2984
+ const runtimeLogDedupeHolder = globalThis;
2985
+ const runtimeLogDedupe = runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ ?? (runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ = /* @__PURE__ */ new Set());
2986
+ function createRuntimeLogKey(category, baseDir, rootPath, version) {
2987
+ return JSON.stringify([
2988
+ category,
2989
+ baseDir ?? process.cwd(),
2990
+ rootPath ?? "",
2991
+ version ?? ""
2992
+ ]);
2993
+ }
2994
+ function markRuntimeLog(category, baseDir, rootPath, version) {
2995
+ const key = createRuntimeLogKey(category, baseDir, rootPath, version);
2996
+ if (runtimeLogDedupe.has(key)) return false;
2997
+ runtimeLogDedupe.add(key);
2998
+ return true;
2999
+ }
3000
+ function logRuntimeTailwindcssTarget(baseDir, rootPath, version) {
3001
+ if (!markRuntimeLog("target", baseDir, rootPath, version)) return;
3002
+ const versionText = version ? ` (v${version})` : "";
3003
+ logger.info("%s 使用 Tailwind CSS%s", "Weapp-tailwindcss", versionText);
3004
+ }
3005
+ function logRuntimeTailwindcssVersion(baseDir, rootPath, version) {
3006
+ if (version) {
3007
+ if (!markRuntimeLog("version", baseDir, rootPath, version)) return;
3008
+ logger.success(`当前使用 ${pc.cyanBright("Tailwind CSS")} 版本为: ${pc.underline(pc.bold(pc.green(version)))}`);
3009
+ return;
3010
+ }
3011
+ if (!markRuntimeLog("missing", baseDir, rootPath, version)) return;
3012
+ logger.warn(`${pc.cyanBright("Tailwind CSS")} 未安装,已跳过版本检测与运行时初始化。`);
3013
+ }
3014
+ //#endregion
3015
+ //#region src/tailwindcss/targets.ts
3016
+ function formatRelativeToBase(targetPath, baseDir) {
3017
+ const normalized = path.normalize(targetPath);
3018
+ if (!baseDir) return normalized.replace(/\\/g, "/");
3019
+ const relative = path.relative(baseDir, normalized);
3020
+ if (!relative || relative === ".") return ".";
3021
+ if (relative.startsWith("..")) return normalized.replace(/\\/g, "/");
3022
+ return path.join(".", relative).replace(/\\/g, "/");
3023
+ }
3024
+ function logTailwindcssTarget(tailwindRuntime, baseDir) {
3025
+ const packageInfo = tailwindRuntime?.packageInfo;
3026
+ const label = "Weapp-tailwindcss";
3027
+ if (!packageInfo?.rootPath) {
3028
+ logger.warn("%s 未找到 Tailwind CSS 依赖,请检查在 %s 是否已安装 tailwindcss", label, baseDir ?? process.cwd());
3029
+ return;
3030
+ }
3031
+ const displayPath = formatRelativeToBase(packageInfo.rootPath, baseDir);
3032
+ const version = packageInfo.version ? ` (v${packageInfo.version})` : "";
3033
+ logRuntimeTailwindcssTarget(baseDir, packageInfo.rootPath, packageInfo.version);
3034
+ logger.debug("%s 解析 Tailwind CSS -> %s%s", label, displayPath, version);
3035
+ }
3036
+ //#endregion
3037
+ //#region src/unocss/index.ts
3038
+ function normalizeUnocssOptions(unocss) {
3039
+ return resolveBooleanObjectOption(unocss, {});
3040
+ }
3041
+ function resolveUnocssBareArbitraryValues(arbitraryValues, unocss) {
3042
+ const baseArbitraryValues = arbitraryValues ?? {};
3043
+ const options = normalizeUnocssOptions(unocss);
3044
+ if (!options) return baseArbitraryValues;
3045
+ if (baseArbitraryValues.bareArbitraryValues !== void 0 && baseArbitraryValues.bareArbitraryValues !== false) return baseArbitraryValues;
3046
+ const bareArbitraryValues = options.bareArbitraryValues ?? true;
3047
+ if (bareArbitraryValues === false) return baseArbitraryValues;
3048
+ return {
3049
+ ...baseArbitraryValues,
3050
+ bareArbitraryValues
3051
+ };
3052
+ }
3053
+ //#endregion
3054
+ //#region src/context/compiler-context-cache.ts
3055
+ const PAREN_CONTENT_RE = /\(([^)]+)\)/u;
3056
+ const AT_LOCATION_RE = /at\s+(\S.*)$/u;
3057
+ const TRAILING_LINE_COL_RE = /:\d+(?::\d+)?$/u;
3058
+ const DEFAULT_COMPILER_CONTEXT_CACHE_MAX = 32;
3059
+ const DEFAULT_COMPILER_CONTEXT_KEY_CACHE_MAX = 64;
3060
+ const globalCacheHolder = globalThis;
3061
+ const compilerContextCache = globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ ?? (globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ = /* @__PURE__ */ new Map());
3062
+ const compilerContextKeyCacheByOptions = /* @__PURE__ */ new WeakMap();
3063
+ const compilerContextKeyCacheWithoutOptions = /* @__PURE__ */ new Map();
3064
+ function resolveCompilerContextCacheMax(defaultValue) {
3065
+ const raw = Number.parseInt(process.env["WEAPP_TW_COMPILER_CONTEXT_CACHE_MAX"] ?? "", 10);
3066
+ if (!Number.isFinite(raw) || raw <= 0) return defaultValue;
3067
+ return Math.floor(raw);
3068
+ }
3069
+ function touchMapValue(map, key, value) {
3070
+ map.delete(key);
3071
+ map.set(key, value);
3072
+ }
3073
+ function pruneMapToMaxSize(map, maxSize) {
3074
+ while (map.size > maxSize) {
3075
+ const firstKey = map.keys().next().value;
3076
+ if (firstKey === void 0) break;
3077
+ map.delete(firstKey);
3078
+ }
3079
+ }
3080
+ function withCircularGuard(value, stack, factory) {
3081
+ if (stack.has(value)) throw new TypeError("Cannot serialize circular structure in compiler context options");
3082
+ stack.add(value);
3083
+ try {
3084
+ return factory();
3085
+ } finally {
3086
+ stack.delete(value);
3087
+ }
3088
+ }
3089
+ function encodeTaggedValue(type, value) {
3090
+ const record = { __type: type };
3091
+ if (value !== void 0) record["value"] = value;
3092
+ return record;
3093
+ }
3094
+ function hasExplicitOptionBasedir(opts) {
3095
+ return typeof opts?.tailwindcssBasedir === "string" && opts.tailwindcssBasedir.length > 0;
3096
+ }
3097
+ function shouldProbeCallerLocation(opts) {
3098
+ if (hasExplicitOptionBasedir(opts)) return false;
3099
+ return !(process.env["WEAPP_TAILWINDCSS_BASEDIR"] || process.env["WEAPP_TAILWINDCSS_BASE_DIR"] || process.env["TAILWINDCSS_BASEDIR"] || process.env["TAILWINDCSS_BASE_DIR"]);
3100
+ }
3101
+ function detectCallerLocation() {
3102
+ const stack = (/* @__PURE__ */ new Error("compiler-context-cache stack probe")).stack;
3103
+ if (!stack) return;
3104
+ const lines = stack.split("\n");
3105
+ for (const line of lines) {
3106
+ const location = (line.match(PAREN_CONTENT_RE) ?? line.match(AT_LOCATION_RE))?.[1];
3107
+ if (!location) continue;
3108
+ const candidatePath = location.replace(TRAILING_LINE_COL_RE, "");
3109
+ if (!candidatePath || !path.isAbsolute(candidatePath)) continue;
3110
+ 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;
3111
+ return candidatePath;
3112
+ }
3113
+ }
3114
+ function getRuntimeCacheScope(opts) {
3115
+ if (hasExplicitOptionBasedir(opts)) return { caller: void 0 };
3116
+ const runtimeScope = {
3117
+ caller: void 0,
3118
+ cwd: process.cwd(),
3119
+ init_cwd: process.env["INIT_CWD"],
3120
+ npm_config_local_prefix: process.env["npm_config_local_prefix"],
3121
+ npm_package_json: process.env["npm_package_json"],
3122
+ pnpm_package_name: process.env["PNPM_PACKAGE_NAME"],
3123
+ pwd: process.env["PWD"],
3124
+ tailwindcss_base_dir: process.env["TAILWINDCSS_BASE_DIR"],
3125
+ tailwindcss_basedir: process.env["TAILWINDCSS_BASEDIR"],
3126
+ uni_app_input_dir: process.env["UNI_APP_INPUT_DIR"],
3127
+ uni_cli_root: process.env["UNI_CLI_ROOT"],
3128
+ uni_input_dir: process.env["UNI_INPUT_DIR"],
3129
+ uni_input_root: process.env["UNI_INPUT_ROOT"],
3130
+ weapp_tailwindcss_base_dir: process.env["WEAPP_TAILWINDCSS_BASE_DIR"],
3131
+ weapp_tailwindcss_basedir: process.env["WEAPP_TAILWINDCSS_BASEDIR"]
3132
+ };
3133
+ if (shouldProbeCallerLocation(opts)) runtimeScope.caller = detectCallerLocation();
3134
+ return runtimeScope;
3135
+ }
3136
+ function serializeNormalizedValue(value) {
3137
+ return JSON.stringify(value);
3138
+ }
3139
+ function createRuntimeCacheScopeKey(opts) {
3140
+ return serializeNormalizedValue(normalizeOptionsValue(getRuntimeCacheScope(opts)));
3141
+ }
3142
+ function getCompilerContextKeyCacheStore(opts) {
3143
+ if (!opts) return compilerContextKeyCacheWithoutOptions;
3144
+ let store = compilerContextKeyCacheByOptions.get(opts);
3145
+ if (!store) {
3146
+ store = /* @__PURE__ */ new Map();
3147
+ compilerContextKeyCacheByOptions.set(opts, store);
3148
+ }
3149
+ return store;
3150
+ }
3151
+ function createComparableNormalizedValue(rawValue, stack) {
3152
+ const normalized = normalizeOptionsValue(rawValue, stack);
3153
+ return {
3154
+ normalized,
3155
+ sortKey: serializeNormalizedValue(normalized)
3156
+ };
3157
+ }
3158
+ function getRuntimeCacheScopeValue(opts) {
3159
+ return {
3160
+ options: opts ?? {},
3161
+ runtime: getRuntimeCacheScope(opts)
3162
+ };
3163
+ }
3164
+ function normalizeOptionsValue(rawValue, stack = /* @__PURE__ */ new WeakSet()) {
3165
+ if (rawValue === null) return null;
3166
+ if (rawValue === void 0) return encodeTaggedValue("Undefined");
3167
+ const type = typeof rawValue;
3168
+ if (type === "string") return rawValue;
3169
+ if (type === "boolean") return rawValue;
3170
+ if (type === "number") {
3171
+ const numericValue = rawValue;
3172
+ if (Number.isNaN(numericValue)) return encodeTaggedValue("Number", "NaN");
3173
+ if (!Number.isFinite(numericValue)) return encodeTaggedValue("Number", numericValue > 0 ? "Infinity" : "-Infinity");
3174
+ if (Object.is(numericValue, -0)) return encodeTaggedValue("Number", "-0");
3175
+ return numericValue;
3176
+ }
3177
+ if (type === "bigint") return encodeTaggedValue("BigInt", rawValue.toString());
3178
+ if (type === "symbol") {
3179
+ const symbolValue = rawValue;
3180
+ return encodeTaggedValue("Symbol", symbolValue.description ?? String(symbolValue));
3181
+ }
3182
+ if (type === "function") return encodeTaggedValue("Function", rawValue.toString());
3183
+ if (Array.isArray(rawValue)) return withCircularGuard(rawValue, stack, () => rawValue.map((item) => normalizeOptionsValue(item, stack)));
3184
+ if (rawValue instanceof Date) return encodeTaggedValue("Date", rawValue.toISOString());
3185
+ if (rawValue instanceof RegExp) return {
3186
+ __type: "RegExp",
3187
+ source: rawValue.source,
3188
+ flags: rawValue.flags
3189
+ };
3190
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(rawValue)) return encodeTaggedValue("Buffer", rawValue.toString("base64"));
3191
+ if (ArrayBuffer.isView(rawValue)) {
3192
+ const view = rawValue;
3193
+ const buffer = Buffer.from(view.buffer, view.byteOffset, view.byteLength);
3194
+ return encodeTaggedValue(view.constructor?.name ?? "ArrayBufferView", buffer.toString("base64"));
3195
+ }
3196
+ if (rawValue instanceof ArrayBuffer) return encodeTaggedValue("ArrayBuffer", Buffer.from(rawValue).toString("base64"));
3197
+ if (rawValue instanceof Set) return withCircularGuard(rawValue, stack, () => {
3198
+ const normalizedEntries = Array.from(rawValue, (element) => createComparableNormalizedValue(element, stack));
3199
+ normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
3200
+ return {
3201
+ __type: "Set",
3202
+ value: normalizedEntries.map((entry) => entry.normalized)
3203
+ };
3204
+ });
3205
+ if (rawValue instanceof Map) return withCircularGuard(rawValue, stack, () => {
3206
+ const normalizedEntries = Array.from(rawValue.entries(), ([key, entryValue]) => {
3207
+ const normalizedKey = createComparableNormalizedValue(key, stack);
3208
+ return {
3209
+ key: normalizedKey.normalized,
3210
+ sortKey: normalizedKey.sortKey,
3211
+ value: normalizeOptionsValue(entryValue, stack)
3212
+ };
3213
+ });
3214
+ normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
3215
+ return {
3216
+ __type: "Map",
3217
+ value: normalizedEntries.map((entry) => [entry.key, entry.value])
3218
+ };
3219
+ });
3220
+ if (typeof URL !== "undefined" && rawValue instanceof URL) return encodeTaggedValue("URL", rawValue.toString());
3221
+ if (rawValue instanceof Error) {
3222
+ const errorValue = rawValue;
3223
+ return {
3224
+ __type: "Error",
3225
+ name: errorValue.name,
3226
+ message: errorValue.message,
3227
+ stack: errorValue.stack ?? ""
3228
+ };
3229
+ }
3230
+ if (rawValue instanceof Promise) return encodeTaggedValue("Promise");
3231
+ if (rawValue instanceof WeakMap) return encodeTaggedValue("WeakMap");
3232
+ if (rawValue instanceof WeakSet) return encodeTaggedValue("WeakSet");
3233
+ if (rawValue && typeof rawValue === "object") return withCircularGuard(rawValue, stack, () => {
3234
+ const result = {};
3235
+ const entries = Object.entries(rawValue);
3236
+ entries.sort(([a], [b]) => a.localeCompare(b));
3237
+ for (const [key, entryValue] of entries) result[key] = normalizeOptionsValue(entryValue, stack);
3238
+ return result;
3239
+ });
3240
+ return encodeTaggedValue(typeof rawValue, String(rawValue));
3241
+ }
3242
+ function createCompilerContextCacheKey(opts) {
3243
+ try {
3244
+ const runtimeCacheScopeKey = createRuntimeCacheScopeKey(opts);
3245
+ const keyStore = getCompilerContextKeyCacheStore(opts);
3246
+ const cached = keyStore.get(runtimeCacheScopeKey);
3247
+ if (cached !== void 0) return cached;
3248
+ const normalized = normalizeOptionsValue(getRuntimeCacheScopeValue(opts));
3249
+ const cacheKey = md5Hash(serializeNormalizedValue(normalized));
3250
+ touchMapValue(keyStore, runtimeCacheScopeKey, cacheKey);
3251
+ pruneMapToMaxSize(keyStore, resolveCompilerContextCacheMax(DEFAULT_COMPILER_CONTEXT_KEY_CACHE_MAX));
3252
+ return cacheKey;
3253
+ } catch (error) {
3254
+ logger.debug("skip compiler context cache: %O", error);
3255
+ return;
3256
+ }
3257
+ }
3258
+ function withCompilerContextCache(opts, factory) {
3259
+ const cacheKey = createCompilerContextCacheKey(opts);
3260
+ if (cacheKey) {
3261
+ const cached = compilerContextCache.get(cacheKey);
3262
+ if (cached) {
3263
+ touchMapValue(compilerContextCache, cacheKey, cached);
3264
+ return cached;
3265
+ }
3266
+ }
3267
+ const ctx = factory();
3268
+ if (cacheKey) {
3269
+ touchMapValue(compilerContextCache, cacheKey, ctx);
3270
+ pruneMapToMaxSize(compilerContextCache, resolveCompilerContextCacheMax(DEFAULT_COMPILER_CONTEXT_CACHE_MAX));
3271
+ }
3272
+ return ctx;
3273
+ }
3274
+ //#endregion
3275
+ //#region src/context/custom-attributes.ts
3276
+ function toCustomAttributesEntities(customAttributes) {
3277
+ if (!customAttributes) return [];
3278
+ if (isMap(customAttributes)) return [...customAttributes.entries()];
3279
+ return Object.entries(customAttributes);
3280
+ }
3281
+ //#endregion
3282
+ //#region src/js/literal-transform.ts
3283
+ function transformLiteralText(literal, options, classContext = true) {
3284
+ if (!options.alwaysEscape && (!options.classNameSet || options.classNameSet.size === 0)) return;
3285
+ const source = options.unescapeUnicode && literal.includes("\\u") ? decodeUnicode2(literal) : literal;
3286
+ const candidates = splitCandidateTokens(source);
3287
+ if (candidates.length === 0) return;
3288
+ const transformOptions = {
3289
+ ...options,
3290
+ classContext
3291
+ };
3292
+ const replacementCache = getReplacementCacheStore(options.escapeMap);
3293
+ let transformed = source;
3294
+ let mutated = false;
3295
+ for (const candidate of candidates) {
3296
+ const result = resolveClassNameTransformWithResult(candidate, transformOptions);
3297
+ if (result.decision === "skip" || !transformed.includes(candidate)) continue;
3298
+ const replacement = result.decision === "escaped" && result.escapedValue ? result.escapedValue : getReplacement(candidate, options.escapeMap, replacementCache);
3299
+ const replaced = transformed.replace(candidate, replacement);
3300
+ if (replaced !== transformed) {
3301
+ transformed = replaced;
3302
+ mutated = true;
3303
+ }
3304
+ }
3305
+ return mutated ? transformed : void 0;
3306
+ }
3307
+ //#endregion
3308
+ //#region src/js/fast-path/oxc.ts
3309
+ const require = createRequire(import.meta.url);
3310
+ let oxcParser;
3311
+ function isOxcParserRuntimeSupported(version = process.versions.node) {
3312
+ const match = /^(\d+)\.(\d+)(?:\.|$)/.exec(version);
3313
+ if (!match) return false;
3314
+ const major = Number(match[1]);
3315
+ const minor = Number(match[2]);
3316
+ if (major === 20) return minor >= 19;
3317
+ if (major === 21) return false;
3318
+ if (major === 22) return minor >= 12;
3319
+ return major > 22;
3320
+ }
3321
+ function loadOxcParser() {
3322
+ if (!isOxcParserRuntimeSupported()) return;
3323
+ if (oxcParser === false) return;
3324
+ if (oxcParser) return oxcParser;
3325
+ try {
3326
+ oxcParser = require("oxc-parser");
3327
+ } catch {
3328
+ oxcParser = false;
3329
+ return;
3330
+ }
3331
+ return oxcParser;
3332
+ }
3333
+ function hasValues(values) {
3334
+ return Array.isArray(values) && values.length > 0;
3335
+ }
3336
+ function hasUnsupportedSourceMarker(rawSource) {
3337
+ return rawSource.includes("eval(") || rawSource.includes("weapp-tw") && rawSource.includes("ignore");
3338
+ }
3339
+ function hasSupportedClassMatchSource(options) {
3340
+ return options.alwaysEscape === true || Boolean(options.classNameSet && options.classNameSet.size > 0);
3341
+ }
3342
+ function canAttemptOxcJsFastPath(options) {
3343
+ if (options.experimentalJsFastPath !== true && options.experimentalJsFastPath !== "oxc") return false;
3344
+ return !options.generateMap && !options.wrapExpression && !options.moduleGraph && !options.moduleSpecifierReplacements && hasSupportedClassMatchSource(options) && !hasValues(options.ignoreCallExpressionIdentifiers);
3345
+ }
3346
+ function getParserLang(filename) {
3347
+ if (filename?.endsWith(".ts") || filename?.endsWith(".mts") || filename?.endsWith(".cts")) return "ts";
3348
+ if (filename?.endsWith(".tsx")) return "tsx";
3349
+ if (filename?.endsWith(".jsx")) return "jsx";
3350
+ return "js";
3351
+ }
3352
+ function getParserSourceType(sourceType) {
3353
+ return sourceType === "script" || sourceType === "module" ? sourceType : "module";
3354
+ }
3355
+ function isRangeValid(start, end) {
3356
+ return typeof start === "number" && typeof end === "number" && start < end;
3357
+ }
3358
+ function getMagicString(rawSource, context) {
3359
+ if (!context.ms) context.ms = new MagicString(rawSource);
3360
+ return context.ms;
3361
+ }
3362
+ function addStringLiteralReplacement(rawSource, node, transformOptions, context) {
3363
+ if (typeof node.value !== "string" || typeof node.raw !== "string" || !isRangeValid(node.start, node.end)) return false;
3364
+ const transformed = transformLiteralText(node.value, transformOptions, false);
3365
+ if (!transformed) return false;
3366
+ const start = node.start + 1;
3367
+ const end = node.end - 1;
3368
+ if (start >= end || transformed === rawSource.slice(start, end)) return false;
3369
+ getMagicString(rawSource, context).update(start, end, jsStringEscape(transformed));
3370
+ return true;
3371
+ }
3372
+ function addTemplateElementReplacement(rawSource, node, transformOptions, context) {
3373
+ const raw = node.value?.raw;
3374
+ if (typeof raw !== "string" || !isRangeValid(node.start, node.end)) return false;
3375
+ const transformed = transformLiteralText(raw, transformOptions, false);
3376
+ if (!transformed || transformed === raw) return false;
3377
+ const first = rawSource[node.start];
3378
+ const last = rawSource[node.end - 1];
3379
+ const start = node.start + (first === "`" || first === "}" ? 1 : 0);
3380
+ const end = node.end - (last === "`" ? 1 : last === "{" ? 2 : 0);
3381
+ if (start >= end) return false;
3382
+ getMagicString(rawSource, context).update(start, end, transformed);
3383
+ return true;
3384
+ }
3385
+ function applyReplacements(rawSource, program, stringLiteralOptions, templateLiteralOptions, context) {
3386
+ let changed = false;
3387
+ walk(program, { enter(node) {
3388
+ if (node.type === "Literal") {
3389
+ changed = addStringLiteralReplacement(rawSource, node, stringLiteralOptions, context) || changed;
3390
+ return;
3391
+ }
3392
+ if (node.type === "TemplateElement") {
3393
+ changed = addTemplateElementReplacement(rawSource, node, templateLiteralOptions, context) || changed;
3394
+ this.skip();
3395
+ }
3396
+ } });
3397
+ return changed;
3398
+ }
3399
+ function hasTaggedTemplateExpression(program) {
3400
+ let found = false;
3401
+ walk(program, { enter(node) {
3402
+ if (node.type === "TaggedTemplateExpression") {
3403
+ found = true;
3404
+ this.skip();
3405
+ }
3406
+ } });
3407
+ return found;
3408
+ }
3409
+ function oxcJsHandler(rawSource, options) {
3410
+ if (!canAttemptOxcJsFastPath(options)) return;
3411
+ if (hasUnsupportedSourceMarker(rawSource)) return;
3412
+ const parser = loadOxcParser();
3413
+ if (!parser) return;
3414
+ let result;
3415
+ try {
3416
+ result = parser.parseSync(options.filename ?? "weapp-tailwindcss.js", rawSource, {
3417
+ sourceType: getParserSourceType(options.babelParserOptions?.sourceType),
3418
+ lang: getParserLang(options.filename)
3419
+ });
3420
+ } catch {
3421
+ return;
3422
+ }
3423
+ if (!result.program || Array.isArray(result.errors) && result.errors.length > 0) return;
3424
+ if (hasValues(options.ignoreTaggedTemplateExpressionIdentifiers) && hasTaggedTemplateExpression(result.program)) return;
3425
+ const stringLiteralOptions = options.needEscaped === true ? options : {
3426
+ ...options,
3427
+ needEscaped: true
3428
+ };
3429
+ const templateLiteralOptions = options.needEscaped === false ? options : {
3430
+ ...options,
3431
+ needEscaped: false
3432
+ };
3433
+ const replacementContext = {};
3434
+ if (!applyReplacements(rawSource, result.program, stringLiteralOptions, templateLiteralOptions, replacementContext)) return { code: rawSource };
3435
+ return { code: replacementContext.ms.toString() };
3436
+ }
3437
+ //#endregion
3438
+ //#region src/js/precheck.ts
3439
+ /** 用于检测源码中是否包含类名相关模式的正则表达式 */
3440
+ 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)-/;
3441
+ /** 用于检测源码中是否包含 import/export/require 语句的正则表达式 */
3442
+ const DEPENDENCY_HINT_RE = /\bimport\s*(?:["'`{]|\*\s+as\b)|\brequire\s*\(|\bexport\s+\*\s+from\s+["'`]|\bexport\s*\{[^}]*\}\s*from\s+["'`]/;
3443
+ /**
3444
+ * 判断源码是否可能声明跨模块依赖。
3445
+ *
3446
+ * 该检查只作为性能预筛:返回 `true` 时必须保守走 AST 模块图分析;
3447
+ * 返回 `false` 时源码中没有可被当前模块图消费的静态 import/export/require 形态。
3448
+ */
3449
+ function hasDependencyHint(rawSource) {
3450
+ return DEPENDENCY_HINT_RE.test(rawSource);
3451
+ }
3452
+ /**
3453
+ * 判断是否可以跳过 JS 转换。
3454
+ * 通过正则快速检测源码内容,避免不必要的 Babel AST 解析。
3455
+ *
3456
+ * @param rawSource - 原始 JS 源码字符串
3457
+ * @param options - 可选的 JS 处理器配置选项
3458
+ * @returns 如果可以跳过转换返回 `true`,否则返回 `false`
3459
+ */
3460
+ function shouldSkipJsTransform(rawSource, options) {
3461
+ if (process.env["WEAPP_TW_DISABLE_JS_PRECHECK"] === "1") return false;
3462
+ if (!rawSource) return true;
3463
+ if (options?.alwaysEscape) return false;
3464
+ if (options?.moduleSpecifierReplacements && Object.keys(options.moduleSpecifierReplacements).length > 0) return false;
3465
+ if (options?.wrapExpression) return false;
3466
+ if (hasDependencyHint(rawSource)) return false;
3467
+ return !FAST_JS_TRANSFORM_HINT_RE.test(rawSource);
3468
+ }
3469
+ //#endregion
3470
+ //#region src/js/index.ts
3471
+ /** 默认 LRU 缓存最大条目数 */
3472
+ const RESULT_CACHE_MAX = 512;
3473
+ /** 仅对短片段做内层结果缓存,避免 bundler 热路径重复 hash 大块 JS。 */
3474
+ const CACHEABLE_SOURCE_MAX_LENGTH = 512;
3475
+ /** 为每个 ClassNameSet 实例分配递增 ID */
3476
+ const classNameSetIds = /* @__PURE__ */ new WeakMap();
3477
+ let nextClassNameSetId = 0;
3478
+ /**
3479
+ * 获取 ClassNameSet 的唯一身份 ID。
3480
+ * 每个 Set 引用分配一个递增整数,用于指纹计算。
3481
+ */
3482
+ function getClassNameSetId(set) {
3483
+ if (!set) return "none";
3484
+ const existing = classNameSetIds.get(set);
3485
+ if (existing !== void 0) return String(existing);
3486
+ const id = nextClassNameSetId++;
3487
+ classNameSetIds.set(set, id);
3488
+ return String(id);
3489
+ }
3490
+ /** 缓存 IJsHandlerOptions -> fingerprint 的映射 */
3491
+ const fingerprintCache = /* @__PURE__ */ new WeakMap();
3492
+ /**
3493
+ * 计算选项指纹,包含所有影响转译结果的字段。
3494
+ * 不包含 filename、moduleGraph、jsPreserveClass。
3495
+ */
3496
+ function getOptionsFingerprint(options) {
3497
+ const cached = fingerprintCache.get(options);
3498
+ if (cached) return cached;
3499
+ const fingerprint = [
3500
+ getClassNameSetId(options.classNameSet),
3501
+ JSON.stringify(options.escapeMap ?? null),
3502
+ options.needEscaped ? "1" : "0",
3503
+ options.alwaysEscape ? "1" : "0",
3504
+ options.unescapeUnicode ? "1" : "0",
3505
+ options.generateMap ? "1" : "0",
3506
+ options.uniAppX ? "1" : "0",
3507
+ options.wrapExpression ? "1" : "0",
3508
+ JSON.stringify(options.arbitraryValues ?? null),
3509
+ JSON.stringify(options.ignoreCallExpressionIdentifiers ?? null),
3510
+ JSON.stringify(options.ignoreTaggedTemplateExpressionIdentifiers?.map((v) => v instanceof RegExp ? v.source : v) ?? null),
3511
+ JSON.stringify(options.moduleSpecifierReplacements ?? null),
3512
+ String(options.experimentalJsFastPath ?? ""),
3513
+ JSON.stringify(options.babelParserOptions ?? null)
3514
+ ].join("|");
3515
+ fingerprintCache.set(options, fingerprint);
3516
+ return fingerprint;
3517
+ }
3518
+ function hasDefinedOverrides(options) {
3519
+ if (!options) return false;
3520
+ for (const key in options) if (options[key] !== void 0) return true;
3521
+ return false;
3522
+ }
3523
+ function shouldCacheJsResult(rawSource, options) {
3524
+ if (rawSource.length === 0 || rawSource.length > CACHEABLE_SOURCE_MAX_LENGTH) return false;
3525
+ if (options.moduleGraph || options.filename) return false;
3526
+ return true;
3527
+ }
3528
+ function resolveFastPathOptions(rawSource, options) {
3529
+ if (!options.moduleGraph) return options;
3530
+ if (options.moduleSpecifierReplacements && Object.keys(options.moduleSpecifierReplacements).length > 0) return options;
3531
+ if (hasDependencyHint(rawSource)) return options;
3532
+ const { moduleGraph: _moduleGraph, ...fastPathOptions } = options;
3533
+ return fastPathOptions;
3534
+ }
3535
+ function createJsHandler(options) {
3536
+ const defaults = {
3537
+ escapeMap: options.escapeMap,
3538
+ jsArbitraryValueFallback: options.jsArbitraryValueFallback,
3539
+ tailwindcssMajorVersion: options.tailwindcssMajorVersion,
3540
+ arbitraryValues: options.arbitraryValues,
3541
+ jsPreserveClass: options.jsPreserveClass,
3542
+ generateMap: options.generateMap,
3543
+ needEscaped: options.needEscaped,
3544
+ alwaysEscape: options.alwaysEscape,
3545
+ unescapeUnicode: options.unescapeUnicode,
3546
+ babelParserOptions: options.babelParserOptions,
3547
+ experimentalJsFastPath: options.experimentalJsFastPath,
3548
+ ignoreCallExpressionIdentifiers: options.ignoreCallExpressionIdentifiers,
3549
+ ignoreTaggedTemplateExpressionIdentifiers: options.ignoreTaggedTemplateExpressionIdentifiers,
3550
+ uniAppX: options.uniAppX,
3551
+ moduleSpecifierReplacements: options.moduleSpecifierReplacements
3552
+ };
3553
+ /** 层1: 无 override 时,classNameSet -> resolvedOptions */
3554
+ const defaultOptionsCache = /* @__PURE__ */ new WeakMap();
3555
+ let resolvedOptionsWithoutClassNameSet;
3556
+ /** 层2: 有 override 时,overrideOptions -> { bySet, noSet } */
3557
+ const overrideOptionsCache = /* @__PURE__ */ new WeakMap();
3558
+ const resultCache = new LRUCache({ max: RESULT_CACHE_MAX });
3559
+ function resolveDefaultOptions(classNameSet) {
3560
+ if (!classNameSet) {
3561
+ if (!resolvedOptionsWithoutClassNameSet) resolvedOptionsWithoutClassNameSet = {
3562
+ ...defaults,
3563
+ classNameSet
3564
+ };
3565
+ return resolvedOptionsWithoutClassNameSet;
3566
+ }
3567
+ const cached = defaultOptionsCache.get(classNameSet);
3568
+ if (cached) return cached;
3569
+ const created = {
3570
+ ...defaults,
3571
+ classNameSet
3572
+ };
3573
+ defaultOptionsCache.set(classNameSet, created);
3574
+ return created;
3575
+ }
3576
+ function getCachedJsResult(rawSource, resolvedOptions) {
3577
+ if (!shouldCacheJsResult(rawSource, resolvedOptions)) return;
3578
+ const key = `${getOptionsFingerprint(resolvedOptions)}:${md5Hash(rawSource)}`;
3579
+ return resultCache.get(key);
3580
+ }
3581
+ function setCachedJsResult(rawSource, resolvedOptions, result) {
3582
+ if (!shouldCacheJsResult(rawSource, resolvedOptions) || result.error || result.linked) return result;
3583
+ const key = `${getOptionsFingerprint(resolvedOptions)}:${md5Hash(rawSource)}`;
3584
+ resultCache.set(key, result);
3585
+ return result;
3586
+ }
3587
+ function resolveOptions(classNameSet, overrideOptions) {
3588
+ if (!hasDefinedOverrides(overrideOptions)) return resolveDefaultOptions(classNameSet);
3589
+ let entry = overrideOptionsCache.get(overrideOptions);
3590
+ if (!entry) {
3591
+ entry = { bySet: /* @__PURE__ */ new WeakMap() };
3592
+ overrideOptionsCache.set(overrideOptions, entry);
3593
+ }
3594
+ if (!classNameSet) {
3595
+ if (entry.noSet) return entry.noSet;
3596
+ const created = defuOverrideArray$1({
3597
+ ...overrideOptions,
3598
+ classNameSet
3599
+ }, defaults);
3600
+ entry.noSet = created;
3601
+ return created;
3602
+ }
3603
+ const cached = entry.bySet.get(classNameSet);
3604
+ if (cached) return cached;
3605
+ const created = defuOverrideArray$1({
3606
+ ...overrideOptions,
3607
+ classNameSet
3608
+ }, defaults);
3609
+ entry.bySet.set(classNameSet, created);
3610
+ return created;
3611
+ }
3612
+ function handler(rawSource, classNameSet, options) {
3613
+ const resolvedOptions = resolveOptions(classNameSet, options);
3614
+ const cached = getCachedJsResult(rawSource, resolvedOptions);
3615
+ if (cached) return cached;
3616
+ return setCachedJsResult(rawSource, resolvedOptions, oxcJsHandler(rawSource, resolveFastPathOptions(rawSource, resolvedOptions)) ?? jsHandler(rawSource, resolvedOptions));
3617
+ }
3618
+ return handler;
3619
+ }
3620
+ //#endregion
3621
+ //#region src/wxml/utils/codegen/legacy-visitor.ts
3622
+ function shouldSkipLegacyStringLiteral(path) {
3623
+ if (t.isMemberExpression(path.parent)) return true;
3624
+ return Boolean(t.isBinaryExpression(path.parent) && (t.isConditionalExpression(path.parentPath?.parent) || t.isLogicalExpression(path.parentPath?.parent)));
3625
+ }
3626
+ function createLegacyTraverseOptions(options, jsTokenUpdater) {
3627
+ const legacyReplaceOptions = {
3628
+ escapeMap: options.escapeMap,
3629
+ classNameSet: options.runtimeSet,
3630
+ needEscaped: true,
3631
+ alwaysEscape: true
3632
+ };
3633
+ return {
3634
+ StringLiteral(path) {
3635
+ if (shouldSkipLegacyStringLiteral(path)) return;
3636
+ jsTokenUpdater.addToken(replaceHandleValue(path, legacyReplaceOptions));
3637
+ },
3638
+ noScope: true
3639
+ };
3640
+ }
3641
+ //#endregion
3642
+ //#region src/wxml/utils/codegen/legacy-rewriter.ts
3643
+ function rewriteLegacyExpression(match, options) {
3644
+ const ast = parseExpression(match);
3645
+ const jsTokenUpdater = new JsTokenUpdater();
3646
+ traverse(ast, createLegacyTraverseOptions(options, jsTokenUpdater));
3647
+ if (jsTokenUpdater.length === 0) return match;
3648
+ const ms = new MagicString(match);
3649
+ jsTokenUpdater.updateMagicString(ms);
3650
+ return ms.toString();
3651
+ }
3652
+ //#endregion
3653
+ //#region src/wxml/utils/codegen.ts
3654
+ const WRAP_EXPRESSION_HANDLER_OPTIONS = Object.freeze({ wrapExpression: true });
3655
+ function generateCode(match, options = {}) {
3656
+ try {
3657
+ const { jsHandler, runtimeSet, wrapExpression } = options;
3658
+ if (jsHandler && runtimeSet) {
3659
+ const initial = jsHandler(match, runtimeSet, wrapExpression ? WRAP_EXPRESSION_HANDLER_OPTIONS : void 0);
3660
+ if (!initial.error || wrapExpression) return initial.code;
3661
+ return jsHandler(match, runtimeSet, WRAP_EXPRESSION_HANDLER_OPTIONS).code;
3662
+ } else return rewriteLegacyExpression(match, options);
3663
+ } catch {
3664
+ return match;
3665
+ }
3666
+ }
3667
+ //#endregion
3668
+ //#region src/wxml/whitespace.ts
3669
+ const WHITESPACE_CODES = /* @__PURE__ */ new Set([
3670
+ 9,
3671
+ 10,
3672
+ 11,
3673
+ 12,
3674
+ 13,
3675
+ 32,
3676
+ 160,
3677
+ 65279
3678
+ ]);
3679
+ function isWhitespace(char) {
3680
+ if (char.length === 0) return false;
3681
+ return WHITESPACE_CODES.has(char.charCodeAt(0));
3682
+ }
3683
+ function isAllWhitespace(value) {
3684
+ for (let i = 0; i < value.length; i++) if (!WHITESPACE_CODES.has(value.charCodeAt(i))) return false;
3685
+ return true;
3686
+ }
3687
+ //#endregion
3688
+ //#region src/wxml/Tokenizer.ts
3689
+ var Tokenizer = class {
3690
+ constructor() {
3691
+ _defineProperty(this, "state", void 0);
3692
+ _defineProperty(this, "buffer", void 0);
3693
+ _defineProperty(this, "tokens", void 0);
3694
+ _defineProperty(this, "bufferStartIndex", void 0);
3695
+ _defineProperty(this, "expressionStartIndex", void 0);
3696
+ _defineProperty(this, "expressionBuffer", void 0);
3697
+ _defineProperty(this, "expressions", void 0);
3698
+ this.reset();
3699
+ }
3700
+ processChar(char, index) {
3701
+ switch (this.state) {
3702
+ case 0:
3703
+ if (isWhitespace(char)) {} else if (char === "{") {
3704
+ this.state = 2;
3705
+ this.bufferStartIndex = index;
3706
+ this.buffer += char;
3707
+ this.expressionBuffer = char;
3708
+ this.expressionStartIndex = index;
3709
+ } else {
3710
+ this.state = 1;
3711
+ this.bufferStartIndex = index;
3712
+ this.buffer += char;
3713
+ }
3714
+ break;
3715
+ case 1:
3716
+ if (isWhitespace(char)) {
3717
+ this.tokens.push({
3718
+ start: this.bufferStartIndex,
3719
+ end: index,
3720
+ value: this.buffer,
3721
+ expressions: this.expressions
3722
+ });
3723
+ this.buffer = "";
3724
+ this.expressions = [];
3725
+ this.state = 0;
3726
+ } else if (char === "{") {
3727
+ this.buffer += char;
3728
+ this.expressionBuffer = char;
3729
+ this.expressionStartIndex = index;
3730
+ this.state = 2;
3731
+ } else this.buffer += char;
3732
+ break;
3733
+ case 2:
3734
+ if (char === "}") {
3735
+ this.buffer += char;
3736
+ this.expressionBuffer += char;
3737
+ this.state = 3;
3738
+ } else {
3739
+ this.buffer += char;
3740
+ this.expressionBuffer += char;
3741
+ }
3742
+ break;
3743
+ case 3:
3744
+ if (char === "}") {
3745
+ this.buffer += char;
3746
+ this.expressionBuffer += char;
3747
+ this.expressions.push({
3748
+ start: this.expressionStartIndex,
3749
+ end: index + 1,
3750
+ value: this.expressionBuffer
3751
+ });
3752
+ this.expressionBuffer = "";
3753
+ this.state = 4;
3754
+ } else {
3755
+ this.buffer += char;
3756
+ this.expressionBuffer += char;
3757
+ this.state = 2;
3758
+ }
3759
+ break;
3760
+ case 4:
3761
+ if (isWhitespace(char)) {
3762
+ this.tokens.push({
3763
+ start: this.bufferStartIndex,
3764
+ end: index,
3765
+ value: this.buffer,
3766
+ expressions: this.expressions
3767
+ });
3768
+ this.buffer = "";
3769
+ this.expressions = [];
3770
+ this.state = 0;
3771
+ } else if (char === "{") {
3772
+ this.expressionStartIndex = index;
3773
+ this.expressionBuffer = char;
3774
+ this.buffer += char;
3775
+ this.state = 2;
3776
+ } else {
3777
+ this.buffer += char;
3778
+ this.state = 1;
3779
+ }
3780
+ break;
3781
+ default: throw new Error("Unexpected state");
3782
+ }
3783
+ }
3784
+ run(input) {
3785
+ this.reset();
3786
+ for (let i = 0; i < input.length; i++) {
3787
+ const char = input[i];
3788
+ if (char === void 0) continue;
3789
+ this.processChar(char, i);
3790
+ }
3791
+ if (this.buffer.length > 0) this.tokens.push({
3792
+ start: this.bufferStartIndex,
3793
+ end: input.length,
3794
+ value: this.buffer,
3795
+ expressions: this.expressions
3796
+ });
3797
+ const tokens = this.tokens;
3798
+ this.reset();
3799
+ return tokens;
3800
+ }
3801
+ reset() {
3802
+ this.state = 0;
3803
+ this.buffer = "";
3804
+ this.tokens = [];
3805
+ this.bufferStartIndex = 0;
3806
+ this.expressionBuffer = "";
3807
+ this.expressionStartIndex = 0;
3808
+ this.expressions = [];
3809
+ }
3810
+ };
3811
+ //#endregion
3812
+ //#region src/wxml/utils/fragment-helpers.ts
3813
+ function updateWhitespaceGap(ms, start, end, options) {
3814
+ const gap = ms.slice(start, end);
3815
+ if (isAllWhitespace(gap)) ms.update(start, end, replaceWxml(gap, {
3816
+ keepEOL: false,
3817
+ escapeMap: options.escapeMap,
3818
+ ignoreHead: true
3819
+ }));
3820
+ }
3821
+ function updateWxmlSegment(ms, start, end, options, keepEOL, ignoreHead) {
3822
+ const value = ms.slice(start, end);
3823
+ const replaceOptions = {
3824
+ keepEOL,
3825
+ escapeMap: options.escapeMap,
3826
+ ignoreHead
3827
+ };
3828
+ if (options.classSetMode === "exact" && options.runtimeSet) {
3829
+ ms.update(start, end, value.replace(/\S+/g, (candidate) => options.runtimeSet.has(candidate) ? replaceWxml(candidate, replaceOptions) : candidate));
3830
+ return;
3831
+ }
3832
+ ms.update(start, end, replaceWxml(value, replaceOptions));
3833
+ }
3834
+ function updateExpressionSegment(ms, exp, options) {
3835
+ const code = `{{${generateCode(exp.value.slice(2, -2), options)}}}`;
3836
+ ms.update(exp.start, exp.end, code);
3837
+ }
3838
+ //#endregion
3839
+ //#region src/wxml/utils/fragment-updater.ts
3840
+ function handleEachClassFragment(ms, tokens, options = {}) {
3841
+ let previousEnd = 0;
3842
+ for (const token of tokens) {
3843
+ if (token.start > previousEnd) updateWhitespaceGap(ms, previousEnd, token.start, options);
3844
+ let p = token.start;
3845
+ if (token.expressions.length > 0) {
3846
+ for (const exp of token.expressions) {
3847
+ if (exp.start > token.start && p < exp.start) updateWxmlSegment(ms, p, exp.start, options, true, p > 0);
3848
+ updateExpressionSegment(ms, exp, options);
3849
+ p = exp.end;
3850
+ }
3851
+ if (token.end > p) updateWxmlSegment(ms, p, token.end, options, false, true);
3852
+ } else updateWxmlSegment(ms, token.start, token.end, options, false, false);
3853
+ previousEnd = token.end;
3854
+ }
3855
+ if (tokens.length > 0) {
3856
+ const lastToken = tokens[tokens.length - 1];
3857
+ if (!lastToken) return;
3858
+ if (lastToken.end < ms.original.length) updateWhitespaceGap(ms, lastToken.end, ms.original.length, options);
3859
+ }
3860
+ }
3861
+ //#endregion
3862
+ //#region src/wxml/utils/template-fragments.ts
3863
+ /**
3864
+ * 模块级共享 Tokenizer 实例,避免每次调用都重新创建。
3865
+ * Tokenizer.run() 末尾已调用 reset(),天然支持复用。
3866
+ */
3867
+ const sharedTokenizer = new Tokenizer();
3868
+ function templateReplacer(original, options = {}, tokenizer) {
3869
+ const ms = new MagicString(original);
3870
+ handleEachClassFragment(ms, (tokenizer ?? sharedTokenizer).run(ms.original), options);
3871
+ return ms.toString();
3872
+ }
3873
+ //#endregion
3874
+ //#region src/wxml/utils/custom-template.ts
3875
+ async function customTemplateHandler(rawSource, options, cachedMatcher) {
3876
+ const { customAttributesEntities = [], disabledDefaultTemplateHandler, inlineWxs, runtimeSet, jsHandler } = options ?? {};
3877
+ const matchCustomAttribute = cachedMatcher ?? createAttributeMatcher(customAttributesEntities);
3878
+ const defaultTemplateHandlerEnabled = !disabledDefaultTemplateHandler;
3879
+ let replaceOptions;
3880
+ let cachedQuote;
3881
+ let s;
3882
+ let tag = "";
3883
+ let wxsArray;
3884
+ function getMagicString() {
3885
+ if (!s) s = new MagicString(rawSource);
3886
+ return s;
3887
+ }
3888
+ function getReplaceOptions(quote) {
3889
+ if (!replaceOptions) {
3890
+ replaceOptions = {
3891
+ ...options,
3892
+ quote
3893
+ };
3894
+ cachedQuote = quote;
3895
+ return replaceOptions;
3896
+ }
3897
+ if (cachedQuote !== quote) {
3898
+ replaceOptions.quote = quote;
3899
+ cachedQuote = quote;
3900
+ }
3901
+ return replaceOptions;
3902
+ }
3903
+ function isDefaultTemplateAttribute(name) {
3904
+ if (name === "class" || name === "hover-class" || name === "virtualhostclass") return true;
3905
+ const lowerName = name.toLowerCase();
3906
+ return lowerName === "class" || lowerName === "hover-class" || lowerName === "virtualhostclass";
3907
+ }
3908
+ const parser = new Parser({
3909
+ onopentagname(name) {
3910
+ tag = name;
3911
+ },
3912
+ onattribute(name, value, quote) {
3913
+ if (!value) return;
3914
+ const shouldHandleDefault = defaultTemplateHandlerEnabled && isDefaultTemplateAttribute(name);
3915
+ const shouldHandleCustom = matchCustomAttribute?.(tag, name) ?? false;
3916
+ if (!shouldHandleDefault && !shouldHandleCustom) return;
3917
+ getMagicString().update(parser.startIndex + name.length + 2, parser.endIndex - 1, templateReplacer(value, getReplaceOptions(quote)));
3918
+ },
3919
+ ontext(data) {
3920
+ if (inlineWxs && tag === "wxs") (wxsArray ?? (wxsArray = [])).push({
3921
+ data,
3922
+ endIndex: parser.endIndex + 1,
3923
+ startIndex: parser.startIndex
3924
+ });
3925
+ },
3926
+ onclosetag() {
3927
+ tag = "";
3928
+ }
3929
+ }, { xmlMode: true });
3930
+ parser.write(rawSource);
3931
+ parser.end();
3932
+ if (jsHandler) for (const { data, endIndex, startIndex } of wxsArray ?? []) {
3933
+ const { code } = await jsHandler(data, runtimeSet);
3934
+ if (code !== data) getMagicString().update(startIndex, endIndex, code);
3935
+ }
3936
+ return s?.toString() ?? rawSource;
3937
+ }
3938
+ //#endregion
3939
+ //#region src/wxml/utils.ts
3940
+ function createTemplateHandler(options = {}) {
3941
+ const cachedMatcher = createAttributeMatcher(options.customAttributesEntities);
3942
+ const defaultOptions = options;
3943
+ let cachedRuntimeSet;
3944
+ let cachedOptionsWithRuntimeSet;
3945
+ return (rawSource, opt) => {
3946
+ const runtimeSet = opt?.runtimeSet;
3947
+ if (opt && Object.keys(opt).some((key) => key !== "runtimeSet")) return customTemplateHandler(rawSource, defuOverrideArray(opt, defaultOptions), opt.customAttributesEntities === void 0 ? cachedMatcher : void 0);
3948
+ if (runtimeSet === void 0) return customTemplateHandler(rawSource, defaultOptions, cachedMatcher);
3949
+ if (cachedRuntimeSet !== runtimeSet || !cachedOptionsWithRuntimeSet) {
3950
+ cachedRuntimeSet = runtimeSet;
3951
+ cachedOptionsWithRuntimeSet = {
3952
+ ...defaultOptions,
3953
+ runtimeSet
3954
+ };
3955
+ }
3956
+ return customTemplateHandler(rawSource, cachedOptionsWithRuntimeSet, cachedMatcher);
3957
+ };
3958
+ }
3959
+ //#endregion
3960
+ //#region src/constants.ts
3961
+ const pluginName = "weapp-tailwindcss";
3962
+ const vitePluginName = "weapp-tailwindcss:adaptor";
3963
+ const DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS = {
3964
+ "tailwind-merge": "@weapp-tailwindcss/merge",
3965
+ "class-variance-authority": "@weapp-tailwindcss/cva",
3966
+ "tailwind-variants": "@weapp-tailwindcss/variants"
3967
+ };
3968
+ //#endregion
3969
+ //#region src/context/runtime-package-replacements.ts
3970
+ function resolveRuntimePackageReplacements(option) {
3971
+ const mapping = resolveBooleanObjectOption(option, DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS);
3972
+ if (!mapping) return;
3973
+ const normalized = {};
3974
+ for (const [from, to] of Object.entries(mapping)) {
3975
+ if (!from || typeof to !== "string" || to.length === 0) continue;
3976
+ normalized[from] = to;
3977
+ }
3978
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
3979
+ }
3980
+ //#endregion
3981
+ //#region src/context/style-options.ts
3982
+ function normalizeStyleHandlerMajorVersion(majorVersion) {
3983
+ return majorVersion === 4 ? 4 : void 0;
3984
+ }
3985
+ function resolveStyleOptionsFromContext(ctx, tailwindcssMajorVersion) {
3986
+ const resolvedUniAppXOptions = resolveUniAppXOptions(ctx.uniAppX);
3987
+ const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(ctx.generator, {
3988
+ appType: ctx.appType,
3989
+ platform: ctx.cssOptions?.platform ?? ctx.platform,
3990
+ tailwindcssMajorVersion,
3991
+ uniAppX: resolvedUniAppXOptions
3992
+ });
3993
+ const branch = resolveGeneratorRuntimeBranch(generatorOptions, {
3994
+ appType: ctx.appType,
3995
+ platform: ctx.cssOptions?.platform ?? ctx.platform,
3996
+ tailwindcssMajorVersion,
3997
+ uniAppX: resolvedUniAppXOptions
3998
+ });
3999
+ const hasCssOptions = ctx.cssOptions !== void 0;
4000
+ const configuredRem2rpx = ctx.cssOptions?.rem2rpx ?? ctx.rem2rpx;
4001
+ const rem2rpx = branch.isWeb && shouldUseUniAppWebRpxCompatibility(ctx.appType) ? false : configuredRem2rpx;
4002
+ const cssOptions = {
4003
+ cssPreflight: ctx.cssOptions?.cssPreflight ?? ctx.cssPreflight,
4004
+ cssPreflightRange: ctx.cssOptions?.cssPreflightRange ?? ctx.cssPreflightRange,
4005
+ cssChildCombinatorReplaceValue: ctx.cssOptions?.cssChildCombinatorReplaceValue ?? ctx.cssChildCombinatorReplaceValue,
4006
+ cssSelectorReplacement: ctx.cssOptions?.cssSelectorReplacement ?? ctx.cssSelectorReplacement,
4007
+ rem2rpx,
4008
+ cssRemoveProperty: ctx.cssOptions?.cssRemoveProperty ?? ctx.cssRemoveProperty,
4009
+ cssRemoveActivePseudoClass: ctx.cssOptions?.cssRemoveActivePseudoClass ?? ctx.cssRemoveActivePseudoClass,
4010
+ cssRemoveHoverPseudoClass: ctx.cssOptions?.cssRemoveHoverPseudoClass ?? ctx.cssRemoveHoverPseudoClass,
4011
+ cssRemoveFocusPseudoClass: ctx.cssOptions?.cssRemoveFocusPseudoClass ?? ctx.cssRemoveFocusPseudoClass,
4012
+ tailwindcssV4GradientFallback: ctx.cssOptions?.tailwindcssV4GradientFallback ?? ctx.tailwindcssV4GradientFallback,
4013
+ cssPresetEnv: ctx.cssOptions?.cssPresetEnv ?? ctx.cssPresetEnv,
4014
+ atRules: ctx.cssOptions?.atRules ?? ctx.atRules,
4015
+ autoprefixer: ctx.cssOptions?.autoprefixer ?? ctx.autoprefixer,
4016
+ cssCalc: ctx.cssOptions?.cssCalc ?? ctx.cssCalc,
4017
+ platform: branch.platform ?? ctx.cssOptions?.platform ?? ctx.platform,
4018
+ px2rpx: ctx.cssOptions?.px2rpx ?? ctx.px2rpx,
4019
+ unitsToPx: ctx.cssOptions?.unitsToPx ?? ctx.unitsToPx,
4020
+ unitConversion: ctx.cssOptions?.unitConversion ?? ctx.unitConversion,
4021
+ injectAdditionalCssVarScope: ctx.cssOptions?.injectAdditionalCssVarScope ?? ctx.injectAdditionalCssVarScope
4022
+ };
4023
+ return {
4024
+ appType: ctx.appType,
4025
+ postcssOptions: ctx.postcssOptions,
4026
+ cssPreflight: cssOptions.cssPreflight,
4027
+ cssPreflightRange: cssOptions.cssPreflightRange,
4028
+ cssChildCombinatorReplaceValue: cssOptions.cssChildCombinatorReplaceValue,
4029
+ cssSelectorReplacement: cssOptions.cssSelectorReplacement,
4030
+ rem2rpx: cssOptions.rem2rpx,
4031
+ ...hasCssOptions ? { cssOptions } : {},
4032
+ cssRemoveProperty: cssOptions.cssRemoveProperty,
4033
+ cssRemoveActivePseudoClass: cssOptions.cssRemoveActivePseudoClass,
4034
+ cssRemoveHoverPseudoClass: cssOptions.cssRemoveHoverPseudoClass,
4035
+ cssRemoveFocusPseudoClass: cssOptions.cssRemoveFocusPseudoClass,
4036
+ tailwindcssV4GradientFallback: cssOptions.tailwindcssV4GradientFallback,
4037
+ cssPresetEnv: cssOptions.cssPresetEnv,
4038
+ atRules: cssOptions.atRules,
4039
+ autoprefixer: cssOptions.autoprefixer,
4040
+ cssCalc: cssOptions.cssCalc,
4041
+ uniAppX: branch.isNativeApp,
4042
+ platform: cssOptions.platform,
4043
+ px2rpx: cssOptions.px2rpx,
4044
+ unitsToPx: cssOptions.unitsToPx,
4045
+ unitConversion: cssOptions.unitConversion
4046
+ };
4047
+ }
4048
+ //#endregion
4049
+ //#region src/context/handlers.ts
4050
+ function createHandlersFromContext(ctx, customAttributesEntities, cssCalcOptions, tailwindcssMajorVersion) {
4051
+ const { escapeMap, injectAdditionalCssVarScope, postcssOptions, uniAppX, arbitraryValues, jsPreserveClass, babelParserOptions, experimentalJsFastPath, ignoreCallExpressionIdentifiers, ignoreTaggedTemplateExpressionIdentifiers, inlineWxs, disabledDefaultTemplateHandler, replaceRuntimePackages } = ctx;
4052
+ const resolvedUniAppXOptions = resolveUniAppXOptions(uniAppX);
4053
+ const styleOptions = resolveStyleOptionsFromContext(ctx, tailwindcssMajorVersion);
4054
+ const resolvedInjectAdditionalCssVarScope = styleOptions.cssOptions?.injectAdditionalCssVarScope ?? injectAdditionalCssVarScope;
4055
+ const uniAppXEnabled = styleOptions.uniAppX === true;
4056
+ const moduleSpecifierReplacements = resolveRuntimePackageReplacements(replaceRuntimePackages);
4057
+ const styleHandler = createStyleHandler({
4058
+ ...styleOptions,
4059
+ escapeMap,
4060
+ injectAdditionalCssVarScope: resolvedInjectAdditionalCssVarScope,
4061
+ postcssOptions,
4062
+ uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
4063
+ cssCalc: cssCalcOptions,
4064
+ majorVersion: normalizeStyleHandlerMajorVersion(tailwindcssMajorVersion)
4065
+ });
4066
+ const jsHandler = createJsHandler({
4067
+ escapeMap,
4068
+ arbitraryValues,
4069
+ jsPreserveClass,
4070
+ generateMap: true,
4071
+ babelParserOptions,
4072
+ experimentalJsFastPath,
4073
+ ignoreCallExpressionIdentifiers,
4074
+ ignoreTaggedTemplateExpressionIdentifiers,
4075
+ uniAppX: uniAppXEnabled,
4076
+ moduleSpecifierReplacements
4077
+ });
4078
+ return {
4079
+ styleHandler,
4080
+ jsHandler,
4081
+ templateHandler: createTemplateHandler({
4082
+ customAttributesEntities,
4083
+ escapeMap,
4084
+ inlineWxs,
4085
+ jsHandler,
4086
+ disabledDefaultTemplateHandler
4087
+ })
4088
+ };
4089
+ }
4090
+ //#endregion
4091
+ //#region src/context/logger.ts
4092
+ const loggerLevelMap = {
4093
+ error: 0,
4094
+ warn: 1,
4095
+ info: 3,
4096
+ silent: -999
4097
+ };
4098
+ function applyLoggerLevel(logLevel) {
4099
+ logger.level = loggerLevelMap[logLevel ?? "info"] ?? loggerLevelMap.info;
4100
+ }
4101
+ //#endregion
4102
+ //#region src/context/index.ts
4103
+ function resolveContextCssPreflight(opts, ctx, majorVersion) {
4104
+ const userCssPreflight = opts?.cssOptions?.cssPreflight ?? opts?.cssPreflight;
4105
+ const cssPreflight = resolveDefaultCssPreflight(userCssPreflight, majorVersion);
4106
+ const shouldUseUniAppXPreflight = ctx.appType === "uni-app-x" || resolveUniAppXOptions(ctx.uniAppX).enabled;
4107
+ if (cssPreflight === false || !shouldUseUniAppXPreflight) return cssPreflight;
4108
+ const userCssPreflightObject = userCssPreflight && typeof userCssPreflight === "object" ? userCssPreflight : void 0;
4109
+ return {
4110
+ ...cssPreflight,
4111
+ "border-width": userCssPreflightObject && "border-width" in userCssPreflightObject ? cssPreflight["border-width"] ?? false : "0",
4112
+ "border-style": userCssPreflightObject && "border-style" in userCssPreflightObject ? cssPreflight["border-style"] ?? false : false,
4113
+ "border": userCssPreflightObject && "border" in userCssPreflightObject ? cssPreflight["border"] ?? false : false
4114
+ };
4115
+ }
4116
+ function syncCssOptionsToLegacyFields(ctx) {
4117
+ if (!ctx.cssOptions) return;
4118
+ const cssOptions = ctx.cssOptions;
4119
+ ctx.cssPreflight = cssOptions.cssPreflight ?? ctx.cssPreflight;
4120
+ ctx.cssPreflightRange = cssOptions.cssPreflightRange ?? ctx.cssPreflightRange;
4121
+ ctx.cssChildCombinatorReplaceValue = cssOptions.cssChildCombinatorReplaceValue ?? ctx.cssChildCombinatorReplaceValue;
4122
+ ctx.cssSelectorReplacement = cssOptions.cssSelectorReplacement ?? ctx.cssSelectorReplacement;
4123
+ ctx.rem2rpx = cssOptions.rem2rpx ?? ctx.rem2rpx;
4124
+ ctx.cssRemoveProperty = cssOptions.cssRemoveProperty ?? ctx.cssRemoveProperty;
4125
+ ctx.cssRemoveActivePseudoClass = cssOptions.cssRemoveActivePseudoClass ?? ctx.cssRemoveActivePseudoClass;
4126
+ ctx.cssRemoveHoverPseudoClass = cssOptions.cssRemoveHoverPseudoClass ?? ctx.cssRemoveHoverPseudoClass;
4127
+ ctx.cssRemoveFocusPseudoClass = cssOptions.cssRemoveFocusPseudoClass ?? ctx.cssRemoveFocusPseudoClass;
4128
+ ctx.tailwindcssV4GradientFallback = cssOptions.tailwindcssV4GradientFallback ?? ctx.tailwindcssV4GradientFallback;
4129
+ ctx.cssPresetEnv = cssOptions.cssPresetEnv ?? ctx.cssPresetEnv;
4130
+ ctx.atRules = cssOptions.atRules ?? ctx.atRules;
4131
+ ctx.autoprefixer = cssOptions.autoprefixer ?? ctx.autoprefixer;
4132
+ ctx.cssCalc = cssOptions.cssCalc ?? ctx.cssCalc;
4133
+ ctx.platform = cssOptions.platform ?? ctx.platform;
4134
+ ctx.px2rpx = cssOptions.px2rpx ?? ctx.px2rpx;
4135
+ ctx.unitsToPx = cssOptions.unitsToPx ?? ctx.unitsToPx;
4136
+ ctx.unitConversion = cssOptions.unitConversion ?? ctx.unitConversion;
4137
+ ctx.injectAdditionalCssVarScope = cssOptions.injectAdditionalCssVarScope ?? ctx.injectAdditionalCssVarScope;
4138
+ }
4139
+ function syncLegacyFieldsToCssOptions(ctx) {
4140
+ if (!ctx.cssOptions) return;
4141
+ ctx.cssOptions = {
4142
+ ...ctx.cssOptions ?? {},
4143
+ cssPreflight: ctx.cssPreflight,
4144
+ cssPreflightRange: ctx.cssPreflightRange,
4145
+ cssChildCombinatorReplaceValue: ctx.cssChildCombinatorReplaceValue,
4146
+ cssSelectorReplacement: ctx.cssSelectorReplacement,
4147
+ rem2rpx: ctx.rem2rpx,
4148
+ cssRemoveProperty: ctx.cssRemoveProperty,
4149
+ cssRemoveActivePseudoClass: ctx.cssRemoveActivePseudoClass,
4150
+ cssRemoveHoverPseudoClass: ctx.cssRemoveHoverPseudoClass,
4151
+ cssRemoveFocusPseudoClass: ctx.cssRemoveFocusPseudoClass,
4152
+ tailwindcssV4GradientFallback: ctx.tailwindcssV4GradientFallback,
4153
+ cssPresetEnv: ctx.cssPresetEnv,
4154
+ atRules: ctx.atRules,
4155
+ autoprefixer: ctx.autoprefixer,
4156
+ cssCalc: ctx.cssCalc,
4157
+ platform: ctx.platform,
4158
+ px2rpx: ctx.px2rpx,
4159
+ unitsToPx: ctx.unitsToPx,
4160
+ unitConversion: ctx.unitConversion,
4161
+ injectAdditionalCssVarScope: ctx.injectAdditionalCssVarScope
4162
+ };
4163
+ }
4164
+ function applyFrameworkPlatformDefaults(ctx) {
4165
+ if (ctx.cssOptions?.platform || ctx.platform) {
4166
+ ctx.platform = normalizeFrameworkStylePlatform(ctx.cssOptions?.platform ?? ctx.platform, ctx.appType);
4167
+ return;
4168
+ }
4169
+ if (ctx.appType === "mpx") ctx.platform = normalizeFrameworkStylePlatform(resolveMpxPlatform().normalized, ctx.appType);
4170
+ }
4171
+ async function clearTailwindcssRuntimeCache(tailwindRuntime, options) {
4172
+ if (!tailwindRuntime) return;
4173
+ const cacheOptions = tailwindRuntime.options?.cache;
4174
+ if (cacheOptions == null || typeof cacheOptions === "object" && cacheOptions.enabled === false) return;
4175
+ if (typeof tailwindRuntime.clearCache === "function") try {
4176
+ await tailwindRuntime.clearCache({ scope: "all" });
4177
+ } catch (error) {
4178
+ logger.debug("failed to clear tailwindcss runtime cache via clearCache(): %O", error);
4179
+ }
4180
+ if (!options?.removeDirectory) return;
4181
+ const cachePaths = /* @__PURE__ */ new Map();
4182
+ const normalizedCacheOptions = typeof cacheOptions === "object" ? cacheOptions : void 0;
4183
+ const privateCachePath = tailwindRuntime?.cacheStore?.options?.path;
4184
+ if (privateCachePath) cachePaths.set(privateCachePath, false);
4185
+ if (normalizedCacheOptions?.path) cachePaths.set(normalizedCacheOptions.path, false);
4186
+ if (options?.removeDirectory && normalizedCacheOptions?.dir) cachePaths.set(normalizedCacheOptions.dir, true);
4187
+ if (!cachePaths.size) return;
4188
+ for (const [cachePath, recursive] of cachePaths.entries()) try {
4189
+ await rm(cachePath, {
4190
+ force: true,
4191
+ recursive
4192
+ });
4193
+ } catch (error) {
4194
+ const err = error;
4195
+ if (err?.code === "ENOENT") continue;
4196
+ logger.debug("failed to clear tailwindcss runtime cache: %s %O", cachePath, err);
4197
+ }
4198
+ }
4199
+ function createInternalCompilerContext(opts) {
4200
+ const ctx = defuOverrideArray$1(opts, getDefaultOptions(), {});
4201
+ ctx.arbitraryValues = resolveUnocssBareArbitraryValues(ctx.arbitraryValues, ctx.unocss);
4202
+ ctx.escapeMap = ctx.customReplaceDictionary;
4203
+ syncCssOptionsToLegacyFields(ctx);
4204
+ applyFrameworkPlatformDefaults(ctx);
4205
+ applyLoggerLevel(ctx.logLevel);
4206
+ const tailwindRuntime = createTailwindcssRuntimeFromContext(ctx);
4207
+ if (opts?.__internalViteDeferRuntimeLogs !== true) {
4208
+ logTailwindcssTarget(tailwindRuntime, ctx.tailwindcssBasedir);
4209
+ logRuntimeTailwindcssVersion(ctx.tailwindcssBasedir, tailwindRuntime.packageInfo?.rootPath, tailwindRuntime.packageInfo?.version);
4210
+ }
4211
+ if (opts?.__internalDeferMissingCssEntriesWarning !== true) warnMissingCssEntries(ctx, tailwindRuntime);
4212
+ ctx.cssPreflight = resolveContextCssPreflight(opts, ctx, tailwindRuntime.majorVersion);
4213
+ const cssCalcOptions = applyV4CssCalcDefaults(ctx.cssCalc, tailwindRuntime);
4214
+ ctx.cssCalc = cssCalcOptions;
4215
+ syncLegacyFieldsToCssOptions(ctx);
4216
+ const customAttributesEntities = toCustomAttributesEntities(ctx.customAttributes);
4217
+ ctx.customAttributesEntities = customAttributesEntities;
4218
+ const { styleHandler, jsHandler, templateHandler } = createHandlersFromContext(ctx, customAttributesEntities, cssCalcOptions, tailwindRuntime.majorVersion);
4219
+ ctx.styleHandler = styleHandler;
4220
+ ctx.jsHandler = jsHandler;
4221
+ ctx.templateHandler = templateHandler;
4222
+ ctx.cache = initializeCache(ctx.cache);
4223
+ ctx.tailwindRuntime = tailwindRuntime;
4224
+ const refreshTailwindcssRuntime = async (options) => {
4225
+ const previousRuntime = ctx.tailwindRuntime;
4226
+ if (options?.clearCache !== false) await clearTailwindcssRuntimeCache(previousRuntime);
4227
+ invalidateRuntimeClassSet(previousRuntime);
4228
+ const nextRuntime = createTailwindcssRuntimeFromContext(ctx);
4229
+ Object.assign(previousRuntime, nextRuntime);
4230
+ ctx.tailwindRuntime = previousRuntime;
4231
+ return previousRuntime;
4232
+ };
4233
+ ctx.refreshTailwindcssRuntime = refreshTailwindcssRuntime;
4234
+ Object.defineProperty(ctx.tailwindRuntime, refreshTailwindcssRuntimeSymbol, {
4235
+ value: refreshTailwindcssRuntime,
4236
+ configurable: true
4237
+ });
4238
+ return ctx;
4239
+ }
4240
+ /**
4241
+ * 获取用户定义选项的内部表示,并初始化相关的处理程序和 Tailwind 运行时。
4242
+ * @param opts - 用户定义的选项,可选。
4243
+ * @returns 返回一个包含内部用户定义选项的对象,包括样式、JS 和模板处理程序,以及 Tailwind CSS 运行时。
4244
+ */
4245
+ function getCompilerContext(opts) {
4246
+ return withCompilerContextCache(opts, () => createInternalCompilerContext(opts));
4247
+ }
4248
+ //#endregion
4249
+ //#region src/core/compiler/transforms.ts
4250
+ const DEFAULT_JS_OPTIONS = Object.freeze({ tailwindcssMajorVersion: 4 });
4251
+ const DEFAULT_STYLE_OPTIONS = Object.freeze({ isMainChunk: true });
4252
+ function clonePostcssResult(result) {
4253
+ return Object.assign(Object.create(Object.getPrototypeOf(result)), result, {
4254
+ messages: [...result.messages],
4255
+ root: result.root.clone()
4256
+ });
4257
+ }
4258
+ function resolveStyleOptions(options) {
4259
+ if (!options) return DEFAULT_STYLE_OPTIONS;
4260
+ return options?.isMainChunk === void 0 ? {
4261
+ ...options,
4262
+ isMainChunk: true
4263
+ } : options;
4264
+ }
4265
+ function resolveCssTransformOptions(options) {
4266
+ const { finalize: _finalize, ...styleOptions } = options ?? {};
4267
+ return {
4268
+ finalize: _finalize,
4269
+ styleOptions: resolveStyleOptions(styleOptions)
4270
+ };
4271
+ }
4272
+ function finalizeResultRoot(result, snapshot, shouldFinalize) {
4273
+ if (!shouldFinalize || result.root.type !== "root") return;
4274
+ finalizeMiniProgramCssRoot(result.root, { isTailwindcssV4: snapshot.target === "weapp" });
4275
+ result.css = result.root.toString();
4276
+ }
4277
+ function createCompilerTransforms({ ensureActive, track, userOptions }) {
4278
+ const context = getCompilerContext({
4279
+ ...userOptions,
4280
+ __internalDeferMissingCssEntriesWarning: true
4281
+ });
4282
+ const styleHandler = context.styleHandler;
4283
+ let cachedTemplateClassSet;
4284
+ let cachedTemplateOptions;
4285
+ function clearCache() {
4286
+ cachedTemplateClassSet = void 0;
4287
+ cachedTemplateOptions = void 0;
4288
+ }
4289
+ function createTemplateOptions(classSet, options) {
4290
+ const isDefault = !options || Object.keys(options).length === 0;
4291
+ if (isDefault && cachedTemplateClassSet === classSet && cachedTemplateOptions) return cachedTemplateOptions;
4292
+ const resolved = {
4293
+ ...options,
4294
+ classSetMode: "exact",
4295
+ jsHandler: (jsSource, _runtimeSet, jsOptions) => context.jsHandler(jsSource, classSet, {
4296
+ ...jsOptions,
4297
+ tailwindcssMajorVersion: jsOptions?.tailwindcssMajorVersion ?? 4
4298
+ }),
4299
+ runtimeSet: classSet
4300
+ };
4301
+ if (isDefault) {
4302
+ cachedTemplateClassSet = classSet;
4303
+ cachedTemplateOptions = resolved;
4304
+ }
4305
+ return resolved;
4306
+ }
4307
+ function transformCss(css, snapshot, options) {
4308
+ ensureActive();
4309
+ getInternalCompilerSnapshot(snapshot);
4310
+ const resolved = resolveCssTransformOptions(options);
4311
+ const shouldFinalize = resolved.finalize ?? snapshot.target === "weapp";
4312
+ return track(styleHandler(css, resolved.styleOptions).then((result) => {
4313
+ const cloned = clonePostcssResult(result);
4314
+ finalizeResultRoot(cloned, snapshot, shouldFinalize);
4315
+ return cloned;
4316
+ }));
4317
+ }
4318
+ function transformCssRoot(root, snapshot, options) {
4319
+ ensureActive();
4320
+ getInternalCompilerSnapshot(snapshot);
4321
+ const resolved = resolveCssTransformOptions(options);
4322
+ const shouldFinalize = resolved.finalize ?? snapshot.target === "weapp";
4323
+ return track(styleHandler.transformRoot(root, resolved.styleOptions).then((result) => {
4324
+ finalizeResultRoot(result, snapshot, shouldFinalize);
4325
+ return result;
4326
+ }));
4327
+ }
4328
+ function transformJavaScript(source, snapshot, options) {
4329
+ ensureActive();
4330
+ const classSet = getInternalCompilerSnapshot(snapshot).classSet;
4331
+ const resolvedOptions = options?.tailwindcssMajorVersion === void 0 ? options ? {
4332
+ ...options,
4333
+ tailwindcssMajorVersion: 4
4334
+ } : DEFAULT_JS_OPTIONS : options;
4335
+ return track(Promise.resolve(shouldSkipJsTransform(source, resolvedOptions) ? { code: source } : context.jsHandler(source, classSet, resolvedOptions)));
4336
+ }
4337
+ function transformTemplate(source, snapshot, options) {
4338
+ ensureActive();
4339
+ const classSet = getInternalCompilerSnapshot(snapshot).classSet;
4340
+ return track(context.templateHandler(source, createTemplateOptions(classSet, options)));
4341
+ }
4342
+ return {
4343
+ clearCache,
4344
+ transformCss,
4345
+ transformCssRoot,
4346
+ transformJavaScript,
4347
+ transformTemplate
4348
+ };
4349
+ }
4350
+ //#endregion
4351
+ //#region src/core/compiler/compiler.ts
4352
+ const DEFAULT_MAX_ROOTS = 128;
4353
+ function createCompiler(options = {}) {
4354
+ const { compiler: compilerOptions, ...userOptions } = options;
4355
+ const rootStore = new CompilerRootStore(Math.max(1, Math.floor(compilerOptions?.maxRoots ?? DEFAULT_MAX_ROOTS)), compilerOptions?.onRootEvicted);
4356
+ const activeTasks = /* @__PURE__ */ new Set();
4357
+ let lifecycle = "active";
4358
+ let disposePromise;
4359
+ function ensureActive() {
4360
+ if (lifecycle !== "active") throw new Error(lifecycle === "disposing" ? "Compiler 正在释放,不能接受新任务。" : "Compiler 已释放。");
4361
+ }
4362
+ function track(task) {
4363
+ activeTasks.add(task);
4364
+ task.then(() => activeTasks.delete(task), () => activeTasks.delete(task));
4365
+ return task;
4366
+ }
4367
+ const { clearCache: clearTransformCache, ...transforms } = createCompilerTransforms({
4368
+ ensureActive,
4369
+ track,
4370
+ userOptions
4371
+ });
4372
+ async function resolveRequestSource(entry, request) {
4373
+ if (request.source && request.sourceOptions) throw new Error("generate() 的 source 与 sourceOptions 互斥。");
4374
+ if (!request.source && !request.sourceOptions) throw new Error("generate() 必须提供 source 或 sourceOptions。");
4375
+ const sourceInput = request.source ?? request.sourceOptions;
4376
+ return {
4377
+ source: entry.source !== void 0 && entry.sourceInput === sourceInput && entry.appliedInvalidation === entry.invalidation ? entry.source : request.source ?? await resolveTailwindV4Source$1(request.sourceOptions),
4378
+ sourceInput
4379
+ };
4380
+ }
4381
+ async function runGenerate(entry, request) {
4382
+ if (!entry.active) throw new Error(`Compiler root 已被移除:${entry.id}`);
4383
+ const invalidation = entry.invalidation;
4384
+ const { source, sourceInput } = await resolveRequestSource(entry, request);
4385
+ const sourceFingerprint = entry.sourceInput === sourceInput && entry.sourceFingerprint !== void 0 && entry.appliedInvalidation === invalidation ? entry.sourceFingerprint : createSourceFingerprint(source);
4386
+ const sourceReused = entry.sourceFingerprint === sourceFingerprint;
4387
+ const engineReused = sourceReused && entry.generator !== void 0 && entry.appliedInvalidation === invalidation;
4388
+ const generator = engineReused ? entry.generator : createWeappTailwindcssGenerator(source);
4389
+ const target = request.target ?? "weapp";
4390
+ const { id: _id, source: _source, sourceOptions: _sourceOptions, target: _target, ...generateOptions } = request;
4391
+ const prepared = prepareCompilerGeneration(entry, request, source, !sourceReused || entry.appliedInvalidation !== invalidation);
4392
+ const generationCacheKey = createCompilerGenerationCacheKey(request, prepared.compilation.candidates, target);
4393
+ const reusableGeneration = engineReused && entry.generationCache && isSameCompilerGenerationCacheKey(entry.generationCache.key, generationCacheKey) ? entry.generationCache.result : void 0;
4394
+ try {
4395
+ const generated = reusableGeneration ? reuseCompilerGenerationResult(reusableGeneration) : await generator.generate({
4396
+ ...generateOptions,
4397
+ candidates: prepared.explicitCandidates ? prepared.compilation.candidates : void 0,
4398
+ incrementalCache: generateOptions.incrementalCache ?? true,
4399
+ target: target === "tailwind" ? "web" : target
4400
+ });
4401
+ if (!entry.active) throw new Error(`Compiler root 已被移除:${entry.id}`);
4402
+ const revision = (getLatestRevision(entry) ?? 0) + 1;
4403
+ const dependencies = [.../* @__PURE__ */ new Set([...source.dependencies, ...generated.dependencies])].sort();
4404
+ const sources = generated.sources ?? source.sources ?? [];
4405
+ const previousSnapshotState = entry.latestSnapshot ? getInternalCompilerSnapshot(entry.latestSnapshot) : void 0;
4406
+ const reusableClassSet = engineReused && generated.incrementalCss === "" && previousSnapshotState && previousSnapshotState.classSet.size === generated.classSet.size && [...generated.classSet].every((candidate) => previousSnapshotState.classSet.has(candidate)) ? previousSnapshotState.classSet : void 0;
4407
+ const reusableClassSetView = reusableClassSet ? entry.latestSnapshot?.classSet : void 0;
4408
+ const snapshot = createRegisteredCompilerSnapshot({
4409
+ classSet: generated.classSet,
4410
+ dependencies,
4411
+ id: entry.id,
4412
+ revision,
4413
+ sources,
4414
+ target
4415
+ }, reusableClassSet, reusableClassSetView);
4416
+ const internalSnapshot = getInternalCompilerSnapshot(snapshot);
4417
+ const previousGenerator = entry.generator;
4418
+ commitCompilerGeneration(entry, prepared, source, dependencies, generated.classSet);
4419
+ entry.generator = generator;
4420
+ entry.generationCache = {
4421
+ key: generationCacheKey,
4422
+ result: generated
4423
+ };
4424
+ entry.source = source;
4425
+ entry.sourceFingerprint = sourceFingerprint;
4426
+ entry.sourceInput = sourceInput;
4427
+ entry.appliedInvalidation = invalidation;
4428
+ entry.latestSnapshot = snapshot;
4429
+ rootStore.attachDependencies(entry, dependencies);
4430
+ rootStore.attachSources(entry, sources);
4431
+ if (!engineReused && previousGenerator !== generator) previousGenerator?.dispose?.();
4432
+ const css = target === "tailwind" ? generated.rawCss : generated.css;
4433
+ const incrementalCss = target === "tailwind" ? generated.incrementalRawCss : generated.incrementalCss;
4434
+ return {
4435
+ ...generated,
4436
+ cache: Object.freeze({
4437
+ engine: engineReused,
4438
+ output: reusableGeneration !== void 0 || engineReused && incrementalCss === "",
4439
+ source: sourceReused
4440
+ }),
4441
+ classSet: snapshot.classSet,
4442
+ css,
4443
+ dependencies: snapshot.dependencies,
4444
+ incrementalCss,
4445
+ rawCandidates: createImmutableSet(generated.rawCandidates),
4446
+ revision,
4447
+ snapshot,
4448
+ sources: internalSnapshot.sources,
4449
+ target
4450
+ };
4451
+ } catch (error) {
4452
+ if (!engineReused) generator.dispose?.();
4453
+ throw error;
4454
+ }
4455
+ }
4456
+ function getLatestRevision(entry) {
4457
+ return entry.latestSnapshot?.roots[0]?.revision;
4458
+ }
4459
+ function generate(request) {
4460
+ ensureActive();
4461
+ const entry = rootStore.get(request.id);
4462
+ entry.pendingCount += 1;
4463
+ const execution = entry.pending.then(() => runGenerate(entry, request));
4464
+ entry.pending = execution.finally(() => {
4465
+ entry.pendingCount -= 1;
4466
+ rootStore.trim();
4467
+ }).then(() => void 0, () => void 0);
4468
+ return track(execution);
4469
+ }
4470
+ function createSnapshot(request) {
4471
+ ensureActive();
4472
+ return createRegisteredCompilerSnapshot(request);
4473
+ }
4474
+ function finalizeCss(css, options) {
4475
+ ensureActive();
4476
+ return finalizeMiniProgramCss(css, options);
4477
+ }
4478
+ function finalizeCssRoot(root, options) {
4479
+ ensureActive();
4480
+ const cloned = root.clone();
4481
+ finalizeMiniProgramCssRoot(cloned, options);
4482
+ return cloned;
4483
+ }
4484
+ function mergeSnapshots(snapshots) {
4485
+ ensureActive();
4486
+ return mergeRegisteredCompilerSnapshots(snapshots);
4487
+ }
4488
+ function invalidate(ids) {
4489
+ ensureActive();
4490
+ return rootStore.invalidate(ids);
4491
+ }
4492
+ async function remove(id) {
4493
+ if (lifecycle === "disposed") return;
4494
+ clearTransformCache();
4495
+ await rootStore.remove(id);
4496
+ }
4497
+ function dispose() {
4498
+ if (disposePromise) return disposePromise;
4499
+ lifecycle = "disposing";
4500
+ disposePromise = (async () => {
4501
+ await Promise.allSettled([...activeTasks]);
4502
+ clearTransformCache();
4503
+ await rootStore.dispose();
4504
+ lifecycle = "disposed";
4505
+ })();
4506
+ return disposePromise;
4507
+ }
4508
+ return {
4509
+ createSnapshot,
4510
+ dispose,
4511
+ finalizeCss,
4512
+ finalizeCssRoot,
4513
+ generate,
4514
+ invalidate,
4515
+ mergeSnapshots,
4516
+ remove,
4517
+ ...transforms
4518
+ };
4519
+ }
4520
+ //#endregion
4521
+ //#region src/compiler/framework-compiler-session.ts
4522
+ /**
4523
+ * 官方 bundler 共享的 compiler 生命周期边界。
4524
+ *
4525
+ * bundler 继续拥有模块图和 scope 投影;本层只负责把逻辑 source root
4526
+ * 映射到一个长期复用的 compiler,并保证 root 删除与 owner 释放可等待。
4527
+ */
4528
+ var FrameworkCompilerSession = class {
4529
+ constructor(options) {
4530
+ _defineProperty(this, "compiler", void 0);
4531
+ _defineProperty(this, "scopeRoots", /* @__PURE__ */ new Map());
4532
+ _defineProperty(this, "activeRoots", /* @__PURE__ */ new Set());
4533
+ _defineProperty(this, "transactionId", 0);
4534
+ _defineProperty(this, "disposed", false);
4535
+ this.compiler = createCompiler(options);
4536
+ }
4537
+ rootId(scopeId, sourceId) {
4538
+ return `framework:${this.encode(scopeId)}:${this.encode(sourceId)}`;
4539
+ }
4540
+ async generate(scopeId, sourceId, source, request) {
4541
+ if (this.disposed) throw new Error("FrameworkCompilerSession 已释放。");
4542
+ const stableId = this.rootId(scopeId, sourceId);
4543
+ const id = this.activeRoots.has(stableId) ? `${stableId}:transaction-${++this.transactionId}` : stableId;
4544
+ let roots = this.scopeRoots.get(scopeId);
4545
+ if (!roots) {
4546
+ roots = /* @__PURE__ */ new Set();
4547
+ this.scopeRoots.set(scopeId, roots);
4548
+ }
4549
+ roots.add(stableId);
4550
+ this.activeRoots.add(stableId);
4551
+ try {
4552
+ return await this.compiler.generate({
4553
+ ...request,
4554
+ id,
4555
+ source: {
4556
+ ...source,
4557
+ dependencies: source.dependencies ?? []
4558
+ }
4559
+ });
4560
+ } finally {
4561
+ this.activeRoots.delete(stableId);
4562
+ if (id !== stableId) await this.compiler.remove(id);
4563
+ }
4564
+ }
4565
+ async syncScope(scopeId, sourceIds) {
4566
+ if (this.disposed) return;
4567
+ const roots = this.scopeRoots.get(scopeId);
4568
+ if (!roots) return;
4569
+ const active = new Set([...sourceIds].map((sourceId) => this.rootId(scopeId, sourceId)));
4570
+ const removed = [...roots].filter((rootId) => !active.has(rootId));
4571
+ await Promise.all(removed.map((rootId) => this.compiler.remove(rootId)));
4572
+ for (const rootId of removed) roots.delete(rootId);
4573
+ if (roots.size === 0) this.scopeRoots.delete(scopeId);
4574
+ }
4575
+ async removeScope(scopeId) {
4576
+ const roots = this.scopeRoots.get(scopeId);
4577
+ if (!roots) return;
4578
+ this.scopeRoots.delete(scopeId);
4579
+ await Promise.all([...roots].map((rootId) => this.compiler.remove(rootId)));
4580
+ }
4581
+ invalidate(ids) {
4582
+ return this.compiler.invalidate(ids);
4583
+ }
4584
+ mergeSnapshots(snapshots) {
4585
+ return this.compiler.mergeSnapshots(snapshots);
4586
+ }
4587
+ dispose() {
4588
+ if (this.disposed) return Promise.resolve();
4589
+ this.disposed = true;
4590
+ this.scopeRoots.clear();
4591
+ return this.compiler.dispose();
4592
+ }
4593
+ encode(value) {
4594
+ return Buffer.from(value, "utf8").toString("base64url");
4595
+ }
4596
+ };
4597
+ const frameworkCompilerSessions = /* @__PURE__ */ new WeakMap();
4598
+ function getFrameworkCompilerSession(owner, options) {
4599
+ let session = frameworkCompilerSessions.get(owner);
4600
+ if (!session) {
4601
+ session = new FrameworkCompilerSession(options);
4602
+ frameworkCompilerSessions.set(owner, session);
4603
+ }
4604
+ return session;
4605
+ }
4606
+ function disposeFrameworkCompilerSession(owner) {
4607
+ const session = frameworkCompilerSessions.get(owner);
4608
+ if (!session) return Promise.resolve();
4609
+ frameworkCompilerSessions.delete(owner);
4610
+ return session.dispose();
4611
+ }
4612
+ //#endregion
4613
+ //#region src/compiler/shadow-report-session.ts
4614
+ const COMPILER_SHADOW_REPORT_CACHE_MAX = 512;
4615
+ function cloneSemanticValue(value) {
4616
+ if (Array.isArray(value)) return value.map(cloneSemanticValue);
4617
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneSemanticValue(entry)]));
4618
+ return value;
4619
+ }
4620
+ function cloneCompilerShadowReport(report) {
4621
+ return {
4622
+ file: report.file,
4623
+ scopeId: report.scopeId,
4624
+ equal: report.equal,
4625
+ differences: report.differences.map((difference) => ({
4626
+ kind: difference.kind,
4627
+ path: difference.path,
4628
+ ..."left" in difference ? { left: cloneSemanticValue(difference.left) } : {},
4629
+ ..."right" in difference ? { right: cloneSemanticValue(difference.right) } : {}
4630
+ })),
4631
+ truncated: report.truncated,
4632
+ legacy: { ...report.legacy },
4633
+ graph: { ...report.graph }
4634
+ };
4635
+ }
4636
+ var CompilerShadowReportSession = class {
4637
+ constructor(maxReports = COMPILER_SHADOW_REPORT_CACHE_MAX) {
4638
+ this.maxReports = maxReports;
4639
+ _defineProperty(this, "reportsByScope", /* @__PURE__ */ new Map());
4640
+ _defineProperty(this, "revision", 0);
4641
+ _defineProperty(this, "dropped", 0);
4642
+ _defineProperty(this, "completed", false);
4643
+ _defineProperty(this, "disposed", false);
4644
+ if (!Number.isInteger(maxReports) || maxReports <= 0) throw new Error("CompilerShadowReportSession 的 maxReports 必须是正整数。");
4645
+ }
4646
+ beginRun() {
4647
+ this.ensureActive();
4648
+ this.revision += 1;
4649
+ this.reportsByScope.clear();
4650
+ this.dropped = 0;
4651
+ this.completed = false;
4652
+ return this.revision;
4653
+ }
4654
+ record(report, revision = this.revision) {
4655
+ this.ensureActive();
4656
+ if (revision !== this.revision || this.completed) return false;
4657
+ const cloned = cloneCompilerShadowReport(report);
4658
+ this.reportsByScope.delete(cloned.scopeId);
4659
+ this.reportsByScope.set(cloned.scopeId, cloned);
4660
+ while (this.reportsByScope.size > this.maxReports) {
4661
+ const oldestScopeId = this.reportsByScope.keys().next().value;
4662
+ if (oldestScopeId === void 0) break;
4663
+ this.reportsByScope.delete(oldestScopeId);
4664
+ this.dropped += 1;
4665
+ }
4666
+ return true;
4667
+ }
4668
+ getRevision() {
4669
+ this.ensureActive();
4670
+ return this.revision;
4671
+ }
4672
+ completeRun(revision = this.revision) {
4673
+ this.ensureActive();
4674
+ if (revision !== this.revision) return;
4675
+ this.completed = true;
4676
+ return this.snapshot();
4677
+ }
4678
+ snapshot() {
4679
+ this.ensureActive();
4680
+ const reports = [...this.reportsByScope.values()].sort((left, right) => left.scopeId.localeCompare(right.scopeId)).map(cloneCompilerShadowReport);
4681
+ return {
4682
+ revision: this.revision,
4683
+ completed: this.completed,
4684
+ reports,
4685
+ summary: {
4686
+ total: reports.length,
4687
+ matched: reports.filter((report) => report.equal).length,
4688
+ mismatched: reports.filter((report) => !report.equal).length,
4689
+ truncated: reports.filter((report) => report.truncated).length,
4690
+ dropped: this.dropped
4691
+ }
4692
+ };
4693
+ }
4694
+ dispose() {
4695
+ this.reportsByScope.clear();
4696
+ this.dropped = 0;
4697
+ this.completed = true;
4698
+ this.disposed = true;
4699
+ }
4700
+ ensureActive() {
4701
+ if (this.disposed) throw new Error("CompilerShadowReportSession 已释放。");
4702
+ }
4703
+ };
4704
+ const compilerShadowReportSessions = /* @__PURE__ */ new WeakMap();
4705
+ function getCompilerShadowReportSession(owner) {
4706
+ ensureCompilerOwnerActive(owner);
4707
+ let session = compilerShadowReportSessions.get(owner);
4708
+ if (!session) {
4709
+ session = new CompilerShadowReportSession();
4710
+ compilerShadowReportSessions.set(owner, session);
4711
+ }
4712
+ return session;
4713
+ }
4714
+ function beginCompilerShadowRun(owner) {
4715
+ return getCompilerShadowReportSession(owner).beginRun();
4716
+ }
4717
+ function getCompilerShadowRunRevision(owner) {
4718
+ return getCompilerShadowReportSession(owner).getRevision();
4719
+ }
4720
+ function recordCompilerShadowReport(owner, report, revision) {
4721
+ return getCompilerShadowReportSession(owner).record(report, revision);
4722
+ }
4723
+ function getCompilerShadowRunSnapshot(owner) {
4724
+ return getCompilerShadowReportSession(owner).snapshot();
4725
+ }
4726
+ function completeCompilerShadowReportRun(owner, revision) {
4727
+ return getCompilerShadowReportSession(owner).completeRun(revision);
4728
+ }
4729
+ function disposeCompilerShadowReportSession(owner) {
4730
+ const session = compilerShadowReportSessions.get(owner);
4731
+ if (!session) return;
4732
+ compilerShadowReportSessions.delete(owner);
4733
+ session.dispose();
4734
+ }
4735
+ //#endregion
4736
+ //#region src/compiler/owner-lifecycle.ts
4737
+ async function disposeCompilerOwnerResources(owner) {
4738
+ disposeCompilationChangeCoordinator(owner);
4739
+ await disposeCompilationSessionPool(owner);
4740
+ await disposeFrameworkCompilerSession(owner);
4741
+ disposeTailwindGenerationSessionPool(owner);
4742
+ disposeCompilerShadowReportSession(owner);
4743
+ }
4744
+ function disposeCompilerOwner(owner) {
4745
+ return runCompilerOwnerDisposal(owner, () => disposeCompilerOwnerResources(owner));
4746
+ }
4747
+ //#endregion
4748
+ //#region src/compiler/platform-adapter.ts
4749
+ function createStylePlatformAdapter(options) {
4750
+ return {
4751
+ id: options.id,
4752
+ prepare(request) {
4753
+ return {
4754
+ ...request,
4755
+ candidates: new Set(request.candidates),
4756
+ scope: { ...request.scope }
4757
+ };
4758
+ },
4759
+ async transform(artifact, context) {
4760
+ const transformed = cloneGenerationArtifact(artifact);
4761
+ for (const fragment of transformed.fragments) {
4762
+ fragment.root = (await options.styleHandler.transformRoot(fragment.root, options.styleOptions)).root.clone();
4763
+ fragment.stage = context.stage;
4764
+ }
4765
+ return transformed;
4766
+ }
4767
+ };
4768
+ }
4769
+ //#endregion
4770
+ //#region src/compiler/runtime-affecting-signature.ts
4771
+ const CSS_BLOCK_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
4772
+ const CSS_AROUND_PUNCTUATION_RE = /\s*([{}:;,>+~()])\s*/g;
4773
+ const CSS_TRAILING_DECLARATION_SEMICOLON_RE = /;\}/g;
4774
+ const CSS_WHITESPACE_RE = /\s+/g;
4775
+ const JS_RUNTIME_AFFECTING_TEXT_HINT_RE = /["'`/]/;
4776
+ const JS_INCOMPLETE_TRAILING_OPERATOR_RE = /(?:=>|[=+\-*%&|^!~?:,.({[\]])\s*$/;
4777
+ const JS_AST_IGNORED_KEYS = /* @__PURE__ */ new Set([
4778
+ "comments",
4779
+ "errors",
4780
+ "extra",
4781
+ "innerComments",
4782
+ "leadingComments",
4783
+ "loc",
4784
+ "tokens",
4785
+ "trailingComments"
4786
+ ]);
4787
+ function isAstNode(value) {
4788
+ return Boolean(value && typeof value === "object" && typeof value.type === "string");
4789
+ }
4790
+ function createHtmlRuntimeAffectingSignature(source) {
4791
+ try {
4792
+ const parts = [];
4793
+ const parser = new Parser({
4794
+ onattribute(name, value) {
4795
+ parts.push(`a:${name}=${value}`);
4796
+ },
4797
+ oncomment(data) {
4798
+ parts.push(`c:${data}`);
4799
+ },
4800
+ ontext(data) {
4801
+ const value = data.trim();
4802
+ if (value.length > 0) parts.push(`t:${value}`);
4803
+ }
4804
+ }, { xmlMode: true });
4805
+ parser.write(source);
4806
+ parser.end();
4807
+ return parts.join("\n");
4808
+ } catch {
4809
+ return source;
4810
+ }
4811
+ }
4812
+ function createJsRuntimeAffectingSignature(source) {
4813
+ if (!JS_RUNTIME_AFFECTING_TEXT_HINT_RE.test(source) && !JS_INCOMPLETE_TRAILING_OPERATOR_RE.test(source)) return "";
4814
+ try {
4815
+ const ast = babelParse(source, {
4816
+ cache: true,
4817
+ cacheKey: "st:unambiguous",
4818
+ plugins: ["jsx", "typescript"],
4819
+ sourceType: "unambiguous"
4820
+ });
4821
+ const parts = [];
4822
+ const stack = [ast];
4823
+ while (stack.length > 0) {
4824
+ const node = stack.pop();
4825
+ if (node.type === "StringLiteral" && typeof node.value === "string") parts.push(`s:${node.value}`);
4826
+ else if (node.type === "TemplateElement" && node.value && typeof node.value === "object" && "raw" in node.value && typeof node.value.raw === "string") parts.push(`t:${node.value.raw}`);
4827
+ else if (node.type === "JSXText" && typeof node.value === "string") {
4828
+ const value = node.value.trim();
4829
+ if (value.length > 0) parts.push(`x:${value}`);
4830
+ }
4831
+ const children = [];
4832
+ for (const [key, value] of Object.entries(node)) {
4833
+ if (JS_AST_IGNORED_KEYS.has(key)) continue;
4834
+ if (Array.isArray(value)) {
4835
+ for (const item of value) if (isAstNode(item)) children.push(item);
4836
+ } else if (isAstNode(value)) children.push(value);
4837
+ }
4838
+ for (let index = children.length - 1; index >= 0; index--) stack.push(children[index]);
4839
+ }
4840
+ const comments = ast.comments;
4841
+ if (Array.isArray(comments)) {
4842
+ for (const comment of comments) if (typeof comment?.value === "string" && comment.value.length > 0) parts.push(`c:${comment.value}`);
4843
+ }
4844
+ return parts.join("\n");
4845
+ } catch {
4846
+ return source;
4847
+ }
4848
+ }
4849
+ function createCssRuntimeAffectingSignature(source) {
4850
+ return source.replace(CSS_BLOCK_COMMENT_RE, "").replace(CSS_AROUND_PUNCTUATION_RE, "$1").replace(CSS_TRAILING_DECLARATION_SEMICOLON_RE, "}").replace(CSS_WHITESPACE_RE, " ").trim();
4851
+ }
4852
+ function createRuntimeAffectingSourceSignature(source, type) {
4853
+ if (type === "html") return createHtmlRuntimeAffectingSignature(source);
4854
+ if (type === "js") return createJsRuntimeAffectingSignature(source);
4855
+ if (type === "css") return createCssRuntimeAffectingSignature(source);
4856
+ return source;
4857
+ }
4858
+ //#endregion
4859
+ //#region src/compiler/runtime-state.ts
4860
+ /** 创建构建器无关的 runtime state,并保留旧字段供现有插件继续使用。 */
4861
+ function createCompilerRuntimeState(options) {
4862
+ const events = options.events ?? createCompilationEventBus();
4863
+ return {
4864
+ tailwindRuntime: options.tailwindRuntime,
4865
+ readyPromise: options.readyPromise ?? Promise.resolve(),
4866
+ refreshTailwindcssRuntime: options.refreshTailwindcssRuntime,
4867
+ events,
4868
+ get revision() {
4869
+ return events.revision;
4870
+ },
4871
+ dispose() {
4872
+ events.clear();
4873
+ }
4874
+ };
4875
+ }
4876
+ //#endregion
4877
+ export { consumeCompilationScopeChanges as A, createGenerationArtifact as B, createTailwindRuntimeReadyPromise as C, createCompilationEventBus as D, normalizeFrameworkStylePlatform as E, getCompilationSessionPool as F, replaceWxml as G, analyzeSource as H, runCompilerOwnerActivity as I, traverse as J, createDebug as K, createCompilationDependencyChanges as L, invalidateCompilationScope as M, recordCompilationDependencyChanges as N, AssetEmissionPlan as O, getTailwindGenerationSessionPool as P, mergeCompilationDependencyChanges as R, collectRuntimeClassSet as S, refreshTailwindRuntimeState as T, JsTokenUpdater as U, createAttributeMatcher as V, isClassContextLiteralPath as W, md5Hash as Y, generateCode as _, beginCompilerShadowRun as a, logTailwindcssTarget as b, getCompilerShadowRunSnapshot as c, createCompiler as d, getCompilerContext as f, vitePluginName as g, pluginName as h, disposeCompilerOwner as i, getCompilationScopeDependencyRevision as j, composeGenerationArtifact as k, recordCompilerShadowReport as l, resolveStyleOptionsFromContext as m, createRuntimeAffectingSourceSignature as n, completeCompilerShadowReportRun as o, normalizeStyleHandlerMajorVersion as p, babelParse as q, createStylePlatformAdapter as r, getCompilerShadowRunRevision as s, createCompilerRuntimeState as t, getFrameworkCompilerSession as u, shouldSkipJsTransform as v, ensureRuntimeClassSet as w, logRuntimeTailwindcssVersion as x, toCustomAttributesEntities as y, createCssFragment as z };