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