weapp-tailwindcss 5.0.2 → 5.0.4

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