weapp-tailwindcss 4.10.3 → 4.11.0-alpha.1

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 (64) hide show
  1. package/dist/{chunk-3XVUGMTY.mjs → chunk-2LH6PZH3.mjs} +8 -4
  2. package/dist/{chunk-3WUHHFLF.mjs → chunk-35EI5JMK.mjs} +4 -2
  3. package/dist/{chunk-RYC23C3K.js → chunk-4LPOQMFS.js} +203 -198
  4. package/dist/{chunk-5U24PLVV.js → chunk-ACTJYB33.js} +4 -2
  5. package/dist/chunk-CZLXTEHN.js +1936 -0
  6. package/dist/{chunk-TNYEOBAC.mjs → chunk-DOH7FULQ.mjs} +1 -1
  7. package/dist/{chunk-E7775SFS.mjs → chunk-FZNYV7VH.mjs} +914 -334
  8. package/dist/{chunk-6Z4GEN2Y.js → chunk-G3G437UE.js} +2 -2
  9. package/dist/{chunk-DEIJXHGJ.js → chunk-G5NLM3AL.js} +978 -398
  10. package/dist/{chunk-W2N6G2QQ.js → chunk-GWDHNCL2.js} +60 -46
  11. package/dist/{chunk-QOTLDKI4.mjs → chunk-IEZ5RBMG.mjs} +197 -192
  12. package/dist/{chunk-RM3SY4S4.mjs → chunk-JBM3HGHP.mjs} +52 -12
  13. package/dist/{chunk-WXT2GI5R.mjs → chunk-KKT2DKMW.mjs} +30 -16
  14. package/dist/chunk-LD7LZ4IK.mjs +1933 -0
  15. package/dist/{chunk-GCRL3ZYP.js → chunk-NOKJXG3W.js} +5 -5
  16. package/dist/{chunk-YUTKX7JZ.js → chunk-OV7FX6XR.js} +1 -1
  17. package/dist/{chunk-SR4GC2F4.js → chunk-OYSABARD.js} +8 -4
  18. package/dist/{chunk-LICQ6EGN.mjs → chunk-QYZCRG7F.mjs} +2 -2
  19. package/dist/{chunk-UYTCZXNE.mjs → chunk-R6KEYO3F.mjs} +6 -5
  20. package/dist/{chunk-WF636Q5E.js → chunk-SQG2MOFQ.js} +10 -9
  21. package/dist/{chunk-L7OBNTRI.js → chunk-W2EMGF7H.js} +57 -17
  22. package/dist/cli.js +45 -42
  23. package/dist/cli.mjs +9 -6
  24. package/dist/core.d.mts +4 -3
  25. package/dist/core.d.ts +4 -3
  26. package/dist/core.js +124 -30
  27. package/dist/core.mjs +119 -25
  28. package/dist/css-macro/postcss.js +6 -5
  29. package/dist/css-macro/postcss.mjs +4 -3
  30. package/dist/css-macro.js +5 -5
  31. package/dist/css-macro.mjs +2 -2
  32. package/dist/defaults.js +3 -3
  33. package/dist/defaults.mjs +2 -2
  34. package/dist/escape.js +2 -1
  35. package/dist/escape.mjs +2 -1
  36. package/dist/gulp.d.mts +1 -1
  37. package/dist/gulp.d.ts +1 -1
  38. package/dist/gulp.js +8 -7
  39. package/dist/gulp.mjs +8 -7
  40. package/dist/index.js +11 -11
  41. package/dist/index.mjs +9 -9
  42. package/dist/postcss-html-transform.js +1 -1
  43. package/dist/postcss-html-transform.mjs +1 -1
  44. package/dist/presets.js +5 -5
  45. package/dist/presets.mjs +2 -2
  46. package/dist/reset.js +1 -1
  47. package/dist/reset.mjs +1 -1
  48. package/dist/types.js +1 -1
  49. package/dist/types.mjs +1 -1
  50. package/dist/vite.d.mts +1 -1
  51. package/dist/vite.d.ts +1 -1
  52. package/dist/vite.js +9 -8
  53. package/dist/vite.mjs +8 -7
  54. package/dist/webpack.d.mts +1 -1
  55. package/dist/webpack.d.ts +1 -1
  56. package/dist/webpack.js +10 -9
  57. package/dist/webpack.mjs +8 -7
  58. package/dist/webpack4.d.mts +1 -1
  59. package/dist/webpack4.d.ts +1 -1
  60. package/dist/webpack4.js +64 -49
  61. package/dist/webpack4.mjs +33 -18
  62. package/package.json +7 -7
  63. package/dist/chunk-PALDKVKG.mjs +0 -1291
  64. package/dist/chunk-YJSFFRNZ.js +0 -1291
