weapp-tailwindcss 5.0.0-next.27 → 5.0.0-next.29

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 (44) hide show
  1. package/dist/{auto-DP-qtQzE.js → auto-TH1jG2UW.js} +1 -1
  2. package/dist/{bundle-state-7DRnJcJp.mjs → bundle-state-Bi-cQua6.mjs} +1 -1
  3. package/dist/{bundle-state-Nn90UQDa.js → bundle-state-Ct_8GcSR.js} +2 -2
  4. package/dist/{chunk-D6vf50IK.js → chunk-C5U5_Hdc.js} +14 -0
  5. package/dist/core.js +1 -1
  6. package/dist/core.mjs +1 -1
  7. package/dist/css-macro.js +3 -3
  8. package/dist/{defaults-C5w9OOrj.js → defaults-zKUH2mDe.js} +1 -1
  9. package/dist/defaults.js +1 -1
  10. package/dist/{generator-DRNbzjx5.js → generator-CrU-Ghc1.js} +10 -3
  11. package/dist/{generator-CbpjNxJh.mjs → generator-Qw-tZ0Z2.mjs} +8 -1
  12. package/dist/generator.js +2 -2
  13. package/dist/generator.mjs +1 -1
  14. package/dist/gulp.js +6 -6
  15. package/dist/gulp.mjs +2 -2
  16. package/dist/{incremental-runtime-class-set-C4JgSgRY.mjs → incremental-runtime-class-set-DLv96b8z.mjs} +3 -2
  17. package/dist/{incremental-runtime-class-set-BQPhkSov.js → incremental-runtime-class-set-fEzwIzRB.js} +5 -4
  18. package/dist/index.js +4 -4
  19. package/dist/index.mjs +4 -4
  20. package/dist/{postcss-YetooK6S.mjs → postcss-C6zOQqlL.mjs} +1 -1
  21. package/dist/{postcss-Br1eOaFd.js → postcss-DAWf9D3C.js} +3 -3
  22. package/dist/postcss-html-transform.js +1 -1
  23. package/dist/postcss.js +1 -1
  24. package/dist/postcss.mjs +1 -1
  25. package/dist/{precheck-uG16Cqaj.mjs → precheck-D7K12zeX.mjs} +30 -5
  26. package/dist/{precheck-B6xigu7s.js → precheck-D7gJSmJz.js} +30 -5
  27. package/dist/presets.js +4 -4
  28. package/dist/reset.js +1 -1
  29. package/dist/{source-candidates-DeK5b9i9.js → source-candidates-DNM8iwXW.js} +2 -2
  30. package/dist/{tailwindcss-DEEtJf4u.js → tailwindcss-B-e2RiXr.js} +3 -3
  31. package/dist/{utils-nta4tfFs.js → utils-D7Ygohep.js} +1 -1
  32. package/dist/{v3-engine-B_33V3Lu.js → v3-engine-CHItlVq5.js} +2 -2
  33. package/dist/vite-7MqNbLiG.mjs +24425 -0
  34. package/dist/vite-D_EMLjvP.js +24439 -0
  35. package/dist/vite.js +1 -1
  36. package/dist/vite.mjs +1 -1
  37. package/dist/weapp-tw-css-import-rewrite-loader.js +9 -1
  38. package/dist/{webpack-BdrjJf41.mjs → webpack-B3u9FGLJ.mjs} +6 -5
  39. package/dist/{webpack-BzPDhzSz.js → webpack-B5k05Upp.js} +9 -8
  40. package/dist/webpack.js +1 -1
  41. package/dist/webpack.mjs +1 -1
  42. package/package.json +5 -5
  43. package/dist/vite-Bg18XZZc.js +0 -2565
  44. package/dist/vite-DOmiMftw.mjs +0 -2551