@@ -0,0 +1,1933 @@
1
+ import {
2
+ pushConcurrentTaskFactories,
3
+ resolveDisabledOptions,
4
+ resolveOutputSpecifier,
5
+ resolvePackageDir,
6
+ resolveTailwindcssImport,
7
+ rewriteTailwindcssImportsInCode,
8
+ toAbsoluteOutputPath
9
+ } from "./chunk-F2CKKG6Q.mjs";
10
+ import {
11
+ processCachedTask
12
+ } from "./chunk-RRHPTTCP.mjs";
13
+ import {
14
+ setupPatchRecorder
15
+ } from "./chunk-QYZCRG7F.mjs";
16
+ import {
17
+ babelParse,
18
+ collectRuntimeClassSet,
19
+ createAttributeMatcher,
20
+ createDebug,
21
+ generateCode,
22
+ getCompilerContext,
23
+ getRuntimeClassSetSignature,
24
+ refreshTailwindRuntimeState,
25
+ replaceWxml,
26
+ toCustomAttributesEntities,
27
+ traverse,
28
+ vitePluginName
29
+ } from "./chunk-FZNYV7VH.mjs";
30
+ import {
31
+ findNearestPackageRoot,
32
+ findTailwindConfig
33
+ } from "./chunk-IEZ5RBMG.mjs";
34
+ import {
35
+ resolveUniUtsPlatform
36
+ } from "./chunk-OOHJLO5M.mjs";
37
+
38
+ // src/bundlers/vite/index.ts
39
+ import { existsSync } from "fs";
40
+ import path4 from "path";
41
+ import process4 from "process";
42
+ import postcssHtmlTransform from "@weapp-tailwindcss/postcss/html-transform";
43
+
44
+ // src/uni-app-x/transform.ts
45
+ import { NodeTypes } from "@vue/compiler-dom";
46
+ import { parse } from "@vue/compiler-sfc";
47
+ import MagicString from "magic-string";
48
+ function traverse2(node, visitor) {
49
+ visitor(node);
50
+ if (Array.isArray(node.children)) {
51
+ for (const child of node.children) {
52
+ if (child && typeof child === "object" && "type" in child) {
53
+ traverse2(child, visitor);
54
+ }
55
+ }
56
+ }
57
+ }
58
+ function updateStaticAttribute(ms, prop) {
59
+ if (!prop.value) {
60
+ return;
61
+ }
62
+ const start = prop.value.loc.start.offset + 1;
63
+ const end = prop.value.loc.end.offset - 1;
64
+ if (start < end) {
65
+ ms.update(start, end, replaceWxml(prop.value.content));
66
+ }
67
+ }
68
+ function updateDirectiveExpression(ms, prop, jsHandler, runtimeSet) {
69
+ if (prop.exp?.type !== NodeTypes.SIMPLE_EXPRESSION) {
70
+ return;
71
+ }
72
+ const start = prop.exp.loc.start.offset;
73
+ const end = prop.exp.loc.end.offset;
74
+ if (start >= end) {
75
+ return;
76
+ }
77
+ const generated = generateCode(prop.exp.content, {
78
+ jsHandler,
79
+ runtimeSet,
80
+ wrapExpression: true
81
+ });
82
+ ms.update(start, end, generated);
83
+ }
84
+ function shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute) {
85
+ const lowerName = attrName.toLowerCase();
86
+ const shouldHandleDefault = !disabledDefaultTemplateHandler && lowerName === "class";
87
+ const shouldHandleCustom = matchCustomAttribute?.(tag, attrName) ?? false;
88
+ return {
89
+ shouldHandleDefault,
90
+ shouldHandleCustom,
91
+ shouldHandle: shouldHandleDefault || shouldHandleCustom
92
+ };
93
+ }
94
+ var defaultCreateJsHandlerOptions = {
95
+ babelParserOptions: {
96
+ plugins: [
97
+ "typescript"
98
+ ]
99
+ }
100
+ };
101
+ var UVUE_NVUE_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
102
+ function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
103
+ if (!UVUE_NVUE_RE.test(id)) {
104
+ return;
105
+ }
106
+ const { customAttributesEntities, disabledDefaultTemplateHandler = false } = options;
107
+ const matchCustomAttribute = createAttributeMatcher(customAttributesEntities);
108
+ const ms = new MagicString(code);
109
+ const { descriptor, errors } = parse(code);
110
+ if (errors.length === 0) {
111
+ if (descriptor.template?.ast) {
112
+ traverse2(descriptor.template.ast, (node) => {
113
+ if (node.type !== NodeTypes.ELEMENT) {
114
+ return;
115
+ }
116
+ const tag = node.tag;
117
+ for (const prop of node.props) {
118
+ if (prop.type === NodeTypes.ATTRIBUTE) {
119
+ const { shouldHandle, shouldHandleDefault } = shouldHandleAttribute(
120
+ tag,
121
+ prop.name,
122
+ disabledDefaultTemplateHandler,
123
+ matchCustomAttribute
124
+ );
125
+ if (!shouldHandle) {
126
+ continue;
127
+ }
128
+ updateStaticAttribute(ms, prop);
129
+ if (shouldHandleDefault) {
130
+ continue;
131
+ }
132
+ } else if (prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.isStatic) {
133
+ const attrName = prop.arg.content;
134
+ const { shouldHandle } = shouldHandleAttribute(
135
+ tag,
136
+ attrName,
137
+ disabledDefaultTemplateHandler,
138
+ matchCustomAttribute
139
+ );
140
+ if (!shouldHandle) {
141
+ continue;
142
+ }
143
+ updateDirectiveExpression(ms, prop, jsHandler, runtimeSet);
144
+ }
145
+ }
146
+ });
147
+ }
148
+ if (descriptor.script) {
149
+ const { code: code2 } = jsHandler(descriptor.script.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
150
+ ms.update(descriptor.script.loc.start.offset, descriptor.script.loc.end.offset, code2);
151
+ }
152
+ if (descriptor.scriptSetup) {
153
+ const { code: code2 } = jsHandler(descriptor.scriptSetup.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
154
+ ms.update(descriptor.scriptSetup.loc.start.offset, descriptor.scriptSetup.loc.end.offset, code2);
155
+ }
156
+ }
157
+ return {
158
+ code: ms.toString(),
159
+ // @ts-ignore
160
+ get map() {
161
+ return ms.generateMap();
162
+ }
163
+ };
164
+ }
165
+
166
+ // src/bundlers/vite/query.ts
167
+ function parseVueRequest(id) {
168
+ const [filename, rawQuery] = id.split(`?`, 2);
169
+ const searchParams = new URLSearchParams(rawQuery);
170
+ const query = Object.fromEntries(searchParams);
171
+ if (query.vue != null) {
172
+ query.vue = true;
173
+ }
174
+ if (query.index != null) {
175
+ query.index = Number(query.index);
176
+ }
177
+ if (query.raw != null) {
178
+ query.raw = true;
179
+ }
180
+ if (query.url != null) {
181
+ query.url = true;
182
+ }
183
+ if (query.scoped != null) {
184
+ query.scoped = true;
185
+ }
186
+ const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
187
+ const langType = query.lang || (langTypeMatch ? langTypeMatch.slice("lang.".length) : void 0);
188
+ if (langType) {
189
+ query.lang = langType;
190
+ }
191
+ return {
192
+ filename,
193
+ query
194
+ };
195
+ }
196
+
197
+ // src/bundlers/vite/utils.ts
198
+ import path from "path";
199
+ import process from "process";
200
+ import { cleanUrl, ensurePosix } from "@weapp-tailwindcss/shared";
201
+ function slash(p) {
202
+ return ensurePosix(p);
203
+ }
204
+ var isWindows = process.platform === "win32";
205
+ var cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`;
206
+ var cssLangRE = new RegExp(cssLangs);
207
+ function isCSSRequest(request) {
208
+ return cssLangRE.test(request);
209
+ }
210
+ function normalizePath(id) {
211
+ return path.posix.normalize(isWindows ? ensurePosix(id) : id);
212
+ }
213
+ async function formatPostcssSourceMap(rawMap, file) {
214
+ const inputFileDir = path.dirname(file);
215
+ const sources = rawMap.sources.map((source) => {
216
+ const cleanSource = cleanUrl(decodeURIComponent(source));
217
+ if (cleanSource[0] === "<" && cleanSource.endsWith(">")) {
218
+ return `\0${cleanSource}`;
219
+ }
220
+ return normalizePath(path.resolve(inputFileDir, cleanSource));
221
+ });
222
+ return {
223
+ file,
224
+ mappings: rawMap.mappings,
225
+ names: rawMap.names,
226
+ sources,
227
+ sourcesContent: rawMap.sourcesContent,
228
+ version: rawMap.version
229
+ };
230
+ }
231
+
232
+ // src/uni-app-x/vite.ts
233
+ var preprocessorLangs = /* @__PURE__ */ new Set(["scss", "sass", "less", "styl", "stylus"]);
234
+ var INLINE_LANG_RE = /lang\.([a-z]+)/i;
235
+ var PREPROCESSOR_EXT_RE = /\.(?:scss|sass|less|styl|stylus)(?:\?|$)/i;
236
+ var UVUE_NVUE_QUERY_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
237
+ var UVUE_NVUE_RE2 = /\.(?:uvue|nvue)$/;
238
+ function isPreprocessorRequest(id, lang) {
239
+ const normalizedLang = lang?.toLowerCase();
240
+ if (normalizedLang && preprocessorLangs.has(normalizedLang)) {
241
+ return true;
242
+ }
243
+ const inlineLangMatch = id.match(INLINE_LANG_RE);
244
+ if (inlineLangMatch && preprocessorLangs.has(inlineLangMatch[1].toLowerCase())) {
245
+ return true;
246
+ }
247
+ return PREPROCESSOR_EXT_RE.test(id);
248
+ }
249
+ function createUniAppXPlugins(options) {
250
+ const {
251
+ appType,
252
+ customAttributesEntities,
253
+ disabledDefaultTemplateHandler,
254
+ isIosPlatform: providedIosPlatform,
255
+ mainCssChunkMatcher,
256
+ runtimeState,
257
+ styleHandler,
258
+ jsHandler,
259
+ ensureRuntimeClassSet,
260
+ getResolvedConfig
261
+ } = options;
262
+ const isIosPlatform = providedIosPlatform ?? resolveUniUtsPlatform().isAppIos;
263
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
264
+ async function transformStyle(code, id, query) {
265
+ const parsed = query ?? parseVueRequest(id).query;
266
+ if (isCSSRequest(id) || parsed.vue && parsed.type === "style") {
267
+ const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
268
+ let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
269
+ if (!styleHandlerOptions) {
270
+ styleHandlerOptions = {
271
+ isMainChunk: mainCssChunkMatcher(id, appType),
272
+ postcssOptions: {
273
+ options: {
274
+ from: id,
275
+ map: {
276
+ inline: false,
277
+ annotation: false,
278
+ // PostCSS 可能返回虚拟文件,因此需要启用这一项以获取源内容
279
+ sourcesContent: true
280
+ // 若上游预处理器已经生成 source map,sources 中可能出现重复条目
281
+ }
282
+ }
283
+ }
284
+ };
285
+ cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
286
+ }
287
+ const postcssResult = await styleHandler(code, styleHandlerOptions);
288
+ const rawPostcssMap = postcssResult.map.toJSON();
289
+ const postcssMap = await formatPostcssSourceMap(
290
+ rawPostcssMap,
291
+ cleanUrl(id)
292
+ );
293
+ return {
294
+ code: postcssResult.css,
295
+ map: postcssMap
296
+ };
297
+ }
298
+ }
299
+ const cssPrePlugin = {
300
+ name: "weapp-tailwindcss:uni-app-x:css:pre",
301
+ enforce: "pre",
302
+ async transform(code, id) {
303
+ await runtimeState.patchPromise;
304
+ const { query } = parseVueRequest(id);
305
+ const lang = query.lang;
306
+ if (isIosPlatform && isPreprocessorRequest(id, lang)) {
307
+ return;
308
+ }
309
+ return transformStyle(code, id, query);
310
+ }
311
+ };
312
+ const cssPlugin = {
313
+ name: "weapp-tailwindcss:uni-app-x:css",
314
+ async transform(code, id) {
315
+ await runtimeState.patchPromise;
316
+ return transformStyle(code, id);
317
+ }
318
+ };
319
+ const cssPlugins = [cssPlugin, cssPrePlugin];
320
+ const nvuePlugin = {
321
+ name: "weapp-tailwindcss:uni-app-x:nvue",
322
+ enforce: "pre",
323
+ async buildStart() {
324
+ await ensureRuntimeClassSet(true);
325
+ },
326
+ async transform(code, id) {
327
+ if (!UVUE_NVUE_QUERY_RE.test(id)) {
328
+ return;
329
+ }
330
+ const resolvedConfig = getResolvedConfig();
331
+ const isServeCommand = resolvedConfig?.command === "serve";
332
+ const isWatchBuild = resolvedConfig?.command === "build" && !!resolvedConfig.build?.watch;
333
+ const isNonWatchBuild = resolvedConfig?.command === "build" && !resolvedConfig.build?.watch;
334
+ const shouldForceRefresh = isServeCommand || isWatchBuild || isNonWatchBuild;
335
+ const currentRuntimeSet = shouldForceRefresh ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
336
+ const extraOptions = customAttributesEntities.length > 0 || disabledDefaultTemplateHandler ? {
337
+ customAttributesEntities,
338
+ disabledDefaultTemplateHandler
339
+ } : void 0;
340
+ if (extraOptions) {
341
+ return transformUVue(code, id, jsHandler, currentRuntimeSet, extraOptions);
342
+ }
343
+ return transformUVue(code, id, jsHandler, currentRuntimeSet);
344
+ },
345
+ async handleHotUpdate(ctx) {
346
+ const resolvedConfig = getResolvedConfig();
347
+ if (resolvedConfig?.command !== "serve") {
348
+ return;
349
+ }
350
+ if (!UVUE_NVUE_RE2.test(ctx.file)) {
351
+ return;
352
+ }
353
+ await ensureRuntimeClassSet(true);
354
+ },
355
+ async watchChange(id) {
356
+ const resolvedConfig = getResolvedConfig();
357
+ if (resolvedConfig?.command !== "build" || !resolvedConfig.build?.watch) {
358
+ return;
359
+ }
360
+ if (!UVUE_NVUE_QUERY_RE.test(id)) {
361
+ return;
362
+ }
363
+ await ensureRuntimeClassSet(true);
364
+ }
365
+ };
366
+ return [
367
+ ...cssPlugins,
368
+ nvuePlugin
369
+ ];
370
+ }
371
+ function createUniAppXAssetTask(file, originalSource, outDir, options) {
372
+ return async () => {
373
+ const {
374
+ cache,
375
+ hashKey,
376
+ createHandlerOptions,
377
+ debug: debug3,
378
+ jsHandler,
379
+ onUpdate,
380
+ runtimeSet,
381
+ applyLinkedResults: applyLinkedResults2
382
+ } = options;
383
+ const absoluteFile = toAbsoluteOutputPath(file, outDir);
384
+ const rawSource = originalSource.source.toString();
385
+ const rawHashSource = options.hashSalt ? `${rawSource}
386
+ /*${options.hashSalt}*/` : rawSource;
387
+ await processCachedTask({
388
+ cache,
389
+ cacheKey: file,
390
+ hashKey,
391
+ rawSource: rawHashSource,
392
+ applyResult(source) {
393
+ originalSource.source = source;
394
+ },
395
+ onCacheHit() {
396
+ debug3("js cache hit: %s", file);
397
+ },
398
+ async transform() {
399
+ const currentSource = originalSource.source.toString();
400
+ const { code, linked } = await jsHandler(currentSource, runtimeSet, createHandlerOptions(absoluteFile, {
401
+ uniAppX: options.uniAppX ?? true,
402
+ babelParserOptions: {
403
+ plugins: [
404
+ "typescript"
405
+ ],
406
+ sourceType: "unambiguous"
407
+ }
408
+ }));
409
+ onUpdate(file, currentSource, code);
410
+ debug3("js handle: %s", file);
411
+ applyLinkedResults2(linked);
412
+ return {
413
+ result: code
414
+ };
415
+ }
416
+ });
417
+ };
418
+ }
419
+
420
+ // src/bundlers/vite/generate-bundle.ts
421
+ import path2 from "path";
422
+ import process2 from "process";
423
+
424
+ // src/bundlers/vite/bundle-entries.ts
425
+ import { Buffer } from "buffer";
426
+ function readOutputEntry(entry) {
427
+ if (entry.output.type === "chunk") {
428
+ return entry.output.code;
429
+ }
430
+ const source = entry.output.source;
431
+ if (typeof source === "string") {
432
+ return source;
433
+ }
434
+ if (source instanceof Uint8Array) {
435
+ return Buffer.from(source).toString();
436
+ }
437
+ const fallbackSource = source;
438
+ if (fallbackSource == null) {
439
+ return void 0;
440
+ }
441
+ if (typeof fallbackSource.toString === "function") {
442
+ return fallbackSource.toString();
443
+ }
444
+ return void 0;
445
+ }
446
+ function isJavaScriptEntry(entry) {
447
+ if (entry.output.type === "chunk") {
448
+ return true;
449
+ }
450
+ return entry.fileName.endsWith(".js");
451
+ }
452
+ function createBundleModuleGraphOptions(outputDir, entries) {
453
+ return {
454
+ resolve(specifier, importer) {
455
+ return resolveOutputSpecifier(specifier, importer, outputDir, (candidate) => entries.has(candidate));
456
+ },
457
+ load(id) {
458
+ const entry = entries.get(id);
459
+ if (!entry) {
460
+ return void 0;
461
+ }
462
+ return readOutputEntry(entry);
463
+ },
464
+ filter(id) {
465
+ return entries.has(id);
466
+ }
467
+ };
468
+ }
469
+ function applyLinkedResults(linked, entries, onLinkedUpdate, onApplied) {
470
+ if (!linked) {
471
+ return;
472
+ }
473
+ for (const [id, { code }] of Object.entries(linked)) {
474
+ const entry = entries.get(id);
475
+ if (!entry) {
476
+ continue;
477
+ }
478
+ const previous = readOutputEntry(entry);
479
+ if (previous == null || previous === code) {
480
+ continue;
481
+ }
482
+ if (entry.output.type === "chunk") {
483
+ entry.output.code = code;
484
+ } else {
485
+ entry.output.source = code;
486
+ }
487
+ onApplied?.(entry, code);
488
+ onLinkedUpdate(entry.fileName, previous, code);
489
+ }
490
+ }
491
+
492
+ // src/bundlers/vite/runtime-affecting-signature.ts
493
+ import { Parser } from "htmlparser2";
494
+ var CSS_BLOCK_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
495
+ var CSS_AROUND_PUNCTUATION_RE = /\s*([{}:;,>+~()])\s*/g;
496
+ var CSS_TRAILING_DECLARATION_SEMICOLON_RE = /;\}/g;
497
+ var CSS_WHITESPACE_RE = /\s+/g;
498
+ function createHtmlRuntimeAffectingSignature(source) {
499
+ try {
500
+ const parts = [];
501
+ const parser = new Parser(
502
+ {
503
+ onattribute(name, value) {
504
+ parts.push(`a:${name}=${value}`);
505
+ },
506
+ oncomment(data) {
507
+ parts.push(`c:${data}`);
508
+ },
509
+ ontext(data) {
510
+ const value = data.trim();
511
+ if (value.length > 0) {
512
+ parts.push(`t:${value}`);
513
+ }
514
+ }
515
+ },
516
+ {
517
+ xmlMode: true
518
+ }
519
+ );
520
+ parser.write(source);
521
+ parser.end();
522
+ return parts.join("\n");
523
+ } catch {
524
+ return source;
525
+ }
526
+ }
527
+ function createJsRuntimeAffectingSignature(source) {
528
+ try {
529
+ const ast = babelParse(source, {
530
+ cache: true,
531
+ cacheKey: "vite-runtime-affecting:unambiguous",
532
+ plugins: ["jsx", "typescript"],
533
+ sourceType: "unambiguous"
534
+ });
535
+ const parts = [];
536
+ traverse(ast, {
537
+ noScope: true,
538
+ StringLiteral(path5) {
539
+ parts.push(`s:${path5.node.value}`);
540
+ },
541
+ TemplateElement(path5) {
542
+ parts.push(`t:${path5.node.value.raw}`);
543
+ },
544
+ JSXText(path5) {
545
+ const value = path5.node.value.trim();
546
+ if (value.length > 0) {
547
+ parts.push(`x:${value}`);
548
+ }
549
+ }
550
+ });
551
+ const comments = ast.comments;
552
+ if (Array.isArray(comments)) {
553
+ for (const comment of comments) {
554
+ if (typeof comment?.value === "string" && comment.value.length > 0) {
555
+ parts.push(`c:${comment.value}`);
556
+ }
557
+ }
558
+ }
559
+ return parts.join("\n");
560
+ } catch {
561
+ return source;
562
+ }
563
+ }
564
+ function createCssRuntimeAffectingSignature(source) {
565
+ return source.replace(CSS_BLOCK_COMMENT_RE, "").replace(CSS_AROUND_PUNCTUATION_RE, "$1").replace(CSS_TRAILING_DECLARATION_SEMICOLON_RE, "}").replace(CSS_WHITESPACE_RE, " ").trim();
566
+ }
567
+ function createRuntimeAffectingSourceSignature(source, type) {
568
+ if (type === "html") {
569
+ return createHtmlRuntimeAffectingSignature(source);
570
+ }
571
+ if (type === "js") {
572
+ return createJsRuntimeAffectingSignature(source);
573
+ }
574
+ if (type === "css") {
575
+ return createCssRuntimeAffectingSignature(source);
576
+ }
577
+ return source;
578
+ }
579
+
580
+ // src/bundlers/vite/bundle-state.ts
581
+ function createBundleBuildState() {
582
+ return {
583
+ iteration: 0,
584
+ sourceHashByFile: /* @__PURE__ */ new Map(),
585
+ runtimeAffectingHashByFile: /* @__PURE__ */ new Map(),
586
+ linkedByEntry: /* @__PURE__ */ new Map(),
587
+ dependentsByLinkedFile: /* @__PURE__ */ new Map()
588
+ };
589
+ }
590
+ function createChangedByType() {
591
+ return {
592
+ html: /* @__PURE__ */ new Set(),
593
+ js: /* @__PURE__ */ new Set(),
594
+ css: /* @__PURE__ */ new Set(),
595
+ other: /* @__PURE__ */ new Set()
596
+ };
597
+ }
598
+ function createProcessFiles() {
599
+ return {
600
+ html: /* @__PURE__ */ new Set(),
601
+ js: /* @__PURE__ */ new Set(),
602
+ css: /* @__PURE__ */ new Set()
603
+ };
604
+ }
605
+ function readEntrySource(output) {
606
+ if (output.type === "chunk") {
607
+ return output.code;
608
+ }
609
+ return output.source.toString();
610
+ }
611
+ function classifyBundleEntry(file, opts) {
612
+ if (opts.cssMatcher(file)) {
613
+ return "css";
614
+ }
615
+ if (opts.htmlMatcher(file)) {
616
+ return "html";
617
+ }
618
+ if (opts.jsMatcher(file) || opts.wxsMatcher(file)) {
619
+ return "js";
620
+ }
621
+ return "other";
622
+ }
623
+ function collectJsEntries(fileName, output, outDir, store) {
624
+ const entry = { fileName, output };
625
+ if (!isJavaScriptEntry(entry)) {
626
+ return;
627
+ }
628
+ const absolute = toAbsoluteOutputPath(fileName, outDir);
629
+ store.set(absolute, entry);
630
+ }
631
+ function markProcessFile(type, file, processFiles) {
632
+ if (type === "html" || type === "js" || type === "css") {
633
+ processFiles[type].add(file);
634
+ }
635
+ }
636
+ function buildBundleSnapshot(bundle, opts, outDir, state, forceAll = false) {
637
+ const sourceHashByFile = /* @__PURE__ */ new Map();
638
+ const runtimeAffectingSignatureByFile = /* @__PURE__ */ new Map();
639
+ const runtimeAffectingHashByFile = /* @__PURE__ */ new Map();
640
+ const changedByType = createChangedByType();
641
+ const runtimeAffectingChangedByType = createChangedByType();
642
+ const processFiles = createProcessFiles();
643
+ const linkedImpactsByEntry = /* @__PURE__ */ new Map();
644
+ const jsEntries = /* @__PURE__ */ new Map();
645
+ const entries = [];
646
+ const firstRun = state.linkedByEntry.size === 0;
647
+ for (const [file, output] of Object.entries(bundle)) {
648
+ const type = classifyBundleEntry(file, opts);
649
+ const source = readEntrySource(output);
650
+ const hash = opts.cache.computeHash(source);
651
+ sourceHashByFile.set(file, hash);
652
+ const runtimeAffectingSignature = createRuntimeAffectingSourceSignature(source, type);
653
+ runtimeAffectingSignatureByFile.set(file, runtimeAffectingSignature);
654
+ const runtimeAffectingHash = opts.cache.computeHash(runtimeAffectingSignature);
655
+ runtimeAffectingHashByFile.set(file, runtimeAffectingHash);
656
+ const previousHash = state.sourceHashByFile.get(file);
657
+ const changed = previousHash == null || previousHash !== hash;
658
+ if (changed) {
659
+ changedByType[type].add(file);
660
+ }
661
+ const previousRuntimeAffectingHash = state.runtimeAffectingHashByFile.get(file);
662
+ const runtimeAffectingChanged = previousRuntimeAffectingHash == null || previousRuntimeAffectingHash !== runtimeAffectingHash;
663
+ if (runtimeAffectingChanged) {
664
+ runtimeAffectingChangedByType[type].add(file);
665
+ }
666
+ if (forceAll || firstRun) {
667
+ markProcessFile(type, file, processFiles);
668
+ } else if (type === "html") {
669
+ processFiles.html.add(file);
670
+ } else if (changed && (type === "js" || type === "css")) {
671
+ processFiles[type].add(file);
672
+ }
673
+ collectJsEntries(file, output, outDir, jsEntries);
674
+ entries.push({
675
+ file,
676
+ output,
677
+ source,
678
+ type
679
+ });
680
+ }
681
+ if (!forceAll && !firstRun) {
682
+ for (const changedFile of changedByType.js) {
683
+ const dependents = state.dependentsByLinkedFile.get(changedFile);
684
+ if (!dependents) {
685
+ continue;
686
+ }
687
+ for (const entryFile of dependents) {
688
+ processFiles.js.add(entryFile);
689
+ let impacts = linkedImpactsByEntry.get(entryFile);
690
+ if (!impacts) {
691
+ impacts = /* @__PURE__ */ new Set();
692
+ linkedImpactsByEntry.set(entryFile, impacts);
693
+ }
694
+ impacts.add(changedFile);
695
+ }
696
+ }
697
+ }
698
+ return {
699
+ entries,
700
+ jsEntries,
701
+ sourceHashByFile,
702
+ runtimeAffectingSignatureByFile,
703
+ runtimeAffectingHashByFile,
704
+ changedByType,
705
+ runtimeAffectingChangedByType,
706
+ processFiles,
707
+ linkedImpactsByEntry
708
+ };
709
+ }
710
+ function buildBundleSnapshotForBuild(bundle, opts, outDir) {
711
+ const processFiles = createProcessFiles();
712
+ const jsEntries = /* @__PURE__ */ new Map();
713
+ const entries = [];
714
+ for (const [file, output] of Object.entries(bundle)) {
715
+ const type = classifyBundleEntry(file, opts);
716
+ const source = readEntrySource(output);
717
+ markProcessFile(type, file, processFiles);
718
+ collectJsEntries(file, output, outDir, jsEntries);
719
+ entries.push({
720
+ file,
721
+ output,
722
+ source,
723
+ type
724
+ });
725
+ }
726
+ return {
727
+ entries,
728
+ jsEntries,
729
+ sourceHashByFile: /* @__PURE__ */ new Map(),
730
+ runtimeAffectingSignatureByFile: /* @__PURE__ */ new Map(),
731
+ runtimeAffectingHashByFile: /* @__PURE__ */ new Map(),
732
+ changedByType: createChangedByType(),
733
+ runtimeAffectingChangedByType: createChangedByType(),
734
+ processFiles,
735
+ linkedImpactsByEntry: /* @__PURE__ */ new Map()
736
+ };
737
+ }
738
+ function invertLinkedByEntry(linkedByEntry) {
739
+ const dependentsByLinkedFile = /* @__PURE__ */ new Map();
740
+ for (const [entryFile, linkedFiles] of linkedByEntry.entries()) {
741
+ for (const linkedFile of linkedFiles) {
742
+ let dependents = dependentsByLinkedFile.get(linkedFile);
743
+ if (!dependents) {
744
+ dependents = /* @__PURE__ */ new Set();
745
+ dependentsByLinkedFile.set(linkedFile, dependents);
746
+ }
747
+ dependents.add(entryFile);
748
+ }
749
+ }
750
+ return dependentsByLinkedFile;
751
+ }
752
+ function updateBundleBuildState(state, snapshot, linkedByEntry) {
753
+ state.iteration += 1;
754
+ state.sourceHashByFile = snapshot.sourceHashByFile;
755
+ state.runtimeAffectingHashByFile = snapshot.runtimeAffectingHashByFile;
756
+ state.linkedByEntry = linkedByEntry;
757
+ state.dependentsByLinkedFile = invertLinkedByEntry(linkedByEntry);
758
+ }
759
+
760
+ // src/bundlers/vite/js-precheck.ts
761
+ var FAST_JS_TRANSFORM_HINT_RE = /className\b|class\s*=|classList\.|\b(?:twMerge|clsx|classnames|cn|cva)\b|\[["'`]class["'`]\]|text-\[|bg-\[|\b(?:[whpm]|px|py|mx|my|rounded|flex|grid|gap)-/;
762
+ var DEPENDENCY_HINT_RE = /\bimport\s*[("'`{*]|\brequire\s*\(|\bexport\s+\*\s+from\s+["'`]|\bexport\s*\{[^}]*\}\s*from\s+["'`]/;
763
+ function shouldSkipViteJsTransform(rawSource, options) {
764
+ if (!rawSource) {
765
+ return true;
766
+ }
767
+ if (options?.alwaysEscape) {
768
+ return false;
769
+ }
770
+ if (options?.moduleSpecifierReplacements && Object.keys(options.moduleSpecifierReplacements).length > 0) {
771
+ return false;
772
+ }
773
+ if (options?.wrapExpression) {
774
+ return false;
775
+ }
776
+ if (DEPENDENCY_HINT_RE.test(rawSource)) {
777
+ return false;
778
+ }
779
+ return !FAST_JS_TRANSFORM_HINT_RE.test(rawSource);
780
+ }
781
+
782
+ // src/bundlers/vite/generate-bundle.ts
783
+ function formatDebugFileList(files, limit = 8) {
784
+ if (files.size === 0) {
785
+ return "-";
786
+ }
787
+ const sorted = [...files].sort();
788
+ if (sorted.length <= limit) {
789
+ return sorted.join(",");
790
+ }
791
+ return `${sorted.slice(0, limit).join(",")},...(+${sorted.length - limit})`;
792
+ }
793
+ function createEmptyMetric() {
794
+ return {
795
+ total: 0,
796
+ transformed: 0,
797
+ cacheHits: 0,
798
+ elapsed: 0
799
+ };
800
+ }
801
+ function createEmptyMetrics() {
802
+ return {
803
+ runtimeSet: 0,
804
+ html: createEmptyMetric(),
805
+ js: createEmptyMetric(),
806
+ css: createEmptyMetric()
807
+ };
808
+ }
809
+ function measureElapsed(start) {
810
+ return performance.now() - start;
811
+ }
812
+ function formatCacheHitRate(metric) {
813
+ if (metric.total === 0) {
814
+ return "0.00%";
815
+ }
816
+ return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
817
+ }
818
+ function formatMs(value) {
819
+ return value.toFixed(2);
820
+ }
821
+ function summarizeStringDiff(previous, next) {
822
+ if (previous === next) {
823
+ return "same";
824
+ }
825
+ const previousLength = previous.length;
826
+ const nextLength = next.length;
827
+ const minLength = Math.min(previousLength, nextLength);
828
+ let prefixLength = 0;
829
+ while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) {
830
+ prefixLength += 1;
831
+ }
832
+ let previousSuffixCursor = previousLength - 1;
833
+ let nextSuffixCursor = nextLength - 1;
834
+ while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) {
835
+ previousSuffixCursor -= 1;
836
+ nextSuffixCursor -= 1;
837
+ }
838
+ const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0;
839
+ const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0;
840
+ return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`;
841
+ }
842
+ function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) {
843
+ const changedLinkedFiles = linkedImpactsByEntry.get(entry);
844
+ if (!changedLinkedFiles || changedLinkedFiles.size === 0) {
845
+ return void 0;
846
+ }
847
+ const parts = [...changedLinkedFiles].sort().map((file) => {
848
+ const hash = sourceHashByFile.get(file) ?? "missing";
849
+ return `${file}:${hash}`;
850
+ });
851
+ return parts.join(",");
852
+ }
853
+ function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
854
+ if (!linkedImpactSignature) {
855
+ return runtimeSignature;
856
+ }
857
+ return `${runtimeSignature}:linked:${linkedImpactSignature}`;
858
+ }
859
+ function hasRuntimeAffectingSourceChanges(changedByType) {
860
+ return changedByType.html.size > 0 || changedByType.js.size > 0;
861
+ }
862
+ function canShareCssTransformResult(rawSource) {
863
+ return !rawSource.includes("@import") && !rawSource.includes("url(");
864
+ }
865
+ function createGenerateBundleHook(context) {
866
+ const state = createBundleBuildState();
867
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
868
+ return async function generateBundle(_opt, bundle) {
869
+ const {
870
+ opts,
871
+ runtimeState,
872
+ ensureBundleRuntimeClassSet,
873
+ debug: debug3,
874
+ getResolvedConfig
875
+ } = context;
876
+ const {
877
+ appType,
878
+ cache,
879
+ mainCssChunkMatcher,
880
+ onEnd,
881
+ onStart,
882
+ onUpdate,
883
+ styleHandler,
884
+ templateHandler,
885
+ jsHandler,
886
+ uniAppX
887
+ } = opts;
888
+ const getCssHandlerOptions = (file) => {
889
+ const majorVersion = runtimeState.twPatcher.majorVersion;
890
+ const isMainChunk = mainCssChunkMatcher(file, appType);
891
+ const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
892
+ const cached = cssHandlerOptionsCache.get(cacheKey);
893
+ if (cached) {
894
+ return cached;
895
+ }
896
+ const created = {
897
+ isMainChunk,
898
+ postcssOptions: {
899
+ options: {
900
+ from: file
901
+ }
902
+ },
903
+ majorVersion
904
+ };
905
+ cssHandlerOptionsCache.set(cacheKey, created);
906
+ return created;
907
+ };
908
+ await runtimeState.patchPromise;
909
+ debug3("start");
910
+ onStart();
911
+ const metrics = createEmptyMetrics();
912
+ const forceRuntimeRefreshByEnv = process2.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
913
+ const disableDirtyOptimization = process2.env.WEAPP_TW_VITE_DISABLE_DIRTY === "1";
914
+ const disableJsPrecheck = process2.env.WEAPP_TW_VITE_DISABLE_JS_PRECHECK === "1";
915
+ const debugCssDiff = process2.env.WEAPP_TW_VITE_DEBUG_CSS_DIFF === "1";
916
+ const resolvedConfig = getResolvedConfig();
917
+ const useIncrementalMode = resolvedConfig?.command !== "build";
918
+ const rootDir = resolvedConfig?.root ? path2.resolve(resolvedConfig.root) : process2.cwd();
919
+ const outDir = resolvedConfig?.build?.outDir ? path2.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
920
+ const snapshot = useIncrementalMode ? buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization) : buildBundleSnapshotForBuild(bundle, opts, outDir);
921
+ const useBundleRuntimeClassSet = useIncrementalMode || runtimeState.twPatcher.majorVersion === 4;
922
+ const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
923
+ const processFiles = snapshot.processFiles;
924
+ if (useIncrementalMode) {
925
+ debug3(
926
+ "dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]",
927
+ state.iteration + 1,
928
+ snapshot.changedByType.html.size,
929
+ formatDebugFileList(snapshot.changedByType.html),
930
+ snapshot.changedByType.js.size,
931
+ formatDebugFileList(snapshot.changedByType.js),
932
+ snapshot.changedByType.css.size,
933
+ formatDebugFileList(snapshot.changedByType.css),
934
+ snapshot.changedByType.other.size,
935
+ formatDebugFileList(snapshot.changedByType.other)
936
+ );
937
+ debug3(
938
+ "process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]",
939
+ state.iteration + 1,
940
+ processFiles.html.size,
941
+ formatDebugFileList(processFiles.html),
942
+ processFiles.js.size,
943
+ formatDebugFileList(processFiles.js),
944
+ processFiles.css.size,
945
+ formatDebugFileList(processFiles.css)
946
+ );
947
+ } else {
948
+ debug3(
949
+ "build mode full process html=%d[%s] js=%d[%s] css=%d[%s]",
950
+ processFiles.html.size,
951
+ formatDebugFileList(processFiles.html),
952
+ processFiles.js.size,
953
+ formatDebugFileList(processFiles.js),
954
+ processFiles.css.size,
955
+ formatDebugFileList(processFiles.css)
956
+ );
957
+ }
958
+ const jsEntries = snapshot.jsEntries;
959
+ const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
960
+ const runtimeStart = performance.now();
961
+ const runtime = useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
962
+ const defaultTemplateHandlerOptions = {
963
+ runtimeSet: runtime
964
+ };
965
+ metrics.runtimeSet = measureElapsed(runtimeStart);
966
+ if (forceRuntimeRefreshBySource) {
967
+ debug3(
968
+ "runtimeSet forced refresh due to source changes: html=%d js=%d",
969
+ snapshot.runtimeAffectingChangedByType.html.size,
970
+ snapshot.runtimeAffectingChangedByType.js.size
971
+ );
972
+ }
973
+ debug3("get runtimeSet, class count: %d", runtime.size);
974
+ const runtimeSignature = getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
975
+ const handleLinkedUpdate = (fileName, previous, next) => {
976
+ onUpdate(fileName, previous, next);
977
+ debug3("js linked handle: %s", fileName);
978
+ };
979
+ const pendingLinkedUpdates = [];
980
+ const scheduleLinkedApply = (entry, code) => {
981
+ pendingLinkedUpdates.push(() => {
982
+ if (entry.output.type === "chunk") {
983
+ entry.output.code = code;
984
+ } else {
985
+ entry.output.source = code;
986
+ }
987
+ });
988
+ };
989
+ const applyLinkedUpdates = (linked) => {
990
+ applyLinkedResults(linked, jsEntries, handleLinkedUpdate, scheduleLinkedApply);
991
+ };
992
+ const createHandlerOptions = (absoluteFilename, extra) => ({
993
+ ...extra,
994
+ filename: absoluteFilename,
995
+ tailwindcssMajorVersion: runtimeState.twPatcher.majorVersion,
996
+ moduleGraph: moduleGraphOptions,
997
+ babelParserOptions: {
998
+ ...extra?.babelParserOptions ?? {},
999
+ sourceFilename: absoluteFilename
1000
+ }
1001
+ });
1002
+ const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
1003
+ const sharedCssResultCache = /* @__PURE__ */ new Map();
1004
+ const tasks = [];
1005
+ const jsTaskFactories = [];
1006
+ for (const entry of snapshot.entries) {
1007
+ const { file, output: originalSource, source: originalEntrySource, type } = entry;
1008
+ if (type === "html" && originalSource.type === "asset") {
1009
+ metrics.html.total++;
1010
+ if (!processFiles.html.has(file)) {
1011
+ continue;
1012
+ }
1013
+ const rawSource = originalEntrySource;
1014
+ tasks.push(
1015
+ processCachedTask({
1016
+ cache,
1017
+ cacheKey: file,
1018
+ rawSource,
1019
+ hashKey: `${file}:html:${runtimeSignature}`,
1020
+ applyResult(source) {
1021
+ originalSource.source = source;
1022
+ },
1023
+ onCacheHit() {
1024
+ metrics.html.cacheHits++;
1025
+ debug3("html cache hit: %s", file);
1026
+ },
1027
+ async transform() {
1028
+ const start = performance.now();
1029
+ const transformed = await templateHandler(rawSource, defaultTemplateHandlerOptions);
1030
+ metrics.html.elapsed += measureElapsed(start);
1031
+ metrics.html.transformed++;
1032
+ onUpdate(file, rawSource, transformed);
1033
+ debug3("html handle: %s", file);
1034
+ return {
1035
+ result: transformed
1036
+ };
1037
+ }
1038
+ })
1039
+ );
1040
+ continue;
1041
+ }
1042
+ if (type === "css" && originalSource.type === "asset") {
1043
+ metrics.css.total++;
1044
+ const rawSource = originalEntrySource;
1045
+ const cssRuntimeAffectingSignature = snapshot.runtimeAffectingSignatureByFile.get(file) ?? rawSource;
1046
+ const shareCssResult = canShareCssTransformResult(rawSource);
1047
+ const cssSharedCacheKey = shareCssResult ? `${runtimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${getCssHandlerOptions(file).isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}` : void 0;
1048
+ tasks.push(
1049
+ processCachedTask({
1050
+ cache,
1051
+ cacheKey: file,
1052
+ hashKey: `${file}:css:${runtimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1053
+ rawSource: cssRuntimeAffectingSignature,
1054
+ applyResult(source) {
1055
+ originalSource.source = source;
1056
+ },
1057
+ onCacheHit() {
1058
+ metrics.css.cacheHits++;
1059
+ debug3("css cache hit: %s", file);
1060
+ },
1061
+ async transform() {
1062
+ if (cssSharedCacheKey) {
1063
+ const sharedCssTask = sharedCssResultCache.get(cssSharedCacheKey);
1064
+ if (sharedCssTask != null) {
1065
+ metrics.css.cacheHits++;
1066
+ debug3("css shared hit: %s", file);
1067
+ const sharedCss = await sharedCssTask;
1068
+ onUpdate(file, rawSource, sharedCss);
1069
+ return {
1070
+ result: sharedCss
1071
+ };
1072
+ }
1073
+ }
1074
+ const runTransform = async () => {
1075
+ const start = performance.now();
1076
+ await runtimeState.patchPromise;
1077
+ const { css: css2 } = await styleHandler(rawSource, getCssHandlerOptions(file));
1078
+ if (debugCssDiff) {
1079
+ debug3("css diff %s: %s", file, summarizeStringDiff(rawSource, css2));
1080
+ }
1081
+ metrics.css.elapsed += measureElapsed(start);
1082
+ metrics.css.transformed++;
1083
+ return css2;
1084
+ };
1085
+ const cssTask = cssSharedCacheKey ? sharedCssResultCache.get(cssSharedCacheKey) ?? runTransform() : runTransform();
1086
+ if (cssSharedCacheKey && !sharedCssResultCache.has(cssSharedCacheKey)) {
1087
+ sharedCssResultCache.set(cssSharedCacheKey, cssTask);
1088
+ }
1089
+ const css = await cssTask;
1090
+ onUpdate(file, rawSource, css);
1091
+ debug3("css handle: %s", file);
1092
+ return {
1093
+ result: css
1094
+ };
1095
+ }
1096
+ })
1097
+ );
1098
+ continue;
1099
+ }
1100
+ if (type !== "js") {
1101
+ continue;
1102
+ }
1103
+ metrics.js.total++;
1104
+ const shouldTransformJs = !useIncrementalMode || processFiles.js.has(file);
1105
+ if (!shouldTransformJs) {
1106
+ debug3("js skip transform (clean), replay cache: %s", file);
1107
+ }
1108
+ if (originalSource.type === "chunk") {
1109
+ const absoluteFile = path2.resolve(outDir, file);
1110
+ const initialRawSource = originalEntrySource;
1111
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1112
+ if (linkedByEntry && linkedSet) {
1113
+ linkedByEntry.set(file, linkedSet);
1114
+ }
1115
+ jsTaskFactories.push(async () => {
1116
+ const linkedImpactSignature = useIncrementalMode ? createLinkedImpactSignature(
1117
+ file,
1118
+ snapshot.linkedImpactsByEntry,
1119
+ snapshot.sourceHashByFile
1120
+ ) : void 0;
1121
+ const hashSalt = createJsHashSalt(runtimeSignature, linkedImpactSignature);
1122
+ await processCachedTask({
1123
+ cache,
1124
+ cacheKey: file,
1125
+ hashKey: `${file}:js`,
1126
+ rawSource: `${initialRawSource}
1127
+ /*${hashSalt}*/`,
1128
+ applyResult(source) {
1129
+ originalSource.code = source;
1130
+ },
1131
+ onCacheHit() {
1132
+ metrics.js.cacheHits++;
1133
+ debug3("js cache hit: %s", file);
1134
+ },
1135
+ async transform() {
1136
+ const start = performance.now();
1137
+ const rawSource = originalSource.code;
1138
+ if (!shouldTransformJs) {
1139
+ debug3("js cache replay miss, fallback transform: %s", file);
1140
+ }
1141
+ const handlerOptions = createHandlerOptions(absoluteFile);
1142
+ if (!disableJsPrecheck && shouldSkipViteJsTransform(rawSource, handlerOptions)) {
1143
+ metrics.js.elapsed += measureElapsed(start);
1144
+ metrics.js.transformed++;
1145
+ return {
1146
+ result: rawSource
1147
+ };
1148
+ }
1149
+ const { code, linked } = await jsHandler(rawSource, runtime, handlerOptions);
1150
+ metrics.js.elapsed += measureElapsed(start);
1151
+ metrics.js.transformed++;
1152
+ onUpdate(file, rawSource, code);
1153
+ debug3("js handle: %s", file);
1154
+ if (linked) {
1155
+ for (const id of Object.keys(linked)) {
1156
+ const linkedEntry = jsEntries.get(id);
1157
+ if (linkedEntry && linkedSet) {
1158
+ linkedSet.add(linkedEntry.fileName);
1159
+ }
1160
+ }
1161
+ }
1162
+ applyLinkedUpdates(linked);
1163
+ return {
1164
+ result: code
1165
+ };
1166
+ }
1167
+ });
1168
+ });
1169
+ } else if (uniAppX && originalSource.type === "asset") {
1170
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1171
+ if (linkedByEntry && linkedSet) {
1172
+ linkedByEntry.set(file, linkedSet);
1173
+ }
1174
+ const baseApplyLinkedUpdates = applyLinkedUpdates;
1175
+ const wrappedApplyLinkedUpdates = (linked) => {
1176
+ if (linked) {
1177
+ for (const id of Object.keys(linked)) {
1178
+ const linkedEntry = jsEntries.get(id);
1179
+ if (linkedEntry && linkedSet) {
1180
+ linkedSet.add(linkedEntry.fileName);
1181
+ }
1182
+ }
1183
+ }
1184
+ baseApplyLinkedUpdates(linked);
1185
+ };
1186
+ const factory = createUniAppXAssetTask(
1187
+ file,
1188
+ originalSource,
1189
+ outDir,
1190
+ {
1191
+ cache,
1192
+ hashKey: `${file}:js`,
1193
+ hashSalt: createJsHashSalt(
1194
+ runtimeSignature,
1195
+ useIncrementalMode ? createLinkedImpactSignature(
1196
+ file,
1197
+ snapshot.linkedImpactsByEntry,
1198
+ snapshot.sourceHashByFile
1199
+ ) : void 0
1200
+ ),
1201
+ createHandlerOptions,
1202
+ debug: debug3,
1203
+ jsHandler,
1204
+ onUpdate,
1205
+ runtimeSet: runtime,
1206
+ applyLinkedResults: wrappedApplyLinkedUpdates,
1207
+ uniAppX
1208
+ }
1209
+ );
1210
+ jsTaskFactories.push(async () => {
1211
+ const start = performance.now();
1212
+ if (!shouldTransformJs) {
1213
+ debug3("js skip transform (clean, uni-app-x), replay cache: %s", file);
1214
+ await factory();
1215
+ metrics.js.elapsed += measureElapsed(start);
1216
+ metrics.js.transformed++;
1217
+ return;
1218
+ }
1219
+ const currentSource = originalEntrySource;
1220
+ const absoluteFile = path2.resolve(outDir, file);
1221
+ const precheckOptions = createHandlerOptions(absoluteFile, {
1222
+ uniAppX: uniAppX ?? true,
1223
+ babelParserOptions: {
1224
+ plugins: ["typescript"],
1225
+ sourceType: "unambiguous"
1226
+ }
1227
+ });
1228
+ if (!disableJsPrecheck && shouldSkipViteJsTransform(currentSource, precheckOptions)) {
1229
+ metrics.js.elapsed += measureElapsed(start);
1230
+ metrics.js.transformed++;
1231
+ return;
1232
+ }
1233
+ await factory();
1234
+ metrics.js.elapsed += measureElapsed(start);
1235
+ metrics.js.transformed++;
1236
+ });
1237
+ }
1238
+ }
1239
+ pushConcurrentTaskFactories(tasks, jsTaskFactories);
1240
+ await Promise.all(tasks);
1241
+ for (const apply of pendingLinkedUpdates) {
1242
+ apply();
1243
+ }
1244
+ if (useIncrementalMode) {
1245
+ updateBundleBuildState(state, snapshot, linkedByEntry ?? /* @__PURE__ */ new Map());
1246
+ }
1247
+ debug3(
1248
+ "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)",
1249
+ useIncrementalMode ? state.iteration : 0,
1250
+ formatMs(metrics.runtimeSet),
1251
+ metrics.html.total,
1252
+ metrics.html.transformed,
1253
+ metrics.html.cacheHits,
1254
+ formatCacheHitRate(metrics.html),
1255
+ formatMs(metrics.html.elapsed),
1256
+ metrics.js.total,
1257
+ metrics.js.transformed,
1258
+ metrics.js.cacheHits,
1259
+ formatCacheHitRate(metrics.js),
1260
+ formatMs(metrics.js.elapsed),
1261
+ metrics.css.total,
1262
+ metrics.css.transformed,
1263
+ metrics.css.cacheHits,
1264
+ formatCacheHitRate(metrics.css),
1265
+ formatMs(metrics.css.elapsed)
1266
+ );
1267
+ onEnd();
1268
+ debug3("end");
1269
+ };
1270
+ }
1271
+
1272
+ // src/bundlers/vite/incremental-runtime-class-set.ts
1273
+ import { mkdir, readFile, rm, writeFile } from "fs/promises";
1274
+ import { createRequire } from "module";
1275
+ import path3 from "path";
1276
+ import process3 from "process";
1277
+ import { extractRawCandidatesWithPositions, extractValidCandidates } from "tailwindcss-patch";
1278
+ var debug = createDebug("[vite:runtime-set] ");
1279
+ var require2 = createRequire(import.meta.url);
1280
+ var EXTENSION_DOT_PREFIX_RE = /^\./;
1281
+ var VALIDATION_FILE_NAME = "runtime-candidates.html";
1282
+ var tailwindNodeModulePromise;
1283
+ function toPosixPath(value) {
1284
+ return value.replaceAll("\\", "/");
1285
+ }
1286
+ function createCssImportSource(imports) {
1287
+ return imports.map((value) => `@import "${toPosixPath(value)}";`).join("\n");
1288
+ }
1289
+ function isPostcssPluginImportTarget(value) {
1290
+ if (!value) {
1291
+ return false;
1292
+ }
1293
+ return value === "@tailwindcss/postcss" || value === "@tailwindcss/postcss7-compat" || value.includes("/postcss");
1294
+ }
1295
+ function resolveTailwindCssImportTarget(patcher) {
1296
+ const tailwindOptions = patcher.options?.tailwind;
1297
+ const cssEntries = tailwindOptions?.v4?.cssEntries?.filter((item) => typeof item === "string" && item.length > 0);
1298
+ if (cssEntries && cssEntries.length > 0) {
1299
+ return createCssImportSource(cssEntries);
1300
+ }
1301
+ const configuredPackageName = tailwindOptions?.packageName;
1302
+ if (typeof configuredPackageName === "string" && configuredPackageName.length > 0 && !isPostcssPluginImportTarget(configuredPackageName)) {
1303
+ return createCssImportSource([configuredPackageName]);
1304
+ }
1305
+ const packageName = patcher.packageInfo?.name;
1306
+ if (typeof packageName === "string" && packageName.length > 0 && !isPostcssPluginImportTarget(packageName)) {
1307
+ return createCssImportSource([packageName]);
1308
+ }
1309
+ return createCssImportSource(["tailwindcss"]);
1310
+ }
1311
+ function getProjectRoot(patcher) {
1312
+ return patcher.options?.projectRoot ?? process3.cwd();
1313
+ }
1314
+ async function importTailwindNodeModule() {
1315
+ if (!tailwindNodeModulePromise) {
1316
+ tailwindNodeModulePromise = (async () => {
1317
+ try {
1318
+ const resolved = require2.resolve("@tailwindcss/node");
1319
+ return await import(resolved);
1320
+ } catch {
1321
+ const tailwindcssPatchEntry = require2.resolve("tailwindcss-patch");
1322
+ const resolved = require2.resolve("@tailwindcss/node", {
1323
+ paths: [path3.dirname(tailwindcssPatchEntry)]
1324
+ });
1325
+ return await import(resolved);
1326
+ }
1327
+ })();
1328
+ }
1329
+ return tailwindNodeModulePromise;
1330
+ }
1331
+ function resolveMaybeAbsolute(base, value) {
1332
+ if (!value) {
1333
+ return void 0;
1334
+ }
1335
+ return path3.isAbsolute(value) ? value : path3.resolve(base, value);
1336
+ }
1337
+ async function resolveTailwindCssSource(patcher) {
1338
+ const projectRoot = getProjectRoot(patcher);
1339
+ const tailwindOptions = patcher.options?.tailwind;
1340
+ const configuredBase = resolveMaybeAbsolute(projectRoot, tailwindOptions?.v4?.base);
1341
+ const configDir = tailwindOptions?.config ? path3.dirname(tailwindOptions.config) : void 0;
1342
+ const sharedFallbacks = [
1343
+ configuredBase,
1344
+ projectRoot,
1345
+ tailwindOptions?.cwd,
1346
+ configDir
1347
+ ].filter((item) => typeof item === "string" && item.length > 0);
1348
+ if (tailwindOptions?.v4?.css) {
1349
+ return {
1350
+ projectRoot,
1351
+ base: configuredBase ?? projectRoot,
1352
+ baseFallbacks: [...new Set(sharedFallbacks)],
1353
+ css: tailwindOptions.v4.css
1354
+ };
1355
+ }
1356
+ const cssEntries = tailwindOptions?.v4?.cssEntries?.filter((item) => typeof item === "string" && item.length > 0) ?? [];
1357
+ if (cssEntries.length > 0) {
1358
+ const resolvedEntries = cssEntries.map((entry) => resolveMaybeAbsolute(projectRoot, entry) ?? entry);
1359
+ const cssChunks = [];
1360
+ const entryDirs = [];
1361
+ for (const entry of resolvedEntries) {
1362
+ try {
1363
+ cssChunks.push(await readFile(entry, "utf8"));
1364
+ entryDirs.push(path3.dirname(entry));
1365
+ } catch {
1366
+ }
1367
+ }
1368
+ if (cssChunks.length > 0) {
1369
+ const base = entryDirs[0] ?? configuredBase ?? projectRoot;
1370
+ const baseFallbacks = [...new Set([
1371
+ ...entryDirs.slice(1),
1372
+ ...sharedFallbacks
1373
+ ].filter((item) => typeof item === "string" && item.length > 0 && item !== base))];
1374
+ return {
1375
+ projectRoot,
1376
+ base,
1377
+ baseFallbacks,
1378
+ css: cssChunks.join("\n")
1379
+ };
1380
+ }
1381
+ }
1382
+ return {
1383
+ projectRoot,
1384
+ base: configuredBase ?? projectRoot,
1385
+ baseFallbacks: [...new Set(sharedFallbacks)],
1386
+ css: resolveTailwindCssImportTarget(patcher)
1387
+ };
1388
+ }
1389
+ function createExtractOptions(context, tempRoot, pattern) {
1390
+ return {
1391
+ cwd: context.projectRoot,
1392
+ base: context.base,
1393
+ baseFallbacks: context.baseFallbacks,
1394
+ css: context.css,
1395
+ sources: [{
1396
+ base: tempRoot,
1397
+ pattern,
1398
+ negated: false
1399
+ }]
1400
+ };
1401
+ }
1402
+ function createRuntimeEntries(snapshot) {
1403
+ return snapshot.entries.filter((entry) => entry.type === "html" || entry.type === "js");
1404
+ }
1405
+ function collectChangedRuntimeFiles(snapshot) {
1406
+ return /* @__PURE__ */ new Set([
1407
+ ...snapshot.runtimeAffectingChangedByType.html,
1408
+ ...snapshot.runtimeAffectingChangedByType.js
1409
+ ]);
1410
+ }
1411
+ async function writeTempEntryFile(tempRoot, file, source) {
1412
+ const absoluteFile = path3.join(tempRoot, file);
1413
+ await mkdir(path3.dirname(absoluteFile), { recursive: true });
1414
+ await writeFile(absoluteFile, source, "utf8");
1415
+ return file;
1416
+ }
1417
+ function resolveEntryExtension(entry) {
1418
+ const ext = path3.extname(entry.file).replace(EXTENSION_DOT_PREFIX_RE, "");
1419
+ if (ext.length > 0) {
1420
+ return ext;
1421
+ }
1422
+ return entry.type === "html" ? "html" : "js";
1423
+ }
1424
+ function createCandidateValidationSource(candidates) {
1425
+ return [...new Set(candidates)].sort().join("\n");
1426
+ }
1427
+ function removeCandidateSet(candidateCountByClass, runtimeSet, candidates) {
1428
+ for (const className of candidates) {
1429
+ const count = candidateCountByClass.get(className);
1430
+ if (count == null) {
1431
+ continue;
1432
+ }
1433
+ if (count <= 1) {
1434
+ candidateCountByClass.delete(className);
1435
+ runtimeSet.delete(className);
1436
+ continue;
1437
+ }
1438
+ candidateCountByClass.set(className, count - 1);
1439
+ }
1440
+ }
1441
+ function addCandidateSet(candidateCountByClass, runtimeSet, candidates) {
1442
+ for (const className of candidates) {
1443
+ const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
1444
+ candidateCountByClass.set(className, nextCount);
1445
+ runtimeSet.add(className);
1446
+ }
1447
+ }
1448
+ function createBundleRuntimeClassSetManager(options = {}) {
1449
+ const customExtractCandidates = options.extractCandidates;
1450
+ const extractCandidates = customExtractCandidates ?? extractValidCandidates;
1451
+ const extractRawCandidates = options.extractRawCandidates ?? extractRawCandidatesWithPositions;
1452
+ const runtimeSet = /* @__PURE__ */ new Set();
1453
+ const candidateCountByClass = /* @__PURE__ */ new Map();
1454
+ const candidatesByFile = /* @__PURE__ */ new Map();
1455
+ const candidateValidityCache = /* @__PURE__ */ new Map();
1456
+ let runtimeSignature;
1457
+ let resolvedTempRoot;
1458
+ let validationContext;
1459
+ let designSystemPromise;
1460
+ async function reset() {
1461
+ runtimeSet.clear();
1462
+ candidateCountByClass.clear();
1463
+ candidatesByFile.clear();
1464
+ candidateValidityCache.clear();
1465
+ runtimeSignature = void 0;
1466
+ validationContext = void 0;
1467
+ designSystemPromise = void 0;
1468
+ if (resolvedTempRoot) {
1469
+ await rm(resolvedTempRoot, { recursive: true, force: true });
1470
+ resolvedTempRoot = void 0;
1471
+ }
1472
+ }
1473
+ async function resolveValidationContextCached(patcher) {
1474
+ if (!validationContext) {
1475
+ validationContext = await resolveTailwindCssSource(patcher);
1476
+ }
1477
+ return validationContext;
1478
+ }
1479
+ async function loadDesignSystem(context) {
1480
+ if (!designSystemPromise) {
1481
+ designSystemPromise = (async () => {
1482
+ const { __unstable__loadDesignSystem } = await importTailwindNodeModule();
1483
+ let lastError;
1484
+ for (const base of [context.base, ...context.baseFallbacks]) {
1485
+ try {
1486
+ return await __unstable__loadDesignSystem(context.css, { base });
1487
+ } catch (error) {
1488
+ lastError = error;
1489
+ }
1490
+ }
1491
+ throw lastError instanceof Error ? lastError : new Error("Failed to load Tailwind CSS design system for incremental runtime validation.");
1492
+ })();
1493
+ }
1494
+ return designSystemPromise;
1495
+ }
1496
+ function populateCandidateValidityCacheFromDesignSystem(designSystem, unknownCandidates) {
1497
+ const parsedCandidates = [...unknownCandidates].filter((candidate) => designSystem.parseCandidate(candidate).length > 0);
1498
+ const cssByCandidate = parsedCandidates.length > 0 ? designSystem.candidatesToCss(parsedCandidates) : [];
1499
+ const validCandidates = /* @__PURE__ */ new Set();
1500
+ for (let index = 0; index < parsedCandidates.length; index += 1) {
1501
+ const candidate = parsedCandidates[index];
1502
+ const css = cssByCandidate[index];
1503
+ if (candidate && typeof css === "string" && css.trim().length > 0) {
1504
+ validCandidates.add(candidate);
1505
+ }
1506
+ }
1507
+ for (const candidate of unknownCandidates) {
1508
+ candidateValidityCache.set(candidate, validCandidates.has(candidate));
1509
+ }
1510
+ }
1511
+ async function validateUnknownCandidates(patcher, tempRoot, unknownCandidates) {
1512
+ if (unknownCandidates.size === 0) {
1513
+ return;
1514
+ }
1515
+ const context = await resolveValidationContextCached(patcher);
1516
+ if (!customExtractCandidates) {
1517
+ try {
1518
+ const designSystem = await loadDesignSystem(context);
1519
+ populateCandidateValidityCacheFromDesignSystem(designSystem, unknownCandidates);
1520
+ return;
1521
+ } catch (error) {
1522
+ debug("incremental design-system validation failed, fallback to extractValidCandidates: %O", error);
1523
+ designSystemPromise = void 0;
1524
+ }
1525
+ }
1526
+ const source = createCandidateValidationSource(unknownCandidates);
1527
+ const pattern = await writeTempEntryFile(tempRoot, VALIDATION_FILE_NAME, source);
1528
+ const validCandidates = new Set(await extractCandidates(createExtractOptions(context, tempRoot, pattern)));
1529
+ for (const candidate of unknownCandidates) {
1530
+ candidateValidityCache.set(candidate, validCandidates.has(candidate));
1531
+ }
1532
+ }
1533
+ async function extractEntryRawCandidates(entry) {
1534
+ const matches = await extractRawCandidates(entry.source, resolveEntryExtension(entry));
1535
+ const candidates = /* @__PURE__ */ new Set();
1536
+ for (const match of matches) {
1537
+ const candidate = match?.rawCandidate;
1538
+ if (typeof candidate === "string" && candidate.length > 0) {
1539
+ candidates.add(candidate);
1540
+ }
1541
+ }
1542
+ return candidates;
1543
+ }
1544
+ async function sync(patcher, snapshot) {
1545
+ const nextSignature = getRuntimeClassSetSignature(patcher) ?? "runtime:missing";
1546
+ const runtimeEntries = createRuntimeEntries(snapshot);
1547
+ const runtimeEntriesByFile = new Map(runtimeEntries.map((entry) => [entry.file, entry]));
1548
+ const currentRuntimeFiles = new Set(runtimeEntriesByFile.keys());
1549
+ const fullRebuild = runtimeSignature !== nextSignature || candidatesByFile.size === 0;
1550
+ if (runtimeSignature !== nextSignature) {
1551
+ debug("runtime signature changed, reset incremental runtime set: %s", nextSignature);
1552
+ await reset();
1553
+ }
1554
+ runtimeSignature = nextSignature;
1555
+ const projectRoot = getProjectRoot(patcher);
1556
+ resolvedTempRoot = options.tempRoot ?? path3.join(
1557
+ projectRoot,
1558
+ "node_modules",
1559
+ ".cache",
1560
+ "weapp-tailwindcss",
1561
+ "vite-runtime-set"
1562
+ );
1563
+ for (const [file, previousCandidates] of candidatesByFile) {
1564
+ if (currentRuntimeFiles.has(file)) {
1565
+ continue;
1566
+ }
1567
+ removeCandidateSet(candidateCountByClass, runtimeSet, previousCandidates);
1568
+ candidatesByFile.delete(file);
1569
+ }
1570
+ const changedRuntimeFiles = fullRebuild ? [...runtimeEntriesByFile.keys()] : [...collectChangedRuntimeFiles(snapshot)];
1571
+ if (changedRuntimeFiles.length === 0) {
1572
+ return new Set(runtimeSet);
1573
+ }
1574
+ const rawCandidatesByFile = /* @__PURE__ */ new Map();
1575
+ const unknownCandidates = /* @__PURE__ */ new Set();
1576
+ await Promise.all(changedRuntimeFiles.map(async (file) => {
1577
+ const entry = runtimeEntriesByFile.get(file);
1578
+ if (!entry) {
1579
+ return;
1580
+ }
1581
+ const candidates = await extractEntryRawCandidates(entry);
1582
+ rawCandidatesByFile.set(file, candidates);
1583
+ for (const candidate of candidates) {
1584
+ if (!candidateValidityCache.has(candidate)) {
1585
+ unknownCandidates.add(candidate);
1586
+ }
1587
+ }
1588
+ }));
1589
+ await validateUnknownCandidates(patcher, resolvedTempRoot, unknownCandidates);
1590
+ let rawCandidateCount = 0;
1591
+ for (const file of changedRuntimeFiles) {
1592
+ const nextRawCandidates = rawCandidatesByFile.get(file);
1593
+ const previousCandidates = candidatesByFile.get(file);
1594
+ if (previousCandidates) {
1595
+ removeCandidateSet(candidateCountByClass, runtimeSet, previousCandidates);
1596
+ }
1597
+ if (!nextRawCandidates || nextRawCandidates.size === 0) {
1598
+ candidatesByFile.delete(file);
1599
+ continue;
1600
+ }
1601
+ rawCandidateCount += nextRawCandidates.size;
1602
+ const nextCandidates = new Set(
1603
+ [...nextRawCandidates].filter((candidate) => candidateValidityCache.get(candidate) === true)
1604
+ );
1605
+ if (nextCandidates.size === 0) {
1606
+ candidatesByFile.delete(file);
1607
+ continue;
1608
+ }
1609
+ addCandidateSet(candidateCountByClass, runtimeSet, nextCandidates);
1610
+ candidatesByFile.set(file, nextCandidates);
1611
+ }
1612
+ debug(
1613
+ "incremental runtime set synced, changedFiles=%d rawCandidates=%d validateMisses=%d runtimeSize=%d trackedFiles=%d",
1614
+ changedRuntimeFiles.length,
1615
+ rawCandidateCount,
1616
+ unknownCandidates.size,
1617
+ runtimeSet.size,
1618
+ candidatesByFile.size
1619
+ );
1620
+ return new Set(runtimeSet);
1621
+ }
1622
+ return {
1623
+ sync,
1624
+ reset
1625
+ };
1626
+ }
1627
+
1628
+ // src/bundlers/vite/rewrite-css-imports.ts
1629
+ function joinPosixPath(base, subpath) {
1630
+ if (base.endsWith("/")) {
1631
+ return `${base}${subpath}`;
1632
+ }
1633
+ return `${base}/${subpath}`;
1634
+ }
1635
+ function isCssLikeImporter(importer) {
1636
+ if (!importer) {
1637
+ return false;
1638
+ }
1639
+ const normalized = cleanUrl(importer);
1640
+ return isCSSRequest(normalized);
1641
+ }
1642
+ function createRewriteCssImportsPlugins(options) {
1643
+ if (!options.shouldRewrite) {
1644
+ return [];
1645
+ }
1646
+ const { appType, weappTailwindcssDirPosix: weappTailwindcssDirPosix2 } = options;
1647
+ return [
1648
+ {
1649
+ name: `${vitePluginName}:rewrite-css-imports`,
1650
+ enforce: "pre",
1651
+ resolveId: {
1652
+ order: "pre",
1653
+ handler(id, importer) {
1654
+ const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix2, {
1655
+ join: joinPosixPath,
1656
+ appType
1657
+ });
1658
+ if (!replacement) {
1659
+ return null;
1660
+ }
1661
+ if (importer && !isCssLikeImporter(importer)) {
1662
+ return null;
1663
+ }
1664
+ return replacement;
1665
+ }
1666
+ },
1667
+ transform: {
1668
+ order: "pre",
1669
+ handler(code, id) {
1670
+ if (!isCSSRequest(id)) {
1671
+ return null;
1672
+ }
1673
+ const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix2, {
1674
+ join: joinPosixPath,
1675
+ appType
1676
+ });
1677
+ if (!rewritten) {
1678
+ return null;
1679
+ }
1680
+ return {
1681
+ code: rewritten,
1682
+ map: null
1683
+ };
1684
+ }
1685
+ }
1686
+ }
1687
+ ];
1688
+ }
1689
+
1690
+ // src/bundlers/vite/index.ts
1691
+ var debug2 = createDebug();
1692
+ var weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
1693
+ var weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1694
+ var PACKAGE_JSON_FILE = "package.json";
1695
+ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1696
+ const resolvedRoot = path4.resolve(root);
1697
+ if (!existsSync(resolvedRoot)) {
1698
+ return resolvedRoot;
1699
+ }
1700
+ const searchRoots = [];
1701
+ let current = resolvedRoot;
1702
+ while (true) {
1703
+ searchRoots.push(current);
1704
+ const parent = path4.dirname(current);
1705
+ if (parent === current) {
1706
+ break;
1707
+ }
1708
+ current = parent;
1709
+ }
1710
+ const tailwindConfigPath = findTailwindConfig(searchRoots);
1711
+ if (tailwindConfigPath) {
1712
+ return path4.dirname(tailwindConfigPath);
1713
+ }
1714
+ const packageRoot = findNearestPackageRoot(resolvedRoot);
1715
+ if (packageRoot && existsSync(path4.join(packageRoot, PACKAGE_JSON_FILE))) {
1716
+ return packageRoot;
1717
+ }
1718
+ return resolvedRoot;
1719
+ }
1720
+ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1721
+ const rewriteCssImportsSpecified = Object.hasOwn(options, "rewriteCssImports");
1722
+ const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1723
+ const opts = getCompilerContext(options);
1724
+ const {
1725
+ disabled,
1726
+ customAttributes,
1727
+ onLoad,
1728
+ mainCssChunkMatcher,
1729
+ appType,
1730
+ styleHandler,
1731
+ jsHandler,
1732
+ twPatcher: initialTwPatcher,
1733
+ refreshTailwindcssPatcher,
1734
+ uniAppX,
1735
+ disabledDefaultTemplateHandler
1736
+ } = opts;
1737
+ const disabledOptions = resolveDisabledOptions(disabled);
1738
+ const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1739
+ const shouldRewriteCssImports = opts.rewriteCssImports !== false && !disabledOptions.rewriteCssImports && (rewriteCssImportsSpecified || tailwindcssMajorVersion >= 4);
1740
+ const rewritePlugins = createRewriteCssImportsPlugins({
1741
+ appType,
1742
+ shouldRewrite: shouldRewriteCssImports,
1743
+ weappTailwindcssDirPosix
1744
+ });
1745
+ if (disabledOptions.plugin) {
1746
+ return rewritePlugins.length ? rewritePlugins : void 0;
1747
+ }
1748
+ const customAttributesEntities = toCustomAttributesEntities(customAttributes);
1749
+ const patchRecorderState = setupPatchRecorder(initialTwPatcher, opts.tailwindcssBasedir, {
1750
+ source: "runtime",
1751
+ cwd: opts.tailwindcssBasedir ?? process4.cwd()
1752
+ });
1753
+ const runtimeState = {
1754
+ twPatcher: initialTwPatcher,
1755
+ patchPromise: patchRecorderState.patchPromise,
1756
+ refreshTailwindcssPatcher,
1757
+ onPatchCompleted: patchRecorderState.onPatchCompleted
1758
+ };
1759
+ let runtimeSet;
1760
+ let runtimeSetPromise;
1761
+ let resolvedConfig;
1762
+ let runtimeRefreshSignature;
1763
+ let runtimeRefreshOptionsKey;
1764
+ const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1765
+ function resolveRuntimeRefreshOptions() {
1766
+ const configPath = runtimeState.twPatcher.options?.tailwind?.config;
1767
+ const signature = getRuntimeClassSetSignature(runtimeState.twPatcher);
1768
+ const optionsKey = JSON.stringify({
1769
+ appType,
1770
+ uniAppX: Boolean(uniAppX),
1771
+ customAttributesEntities,
1772
+ disabledDefaultTemplateHandler,
1773
+ configPath,
1774
+ rewriteCssImports: shouldRewriteCssImports
1775
+ });
1776
+ const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1777
+ runtimeRefreshSignature = signature;
1778
+ runtimeRefreshOptionsKey = optionsKey;
1779
+ return {
1780
+ changed,
1781
+ signature,
1782
+ optionsKey
1783
+ };
1784
+ }
1785
+ async function refreshRuntimeState(force) {
1786
+ const invalidation = resolveRuntimeRefreshOptions();
1787
+ const shouldRefresh = force || invalidation.changed;
1788
+ const refreshed = await refreshTailwindRuntimeState(runtimeState, {
1789
+ force: shouldRefresh,
1790
+ clearCache: force || invalidation.changed
1791
+ });
1792
+ if (invalidation.changed) {
1793
+ debug2("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
1794
+ }
1795
+ if (refreshed) {
1796
+ runtimeSet = void 0;
1797
+ runtimeSetPromise = void 0;
1798
+ }
1799
+ }
1800
+ async function ensureRuntimeClassSet(force = false) {
1801
+ const forceRuntimeRefresh = force || process4.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1802
+ await refreshRuntimeState(force);
1803
+ await runtimeState.patchPromise;
1804
+ if (!forceRuntimeRefresh && runtimeSet) {
1805
+ return runtimeSet;
1806
+ }
1807
+ if (forceRuntimeRefresh || !runtimeSetPromise) {
1808
+ const invalidation = resolveRuntimeRefreshOptions();
1809
+ const task2 = collectRuntimeClassSet(runtimeState.twPatcher, {
1810
+ force: forceRuntimeRefresh || invalidation.changed,
1811
+ skipRefresh: forceRuntimeRefresh,
1812
+ clearCache: forceRuntimeRefresh || invalidation.changed
1813
+ });
1814
+ runtimeSetPromise = task2;
1815
+ }
1816
+ const task = runtimeSetPromise;
1817
+ try {
1818
+ runtimeSet = await task;
1819
+ return runtimeSet;
1820
+ } finally {
1821
+ if (runtimeSetPromise === task) {
1822
+ runtimeSetPromise = void 0;
1823
+ }
1824
+ }
1825
+ }
1826
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
1827
+ const forceRuntimeRefresh = forceRefresh || process4.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1828
+ const invalidation = resolveRuntimeRefreshOptions();
1829
+ const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
1830
+ const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
1831
+ await refreshRuntimeState(shouldRefreshPatcher);
1832
+ await runtimeState.patchPromise;
1833
+ if (shouldRefreshPatcher) {
1834
+ runtimeSet = void 0;
1835
+ runtimeSetPromise = void 0;
1836
+ await bundleRuntimeClassSetManager.reset();
1837
+ }
1838
+ if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) {
1839
+ try {
1840
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
1841
+ runtimeSet = nextRuntimeSet;
1842
+ return nextRuntimeSet;
1843
+ } catch (error) {
1844
+ debug2("incremental runtime set sync failed, fallback to full collect: %O", error);
1845
+ await bundleRuntimeClassSetManager.reset();
1846
+ }
1847
+ }
1848
+ if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) {
1849
+ return runtimeSet;
1850
+ }
1851
+ const task = collectRuntimeClassSet(runtimeState.twPatcher, {
1852
+ force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
1853
+ skipRefresh: forceRuntimeRefresh,
1854
+ clearCache: forceRuntimeRefresh || invalidation.changed
1855
+ });
1856
+ runtimeSetPromise = task;
1857
+ try {
1858
+ runtimeSet = await task;
1859
+ return runtimeSet;
1860
+ } finally {
1861
+ if (runtimeSetPromise === task) {
1862
+ runtimeSetPromise = void 0;
1863
+ }
1864
+ }
1865
+ }
1866
+ onLoad();
1867
+ const getResolvedConfig = () => resolvedConfig;
1868
+ const utsPlatform = resolveUniUtsPlatform();
1869
+ const isIosPlatform = utsPlatform.isAppIos;
1870
+ const uniAppXPlugins = uniAppX ? createUniAppXPlugins({
1871
+ appType,
1872
+ customAttributesEntities,
1873
+ disabledDefaultTemplateHandler,
1874
+ isIosPlatform,
1875
+ mainCssChunkMatcher,
1876
+ runtimeState,
1877
+ styleHandler,
1878
+ jsHandler,
1879
+ ensureRuntimeClassSet,
1880
+ getResolvedConfig
1881
+ }) : void 0;
1882
+ const plugins = [
1883
+ ...rewritePlugins,
1884
+ {
1885
+ name: `${vitePluginName}:post`,
1886
+ enforce: "post",
1887
+ async configResolved(config) {
1888
+ resolvedConfig = config;
1889
+ const resolvedRoot = config.root ? path4.resolve(config.root) : void 0;
1890
+ if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
1891
+ const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
1892
+ if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
1893
+ const previousBasedir = opts.tailwindcssBasedir;
1894
+ opts.tailwindcssBasedir = nextTailwindcssBasedir;
1895
+ debug2(
1896
+ "align tailwindcss basedir with vite root: %s -> %s",
1897
+ previousBasedir ?? "undefined",
1898
+ nextTailwindcssBasedir
1899
+ );
1900
+ await refreshRuntimeState(true);
1901
+ }
1902
+ }
1903
+ if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
1904
+ const postcssPlugins = config.css.postcss.plugins;
1905
+ const idx = postcssPlugins.findIndex((x) => (
1906
+ // @ts-ignore
1907
+ x.postcssPlugin === "postcss-html-transform"
1908
+ ));
1909
+ if (idx > -1) {
1910
+ postcssPlugins.splice(idx, 1, postcssHtmlTransform());
1911
+ debug2("remove postcss-html-transform plugin from vite config");
1912
+ }
1913
+ }
1914
+ },
1915
+ generateBundle: createGenerateBundleHook({
1916
+ opts,
1917
+ runtimeState,
1918
+ ensureRuntimeClassSet,
1919
+ ensureBundleRuntimeClassSet,
1920
+ debug: debug2,
1921
+ getResolvedConfig
1922
+ })
1923
+ }
1924
+ ];
1925
+ if (uniAppXPlugins) {
1926
+ plugins.push(...uniAppXPlugins);
1927
+ }
1928
+ return plugins;
1929
+ }
1930
+
1931
+ export {
1932
+ UnifiedViteWeappTailwindcssPlugin
1933
+ };