@@ -1,2551 +0,0 @@
1
- import { B as createDebug, E as filterUnsupportedMiniProgramTailwindV4Candidates, J as findNearestPackageRoot, U as findTailwindConfig, W as resolveTailwindcssOptions, _ as resolveViteSourceScanEntries, g as resolveTailwindV4EntriesFromCssCached, l as getRuntimeClassSetSignature, m as discoverTailwindV4CssEntries, p as createViteSourceScanMatcher, q as omitUndefined, v as resolveViteTailwindV4CssDependencies } from "./v3-engine-DcvCCHfs.mjs";
2
- import { i as normalizeWeappTailwindcssGeneratorOptions } from "./generator-CbpjNxJh.mjs";
3
- import { a as validateCandidatesByGenerator, c as hasTailwindSourceDirectives, i as generateCssByGenerator, l as normalizeTailwindSourceForGenerator, n as createHmrTimingRecorder, o as processCachedTask, s as hasTailwindRootDirectives, t as createBundleRuntimeClassSetManager, u as hasTailwindGeneratedCssMarkers } from "./incremental-runtime-class-set-C4JgSgRY.mjs";
4
- import { _ as collectRuntimeClassSet, a as vitePluginName, b as refreshTailwindRuntimeState, c as createAttributeMatcher, d as _defineProperty, f as isClassContextLiteralPath, g as toCustomAttributesEntities, l as analyzeSource, m as babelParse, n as getCompilerContext, p as replaceWxml, s as generateCode, t as shouldSkipJsTransform, u as JsTokenUpdater, v as createTailwindRuntimeReadyPromise } from "./precheck-uG16Cqaj.mjs";
5
- import { o as resolveUniUtsPlatform } from "./utils-DsaS975I.mjs";
6
- import { c as upsertTailwindV4CssSource, i as resolveUniAppXOptions, r as isUniAppXEnabled, s as hasConfiguredTailwindV4CssRoots } from "./tailwindcss-C7dJHZ0G.mjs";
7
- import { n as isSourceCandidateRequest, t as createSourceCandidateCollector } from "./source-candidates-CX2ozpKM.mjs";
8
- import { a as createBundleModuleGraphOptions, b as toAbsoluteOutputPath, c as hasBundlerGeneratedCssMarker, d as resolvePluginDisabledState, f as cleanUrl, g as isSourceStyleRequest, h as slash, i as applyLinkedResults, l as stripBundlerGeneratedCssMarkers, m as isCSSRequest, n as createBundleBuildState, o as pushConcurrentTaskFactories, p as formatPostcssSourceMap, r as updateBundleBuildState, s as createBundlerGeneratedCssMarker, t as buildBundleSnapshot, u as resolvePackageDir, v as normalizeOutputPathKey } from "./bundle-state-7DRnJcJp.mjs";
9
- import { t as logger$1 } from "./logger-BNzxZbZj.mjs";
10
- import fs, { existsSync, readFileSync } from "node:fs";
11
- import postcss from "postcss";
12
- import path from "node:path";
13
- import process from "node:process";
14
- import { logger } from "@weapp-tailwindcss/logger";
15
- import { readFile } from "node:fs/promises";
16
- import MagicString from "magic-string";
17
- import { splitCode } from "@weapp-tailwindcss/shared/extractors";
18
- import postcssHtmlTransform from "@weapp-tailwindcss/postcss/html-transform";
19
- import { NodeTypes } from "@vue/compiler-dom";
20
- import { parse } from "@vue/compiler-sfc";
21
- import { parse as parse$1 } from "comment-json";
22
- import postcssrc from "postcss-load-config";
23
- //#region src/uni-app-x/component-local-style.ts
24
- const EXPRESSION_WRAPPER_PREFIX = "(\n";
25
- const EXPRESSION_WRAPPER_SUFFIX = "\n)";
26
- const COMPONENT_RE = /(?:^|[/\\])components(?:[/\\].+)?\.(?:uvue|nvue)$/;
27
- function createStableHash(input) {
28
- let hash = 2166136261;
29
- for (let i = 0; i < input.length; i++) {
30
- hash ^= input.charCodeAt(i);
31
- hash = Math.imul(hash, 16777619);
32
- }
33
- return (hash >>> 0).toString(36);
34
- }
35
- function extractLiteralValue(path) {
36
- const allowDoubleQuotes = path.isTemplateElement();
37
- if (path.isStringLiteral()) return {
38
- allowDoubleQuotes,
39
- literal: path.node.value,
40
- offset: 1
41
- };
42
- return {
43
- allowDoubleQuotes,
44
- literal: typeof path.node.value === "string" ? path.node.value : path.node.value.raw,
45
- offset: 0
46
- };
47
- }
48
- function createAlias(fileId, utility, index) {
49
- return `wtu-${createStableHash(`${fileId}:${utility}`)}-${index.toString(36)}`;
50
- }
51
- function isRuntimeCandidate(candidate, runtimeSet) {
52
- if (!runtimeSet || runtimeSet.size === 0) return false;
53
- return runtimeSet.has(candidate) || runtimeSet.has(replaceWxml(candidate));
54
- }
55
- function shouldEnableComponentLocalStyle(id) {
56
- return COMPONENT_RE.test(id);
57
- }
58
- var UniAppXComponentLocalStyleCollector = class {
59
- constructor(fileId, runtimeSet) {
60
- this.fileId = fileId;
61
- this.runtimeSet = runtimeSet;
62
- _defineProperty(this, "aliasByUtility", /* @__PURE__ */ new Map());
63
- _defineProperty(this, "aliasByLookup", /* @__PURE__ */ new Map());
64
- }
65
- ensureAlias(utility) {
66
- const cached = this.aliasByUtility.get(utility);
67
- if (cached) return cached;
68
- const alias = createAlias(this.fileId, utility, this.aliasByUtility.size);
69
- this.aliasByUtility.set(utility, alias);
70
- this.aliasByLookup.set(utility, alias);
71
- this.aliasByLookup.set(replaceWxml(utility), alias);
72
- return alias;
73
- }
74
- rewriteLiteral(literal, shouldInclude) {
75
- const candidates = splitCode(literal);
76
- if (candidates.length === 0) return literal;
77
- let rewritten = literal;
78
- for (const candidate of candidates) {
79
- if (!shouldInclude(candidate)) continue;
80
- rewritten = rewritten.replace(candidate, this.ensureAlias(candidate));
81
- }
82
- return rewritten;
83
- }
84
- collectAndRewriteStaticClass(literal) {
85
- return this.rewriteLiteral(literal, (candidate) => isRuntimeCandidate(candidate, this.runtimeSet));
86
- }
87
- collectRuntimeClasses(rawSource, options = {}) {
88
- const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
89
- try {
90
- const analysis = analyzeSource(babelParse(wrapped, {
91
- plugins: ["typescript"],
92
- sourceType: options.wrapExpression ? "module" : "unambiguous"
93
- }), {}, void 0, false);
94
- for (const path of analysis.targetPaths) {
95
- const { literal, allowDoubleQuotes } = extractLiteralValue(path);
96
- const candidates = splitCode(literal, allowDoubleQuotes);
97
- const classContext = options.wrapExpression || isClassContextLiteralPath(path);
98
- for (const candidate of candidates) {
99
- if (!candidate || !classContext && !isRuntimeCandidate(candidate, this.runtimeSet)) continue;
100
- if (isRuntimeCandidate(candidate, this.runtimeSet)) this.ensureAlias(candidate);
101
- }
102
- }
103
- } catch {}
104
- }
105
- rewriteTransformedCode(rawSource, options = {}) {
106
- if (this.aliasByLookup.size === 0) return rawSource;
107
- const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
108
- try {
109
- const analysis = analyzeSource(babelParse(wrapped, {
110
- plugins: ["typescript"],
111
- sourceType: options.wrapExpression ? "module" : "unambiguous"
112
- }), {}, void 0, false);
113
- if (analysis.targetPaths.length === 0) return rawSource;
114
- const updater = new JsTokenUpdater();
115
- for (const path of analysis.targetPaths) {
116
- const { literal, allowDoubleQuotes, offset } = extractLiteralValue(path);
117
- const candidates = splitCode(literal, allowDoubleQuotes);
118
- if (candidates.length === 0) continue;
119
- let rewritten = literal;
120
- let mutated = false;
121
- for (const candidate of candidates) {
122
- const alias = this.aliasByLookup.get(candidate);
123
- if (!alias) continue;
124
- const replaced = rewritten.replace(candidate, alias);
125
- if (replaced !== rewritten) {
126
- rewritten = replaced;
127
- mutated = true;
128
- }
129
- }
130
- if (!mutated || typeof path.node.start !== "number" || typeof path.node.end !== "number") continue;
131
- updater.addToken({
132
- start: path.node.start + offset,
133
- end: path.node.end - offset,
134
- value: rewritten,
135
- path
136
- });
137
- }
138
- if (updater.length === 0) return rawSource;
139
- const ms = new MagicString(wrapped);
140
- updater.updateMagicString(ms);
141
- if (options.wrapExpression) {
142
- ms.remove(0, 2);
143
- ms.remove(wrapped.length - 2, wrapped.length);
144
- }
145
- return ms.toString();
146
- } catch {
147
- return rawSource;
148
- }
149
- }
150
- hasStyles() {
151
- return this.aliasByUtility.size > 0;
152
- }
153
- toStyleBlock() {
154
- if (!this.hasStyles()) return "";
155
- const lines = ["<style scoped>"];
156
- for (const [utility, alias] of this.aliasByUtility) {
157
- lines.push(`.${alias} {`);
158
- lines.push(` @apply ${utility};`);
159
- lines.push("}");
160
- }
161
- lines.push("</style>");
162
- return `${lines.join("\n")}\n`;
163
- }
164
- };
165
- //#endregion
166
- //#region src/uni-app-x/transform.ts
167
- function traverse(node, visitor) {
168
- visitor(node);
169
- if (Array.isArray(node.children)) {
170
- for (const child of node.children) if (child && typeof child === "object" && "type" in child) traverse(child, visitor);
171
- }
172
- }
173
- function updateStaticAttribute(ms, prop, content = prop.value?.content) {
174
- if (!prop.value) return;
175
- const start = prop.value.loc.start.offset + 1;
176
- const end = prop.value.loc.end.offset - 1;
177
- if (start < end) ms.update(start, end, replaceWxml(content ?? ""));
178
- }
179
- function updateStaticAttributeWithLocalStyle(ms, prop, collector, content = prop.value?.content) {
180
- if (!prop.value) return;
181
- const start = prop.value.loc.start.offset + 1;
182
- const end = prop.value.loc.end.offset - 1;
183
- if (start < end) ms.update(start, end, collector.collectAndRewriteStaticClass(content ?? ""));
184
- }
185
- function updateDirectiveExpression(ms, prop, jsHandler, runtimeSet) {
186
- if (prop.exp?.type !== NodeTypes.SIMPLE_EXPRESSION) return;
187
- const expression = prop.exp.content;
188
- const start = prop.exp.loc.start.offset;
189
- const end = prop.exp.loc.end.offset;
190
- if (start >= end) return;
191
- const generated = generateCode(expression, {
192
- jsHandler,
193
- runtimeSet,
194
- wrapExpression: true
195
- });
196
- ms.update(start, end, generated);
197
- }
198
- function updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, collector, runtimeSet) {
199
- if (prop.exp?.type !== NodeTypes.SIMPLE_EXPRESSION) return;
200
- const expression = prop.exp.content;
201
- const start = prop.exp.loc.start.offset;
202
- const end = prop.exp.loc.end.offset;
203
- if (start >= end) return;
204
- collector.collectRuntimeClasses(expression, { wrapExpression: true });
205
- const generated = generateCode(expression, {
206
- jsHandler,
207
- runtimeSet,
208
- wrapExpression: true
209
- });
210
- ms.update(start, end, collector.rewriteTransformedCode(generated, { wrapExpression: true }));
211
- }
212
- function shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute) {
213
- const lowerName = attrName.toLowerCase();
214
- const shouldHandleDefault = !disabledDefaultTemplateHandler && lowerName === "class";
215
- const shouldHandleCustom = matchCustomAttribute?.(tag, attrName) ?? false;
216
- return {
217
- shouldHandleDefault,
218
- shouldHandleCustom,
219
- shouldHandle: shouldHandleDefault || shouldHandleCustom
220
- };
221
- }
222
- const defaultCreateJsHandlerOptions = { babelParserOptions: { plugins: ["typescript"] } };
223
- const UVUE_NVUE_RE$1 = /\.(?:uvue|nvue)(?:\?.*)?$/;
224
- function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
225
- if (!UVUE_NVUE_RE$1.test(id)) return;
226
- const { customAttributesEntities, disabledDefaultTemplateHandler = false } = options;
227
- const matchCustomAttribute = createAttributeMatcher(customAttributesEntities);
228
- const ms = new MagicString(code);
229
- const { descriptor, errors } = parse(code);
230
- const localStyleCollector = options.enableComponentLocalStyle && shouldEnableComponentLocalStyle(id) ? new UniAppXComponentLocalStyleCollector(id, runtimeSet) : void 0;
231
- if (errors.length === 0) {
232
- if (descriptor.template?.ast) traverse(descriptor.template.ast, (node) => {
233
- if (node.type !== NodeTypes.ELEMENT) return;
234
- const tag = node.tag;
235
- for (const prop of node.props) if (prop.type === NodeTypes.ATTRIBUTE) {
236
- const { shouldHandle, shouldHandleDefault } = shouldHandleAttribute(tag, prop.name, disabledDefaultTemplateHandler, matchCustomAttribute);
237
- if (!shouldHandle) continue;
238
- if (shouldHandleDefault && localStyleCollector) updateStaticAttributeWithLocalStyle(ms, prop, localStyleCollector);
239
- else updateStaticAttribute(ms, prop);
240
- if (shouldHandleDefault) continue;
241
- } else if (prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.isStatic) {
242
- const attrName = prop.arg.content;
243
- const { shouldHandle } = shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute);
244
- if (!shouldHandle) continue;
245
- if (attrName.toLowerCase() === "class" && localStyleCollector) updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, localStyleCollector, runtimeSet);
246
- else updateDirectiveExpression(ms, prop, jsHandler, runtimeSet);
247
- }
248
- });
249
- if (descriptor.script) {
250
- localStyleCollector?.collectRuntimeClasses(descriptor.script.content);
251
- const { code } = jsHandler(descriptor.script.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
252
- ms.update(descriptor.script.loc.start.offset, descriptor.script.loc.end.offset, localStyleCollector ? localStyleCollector.rewriteTransformedCode(code) : code);
253
- }
254
- if (descriptor.scriptSetup) {
255
- localStyleCollector?.collectRuntimeClasses(descriptor.scriptSetup.content);
256
- const { code } = jsHandler(descriptor.scriptSetup.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
257
- ms.update(descriptor.scriptSetup.loc.start.offset, descriptor.scriptSetup.loc.end.offset, localStyleCollector ? localStyleCollector.rewriteTransformedCode(code) : code);
258
- }
259
- if (localStyleCollector?.hasStyles()) ms.append(`\n${localStyleCollector.toStyleBlock()}`);
260
- }
261
- const result = {
262
- code: ms.toString(),
263
- map: null
264
- };
265
- Object.defineProperty(result, "map", {
266
- configurable: true,
267
- enumerable: true,
268
- get() {
269
- return ms.generateMap();
270
- }
271
- });
272
- return result;
273
- }
274
- //#endregion
275
- //#region src/bundlers/vite/query.ts
276
- function parseVueRequest(id) {
277
- const [filename = id, rawQuery] = id.split(`?`, 2);
278
- const searchParams = new URLSearchParams(rawQuery);
279
- const query = Object.fromEntries(searchParams);
280
- if (query.vue != null) query.vue = true;
281
- if (query.index != null) query.index = Number(query.index);
282
- if (query.raw != null) query.raw = true;
283
- if (query.url != null) query.url = true;
284
- if (query.scoped != null) query.scoped = true;
285
- const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
286
- const langType = query.lang || (langTypeMatch ? langTypeMatch.slice(5) : void 0);
287
- if (langType) query.lang = langType;
288
- return {
289
- filename,
290
- query
291
- };
292
- }
293
- //#endregion
294
- //#region src/uni-app-x/style-isolation.ts
295
- const manifestCache = /* @__PURE__ */ new Map();
296
- function resolveUniAppXStyleIsolationEnabled(root) {
297
- if (!root) return false;
298
- const normalizedRoot = path.resolve(root);
299
- const cached = manifestCache.get(normalizedRoot);
300
- if (cached !== void 0) return cached;
301
- const manifestPath = path.join(normalizedRoot, "manifest.json");
302
- let enabled = false;
303
- try {
304
- enabled = `${parse$1(fs.readFileSync(manifestPath, "utf8"))["uni-app-x"]?.styleIsolationVersion ?? ""}` === "2";
305
- } catch {
306
- enabled = false;
307
- }
308
- manifestCache.set(normalizedRoot, enabled);
309
- return enabled;
310
- }
311
- //#endregion
312
- //#region src/uni-app-x/vite.ts
313
- const preprocessorLangs = new Set([
314
- "scss",
315
- "sass",
316
- "less",
317
- "styl",
318
- "stylus"
319
- ]);
320
- const INLINE_LANG_RE = /lang\.([a-z]+)/i;
321
- const PREPROCESSOR_EXT_RE = /\.(?:scss|sass|less|styl|stylus)(?:\?|$)/i;
322
- const UVUE_NVUE_QUERY_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
323
- const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
324
- function isPreprocessorRequest(id, lang) {
325
- const normalizedLang = lang?.toLowerCase();
326
- if (normalizedLang && preprocessorLangs.has(normalizedLang)) return true;
327
- const inlineLang = id.match(INLINE_LANG_RE)?.[1];
328
- if (inlineLang && preprocessorLangs.has(inlineLang.toLowerCase())) return true;
329
- return PREPROCESSOR_EXT_RE.test(id);
330
- }
331
- function resolveUniAppXCssTarget(id) {
332
- return UVUE_NVUE_RE.test(cleanUrl(id)) ? "uvue" : void 0;
333
- }
334
- function resolveUniAppXJsTransformEnabled$1(uniAppX) {
335
- return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
336
- }
337
- function createUniAppXPlugins(options) {
338
- const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, jsHandler, ensureRuntimeClassSet, getResolvedConfig, uniAppX } = options;
339
- const resolvedUniAppXOptions = resolveUniAppXOptions(uniAppX);
340
- const isIosPlatform = providedIosPlatform ?? resolveUniUtsPlatform().isAppIos;
341
- const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
342
- let componentLocalStyleEnabled;
343
- function shouldEnableComponentLocalStyle() {
344
- if (!resolvedUniAppXOptions.componentLocalStyles.enabled) {
345
- componentLocalStyleEnabled = false;
346
- return false;
347
- }
348
- if (!resolvedUniAppXOptions.componentLocalStyles.onlyWhenStyleIsolationVersion2) {
349
- componentLocalStyleEnabled = true;
350
- return true;
351
- }
352
- if (componentLocalStyleEnabled !== void 0) return componentLocalStyleEnabled;
353
- const root = getResolvedConfig()?.root;
354
- componentLocalStyleEnabled = resolveUniAppXStyleIsolationEnabled(root);
355
- return componentLocalStyleEnabled;
356
- }
357
- async function transformStyle(code, id, query) {
358
- const parsed = query ?? parseVueRequest(id).query;
359
- if (isCSSRequest(id) || parsed.vue && parsed.type === "style") {
360
- const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
361
- let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
362
- if (!styleHandlerOptions) {
363
- styleHandlerOptions = omitUndefined({
364
- isMainChunk: mainCssChunkMatcher(id, appType),
365
- uniAppXCssTarget: resolveUniAppXCssTarget(id),
366
- uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
367
- postcssOptions: { options: {
368
- from: id,
369
- map: {
370
- inline: false,
371
- annotation: false,
372
- sourcesContent: true
373
- }
374
- } }
375
- });
376
- cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
377
- }
378
- const postcssResult = await styleHandler(code, styleHandlerOptions);
379
- const warnings = typeof postcssResult.warnings === "function" ? postcssResult.warnings() : [];
380
- for (const warning of warnings) logger$1.warn(warning.toString());
381
- const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), cleanUrl(id));
382
- return {
383
- code: postcssResult.css,
384
- map: postcssMap
385
- };
386
- }
387
- }
388
- const cssPlugins = [{
389
- name: "weapp-tailwindcss:uni-app-x:css",
390
- async transform(code, id) {
391
- await runtimeState.readyPromise;
392
- return transformStyle(code, id);
393
- }
394
- }, {
395
- name: "weapp-tailwindcss:uni-app-x:css:pre",
396
- enforce: "pre",
397
- async transform(code, id) {
398
- await runtimeState.readyPromise;
399
- const { query } = parseVueRequest(id);
400
- const lang = query.lang;
401
- if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
402
- return transformStyle(code, id, query);
403
- }
404
- }];
405
- const nvuePlugin = {
406
- name: "weapp-tailwindcss:uni-app-x:nvue",
407
- enforce: "pre",
408
- async buildStart() {
409
- await ensureRuntimeClassSet(true);
410
- },
411
- async transform(code, id) {
412
- if (!UVUE_NVUE_QUERY_RE.test(id)) return;
413
- const resolvedConfig = getResolvedConfig();
414
- const isServeCommand = resolvedConfig?.command === "serve";
415
- const isWatchBuild = resolvedConfig?.command === "build" && !!resolvedConfig.build?.watch;
416
- const isNonWatchBuild = resolvedConfig?.command === "build" && !resolvedConfig.build?.watch;
417
- const currentRuntimeSet = isServeCommand || isWatchBuild || isNonWatchBuild ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
418
- const extraOptions = customAttributesEntities.length > 0 || disabledDefaultTemplateHandler ? {
419
- customAttributesEntities,
420
- disabledDefaultTemplateHandler,
421
- enableComponentLocalStyle: shouldEnableComponentLocalStyle()
422
- } : void 0;
423
- if (extraOptions) return transformUVue(code, id, jsHandler, currentRuntimeSet, extraOptions);
424
- if (shouldEnableComponentLocalStyle()) return transformUVue(code, id, jsHandler, currentRuntimeSet, { enableComponentLocalStyle: true });
425
- return transformUVue(code, id, jsHandler, currentRuntimeSet);
426
- },
427
- async handleHotUpdate(ctx) {
428
- if (getResolvedConfig()?.command !== "serve") return;
429
- if (!UVUE_NVUE_RE.test(ctx.file)) return;
430
- await ensureRuntimeClassSet(true);
431
- },
432
- async watchChange(id) {
433
- const resolvedConfig = getResolvedConfig();
434
- if (resolvedConfig?.command !== "build" || !resolvedConfig.build?.watch) return;
435
- if (!UVUE_NVUE_QUERY_RE.test(id)) return;
436
- await ensureRuntimeClassSet(true);
437
- }
438
- };
439
- return [...cssPlugins, nvuePlugin];
440
- }
441
- function createUniAppXAssetTask(file, originalSource, outDir, options) {
442
- return async () => {
443
- const { cache, hashKey, createHandlerOptions, debug, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
444
- const absoluteFile = toAbsoluteOutputPath(file, outDir);
445
- const rawSource = originalSource.source.toString();
446
- await processCachedTask({
447
- cache,
448
- cacheKey: file,
449
- hashKey,
450
- rawSource: options.hashSalt ? `${rawSource}\n/*${options.hashSalt}*/` : rawSource,
451
- applyResult(source) {
452
- originalSource.source = source;
453
- },
454
- onCacheHit() {
455
- debug("js cache hit: %s", file);
456
- },
457
- async transform() {
458
- const currentSource = originalSource.source.toString();
459
- const { code, linked } = await jsHandler(currentSource, runtimeSet, createHandlerOptions(absoluteFile, {
460
- uniAppX: resolveUniAppXJsTransformEnabled$1(options.uniAppX),
461
- babelParserOptions: {
462
- plugins: ["typescript"],
463
- sourceType: "unambiguous"
464
- }
465
- }));
466
- onUpdate(file, currentSource, code);
467
- debug("js handle: %s", file);
468
- applyLinkedResults(linked);
469
- return { result: code };
470
- }
471
- });
472
- };
473
- }
474
- //#endregion
475
- //#region src/bundlers/vite/processed-css-assets.ts
476
- const CSS_OUTPUT_FILE_RE = /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i;
477
- function isCssOutputFile(file) {
478
- return CSS_OUTPUT_FILE_RE.test(file);
479
- }
480
- function getAssetFile(bundleFile, asset) {
481
- return asset.fileName || bundleFile;
482
- }
483
- function readAssetSource(asset) {
484
- return typeof asset.source === "string" ? asset.source : asset.source.toString();
485
- }
486
- function appendCss(baseCss, css) {
487
- if (baseCss.length === 0) return css;
488
- if (css.length === 0) return baseCss;
489
- return `${baseCss}\n${css}`;
490
- }
491
- function collectViteProcessedCssAssetResults(bundle, options) {
492
- let collected = 0;
493
- for (const [bundleFile, output] of Object.entries(bundle)) {
494
- if (output.type !== "asset") continue;
495
- const file = getAssetFile(bundleFile, output);
496
- if (!isCssOutputFile(file) || !options.isViteProcessedCssAsset?.(output, file)) continue;
497
- const rawSource = readAssetSource(output);
498
- const nextCss = stripBundlerGeneratedCssMarkers(rawSource);
499
- if (nextCss !== rawSource) output.source = nextCss;
500
- options.markCssAssetProcessed?.(output, file);
501
- options.recordCssAssetResult?.(file, nextCss);
502
- options.recordViteProcessedCssAssetResult?.(file, nextCss);
503
- options.debug?.("collect vite-processed css asset: %s bytes=%d", file, nextCss.length);
504
- collected++;
505
- }
506
- return collected;
507
- }
508
- function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
509
- const viteCssResults = [...options.getViteProcessedCssAssetResults?.() ?? []].filter(([file, css]) => isCssOutputFile(file) && css.length > 0);
510
- if (viteCssResults.length === 0) return 0;
511
- let injected = 0;
512
- for (const [bundleFile, output] of Object.entries(bundle)) {
513
- if (output.type !== "asset") continue;
514
- const file = getAssetFile(bundleFile, output);
515
- if (!options.opts.cssMatcher(file) || !options.opts.mainCssChunkMatcher(file, options.opts.appType)) continue;
516
- const mainFileKey = normalizeOutputPathKey(file);
517
- const originalSource = readAssetSource(output);
518
- let nextCss = originalSource;
519
- for (const [sourceFile, sourceCss] of viteCssResults) {
520
- if (normalizeOutputPathKey(sourceFile) === mainFileKey || options.opts.mainCssChunkMatcher(sourceFile, options.opts.appType)) continue;
521
- const css = stripBundlerGeneratedCssMarkers(sourceCss).trim();
522
- if (css.length === 0 || nextCss.includes(css)) continue;
523
- nextCss = appendCss(nextCss, css);
524
- }
525
- if (nextCss === originalSource) continue;
526
- output.source = nextCss;
527
- options.markCssAssetProcessed?.(output, file);
528
- options.recordCssAssetResult?.(file, nextCss);
529
- options.onUpdate?.(file, originalSource, nextCss);
530
- options.debug?.("inject vite-processed css into main css asset: %s bytes=%d", file, nextCss.length);
531
- injected++;
532
- }
533
- return injected;
534
- }
535
- //#endregion
536
- //#region src/bundlers/vite/css-finalizer.ts
537
- function isAddWatchFileInvalidRollupPhaseError$1(error) {
538
- const candidate = error;
539
- return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
540
- }
541
- function registerGeneratorDependencies$1(ctx, dependencies) {
542
- if (typeof ctx.addWatchFile !== "function") return;
543
- for (const dependency of dependencies ?? []) try {
544
- ctx.addWatchFile(dependency);
545
- } catch (error) {
546
- if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
547
- logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
548
- continue;
549
- }
550
- throw error;
551
- }
552
- }
553
- function createCssHandlerOptions(opts, majorVersion, file) {
554
- return {
555
- isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
556
- postcssOptions: { options: { from: file } },
557
- ...majorVersion === void 0 ? {} : { majorVersion }
558
- };
559
- }
560
- function shouldGenerateCssByGenerator(opts, file, rawSource, processed) {
561
- const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
562
- if (generatorOptions.target === "web" && opts.twPatcher.majorVersion !== 3) return false;
563
- if (hasTailwindGeneratedCssMarkers(rawSource) || hasTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })) return true;
564
- if (opts.twPatcher.majorVersion === 3) return false;
565
- return processed && shouldFinalizeProcessedCssAsset(opts, file);
566
- }
567
- function shouldFinalizeProcessedCssAsset(opts, file) {
568
- return opts.mainCssChunkMatcher(file, opts.appType);
569
- }
570
- function createViteCssFinalizerOutputPlugin(context) {
571
- return {
572
- name: "weapp-tailwindcss:adaptor:css-finalizer",
573
- enforce: "post",
574
- generateBundle: {
575
- order: "post",
576
- async handler(_options, bundle) {
577
- const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getRecordedGeneratorCandidates, getSourceCandidates, getSourceCandidatesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSource, isViteProcessedCssAsset } = context;
578
- if (getResolvedConfig()?.command !== "build") return;
579
- collectViteProcessedCssAssetResults(bundle, {
580
- isViteProcessedCssAsset,
581
- markCssAssetProcessed,
582
- recordCssAssetResult,
583
- recordViteProcessedCssAssetResult,
584
- debug
585
- });
586
- const isCssOutputAssetEntry = (entry) => {
587
- const [, output] = entry;
588
- return output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName));
589
- };
590
- const entries = Object.entries(bundle).filter(isCssOutputAssetEntry);
591
- if (entries.length === 0) {
592
- injectViteProcessedCssIntoMainCssAssets(bundle, {
593
- opts,
594
- getViteProcessedCssAssetResults,
595
- markCssAssetProcessed,
596
- recordCssAssetResult,
597
- debug,
598
- onUpdate: opts.onUpdate
599
- });
600
- return;
601
- }
602
- await runtimeState.readyPromise;
603
- await waitForSourceCandidateSyncs?.();
604
- const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
605
- const runtime = getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet();
606
- const collectedGeneratorCandidates = new Set([...runtime, ...getSourceCandidates?.() ?? []]);
607
- const generatorRuntime = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp" ? filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
608
- await Promise.all(entries.map(async ([bundleFile, output]) => {
609
- const file = output.fileName || bundleFile;
610
- const rawSource = output.source.toString();
611
- if (isViteProcessedCssAsset?.(output, file)) {
612
- const nextCss = stripBundlerGeneratedCssMarkers(rawSource);
613
- output.source = nextCss;
614
- markCssAssetProcessed(output, file);
615
- recordCssAssetResult?.(file, nextCss);
616
- debug("css finalizer skip vite-processed css: %s", file);
617
- return;
618
- }
619
- const cssHandlerOptions = createCssHandlerOptions(opts, runtimeState.twPatcher.majorVersion, file);
620
- const cssUserHandlerOptions = {
621
- ...cssHandlerOptions,
622
- isMainChunk: false
623
- };
624
- const processed = isCssAssetProcessed(output, file);
625
- const generatorRawSource = processed && cssHandlerOptions.isMainChunk ? getRememberedMainCssSource?.(file) ?? rawSource : rawSource;
626
- const generated = shouldGenerateCssByGenerator(opts, file, generatorRawSource, processed) ? await generateCssByGenerator({
627
- opts,
628
- runtimeState,
629
- runtime: generatorRuntime,
630
- rawSource: generatorRawSource,
631
- file,
632
- cssHandlerOptions,
633
- cssUserHandlerOptions,
634
- getSourceCandidatesForEntries,
635
- styleHandler: opts.styleHandler,
636
- debug
637
- }) : void 0;
638
- const nextCss = generated?.css ?? (generatorOptions.target === "web" ? rawSource : (await opts.styleHandler(rawSource, cssHandlerOptions)).css);
639
- if (generated) {
640
- registerGeneratorDependencies$1(this, generated.dependencies);
641
- debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
642
- recordCssAssetResult?.(file, nextCss);
643
- if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, generatorRawSource);
644
- }
645
- output.source = nextCss;
646
- markCssAssetProcessed(output, file);
647
- opts.onUpdate(file, rawSource, nextCss);
648
- debug("css finalizer handle: %s", file);
649
- }));
650
- injectViteProcessedCssIntoMainCssAssets(bundle, {
651
- opts,
652
- getViteProcessedCssAssetResults,
653
- markCssAssetProcessed,
654
- recordCssAssetResult,
655
- debug,
656
- onUpdate: opts.onUpdate
657
- });
658
- }
659
- }
660
- };
661
- }
662
- //#endregion
663
- //#region src/bundlers/vite/generate-bundle/candidates.ts
664
- const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
665
- const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
666
- function isArbitraryValueCandidate(candidate) {
667
- return candidate.includes("[") && candidate.includes("]");
668
- }
669
- function collectUnescapedDynamicCandidates(source) {
670
- const matches = /* @__PURE__ */ new Set();
671
- for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
672
- QUOTED_LITERAL_RE.lastIndex = 0;
673
- let quoted = QUOTED_LITERAL_RE.exec(expression);
674
- while (quoted !== null) {
675
- const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
676
- for (const candidate of splitCode(literal, true)) {
677
- const normalized = candidate.trim();
678
- if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
679
- matches.add(normalized);
680
- }
681
- quoted = QUOTED_LITERAL_RE.exec(expression);
682
- }
683
- }
684
- return [...matches];
685
- }
686
- function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
687
- if (candidates.has("container")) return candidates;
688
- if (!sourceCandidates.has("container")) return candidates;
689
- return new Set([...candidates, "container"]);
690
- }
691
- //#endregion
692
- //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
693
- function createCssHandlerOptionsCache(options) {
694
- const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
695
- const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
696
- const getCssHandlerOptions = (file) => {
697
- const majorVersion = options.getMajorVersion();
698
- const appType = options.getAppType();
699
- const isMainChunk = options.mainCssChunkMatcher(file, appType);
700
- const outputRoot = options.getOutputRoot?.();
701
- const cacheKey = `${majorVersion ?? "unknown"}:${appType ?? "unknown"}:${isMainChunk ? "1" : "0"}:${outputRoot ?? ""}:${file}`;
702
- const cached = cssHandlerOptionsCache.get(cacheKey);
703
- if (cached) return cached;
704
- const created = {
705
- isMainChunk,
706
- postcssOptions: { options: { from: file } },
707
- majorVersion,
708
- sourceOptions: { outputRoot }
709
- };
710
- cssHandlerOptionsCache.set(cacheKey, created);
711
- return created;
712
- };
713
- const getCssUserHandlerOptions = (file) => {
714
- const majorVersion = options.getMajorVersion();
715
- const outputRoot = options.getOutputRoot?.();
716
- const cacheKey = `${majorVersion ?? "unknown"}:${outputRoot ?? ""}:${file}`;
717
- const cached = cssUserHandlerOptionsCache.get(cacheKey);
718
- if (cached) return cached;
719
- const created = {
720
- ...getCssHandlerOptions(file),
721
- isMainChunk: false
722
- };
723
- cssUserHandlerOptionsCache.set(cacheKey, created);
724
- return created;
725
- };
726
- return {
727
- getCssHandlerOptions,
728
- getCssUserHandlerOptions
729
- };
730
- }
731
- //#endregion
732
- //#region src/bundlers/vite/generate-bundle/css-share-scope.ts
733
- const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
734
- const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
735
- const CSS_IMPORT_RE = /@import\b/i;
736
- function isPathIndependentCssUrl(value) {
737
- const normalized = value.trim();
738
- return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
739
- }
740
- function hasPathDependentCssUrl(rawSource) {
741
- CSS_URL_FUNCTION_RE.lastIndex = 0;
742
- let match = CSS_URL_FUNCTION_RE.exec(rawSource);
743
- while (match !== null) {
744
- if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
745
- match = CSS_URL_FUNCTION_RE.exec(rawSource);
746
- }
747
- return false;
748
- }
749
- function createCssTransformShareScope(file, rawSource) {
750
- if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${normalizeOutputPathKey(path.dirname(file))}`;
751
- return "global";
752
- }
753
- function createCssTransformShareScopeKey(opts, file, rawSource) {
754
- if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${normalizeOutputPathKey(file)}`;
755
- const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
756
- if (hasTailwindGeneratedCssMarkers(rawSource) || hasTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })) return `source:${normalizeOutputPathKey(file)}`;
757
- return createCssTransformShareScope(file, rawSource);
758
- }
759
- function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
760
- return `${runtimeSignature}:${generatorCandidateSignature}`;
761
- }
762
- //#endregion
763
- //#region src/bundlers/vite/generate-bundle/dirty-state.ts
764
- function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
765
- const currentFileSet = new Set(currentBundleFiles);
766
- for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
767
- return false;
768
- }
769
- //#endregion
770
- //#region src/bundlers/vite/generate-bundle/js-entries.ts
771
- function createJsEntryResolver(jsEntries) {
772
- const normalizedJsEntries = /* @__PURE__ */ new Map();
773
- for (const [id, entry] of jsEntries) normalizedJsEntries.set(normalizeOutputPathKey(id), entry);
774
- return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(normalizeOutputPathKey(id));
775
- }
776
- //#endregion
777
- //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
778
- function resolveUniAppXJsTransformEnabled(uniAppX) {
779
- return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
780
- }
781
- function createJsHandlerOptionsFactory(options) {
782
- return (absoluteFilename, extra) => ({
783
- ...extra,
784
- filename: absoluteFilename,
785
- tailwindcssMajorVersion: options.getMajorVersion(),
786
- moduleGraph: options.moduleGraph,
787
- babelParserOptions: {
788
- ...extra?.babelParserOptions ?? {},
789
- sourceFilename: absoluteFilename
790
- }
791
- });
792
- }
793
- //#endregion
794
- //#region src/bundlers/vite/generate-bundle/js-linking.ts
795
- function createLinkedUpdateHelpers(options) {
796
- const pendingLinkedUpdates = [];
797
- const handleLinkedUpdate = (fileName, previous, next) => {
798
- options.onUpdate(fileName, previous, next);
799
- options.debug("js linked handle: %s", fileName);
800
- };
801
- const scheduleLinkedApply = (entry, code) => {
802
- pendingLinkedUpdates.push(() => {
803
- if (entry.output.type === "chunk") entry.output.code = code;
804
- else entry.output.source = code;
805
- });
806
- };
807
- const applyLinkedUpdates = (linked) => {
808
- applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
809
- };
810
- return {
811
- applyLinkedUpdates,
812
- pendingLinkedUpdates
813
- };
814
- }
815
- function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
816
- if (!linked || !linkedSet) return;
817
- for (const id of Object.keys(linked)) {
818
- const linkedEntry = getJsEntry(id);
819
- if (linkedEntry) linkedSet.add(linkedEntry.fileName);
820
- }
821
- }
822
- //#endregion
823
- //#region src/bundlers/vite/generate-bundle/metrics.ts
824
- function formatDebugFileList(files, limit = 8) {
825
- if (files.size === 0) return "-";
826
- const sorted = [...files].sort();
827
- if (sorted.length <= limit) return sorted.join(",");
828
- return `${sorted.slice(0, limit).join(",")},...(+${sorted.length - limit})`;
829
- }
830
- function createEmptyMetric() {
831
- return {
832
- total: 0,
833
- transformed: 0,
834
- cacheHits: 0,
835
- elapsed: 0
836
- };
837
- }
838
- function createEmptyMetrics() {
839
- return {
840
- runtimeSet: 0,
841
- html: createEmptyMetric(),
842
- js: createEmptyMetric(),
843
- css: createEmptyMetric()
844
- };
845
- }
846
- function measureElapsed(start) {
847
- return performance.now() - start;
848
- }
849
- function formatCacheHitRate(metric) {
850
- if (metric.total === 0) return "0.00%";
851
- return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
852
- }
853
- function formatMs(value) {
854
- return value.toFixed(2);
855
- }
856
- //#endregion
857
- //#region src/bundlers/vite/generate-bundle/process-plan.ts
858
- function logBundleProcessPlan(options) {
859
- const { debug, snapshot, useIncrementalMode, iteration } = options;
860
- const { processFiles } = snapshot;
861
- if (useIncrementalMode) {
862
- debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", iteration, snapshot.changedByType.html.size, formatDebugFileList(snapshot.changedByType.html), snapshot.changedByType.js.size, formatDebugFileList(snapshot.changedByType.js), snapshot.changedByType.css.size, formatDebugFileList(snapshot.changedByType.css), snapshot.changedByType.other.size, formatDebugFileList(snapshot.changedByType.other));
863
- debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", iteration, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
864
- return;
865
- }
866
- debug("build mode full process html=%d[%s] js=%d[%s] css=%d[%s]", processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
867
- }
868
- //#endregion
869
- //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
870
- function createReplayCssAsset(fileName, source) {
871
- return {
872
- type: "asset",
873
- fileName,
874
- name: void 0,
875
- source,
876
- needsCodeReference: false,
877
- names: [],
878
- originalFileName: null,
879
- originalFileNames: []
880
- };
881
- }
882
- function isAddWatchFileInvalidRollupPhaseError(error) {
883
- const candidate = error;
884
- return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
885
- }
886
- function registerGeneratorDependencies(ctx, dependencies) {
887
- if (typeof ctx.addWatchFile !== "function") return;
888
- for (const dependency of dependencies ?? []) try {
889
- ctx.addWatchFile(dependency);
890
- } catch (error) {
891
- if (isAddWatchFileInvalidRollupPhaseError(error)) {
892
- logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
893
- continue;
894
- }
895
- throw error;
896
- }
897
- }
898
- //#endregion
899
- //#region src/bundlers/vite/generate-bundle/signatures.ts
900
- function summarizeStringDiff(previous, next) {
901
- if (previous === next) return "same";
902
- const previousLength = previous.length;
903
- const nextLength = next.length;
904
- const minLength = Math.min(previousLength, nextLength);
905
- let prefixLength = 0;
906
- while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) prefixLength += 1;
907
- let previousSuffixCursor = previousLength - 1;
908
- let nextSuffixCursor = nextLength - 1;
909
- while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) {
910
- previousSuffixCursor -= 1;
911
- nextSuffixCursor -= 1;
912
- }
913
- const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0;
914
- const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0;
915
- return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`;
916
- }
917
- function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) {
918
- const changedLinkedFiles = linkedImpactsByEntry.get(entry);
919
- if (!changedLinkedFiles || changedLinkedFiles.size === 0) return;
920
- return [...changedLinkedFiles].sort().map((file) => {
921
- return `${file}:${sourceHashByFile.get(file) ?? "missing"}`;
922
- }).join(",");
923
- }
924
- function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
925
- if (!linkedImpactSignature) return runtimeSignature;
926
- return `${runtimeSignature}:linked:${linkedImpactSignature}`;
927
- }
928
- function createStableTextSignature(input) {
929
- let hash = 2166136261;
930
- for (let i = 0; i < input.length; i++) {
931
- hash ^= input.charCodeAt(i);
932
- hash = Math.imul(hash, 16777619);
933
- }
934
- return (hash >>> 0).toString(36);
935
- }
936
- function createCandidateSignature(candidates) {
937
- if (candidates.size === 0) return "empty";
938
- return createStableTextSignature([...candidates].sort().join("\n"));
939
- }
940
- function getSnapshotHash(snapshotMap, file, fallback) {
941
- return snapshotMap.get(file) ?? fallback;
942
- }
943
- function hasRuntimeAffectingSourceChanges(changedByType) {
944
- return changedByType.html.size > 0 || changedByType.js.size > 0;
945
- }
946
- //#endregion
947
- //#region src/bundlers/vite/generate-bundle.ts
948
- function addSiblingCssFile(files, file) {
949
- if (file.endsWith(".wxml")) files.add(file.replace(/\.wxml$/, ".wxss"));
950
- else if (file.endsWith(".js")) files.add(file.replace(/\.js$/, ".wxss"));
951
- }
952
- function collectRuntimeLinkedCssFiles(snapshot) {
953
- const files = /* @__PURE__ */ new Set();
954
- for (const file of snapshot.runtimeAffectingChangedByType.html) addSiblingCssFile(files, file);
955
- for (const file of snapshot.runtimeAffectingChangedByType.js) addSiblingCssFile(files, file);
956
- return files;
957
- }
958
- function resolveReplayCssOutputFile(rootDir, file) {
959
- const normalizedFile = normalizeOutputPathKey(path.isAbsolute(file) ? path.relative(rootDir, file) : file);
960
- if (normalizedFile.length === 0 || normalizedFile === "." || normalizedFile === ".." || normalizedFile.startsWith("../")) return normalizeOutputPathKey(path.basename(file));
961
- return normalizedFile;
962
- }
963
- const SOURCE_STYLE_OUTPUT_EXT_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss)$/i;
964
- const SOURCE_STYLE_NON_CSS_SYNTAX_RE = /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@(?:use|forward|mixin|include|function)\b)/;
965
- function resolveViteCssOutputFile(file, opts, isWebGeneratorTarget) {
966
- if (isWebGeneratorTarget || opts.cssMatcher(file) || !SOURCE_STYLE_OUTPUT_EXT_RE.test(file) || !isCSSRequest(file)) return file;
967
- return file.replace(SOURCE_STYLE_OUTPUT_EXT_RE, ".wxss");
968
- }
969
- function canProcessViteSourceStyleAsCss(source, file) {
970
- if (SOURCE_STYLE_NON_CSS_SYNTAX_RE.test(source)) return false;
971
- try {
972
- postcss.parse(source, { from: file });
973
- return true;
974
- } catch {
975
- return false;
976
- }
977
- }
978
- function createGenerateBundleHook(context) {
979
- const state = createBundleBuildState();
980
- const lastCssResultByFile = /* @__PURE__ */ new Map();
981
- let currentOutDir;
982
- const cssHandlerOptions = createCssHandlerOptionsCache({
983
- getAppType: () => context.opts.appType,
984
- mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
985
- getMajorVersion: () => context.runtimeState.twPatcher.majorVersion,
986
- getOutputRoot: () => currentOutDir
987
- });
988
- return async function generateBundle(_opt, bundle) {
989
- const addWatchFile = (id) => this.addWatchFile?.(id);
990
- const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, isViteProcessedCssAsset, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getSourceCandidates, getSourceCandidatesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates, hmrTimingRecorder } = context;
991
- const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
992
- const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
993
- const isWebGeneratorTarget = generatorOptions.target === "web";
994
- const shouldGenerateWebCssByGenerator = isWebGeneratorTarget && runtimeState.twPatcher.majorVersion === 3;
995
- const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
996
- await runtimeState.readyPromise;
997
- debug("start");
998
- onStart();
999
- collectViteProcessedCssAssetResults(bundle, {
1000
- isViteProcessedCssAsset,
1001
- markCssAssetProcessed,
1002
- recordCssAssetResult,
1003
- recordViteProcessedCssAssetResult,
1004
- debug
1005
- });
1006
- const hmrTimingStartedAt = performance.now();
1007
- const timingDetails = {};
1008
- const recordTimingDetail = (name, startedAt) => {
1009
- timingDetails[name] = (timingDetails[name] ?? 0) + Math.max(0, performance.now() - startedAt);
1010
- };
1011
- const timeTask = async (name, task) => {
1012
- const start = performance.now();
1013
- try {
1014
- await task();
1015
- } finally {
1016
- recordTimingDetail(`tasks.${name}`, start);
1017
- }
1018
- };
1019
- const metrics = createEmptyMetrics();
1020
- const forceRuntimeRefreshByEnv = process.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1021
- const disableDirtyOptimization = process.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1";
1022
- const disableJsPrecheck = process.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1";
1023
- const debugCssDiff = process.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1";
1024
- const disableV3OxideSourceRuntime = process.env["WEAPP_TW_VITE_DISABLE_V3_OXIDE_RUNTIME"] === "1";
1025
- const resolvedConfig = getResolvedConfig();
1026
- const bundleFiles = Object.keys(bundle);
1027
- const buildCommand = resolvedConfig?.command === "build";
1028
- const hasPreviousBundleState = state.iteration > 0 || state.sourceHashByFile.size > 0;
1029
- const useIncrementalMode = !buildCommand || hasPreviousBundleState || hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
1030
- const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process.cwd();
1031
- const outDir = resolvedConfig?.build?.outDir ? path.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
1032
- currentOutDir = outDir;
1033
- const snapshotStart = performance.now();
1034
- const snapshot = buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode);
1035
- recordTimingDetail("snapshot", snapshotStart);
1036
- const useBundleRuntimeClassSet = !isWebGeneratorTarget && (useIncrementalMode || runtimeState.twPatcher.majorVersion === 4);
1037
- const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1038
- const processFiles = snapshot.processFiles;
1039
- logBundleProcessPlan({
1040
- debug,
1041
- snapshot,
1042
- useIncrementalMode,
1043
- iteration: state.iteration + 1
1044
- });
1045
- const sourceCandidateWaitStart = performance.now();
1046
- await waitForSourceCandidateSyncs?.();
1047
- recordTimingDetail("sourceCandidates.wait", sourceCandidateWaitStart);
1048
- const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
1049
- const jsEntries = snapshot.jsEntries;
1050
- const getJsEntry = createJsEntryResolver(jsEntries);
1051
- const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
1052
- const hasCssAssetEntry = snapshot.entries.some((entry) => entry.type === "css" && entry.output.type === "asset");
1053
- const hasRuntimeAffectingChanges = hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1054
- const useV3OxideSourceRuntime = runtimeState.twPatcher.majorVersion === 3 && sourceCandidates.size > 0 && hasCssAssetEntry && !forceRuntimeRefreshByEnv && !disableV3OxideSourceRuntime;
1055
- const runtimeStart = performance.now();
1056
- const runtime = isWebGeneratorTarget && !shouldGenerateWebCssByGenerator ? /* @__PURE__ */ new Set() : useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, {
1057
- allowBaselineOnlyInitialSync: true,
1058
- baseClassSet: sourceCandidates
1059
- }) : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, { allowBaselineOnlyInitialSync: buildCommand }) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1060
- if (useV3OxideSourceRuntime) debug("[tailwindcss:v3] use oxide source candidates as runtime input, candidates=%d", sourceCandidates.size);
1061
- const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
1062
- const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
1063
- let generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
1064
- let transformRuntime = runtime;
1065
- if (runtimeState.twPatcher.majorVersion === 3 && generatorRuntime.size > 0 && !useV3OxideSourceRuntime) {
1066
- const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
1067
- const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
1068
- if (mainCssEntry) {
1069
- const validatedRuntime = await validateCandidatesByGenerator({
1070
- opts,
1071
- runtimeState,
1072
- candidates: generatorRuntime,
1073
- rawSource: mainCssEntry.source,
1074
- file: mainCssEntry.file,
1075
- cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
1076
- cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
1077
- styleHandler,
1078
- debug
1079
- });
1080
- if (validatedRuntime.size > 0) {
1081
- generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, validatedRuntime);
1082
- transformRuntime = generatorRuntime;
1083
- } else {
1084
- generatorRuntime = validatedRuntime;
1085
- transformRuntime = validatedRuntime;
1086
- }
1087
- }
1088
- }
1089
- const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
1090
- const generatorCandidatesChanged = state.generatorCandidateSignature !== generatorCandidateSignature;
1091
- const runtimeLinkedCssFiles = collectRuntimeLinkedCssFiles(snapshot);
1092
- recordGeneratorCandidates?.(generatorRuntime);
1093
- const defaultTemplateHandlerOptions = { runtimeSet: transformRuntime };
1094
- metrics.runtimeSet = measureElapsed(runtimeStart);
1095
- timingDetails["runtime"] = metrics.runtimeSet;
1096
- if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
1097
- debug("get runtimeSet, class count: %d, transform class count: %d", runtime.size, transformRuntime.size);
1098
- const runtimeSignature = getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1099
- const shouldProcessTailwindGeneration = !useIncrementalMode || hasRuntimeAffectingChanges || generatorCandidatesChanged || snapshot.processFiles.css.size > 0;
1100
- const { applyLinkedUpdates, pendingLinkedUpdates } = createLinkedUpdateHelpers({
1101
- jsEntries,
1102
- onUpdate,
1103
- debug
1104
- });
1105
- const createHandlerOptions = createJsHandlerOptionsFactory({
1106
- getMajorVersion: () => runtimeState.twPatcher.majorVersion,
1107
- moduleGraph: moduleGraphOptions
1108
- });
1109
- const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
1110
- const sharedCssResultCache = /* @__PURE__ */ new Map();
1111
- const tasks = [];
1112
- const jsTaskFactories = [];
1113
- for (const entry of snapshot.entries) {
1114
- const { file, output: originalSource, source: originalEntrySource, type } = entry;
1115
- if (type === "html" && originalSource.type === "asset") {
1116
- metrics.html.total++;
1117
- if (isWebGeneratorTarget) {
1118
- debug("html skip web target: %s", file);
1119
- continue;
1120
- }
1121
- if (!processFiles.html.has(file)) continue;
1122
- const rawSource = originalEntrySource;
1123
- tasks.push(timeTask("html", () => processCachedTask({
1124
- cache,
1125
- cacheKey: file,
1126
- hashKey: `${file}:html:${runtimeSignature}`,
1127
- hash: getSnapshotHash(snapshot.sourceHashByFile, file, rawSource),
1128
- applyResult(source) {
1129
- originalSource.source = source;
1130
- },
1131
- onCacheHit() {
1132
- metrics.html.cacheHits++;
1133
- debug("html cache hit: %s", file);
1134
- },
1135
- async transform() {
1136
- const start = performance.now();
1137
- let transformed = await templateHandler(rawSource, defaultTemplateHandlerOptions);
1138
- let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1139
- if (unresolvedDynamicCandidates.length > 0) {
1140
- logger.warn("检测到 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
1141
- transformed = await templateHandler(rawSource, { runtimeSet: new Set([...await context.ensureRuntimeClassSet(true), ...unresolvedDynamicCandidates]) });
1142
- unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1143
- if (unresolvedDynamicCandidates.length > 0) logger.warn("WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
1144
- }
1145
- metrics.html.elapsed += measureElapsed(start);
1146
- metrics.html.transformed++;
1147
- onUpdate(file, rawSource, transformed);
1148
- debug("html handle: %s", file);
1149
- return { result: transformed };
1150
- }
1151
- })));
1152
- continue;
1153
- }
1154
- if (type === "css" && originalSource.type === "asset") {
1155
- metrics.css.total++;
1156
- const rawSource = originalEntrySource;
1157
- const outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget);
1158
- if (outputFile !== file && !canProcessViteSourceStyleAsCss(rawSource, file)) {
1159
- delete bundle[file];
1160
- debug("css skip raw source style asset: %s -> %s", file, outputFile);
1161
- continue;
1162
- }
1163
- const applyCssResult = (source) => {
1164
- if (outputFile !== file) {
1165
- delete bundle[file];
1166
- if (typeof this.emitFile === "function") this.emitFile({
1167
- type: "asset",
1168
- fileName: outputFile,
1169
- source
1170
- });
1171
- else bundle[outputFile] = originalSource;
1172
- originalSource.fileName = outputFile;
1173
- }
1174
- originalSource.source = source;
1175
- };
1176
- if (isViteProcessedCssAsset?.(originalSource, file)) {
1177
- const nextCss = stripBundlerGeneratedCssMarkers(rawSource);
1178
- applyCssResult(nextCss);
1179
- markCssAssetProcessed?.(originalSource, outputFile);
1180
- recordCssAssetResult?.(outputFile, nextCss);
1181
- onUpdate(outputFile, rawSource, nextCss);
1182
- debug("css skip vite-processed asset: %s", outputFile);
1183
- continue;
1184
- }
1185
- if (isWebGeneratorTarget && !shouldGenerateWebCssByGenerator) {
1186
- applyCssResult(rawSource);
1187
- markCssAssetProcessed?.(originalSource, outputFile);
1188
- onUpdate(outputFile, rawSource, rawSource);
1189
- debug("css skip web target: %s", outputFile);
1190
- continue;
1191
- }
1192
- const cssRuntimeAffectingSignature = snapshot.runtimeAffectingSignatureByFile.get(file) ?? rawSource;
1193
- const cssShareScope = createCssTransformShareScopeKey(opts, file, rawSource);
1194
- const cssHandlerOptions = getCssHandlerOptions(file);
1195
- const shouldTrackGeneratorRuntime = shouldProcessTailwindGeneration && (!useIncrementalMode || cssHandlerOptions.isMainChunk || processFiles.css.has(file) || runtimeLinkedCssFiles.has(file));
1196
- const scopedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? generatorCandidateSignature : "generator:stable";
1197
- const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, scopedGeneratorCandidateSignature);
1198
- const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
1199
- if (!shouldTrackGeneratorRuntime) {
1200
- const lastCss = lastCssResultByFile.get(outputFile) ?? lastCssResultByFile.get(file);
1201
- if (lastCss != null) {
1202
- applyCssResult(lastCss);
1203
- markCssAssetProcessed?.(originalSource, outputFile);
1204
- metrics.css.cacheHits++;
1205
- debug("css replay last result: %s", outputFile);
1206
- continue;
1207
- }
1208
- }
1209
- tasks.push(timeTask("css", () => processCachedTask({
1210
- cache,
1211
- cacheKey: file,
1212
- hashKey: `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1213
- hash: `${getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature)}:${scopedGeneratorCandidateSignature}`,
1214
- applyResult(source) {
1215
- applyCssResult(source);
1216
- lastCssResultByFile.set(outputFile, source);
1217
- markCssAssetProcessed?.(originalSource, outputFile);
1218
- if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(outputFile, rawSource, cssRuntimeSignature);
1219
- },
1220
- onCacheHit() {
1221
- metrics.css.cacheHits++;
1222
- debug("css cache hit: %s", file);
1223
- },
1224
- async transform() {
1225
- if (cssSharedCacheKey) {
1226
- const sharedCssTask = sharedCssResultCache.get(cssSharedCacheKey);
1227
- if (sharedCssTask != null) {
1228
- metrics.css.cacheHits++;
1229
- debug("css shared hit: %s", file);
1230
- const sharedCss = await sharedCssTask;
1231
- onUpdate(file, rawSource, sharedCss);
1232
- return { result: sharedCss };
1233
- }
1234
- }
1235
- const runTransform = async () => {
1236
- const start = performance.now();
1237
- await runtimeState.readyPromise;
1238
- const previousCss = useIncrementalMode && !snapshot.changedByType.css.has(file) ? lastCssResultByFile.get(file) : void 0;
1239
- const generated = await generateCssByGenerator({
1240
- opts,
1241
- runtimeState,
1242
- runtime: generatorRuntime,
1243
- rawSource,
1244
- file,
1245
- cssHandlerOptions,
1246
- cssUserHandlerOptions: getCssUserHandlerOptions(file),
1247
- getSourceCandidatesForEntries,
1248
- styleHandler,
1249
- debug,
1250
- previousCss
1251
- });
1252
- if (generated) {
1253
- registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
1254
- if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, generated.css));
1255
- debug("css generated result: %s bytes=%d", file, generated.css.length);
1256
- recordCssAssetResult?.(outputFile, generated.css);
1257
- metrics.css.elapsed += measureElapsed(start);
1258
- metrics.css.transformed++;
1259
- debug("css handle via tailwind v%s engine(%s): %s", runtimeState.twPatcher.majorVersion, generated.target, outputFile);
1260
- return generated.css;
1261
- }
1262
- if (isWebGeneratorTarget) {
1263
- metrics.css.elapsed += measureElapsed(start);
1264
- metrics.css.transformed++;
1265
- debug("css preserve web target: %s", outputFile);
1266
- return rawSource;
1267
- }
1268
- const { css } = await styleHandler(rawSource, getCssHandlerOptions(file));
1269
- if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, css));
1270
- metrics.css.elapsed += measureElapsed(start);
1271
- metrics.css.transformed++;
1272
- return css;
1273
- };
1274
- const cssTask = cssSharedCacheKey ? sharedCssResultCache.get(cssSharedCacheKey) ?? runTransform() : runTransform();
1275
- if (cssSharedCacheKey && !sharedCssResultCache.has(cssSharedCacheKey)) sharedCssResultCache.set(cssSharedCacheKey, cssTask);
1276
- const css = await cssTask;
1277
- onUpdate(outputFile, rawSource, css);
1278
- debug("css handle: %s", outputFile);
1279
- return { result: css };
1280
- }
1281
- })));
1282
- continue;
1283
- }
1284
- if (type !== "js") continue;
1285
- metrics.js.total++;
1286
- if (isWebGeneratorTarget) {
1287
- debug("js skip web target: %s", file);
1288
- continue;
1289
- }
1290
- const shouldTransformJs = !useIncrementalMode || processFiles.js.has(file);
1291
- if (!shouldTransformJs) debug("js skip transform (clean), replay cache: %s", file);
1292
- if (originalSource.type === "chunk") {
1293
- const absoluteFile = path.resolve(outDir, file);
1294
- const initialRawSource = originalEntrySource;
1295
- const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1296
- if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1297
- jsTaskFactories.push(async () => {
1298
- await timeTask("js", async () => {
1299
- const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1300
- await processCachedTask({
1301
- cache,
1302
- cacheKey: file,
1303
- hashKey: `${file}:js`,
1304
- hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
1305
- applyResult(source) {
1306
- originalSource.code = source;
1307
- },
1308
- onCacheHit() {
1309
- metrics.js.cacheHits++;
1310
- debug("js cache hit: %s", file);
1311
- },
1312
- async transform() {
1313
- const start = performance.now();
1314
- const rawSource = originalSource.code;
1315
- if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1316
- const handlerOptions = createHandlerOptions(absoluteFile);
1317
- if (!disableJsPrecheck && shouldSkipJsTransform(rawSource, handlerOptions)) {
1318
- metrics.js.elapsed += measureElapsed(start);
1319
- metrics.js.transformed++;
1320
- return { result: rawSource };
1321
- }
1322
- const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
1323
- metrics.js.elapsed += measureElapsed(start);
1324
- metrics.js.transformed++;
1325
- onUpdate(file, rawSource, code);
1326
- debug("js handle: %s", file);
1327
- collectLinkedFileNames(linked, getJsEntry, linkedSet);
1328
- applyLinkedUpdates(linked);
1329
- return { result: code };
1330
- }
1331
- });
1332
- });
1333
- });
1334
- } else if (uniAppX && originalSource.type === "asset") {
1335
- const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1336
- if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1337
- const baseApplyLinkedUpdates = applyLinkedUpdates;
1338
- const wrappedApplyLinkedUpdates = (linked) => {
1339
- collectLinkedFileNames(linked, getJsEntry, linkedSet);
1340
- baseApplyLinkedUpdates(linked);
1341
- };
1342
- const factory = createUniAppXAssetTask(file, originalSource, outDir, {
1343
- cache,
1344
- hashKey: `${file}:js`,
1345
- hashSalt: createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0),
1346
- createHandlerOptions,
1347
- debug,
1348
- jsHandler,
1349
- onUpdate,
1350
- runtimeSet: transformRuntime,
1351
- applyLinkedResults: wrappedApplyLinkedUpdates,
1352
- uniAppX
1353
- });
1354
- jsTaskFactories.push(async () => {
1355
- await timeTask("js", async () => {
1356
- const start = performance.now();
1357
- if (!shouldTransformJs) {
1358
- debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
1359
- await factory();
1360
- metrics.js.elapsed += measureElapsed(start);
1361
- metrics.js.transformed++;
1362
- return;
1363
- }
1364
- const currentSource = originalEntrySource;
1365
- const precheckOptions = createHandlerOptions(path.resolve(outDir, file), {
1366
- uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
1367
- babelParserOptions: {
1368
- plugins: ["typescript"],
1369
- sourceType: "unambiguous"
1370
- }
1371
- });
1372
- if (!disableJsPrecheck && shouldSkipJsTransform(currentSource, precheckOptions)) {
1373
- metrics.js.elapsed += measureElapsed(start);
1374
- metrics.js.transformed++;
1375
- return;
1376
- }
1377
- await factory();
1378
- metrics.js.elapsed += measureElapsed(start);
1379
- metrics.js.transformed++;
1380
- });
1381
- });
1382
- }
1383
- }
1384
- const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1385
- if (useIncrementalMode) for (const [file, rawSource] of getRememberedMainCssSources?.() ?? []) {
1386
- if (bundleFiles.includes(file) || getRememberedMainCssSignature?.(file) === cssRuntimeSignature) continue;
1387
- const outputFile = resolveReplayCssOutputFile(rootDir, file);
1388
- tasks.push(timeTask("css.replay", async () => {
1389
- const start = performance.now();
1390
- const cssHandlerOptions = getCssHandlerOptions(outputFile);
1391
- const generated = await generateCssByGenerator({
1392
- opts,
1393
- runtimeState,
1394
- runtime: generatorRuntime,
1395
- rawSource,
1396
- file: outputFile,
1397
- cssHandlerOptions,
1398
- cssUserHandlerOptions: getCssUserHandlerOptions(outputFile),
1399
- getSourceCandidatesForEntries,
1400
- styleHandler,
1401
- debug
1402
- });
1403
- const css = generated?.css ?? (await styleHandler(rawSource, cssHandlerOptions)).css;
1404
- setRememberedMainCssSignature?.(file, cssRuntimeSignature);
1405
- if (generated) {
1406
- registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
1407
- recordCssAssetResult?.(outputFile, generated.css);
1408
- debug("css replay generated result: %s bytes=%d", outputFile, css.length);
1409
- }
1410
- const replayAsset = createReplayCssAsset(outputFile, css);
1411
- if (typeof this.emitFile === "function") this.emitFile({
1412
- type: "asset",
1413
- fileName: outputFile,
1414
- source: css
1415
- });
1416
- else bundle[outputFile] = replayAsset;
1417
- markCssAssetProcessed?.(replayAsset, outputFile);
1418
- metrics.css.elapsed += measureElapsed(start);
1419
- metrics.css.transformed++;
1420
- onUpdate(outputFile, rawSource, css);
1421
- debug("css replay handle: %s", outputFile);
1422
- }));
1423
- }
1424
- pushConcurrentTaskFactories(tasks, jsTaskFactories);
1425
- const tasksStart = performance.now();
1426
- await Promise.all(tasks);
1427
- recordTimingDetail("tasks", tasksStart);
1428
- for (const apply of pendingLinkedUpdates) apply();
1429
- injectViteProcessedCssIntoMainCssAssets(bundle, {
1430
- opts,
1431
- getViteProcessedCssAssetResults,
1432
- markCssAssetProcessed,
1433
- recordCssAssetResult,
1434
- debug,
1435
- onUpdate
1436
- });
1437
- const stateUpdateStart = performance.now();
1438
- updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1439
- state.generatorCandidateSignature = generatorCandidateSignature;
1440
- recordTimingDetail("state.update", stateUpdateStart);
1441
- debug("metrics iteration=%d runtime=%sms html(total=%d transform=%d hit=%d rate=%s elapsed=%sms) js(total=%d transform=%d hit=%d rate=%s elapsed=%sms) css(total=%d transform=%d hit=%d rate=%s elapsed=%sms)", useIncrementalMode ? state.iteration : 0, formatMs(metrics.runtimeSet), metrics.html.total, metrics.html.transformed, metrics.html.cacheHits, formatCacheHitRate(metrics.html), formatMs(metrics.html.elapsed), metrics.js.total, metrics.js.transformed, metrics.js.cacheHits, formatCacheHitRate(metrics.js), formatMs(metrics.js.elapsed), metrics.css.total, metrics.css.transformed, metrics.css.cacheHits, formatCacheHitRate(metrics.css), formatMs(metrics.css.elapsed));
1442
- if (hmrTimingRecorder) {
1443
- hmrTimingRecorder.record("generateBundle", performance.now() - hmrTimingStartedAt, timingDetails);
1444
- hmrTimingRecorder.emitTotal();
1445
- }
1446
- onEnd();
1447
- debug("end");
1448
- };
1449
- }
1450
- //#endregion
1451
- //#region src/bundlers/vite/official-tailwind-plugins.ts
1452
- const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1453
- function getPostcssPluginName(plugin) {
1454
- if (!plugin) return;
1455
- if (typeof plugin === "function" && "postcss" in plugin) try {
1456
- return getPostcssPluginName(plugin());
1457
- } catch {
1458
- return;
1459
- }
1460
- if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1461
- const { postcssPlugin } = plugin;
1462
- return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1463
- }
1464
- function isTailwindPostcssPlugin(plugin) {
1465
- const name = getPostcssPluginName(plugin);
1466
- return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1467
- }
1468
- function removeTailwindPostcssPlugins(plugins) {
1469
- let removed = 0;
1470
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1471
- plugins.splice(i, 1);
1472
- removed++;
1473
- }
1474
- return removed;
1475
- }
1476
- function isTailwindVitePlugin(plugin) {
1477
- if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1478
- const { name } = plugin;
1479
- return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1480
- }
1481
- function removeTailwindVitePlugins(plugins) {
1482
- let removed = 0;
1483
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1484
- plugins.splice(i, 1);
1485
- removed++;
1486
- }
1487
- return removed;
1488
- }
1489
- function disableTailwindVitePlugin(plugin) {
1490
- if (!isTailwindVitePlugin(plugin)) return false;
1491
- const mutablePlugin = plugin;
1492
- for (const hook of [
1493
- "configResolved",
1494
- "configureServer",
1495
- "transform",
1496
- "hotUpdate",
1497
- "handleHotUpdate"
1498
- ]) delete mutablePlugin[hook];
1499
- return true;
1500
- }
1501
- function disableAndRemoveTailwindVitePlugins(plugins) {
1502
- let removed = 0;
1503
- for (let i = plugins.length - 1; i >= 0; i--) {
1504
- const plugin = plugins[i];
1505
- if (Array.isArray(plugin)) {
1506
- removed += disableAndRemoveTailwindVitePlugins(plugin);
1507
- if (plugin.length === 0) plugins.splice(i, 1);
1508
- continue;
1509
- }
1510
- if (disableTailwindVitePlugin(plugin)) {
1511
- plugins.splice(i, 1);
1512
- removed++;
1513
- }
1514
- }
1515
- return removed;
1516
- }
1517
- //#endregion
1518
- //#region src/bundlers/vite/postcss-config.ts
1519
- async function resolveFilteredPostcssConfig(root) {
1520
- try {
1521
- const loaded = await postcssrc({}, root);
1522
- const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1523
- const removed = removeTailwindPostcssPlugins(plugins);
1524
- if (removed === 0) return;
1525
- return {
1526
- options: loaded.options,
1527
- plugins,
1528
- removed
1529
- };
1530
- } catch (error) {
1531
- if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1532
- throw error;
1533
- }
1534
- }
1535
- //#endregion
1536
- //#region src/bundlers/vite/resolve-app-type.ts
1537
- const PACKAGE_JSON_FILE$1 = "package.json";
1538
- const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
1539
- const TARO_SCRIPT_RE = /\btaro\b/u;
1540
- const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
1541
- function resolveDependencyNames(pkg) {
1542
- return new Set([
1543
- ...Object.keys(pkg.dependencies ?? {}),
1544
- ...Object.keys(pkg.devDependencies ?? {}),
1545
- ...Object.keys(pkg.peerDependencies ?? {}),
1546
- ...Object.keys(pkg.optionalDependencies ?? {})
1547
- ]);
1548
- }
1549
- function hasScriptMatch(pkg, pattern) {
1550
- return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
1551
- }
1552
- function resolveAppTypeFromPackageJson(pkg) {
1553
- const dependencyNames = resolveDependencyNames(pkg);
1554
- if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
1555
- if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
1556
- if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
1557
- if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
1558
- if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
1559
- }
1560
- function tryReadUniAppManifest(root) {
1561
- const manifestPath = path.join(root, "manifest.json");
1562
- if (!existsSync(manifestPath)) return;
1563
- try {
1564
- return JSON.parse(readFileSync(manifestPath, "utf8"));
1565
- } catch {}
1566
- }
1567
- function tryReadPackageJson(root) {
1568
- const packageJsonPath = path.join(root, PACKAGE_JSON_FILE$1);
1569
- if (!existsSync(packageJsonPath)) return;
1570
- try {
1571
- return JSON.parse(readFileSync(packageJsonPath, "utf8"));
1572
- } catch {}
1573
- }
1574
- function resolveAppTypeFromMarkers(root) {
1575
- for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if (existsSync(path.join(root, relativePath))) return appType;
1576
- }
1577
- function resolveImplicitAppTypeFromViteRoot(root) {
1578
- const resolvedRoot = path.resolve(root);
1579
- if (!existsSync(resolvedRoot)) return;
1580
- const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
1581
- if (markerDetected) return markerDetected;
1582
- let current = resolvedRoot;
1583
- while (true) {
1584
- const manifest = tryReadUniAppManifest(current);
1585
- if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
1586
- const pkg = tryReadPackageJson(current);
1587
- if (pkg) {
1588
- const detected = resolveAppTypeFromPackageJson(pkg);
1589
- if (detected) return detected;
1590
- }
1591
- const parent = path.dirname(current);
1592
- if (parent === current) break;
1593
- current = parent;
1594
- }
1595
- }
1596
- //#endregion
1597
- //#region src/bundlers/shared/css-imports.ts
1598
- const tailwindcssImportRE = /^(?:tailwindcss|weapp-tailwindcss)(?:\/.*)?$/;
1599
- const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])((?:tailwindcss|weapp-tailwindcss)(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
1600
- function normalizeTailwindcssSpecifier(specifier) {
1601
- if (specifier === "tailwindcss$" || specifier === "weapp-tailwindcss$") return specifier.slice(0, -1);
1602
- return specifier;
1603
- }
1604
- function getTailwindcssSubpath(specifier) {
1605
- if (specifier === "tailwindcss" || specifier === "weapp-tailwindcss") return "index.css";
1606
- return specifier.replace(/^(?:tailwindcss|weapp-tailwindcss)\//, "");
1607
- }
1608
- function resolveTailwindcssImport(specifier, pkgDir, options) {
1609
- const normalized = normalizeTailwindcssSpecifier(specifier);
1610
- if (!tailwindcssImportRE.test(normalized)) return null;
1611
- if (normalized === "tailwindcss" || normalized === "weapp-tailwindcss") return options?.rootImport ?? (options?.join ?? path.join)(pkgDir, "index.css");
1612
- return (options?.join ?? path.join)(pkgDir, getTailwindcssSubpath(normalized));
1613
- }
1614
- function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
1615
- let hasReplacements = false;
1616
- const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
1617
- const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
1618
- if (!replacement) return full;
1619
- hasReplacements = true;
1620
- return `${prefix}${quote}${replacement}${suffix}`;
1621
- });
1622
- return hasReplacements ? rewritten : void 0;
1623
- }
1624
- //#endregion
1625
- //#region src/bundlers/vite/rewrite-css-imports.ts
1626
- function joinPosixPath(base, subpath) {
1627
- if (base.endsWith("/")) return `${base}${subpath}`;
1628
- return `${base}/${subpath}`;
1629
- }
1630
- function isCssLikeImporter(importer) {
1631
- if (!importer) return false;
1632
- const normalized = cleanUrl(importer);
1633
- return isSourceStyleRequest(importer) || isCSSRequest(normalized) || normalized.endsWith("/*");
1634
- }
1635
- function stripTailwindConfigDirectives(code) {
1636
- return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
1637
- }
1638
- function createRewriteCssImportsPlugins(options) {
1639
- if (!options.shouldRewrite && !options.shouldOwnTailwindGeneration) return [];
1640
- const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
1641
- const resolveAppType = () => getAppType?.() ?? appType;
1642
- return [{
1643
- name: `${vitePluginName}:rewrite-css-imports`,
1644
- enforce: "pre",
1645
- resolveId(id, importer) {
1646
- if (!options.shouldRewrite) return null;
1647
- const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1648
- join: joinPosixPath,
1649
- appType: resolveAppType(),
1650
- rootImport
1651
- });
1652
- if (!replacement) return null;
1653
- if (importer && !isCssLikeImporter(importer)) return null;
1654
- return replacement;
1655
- },
1656
- async transform(code, id) {
1657
- if (!isCSSRequest(id)) return null;
1658
- if (hasTailwindRootDirectives(code)) {
1659
- await options.onTailwindRootCss?.(id, code);
1660
- if (options.shouldOwnTailwindGeneration) {
1661
- const generatedCss = await options.generateTailwindCss?.(id, code, this);
1662
- if (generatedCss !== void 0) return {
1663
- code: generatedCss,
1664
- map: null
1665
- };
1666
- }
1667
- }
1668
- if (!options.shouldRewrite) return null;
1669
- const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1670
- join: joinPosixPath,
1671
- appType: resolveAppType(),
1672
- rootImport
1673
- });
1674
- const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? code) : rewritten;
1675
- if (!nextCode || nextCode === code) return null;
1676
- return {
1677
- code: nextCode,
1678
- map: null
1679
- };
1680
- }
1681
- }];
1682
- }
1683
- //#endregion
1684
- //#region src/bundlers/vite/runtime-class-set.ts
1685
- function createViteRuntimeClassSet(options) {
1686
- const { opts, initialTwPatcher, refreshTailwindcssPatcher, uniAppXEnabled, customAttributesEntities, disabledDefaultTemplateHandler, debug } = options;
1687
- const runtimeState = {
1688
- twPatcher: initialTwPatcher,
1689
- readyPromise: createTailwindRuntimeReadyPromise(initialTwPatcher),
1690
- refreshTailwindcssPatcher
1691
- };
1692
- const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1693
- let runtimeSet;
1694
- let runtimeSetPromise;
1695
- let runtimeRefreshSignature;
1696
- let runtimeRefreshOptionsKey;
1697
- function resolveRuntimeRefreshOptions() {
1698
- const configPath = resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1699
- const signature = getRuntimeClassSetSignature(runtimeState.twPatcher);
1700
- const optionsKey = JSON.stringify({
1701
- appType: opts.appType,
1702
- uniAppX: uniAppXEnabled,
1703
- customAttributesEntities,
1704
- disabledDefaultTemplateHandler,
1705
- configPath
1706
- });
1707
- const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1708
- runtimeRefreshSignature = signature;
1709
- runtimeRefreshOptionsKey = optionsKey;
1710
- return {
1711
- changed,
1712
- signature,
1713
- optionsKey
1714
- };
1715
- }
1716
- async function refreshRuntimeState(force) {
1717
- const invalidation = resolveRuntimeRefreshOptions();
1718
- const refreshed = await refreshTailwindRuntimeState(runtimeState, {
1719
- force: force || invalidation.changed,
1720
- clearCache: force || invalidation.changed
1721
- });
1722
- if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
1723
- if (refreshed) {
1724
- runtimeSet = void 0;
1725
- runtimeSetPromise = void 0;
1726
- }
1727
- }
1728
- async function ensureRuntimeClassSet(force = false) {
1729
- const forceRuntimeRefresh = force || process.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1730
- await refreshRuntimeState(force);
1731
- await runtimeState.readyPromise;
1732
- if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
1733
- if (forceRuntimeRefresh || !runtimeSetPromise) {
1734
- const invalidation = resolveRuntimeRefreshOptions();
1735
- runtimeSetPromise = collectRuntimeClassSet(runtimeState.twPatcher, {
1736
- force: forceRuntimeRefresh || invalidation.changed,
1737
- skipRefresh: forceRuntimeRefresh,
1738
- clearCache: forceRuntimeRefresh || invalidation.changed
1739
- });
1740
- }
1741
- const task = runtimeSetPromise;
1742
- try {
1743
- runtimeSet = await task;
1744
- return runtimeSet;
1745
- } finally {
1746
- if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1747
- }
1748
- }
1749
- async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false, options = {}) {
1750
- const forceRuntimeRefresh = forceRefresh || process.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1751
- const invalidation = resolveRuntimeRefreshOptions();
1752
- const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
1753
- const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
1754
- await refreshRuntimeState(shouldRefreshPatcher);
1755
- await runtimeState.readyPromise;
1756
- if (shouldRefreshPatcher) {
1757
- runtimeSet = void 0;
1758
- runtimeSetPromise = void 0;
1759
- await bundleRuntimeClassSetManager.reset();
1760
- }
1761
- if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
1762
- const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
1763
- runtimeSet = nextRuntimeSet;
1764
- return nextRuntimeSet;
1765
- } catch (error) {
1766
- debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1767
- await bundleRuntimeClassSetManager.reset();
1768
- }
1769
- if (runtimeState.twPatcher.majorVersion === 3 && !forceRuntimeRefresh) try {
1770
- let baseClassSet = options.baseClassSet;
1771
- if (!baseClassSet && (!runtimeSet || shouldRefreshPatcher)) baseClassSet = await collectRuntimeClassSet(runtimeState.twPatcher, {
1772
- force: true,
1773
- skipRefresh: shouldRefreshPatcher,
1774
- clearCache: shouldRefreshPatcher
1775
- });
1776
- const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot, {
1777
- baseClassSet: baseClassSet ?? (options.allowBaselineOnlyInitialSync === true ? runtimeSet : void 0),
1778
- skipInitialFullScanWithBase: options.allowBaselineOnlyInitialSync === true && Boolean(runtimeSet)
1779
- });
1780
- runtimeSet = nextRuntimeSet;
1781
- return nextRuntimeSet;
1782
- } catch (error) {
1783
- debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1784
- await bundleRuntimeClassSetManager.reset();
1785
- }
1786
- if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
1787
- const task = collectRuntimeClassSet(runtimeState.twPatcher, {
1788
- force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
1789
- skipRefresh: forceRuntimeRefresh,
1790
- clearCache: forceRuntimeRefresh || invalidation.changed
1791
- });
1792
- runtimeSetPromise = task;
1793
- try {
1794
- runtimeSet = await task;
1795
- return runtimeSet;
1796
- } finally {
1797
- if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1798
- }
1799
- }
1800
- return {
1801
- runtimeState,
1802
- refreshRuntimeState,
1803
- ensureRuntimeClassSet,
1804
- ensureBundleRuntimeClassSet
1805
- };
1806
- }
1807
- //#endregion
1808
- //#region src/bundlers/vite/serve-css-generation.ts
1809
- const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
1810
- const COMMON_JS_PROXY_RE = /\?commonjs-proxy/;
1811
- const VITE_CSS_HMR_MODULE_RE = /\b__vite__updateStyle\s*\(/;
1812
- const VITE_CSS_CONST_RE = /\bconst\s+__vite__css\s*=\s*("(?:\\[\s\S]|[^"])*")/;
1813
- function decodeJsStringLiteral(literal) {
1814
- try {
1815
- return JSON.parse(literal);
1816
- } catch {
1817
- return;
1818
- }
1819
- }
1820
- function encodeJsStringLiteral(value) {
1821
- return JSON.stringify(value);
1822
- }
1823
- function extractViteCssHmrModuleCss(code) {
1824
- const match = VITE_CSS_CONST_RE.exec(code);
1825
- if (!match?.[1]) return;
1826
- const css = decodeJsStringLiteral(match[1]);
1827
- if (typeof css !== "string") return;
1828
- return {
1829
- css,
1830
- start: match.index + match[0].lastIndexOf(match[1]),
1831
- end: match.index + match[0].length
1832
- };
1833
- }
1834
- function replaceViteCssHmrModuleCss(code, css) {
1835
- const extracted = extractViteCssHmrModuleCss(code);
1836
- if (!extracted) return;
1837
- return `${code.slice(0, extracted.start)}${encodeJsStringLiteral(css)}${code.slice(extracted.end)}`;
1838
- }
1839
- function isViteServeStyleRequest(id, command) {
1840
- return command === "serve" && isSourceStyleRequest(id) && !SPECIAL_QUERY_RE.test(id) && !COMMON_JS_PROXY_RE.test(id);
1841
- }
1842
- function isViteServeCssRootRequest(id, command) {
1843
- return command === "serve" && isCSSRequest(id) && !SPECIAL_QUERY_RE.test(id) && !COMMON_JS_PROXY_RE.test(id);
1844
- }
1845
- function isViteCssHmrModule(code, id, command) {
1846
- return isViteServeStyleRequest(id, command) && VITE_CSS_HMR_MODULE_RE.test(code) && /[?&](?:direct|vue)(?:&|$)/.test(id);
1847
- }
1848
- function createViteServeCssGenerationPlugins(options) {
1849
- return [{
1850
- name: `${vitePluginName}:generate:serve`,
1851
- apply: "serve",
1852
- enforce: "pre",
1853
- async transform(code, id) {
1854
- if (!options.shouldGenerate() || !isViteServeCssRootRequest(id, options.getCommand())) return;
1855
- if (!hasTailwindRootDirectives(code)) return;
1856
- await options.onTailwindRootCss?.(id, code);
1857
- const generatedCss = await options.generateCss(id, code, this);
1858
- if (generatedCss === void 0 || generatedCss === code) return;
1859
- return {
1860
- code: generatedCss,
1861
- map: null
1862
- };
1863
- }
1864
- }, {
1865
- name: `${vitePluginName}:generate:serve-hmr`,
1866
- apply: "serve",
1867
- enforce: "post",
1868
- async transform(code, id) {
1869
- if (!options.shouldGenerate() || !isViteCssHmrModule(code, id, options.getCommand())) return;
1870
- const extracted = extractViteCssHmrModuleCss(code);
1871
- if (!extracted) return;
1872
- await options.onTailwindRootCss?.(id, extracted.css);
1873
- const generatedCss = await options.generateCss(id, extracted.css, this);
1874
- if (generatedCss === void 0 || generatedCss === extracted.css) return;
1875
- const nextCode = replaceViteCssHmrModuleCss(code, generatedCss);
1876
- if (nextCode === void 0 || nextCode === code) return;
1877
- return {
1878
- code: nextCode,
1879
- map: null
1880
- };
1881
- }
1882
- }];
1883
- }
1884
- //#endregion
1885
- //#region src/bundlers/vite/tailwind-basedir.ts
1886
- const PACKAGE_JSON_FILE = "package.json";
1887
- function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1888
- const resolvedRoot = path.resolve(root);
1889
- if (!existsSync(resolvedRoot)) return resolvedRoot;
1890
- const searchRoots = [];
1891
- let current = resolvedRoot;
1892
- while (true) {
1893
- searchRoots.push(current);
1894
- const parent = path.dirname(current);
1895
- if (parent === current) break;
1896
- current = parent;
1897
- }
1898
- const tailwindConfigPath = findTailwindConfig(searchRoots);
1899
- if (tailwindConfigPath) return path.dirname(tailwindConfigPath);
1900
- const packageRoot = findNearestPackageRoot(resolvedRoot);
1901
- if (packageRoot && existsSync(path.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1902
- return resolvedRoot;
1903
- }
1904
- //#endregion
1905
- //#region src/bundlers/vite/index.ts
1906
- const debug = createDebug();
1907
- const weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
1908
- const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1909
- const sourceCandidateScanSnapshotCache = /* @__PURE__ */ new Map();
1910
- function normalizeSignaturePath(value) {
1911
- return slash(path.resolve(value));
1912
- }
1913
- function serializeInlineCandidates(inlineCandidates) {
1914
- return {
1915
- excluded: [...inlineCandidates?.excluded ?? []].sort(),
1916
- included: [...inlineCandidates?.included ?? []].sort()
1917
- };
1918
- }
1919
- function serializeSourceEntries(entries) {
1920
- return (entries ?? []).map((entry) => ({
1921
- base: normalizeSignaturePath(entry.base),
1922
- negated: entry.negated,
1923
- pattern: entry.pattern
1924
- })).sort((a, b) => `${a.base}\0${a.pattern}\0${a.negated}`.localeCompare(`${b.base}\0${b.pattern}\0${b.negated}`));
1925
- }
1926
- function createSourceCandidateScanSignature(input) {
1927
- return JSON.stringify({
1928
- inlineCandidates: serializeInlineCandidates(input.inlineCandidates),
1929
- outDir: input.outDir ? normalizeSignaturePath(input.outDir) : void 0,
1930
- roots: input.roots.map((root) => ({
1931
- entries: serializeSourceEntries(root.entries),
1932
- root: normalizeSignaturePath(root.root)
1933
- })),
1934
- scanAllSources: input.scanAllSources ?? false
1935
- });
1936
- }
1937
- /**
1938
- * @name WeappTailwindcss
1939
- * @description uni-app vite / uni-app-x 版本插件
1940
- * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
1941
- */
1942
- function WeappTailwindcss(options = {}) {
1943
- const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
1944
- const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1945
- const opts = getCompilerContext({
1946
- ...options,
1947
- __internalDeferMissingCssEntriesWarning: true
1948
- });
1949
- const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
1950
- const uniAppXEnabled = isUniAppXEnabled(uniAppX);
1951
- const disabledOptions = resolvePluginDisabledState(disabled);
1952
- const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1953
- const shouldOwnTailwindGeneration = !disabledOptions.plugin;
1954
- const shouldRewriteCssImports = tailwindcssMajorVersion >= 4;
1955
- const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
1956
- const shouldInferAppType = !hasExplicitAppType && generatorOptions.target !== "web";
1957
- const hasInitialTailwindCssRoots = hasConfiguredTailwindV4CssRoots({
1958
- ...options,
1959
- cssEntries: opts.cssEntries ?? options.cssEntries
1960
- });
1961
- const autoCssSourceContent = /* @__PURE__ */ new Map();
1962
- let refreshRuntimeStateForAutoCssSources;
1963
- let autoCssSourcesRefresh;
1964
- let autoCssSourcesDiscovered = false;
1965
- const syncTailwindCssSourceCandidates = async (id, css) => {
1966
- await sourceCandidateCollector.syncCss(id, css);
1967
- cacheCurrentSourceCandidateScan();
1968
- };
1969
- const registerAutoCssSource = async (id, css, options = {}) => {
1970
- if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots) return;
1971
- const file = cleanUrl(id);
1972
- if (!path.isAbsolute(file)) return;
1973
- const sourceFile = path.normalize(file);
1974
- const sourceCss = normalizeTailwindSourceForGenerator(css, { importFallback: true });
1975
- if (autoCssSourceContent.get(sourceFile) === sourceCss) return;
1976
- autoCssSourceContent.set(sourceFile, sourceCss);
1977
- await syncTailwindCssSourceCandidates(sourceFile, sourceCss);
1978
- const dependencies = await resolveViteTailwindV4CssDependencies(sourceCss, path.dirname(sourceFile));
1979
- if (!upsertTailwindV4CssSource(opts, {
1980
- file: sourceFile,
1981
- base: path.dirname(sourceFile),
1982
- css: sourceCss,
1983
- dependencies
1984
- })) return;
1985
- invalidateSourceCandidateScan();
1986
- debug("detected tailwindcss v4 css source from vite css module: %s", sourceFile);
1987
- if (options.refresh === false) return;
1988
- autoCssSourcesRefresh = (autoCssSourcesRefresh ?? Promise.resolve()).then(async () => {
1989
- await refreshRuntimeStateForAutoCssSources?.(true);
1990
- await syncSourceCandidateScan({ force: true });
1991
- });
1992
- await autoCssSourcesRefresh;
1993
- };
1994
- const discoverAndRegisterAutoCssSources = async () => {
1995
- if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots || !resolvedConfig?.root) return;
1996
- const cssEntries = await discoverTailwindV4CssEntries(resolvedConfig.root, resolvedConfig.build?.outDir);
1997
- autoCssSourcesDiscovered = true;
1998
- let changed = false;
1999
- for (const cssEntry of cssEntries) {
2000
- const sourceFile = path.resolve(cssEntry);
2001
- const sourceCss = normalizeTailwindSourceForGenerator(await readFile(sourceFile, "utf8"), { importFallback: true });
2002
- if (autoCssSourceContent.get(sourceFile) === sourceCss) continue;
2003
- autoCssSourceContent.set(sourceFile, sourceCss);
2004
- await syncTailwindCssSourceCandidates(sourceFile, sourceCss);
2005
- const resolved = await resolveTailwindV4EntriesFromCssCached(sourceCss, path.dirname(sourceFile));
2006
- changed = upsertTailwindV4CssSource(opts, {
2007
- file: sourceFile,
2008
- base: path.dirname(sourceFile),
2009
- css: sourceCss,
2010
- dependencies: resolved?.dependencies ?? []
2011
- }) || changed;
2012
- }
2013
- if (!changed) return;
2014
- invalidateSourceCandidateScan();
2015
- await refreshRuntimeStateForAutoCssSources?.(true);
2016
- };
2017
- const customAttributesEntities = toCustomAttributesEntities(customAttributes);
2018
- let resolvedConfig;
2019
- let recordedGeneratorCandidates;
2020
- const sourceCandidateCollector = createSourceCandidateCollector();
2021
- const sourceCandidateScanCache = /* @__PURE__ */ new Map();
2022
- let sourceScanEntries;
2023
- let sourceScanMatcher;
2024
- let sourceScanDependencies = /* @__PURE__ */ new Set();
2025
- let sourceScanExplicit = false;
2026
- let sourceCandidateScanSignature;
2027
- let sourceCandidateScanInvalidated = true;
2028
- const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
2029
- const pendingSourceCandidateSyncByFile = /* @__PURE__ */ new Map();
2030
- const processedCssAssets = /* @__PURE__ */ new WeakSet();
2031
- const processedCssAssetFiles = /* @__PURE__ */ new Set();
2032
- const viteProcessedCssSourceFiles = /* @__PURE__ */ new Set();
2033
- const viteGeneratedCssByFile = /* @__PURE__ */ new Map();
2034
- const viteProcessedCssAssetResults = /* @__PURE__ */ new Map();
2035
- const rememberedMainCssSources = /* @__PURE__ */ new Map();
2036
- const rememberedMainCssSignatureByFile = /* @__PURE__ */ new Map();
2037
- const tailwindRootCssModuleIds = /* @__PURE__ */ new Set();
2038
- const { runtimeState, refreshRuntimeState, ensureRuntimeClassSet, ensureBundleRuntimeClassSet } = createViteRuntimeClassSet({
2039
- opts,
2040
- initialTwPatcher,
2041
- refreshTailwindcssPatcher,
2042
- uniAppXEnabled,
2043
- customAttributesEntities,
2044
- disabledDefaultTemplateHandler,
2045
- debug
2046
- });
2047
- const hmrTimingRecorder = createHmrTimingRecorder("vite");
2048
- refreshRuntimeStateForAutoCssSources = refreshRuntimeState;
2049
- onLoad();
2050
- const getResolvedConfig = () => resolvedConfig;
2051
- const markCssAssetProcessed = (asset, file) => {
2052
- processedCssAssets.add(asset);
2053
- if (file) processedCssAssetFiles.add(normalizeOutputPathKey(file));
2054
- };
2055
- const isCssAssetProcessed = (asset, file) => {
2056
- return processedCssAssets.has(asset) || (file ? processedCssAssetFiles.has(normalizeOutputPathKey(file)) : false);
2057
- };
2058
- const recordGeneratorCandidates = (candidates) => {
2059
- recordedGeneratorCandidates = new Set(candidates);
2060
- };
2061
- const getRecordedGeneratorCandidates = () => recordedGeneratorCandidates;
2062
- const invalidateRecordedGeneratorCandidates = () => {
2063
- recordedGeneratorCandidates = void 0;
2064
- };
2065
- const getSourceCandidates = () => sourceCandidateCollector.values();
2066
- const getSourceCandidatesForEntries = (entries) => sourceCandidateCollector.valuesForEntries(entries);
2067
- const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
2068
- const isWatchLikeBuild = () => isWatchBuild() || resolvedConfig?.command === "serve" || process.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || process.env["WEAPP_TW_HMR_TIMING"] === "1";
2069
- const hasSourceCandidateScanState = () => sourceCandidateScanSignature !== void 0;
2070
- const normalizeSourceScanDependency = (file) => path.normalize(path.resolve(cleanUrl(file)));
2071
- const isSourceScanDependency = (file) => sourceScanDependencies.has(normalizeSourceScanDependency(file));
2072
- const invalidateSourceCandidateScan = () => {
2073
- sourceCandidateScanInvalidated = true;
2074
- };
2075
- const collectSourceCandidateScanRoots = (root, entries) => {
2076
- if (entries?.length) return [{
2077
- entries,
2078
- explicit: sourceScanExplicit,
2079
- root
2080
- }];
2081
- if (sourceScanExplicit) return [];
2082
- const roots = [{
2083
- entries,
2084
- root
2085
- }];
2086
- const normalizedRoot = path.resolve(root);
2087
- const seenRoots = new Set([normalizedRoot]);
2088
- const basedir = opts.tailwindcssBasedir ? path.resolve(opts.tailwindcssBasedir) : void 0;
2089
- if (basedir && !seenRoots.has(basedir)) {
2090
- roots.push({ root: basedir });
2091
- seenRoots.add(basedir);
2092
- }
2093
- for (const cssEntry of opts.tailwindcss?.v4?.cssEntries ?? []) {
2094
- const cssEntryRoot = path.dirname(path.resolve(cssEntry));
2095
- if (seenRoots.has(cssEntryRoot)) continue;
2096
- roots.push({ root: cssEntryRoot });
2097
- seenRoots.add(cssEntryRoot);
2098
- }
2099
- return roots;
2100
- };
2101
- const scanSourceCandidateRoots = async (roots, outDir) => {
2102
- await Promise.all(roots.map((root) => sourceCandidateCollector.scanRoot({
2103
- entries: root.entries,
2104
- explicit: root.explicit,
2105
- root: root.root,
2106
- outDir
2107
- })));
2108
- };
2109
- const cacheCurrentSourceCandidateScan = () => {
2110
- if (sourceCandidateScanSignature) {
2111
- sourceCandidateScanCache.set(sourceCandidateScanSignature, sourceCandidateCollector.snapshot());
2112
- sourceCandidateScanSnapshotCache.set(sourceCandidateScanSignature, sourceCandidateCollector.snapshot());
2113
- }
2114
- };
2115
- const shouldDiscoverAutoCssSources = () => {
2116
- if (!autoCssSourcesDiscovered) return true;
2117
- if (!isWatchLikeBuild()) return true;
2118
- return sourceCandidateScanInvalidated;
2119
- };
2120
- async function syncSourceCandidateScan(options = {}) {
2121
- if (!shouldOwnTailwindGeneration) return;
2122
- if (!options.force && isWatchLikeBuild() && hasSourceCandidateScanState() && !sourceCandidateScanInvalidated) {
2123
- debug("reuse vite source candidate scan definition for watch rebuild");
2124
- return;
2125
- }
2126
- const root = resolvedConfig?.root ?? process.cwd();
2127
- const outDir = resolvedConfig?.build?.outDir;
2128
- const sourceScan = await resolveViteSourceScanEntries(opts, runtimeState.twPatcher, {
2129
- outDir,
2130
- root
2131
- });
2132
- sourceScanEntries = sourceScan?.entries;
2133
- sourceScanExplicit = sourceScan?.explicit ?? false;
2134
- sourceScanMatcher = createViteSourceScanMatcher(sourceScanEntries);
2135
- sourceScanDependencies = new Set((sourceScan?.dependencies ?? []).map(normalizeSourceScanDependency));
2136
- const roots = collectSourceCandidateScanRoots(root, sourceScanEntries);
2137
- const nextScanSignature = createSourceCandidateScanSignature({
2138
- inlineCandidates: sourceScan?.inlineCandidates,
2139
- outDir,
2140
- roots,
2141
- scanAllSources: !sourceScanExplicit
2142
- });
2143
- if (hasSourceCandidateScanState() && sourceCandidateScanSignature === nextScanSignature) {
2144
- sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2145
- sourceCandidateScanCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
2146
- debug("reuse vite source candidate scan for watch rebuild");
2147
- sourceCandidateScanInvalidated = false;
2148
- return;
2149
- }
2150
- const cachedScan = isWatchLikeBuild() ? sourceCandidateScanCache.get(nextScanSignature) ?? sourceCandidateScanSnapshotCache.get(nextScanSignature) : void 0;
2151
- if (cachedScan) {
2152
- sourceCandidateCollector.restore(cachedScan);
2153
- sourceCandidateScanSignature = nextScanSignature;
2154
- debug("reuse cached vite source candidate scan for watch rebuild");
2155
- sourceCandidateScanInvalidated = false;
2156
- return;
2157
- }
2158
- sourceCandidateCollector.clear();
2159
- sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2160
- await scanSourceCandidateRoots(roots, outDir);
2161
- sourceCandidateScanSignature = nextScanSignature;
2162
- sourceCandidateScanInvalidated = false;
2163
- if (isWatchLikeBuild()) {
2164
- sourceCandidateScanCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
2165
- sourceCandidateScanSnapshotCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
2166
- }
2167
- }
2168
- const waitForSourceCandidateSyncs = async () => {
2169
- while (pendingSourceCandidateSyncs.size > 0) await Promise.all(pendingSourceCandidateSyncs);
2170
- };
2171
- const syncChangedSourceCandidateFile = (id) => {
2172
- if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return Promise.resolve();
2173
- const file = cleanUrl(id);
2174
- if (isSourceScanDependency(file)) invalidateSourceCandidateScan();
2175
- if (sourceScanMatcher && !sourceScanMatcher(file)) {
2176
- sourceCandidateCollector.remove(file);
2177
- cacheCurrentSourceCandidateScan();
2178
- return Promise.resolve();
2179
- }
2180
- if (sourceScanExplicit && sourceScanEntries?.length === 0) {
2181
- cacheCurrentSourceCandidateScan();
2182
- return Promise.resolve();
2183
- }
2184
- const existingTask = pendingSourceCandidateSyncByFile.get(file);
2185
- if (existingTask) return existingTask;
2186
- const task = sourceCandidateCollector.syncCurrentFile(id).catch((error) => {
2187
- debug("source candidate watch sync failed: %s %O", id, error);
2188
- }).then(() => {
2189
- cacheCurrentSourceCandidateScan();
2190
- }).finally(() => {
2191
- pendingSourceCandidateSyncs.delete(task);
2192
- pendingSourceCandidateSyncByFile.delete(file);
2193
- });
2194
- pendingSourceCandidateSyncs.add(task);
2195
- pendingSourceCandidateSyncByFile.set(file, task);
2196
- return task;
2197
- };
2198
- const shouldCollectTransformedSourceCandidates = (id) => {
2199
- if (id.search(/[?#]/) < 0) return true;
2200
- const file = cleanUrl(id);
2201
- return !/\.(?:vue|uvue|nvue|svelte|mpx)$/i.test(file);
2202
- };
2203
- const rememberMainCssSource = (file, rawSource, cssRuntimeSignature) => {
2204
- rememberedMainCssSources.set(file, rawSource);
2205
- if (cssRuntimeSignature) rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2206
- };
2207
- const getRememberedMainCssSources = () => rememberedMainCssSources;
2208
- const getRememberedMainCssSource = (file) => rememberedMainCssSources.get(file);
2209
- const getRememberedMainCssSignature = (file) => rememberedMainCssSignatureByFile.get(file);
2210
- const setRememberedMainCssSignature = (file, cssRuntimeSignature) => {
2211
- rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2212
- };
2213
- const recordCssAssetResult = (file, css) => {
2214
- viteGeneratedCssByFile.set(file, css);
2215
- };
2216
- const recordViteProcessedCssAssetResult = (file, css) => {
2217
- viteProcessedCssAssetResults.set(normalizeOutputPathKey(file), css);
2218
- };
2219
- const getViteProcessedCssAssetResults = () => viteProcessedCssAssetResults.entries();
2220
- const normalizeViteProcessedCssFile = (file) => path.resolve(cleanUrl(file));
2221
- const markViteProcessedCssSource = (file) => {
2222
- viteProcessedCssSourceFiles.add(normalizeViteProcessedCssFile(file));
2223
- };
2224
- const rememberTailwindRootCssModule = (id) => {
2225
- if (!shouldOwnTailwindGeneration) return;
2226
- tailwindRootCssModuleIds.add(id);
2227
- tailwindRootCssModuleIds.add(cleanUrl(id));
2228
- };
2229
- const resolveHotTailwindCssModules = (ctx) => {
2230
- const modules = [];
2231
- const seenModules = /* @__PURE__ */ new Set();
2232
- const collectModule = (mod) => {
2233
- if (mod == null || seenModules.has(mod)) return;
2234
- if (!isSourceStyleRequest(mod.id ?? mod.url)) return;
2235
- seenModules.add(mod);
2236
- ctx.server.moduleGraph.invalidateModule(mod);
2237
- modules.push(mod);
2238
- };
2239
- for (const id of tailwindRootCssModuleIds) {
2240
- const candidates = [
2241
- ctx.server.moduleGraph.getModuleById(id),
2242
- ctx.server.moduleGraph.getModuleById(cleanUrl(id)),
2243
- ...ctx.server.moduleGraph.getModulesByFile(id) ?? [],
2244
- ...ctx.server.moduleGraph.getModulesByFile(cleanUrl(id)) ?? []
2245
- ];
2246
- for (const mod of candidates) collectModule(mod);
2247
- }
2248
- return modules;
2249
- };
2250
- const resolveModuleHotUrl = (mod) => {
2251
- if (typeof mod.url === "string" && mod.url.length > 0) return mod.url;
2252
- if (typeof mod.id === "string" && mod.id.startsWith("/")) return mod.id;
2253
- };
2254
- const includesHotModule = (modules, target) => {
2255
- const targetUrl = resolveModuleHotUrl(target);
2256
- const targetId = target.id;
2257
- return modules.some((mod) => {
2258
- if (mod === target) return true;
2259
- return targetUrl !== void 0 && resolveModuleHotUrl(mod) === targetUrl || typeof targetId === "string" && targetId.length > 0 && mod.id === targetId;
2260
- });
2261
- };
2262
- const hasSelfAcceptingNonStyleHotModule = (modules) => {
2263
- return modules.some((mod) => {
2264
- return !isSourceStyleRequest(mod.id ?? mod.url) && mod.isSelfAccepting === true;
2265
- });
2266
- };
2267
- const isUniViteProject = () => {
2268
- return resolvedConfig?.plugins?.some((plugin) => plugin.name.includes("uni")) ?? false;
2269
- };
2270
- const sendSupplementalCssHotUpdates = (ctx, cssModules) => {
2271
- const updates = cssModules.filter((mod) => !includesHotModule(ctx.modules, mod)).map((mod) => {
2272
- const hotUrl = resolveModuleHotUrl(mod);
2273
- if (!hotUrl) return;
2274
- return {
2275
- type: "js-update",
2276
- timestamp: ctx.timestamp,
2277
- path: hotUrl,
2278
- acceptedPath: hotUrl,
2279
- explicitImportRequired: false,
2280
- isWithinCircularImport: false
2281
- };
2282
- }).filter((update) => update !== void 0);
2283
- if (updates.length === 0) return;
2284
- queueMicrotask(() => {
2285
- ctx.server.ws?.send?.({
2286
- type: "update",
2287
- updates
2288
- });
2289
- });
2290
- };
2291
- const sendFullReloadForUnresolvedHotUpdate = (ctx) => {
2292
- ctx.server.ws?.send?.({
2293
- type: "full-reload",
2294
- path: "*",
2295
- triggeredBy: ctx.file
2296
- });
2297
- };
2298
- const matchesViteProcessedCssSource = (candidate) => {
2299
- const normalized = normalizeViteProcessedCssFile(candidate);
2300
- return viteProcessedCssSourceFiles.has(normalized);
2301
- };
2302
- const isViteProcessedCssAsset = (asset, file) => {
2303
- if (hasBundlerGeneratedCssMarker(asset.source)) return true;
2304
- return [
2305
- file,
2306
- asset.originalFileName,
2307
- ...asset.originalFileNames ?? []
2308
- ].filter((item) => typeof item === "string" && item.length > 0).some((candidate) => matchesViteProcessedCssSource(cleanUrl(candidate)));
2309
- };
2310
- const transformCssHandlerOptions = createCssHandlerOptionsCache({
2311
- getAppType: () => opts.appType,
2312
- mainCssChunkMatcher,
2313
- getMajorVersion: () => runtimeState.twPatcher.majorVersion,
2314
- getOutputRoot: () => resolvedConfig?.build?.outDir ? path.resolve(resolvedConfig.root, resolvedConfig.build.outDir) : resolvedConfig?.root
2315
- });
2316
- const generateTailwindCssForVitePipeline = async (id, code, hookContext) => {
2317
- if (!shouldOwnTailwindGeneration) return;
2318
- await runtimeState.readyPromise;
2319
- await waitForSourceCandidateSyncs();
2320
- const file = cleanUrl(id);
2321
- const runtime = getRecordedGeneratorCandidates() ?? getSourceCandidates() ?? await ensureRuntimeClassSet();
2322
- const generated = await generateCssByGenerator({
2323
- opts,
2324
- runtimeState,
2325
- runtime,
2326
- rawSource: code,
2327
- file,
2328
- cssHandlerOptions: transformCssHandlerOptions.getCssHandlerOptions(file),
2329
- cssUserHandlerOptions: transformCssHandlerOptions.getCssUserHandlerOptions(file),
2330
- getSourceCandidatesForEntries,
2331
- styleHandler,
2332
- debug,
2333
- previousCss: viteGeneratedCssByFile.get(file)
2334
- });
2335
- if (!generated) return;
2336
- for (const dependency of generated.dependencies) hookContext?.addWatchFile?.(dependency);
2337
- viteGeneratedCssByFile.set(file, generated.css);
2338
- markViteProcessedCssSource(file);
2339
- rememberTailwindRootCssModule(id);
2340
- recordGeneratorCandidates(runtime);
2341
- rememberMainCssSource(file, code);
2342
- debug("css generated for vite postcss pipeline: %s bytes=%d", file, generated.css.length);
2343
- return `${createBundlerGeneratedCssMarker("vite", normalizeViteProcessedCssFile(file))}\n${generated.css}`;
2344
- };
2345
- const rewritePlugins = createRewriteCssImportsPlugins({
2346
- getAppType: () => opts.appType,
2347
- generateTailwindCss: generateTailwindCssForVitePipeline,
2348
- rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
2349
- onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
2350
- shouldOwnTailwindGeneration,
2351
- shouldRewrite: shouldRewriteCssImports,
2352
- weappTailwindcssDirPosix
2353
- });
2354
- if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
2355
- const generateBundleHook = createGenerateBundleHook({
2356
- opts,
2357
- runtimeState,
2358
- ensureRuntimeClassSet,
2359
- ensureBundleRuntimeClassSet,
2360
- debug,
2361
- getResolvedConfig,
2362
- markCssAssetProcessed,
2363
- isViteProcessedCssAsset,
2364
- recordCssAssetResult,
2365
- recordViteProcessedCssAssetResult,
2366
- getViteProcessedCssAssetResults,
2367
- getSourceCandidates,
2368
- getSourceCandidatesForEntries,
2369
- waitForSourceCandidateSyncs,
2370
- rememberMainCssSource,
2371
- getRememberedMainCssSources,
2372
- getRememberedMainCssSignature,
2373
- setRememberedMainCssSignature,
2374
- recordGeneratorCandidates,
2375
- hmrTimingRecorder
2376
- });
2377
- const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
2378
- opts,
2379
- runtimeState,
2380
- ensureRuntimeClassSet,
2381
- debug,
2382
- getResolvedConfig,
2383
- markCssAssetProcessed,
2384
- isCssAssetProcessed,
2385
- isViteProcessedCssAsset,
2386
- recordCssAssetResult,
2387
- recordViteProcessedCssAssetResult,
2388
- getViteProcessedCssAssetResults,
2389
- getRecordedGeneratorCandidates,
2390
- getSourceCandidates,
2391
- getSourceCandidatesForEntries,
2392
- waitForSourceCandidateSyncs,
2393
- rememberMainCssSource,
2394
- getRememberedMainCssSource
2395
- });
2396
- const isIosPlatform = resolveUniUtsPlatform().isAppIos;
2397
- const prepareTailwindGeneration = async () => {
2398
- if (shouldDiscoverAutoCssSources()) await discoverAndRegisterAutoCssSources();
2399
- await syncSourceCandidateScan();
2400
- };
2401
- const uniAppXPlugins = uniAppXEnabled ? createUniAppXPlugins({
2402
- appType: opts.appType ?? "uni-app-x",
2403
- customAttributesEntities,
2404
- disabledDefaultTemplateHandler,
2405
- isIosPlatform,
2406
- mainCssChunkMatcher,
2407
- runtimeState,
2408
- styleHandler,
2409
- jsHandler,
2410
- ensureRuntimeClassSet,
2411
- getResolvedConfig,
2412
- uniAppX
2413
- }) : void 0;
2414
- const plugins = [
2415
- ...rewritePlugins,
2416
- {
2417
- name: `${vitePluginName}:source-candidates`,
2418
- enforce: "pre",
2419
- async transform(code, id) {
2420
- if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id) || !shouldCollectTransformedSourceCandidates(id)) return;
2421
- return hmrTimingRecorder.measure("sourceCandidates.transform", async () => {
2422
- const file = cleanUrl(id);
2423
- if (sourceScanMatcher && !sourceScanMatcher(file)) {
2424
- sourceCandidateCollector.remove(file);
2425
- cacheCurrentSourceCandidateScan();
2426
- return;
2427
- }
2428
- if (sourceScanExplicit && sourceScanEntries?.length === 0) {
2429
- cacheCurrentSourceCandidateScan();
2430
- return;
2431
- }
2432
- await sourceCandidateCollector.merge(id, code);
2433
- cacheCurrentSourceCandidateScan();
2434
- }, { emit: false });
2435
- },
2436
- async watchChange(id, change) {
2437
- await hmrTimingRecorder.measure("sourceCandidates.watchChange", async () => {
2438
- if (isSourceScanDependency(id)) invalidateSourceCandidateScan();
2439
- if (change.event === "delete") {
2440
- sourceCandidateCollector.remove(id);
2441
- cacheCurrentSourceCandidateScan();
2442
- return;
2443
- }
2444
- await syncChangedSourceCandidateFile(id);
2445
- }, { emit: false });
2446
- },
2447
- async handleHotUpdate(ctx) {
2448
- return hmrTimingRecorder.measure("sourceCandidates.handleHotUpdate", async () => {
2449
- const isSourceCandidateHotUpdate = shouldOwnTailwindGeneration && isSourceCandidateRequest(ctx.file);
2450
- await syncChangedSourceCandidateFile(ctx.file);
2451
- invalidateRecordedGeneratorCandidates();
2452
- const cssModules = resolveHotTailwindCssModules(ctx);
2453
- if (isSourceCandidateHotUpdate && !isSourceStyleRequest(ctx.file) && (!hasSelfAcceptingNonStyleHotModule(ctx.modules) && cssModules.length === 0 || cssModules.length > 0 && isUniViteProject())) {
2454
- sendFullReloadForUnresolvedHotUpdate(ctx);
2455
- return [];
2456
- }
2457
- sendSupplementalCssHotUpdates(ctx, cssModules);
2458
- return cssModules.length > 0 ? [...ctx.modules, ...cssModules] : void 0;
2459
- }, { emit: false });
2460
- },
2461
- async buildStart() {
2462
- await hmrTimingRecorder.measure("sourceCandidates.buildStart", async () => {
2463
- await prepareTailwindGeneration();
2464
- }, { emit: false });
2465
- }
2466
- },
2467
- ...createViteServeCssGenerationPlugins({
2468
- generateCss: generateTailwindCssForVitePipeline,
2469
- getCommand: () => resolvedConfig?.command,
2470
- onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
2471
- shouldGenerate: () => shouldOwnTailwindGeneration
2472
- }),
2473
- {
2474
- name: `${vitePluginName}:post`,
2475
- enforce: "post",
2476
- config(config) {
2477
- if (!shouldOwnTailwindGeneration) return;
2478
- if (Array.isArray(config.plugins)) {
2479
- const removed = disableAndRemoveTailwindVitePlugins(config.plugins);
2480
- if (removed > 0) debug("disable official tailwind vite plugins in generator mode: %d", removed);
2481
- }
2482
- const root = config.root ? path.resolve(config.root) : process.cwd();
2483
- const baseConfig = { resolve: { alias: [{
2484
- find: /^tailwindcss$/,
2485
- replacement: path.join(weappTailwindcssPackageDir, "generator-placeholder.css")
2486
- }] } };
2487
- if (config.css?.postcss !== void 0) return baseConfig;
2488
- return resolveFilteredPostcssConfig(root).then((postcssConfig) => {
2489
- if (!postcssConfig) return baseConfig;
2490
- debug("inline filtered postcss config without official tailwind plugins in generator mode: %d", postcssConfig.removed);
2491
- return {
2492
- ...baseConfig,
2493
- css: { postcss: {
2494
- ...postcssConfig.options,
2495
- plugins: postcssConfig.plugins
2496
- } }
2497
- };
2498
- });
2499
- },
2500
- async configResolved(config) {
2501
- await hmrTimingRecorder.measure("configResolved", async () => {
2502
- resolvedConfig = config;
2503
- if (shouldOwnTailwindGeneration) {
2504
- const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
2505
- if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
2506
- }
2507
- const resolvedRoot = config.root ? path.resolve(config.root) : void 0;
2508
- let shouldRefreshRuntime = false;
2509
- if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
2510
- const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
2511
- if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
2512
- const previousBasedir = opts.tailwindcssBasedir;
2513
- opts.tailwindcssBasedir = nextTailwindcssBasedir;
2514
- debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
2515
- shouldRefreshRuntime = true;
2516
- }
2517
- }
2518
- if (shouldInferAppType && resolvedRoot) {
2519
- const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
2520
- if (nextAppType && opts.appType !== nextAppType) {
2521
- const previousAppType = opts.appType;
2522
- opts.appType = nextAppType;
2523
- logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
2524
- debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
2525
- shouldRefreshRuntime = true;
2526
- }
2527
- }
2528
- if (shouldRefreshRuntime) await refreshRuntimeState(true);
2529
- if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
2530
- const postcssPlugins = config.css.postcss.plugins;
2531
- if (shouldOwnTailwindGeneration) {
2532
- const removed = removeTailwindPostcssPlugins(postcssPlugins);
2533
- if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
2534
- }
2535
- const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
2536
- if (idx > -1) {
2537
- postcssPlugins.splice(idx, 1, postcssHtmlTransform());
2538
- debug("remove postcss-html-transform plugin from vite config");
2539
- }
2540
- }
2541
- }, { emit: false });
2542
- },
2543
- generateBundle: generateBundleHook
2544
- },
2545
- cssFinalizerOutputPlugin
2546
- ];
2547
- if (uniAppXPlugins) plugins.push(...uniAppXPlugins);
2548
- return plugins;
2549
- }
2550
- //#endregion
2551
- export { WeappTailwindcss as t };