weapp-tailwindcss 5.0.5 → 5.0.7

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 (103) hide show
  1. package/dist/{bundle-state-Cso_ceUo.js → bundle-state-BzwPS-UI.js} +2 -1
  2. package/dist/{bundle-state-DEyxCR4f.mjs → bundle-state-ChcOKb9w.mjs} +2 -1
  3. package/dist/bundlers/gulp/index.d.ts +3 -4
  4. package/dist/bundlers/gulp/module-graph.d.ts +2 -0
  5. package/dist/bundlers/gulp/runtime-snapshot.d.ts +5 -0
  6. package/dist/bundlers/gulp/vinyl-transform.d.ts +3 -0
  7. package/dist/bundlers/shared/css-cleanup.d.ts +1 -1
  8. package/dist/bundlers/shared/css-source-trace.d.ts +20 -0
  9. package/dist/bundlers/shared/generator-css/directives/fallback.d.ts +11 -0
  10. package/dist/bundlers/shared/generator-css/generation-helpers.d.ts +56 -0
  11. package/dist/bundlers/shared/generator-css/local-imports.d.ts +7 -0
  12. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +1 -1
  13. package/dist/bundlers/shared/generator-css/types.d.ts +27 -0
  14. package/dist/bundlers/shared/generator-css/user-css.d.ts +26 -0
  15. package/dist/bundlers/shared/generator-css/validate.d.ts +5 -0
  16. package/dist/bundlers/shared/generator-css.d.ts +4 -32
  17. package/dist/bundlers/vite/css-finalizer.d.ts +3 -0
  18. package/dist/bundlers/vite/generate-bundle/css-config-directives.d.ts +2 -0
  19. package/dist/bundlers/vite/generate-bundle/css-output.d.ts +14 -0
  20. package/dist/bundlers/vite/generate-bundle/remembered-css.d.ts +11 -0
  21. package/dist/bundlers/vite/generate-bundle/sfc-style-source.d.ts +9 -0
  22. package/dist/bundlers/vite/generate-bundle/style-matching.d.ts +5 -0
  23. package/dist/bundlers/vite/generate-bundle/subpackages.d.ts +7 -0
  24. package/dist/bundlers/vite/generate-bundle/types.d.ts +68 -0
  25. package/dist/bundlers/vite/generate-bundle.d.ts +4 -62
  26. package/dist/bundlers/vite/incremental-runtime-class-set/entries.d.ts +4 -0
  27. package/dist/bundlers/vite/incremental-runtime-class-set/escaped-candidates.d.ts +2 -0
  28. package/dist/bundlers/vite/incremental-runtime-class-set/v3-candidates.d.ts +13 -0
  29. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +1 -0
  30. package/dist/bundlers/vite/processed-css-assets/css-rules.d.ts +17 -0
  31. package/dist/bundlers/vite/processed-css-assets.d.ts +2 -0
  32. package/dist/bundlers/vite/source-candidates/scan-root.d.ts +10 -0
  33. package/dist/bundlers/vite/source-candidates/script.d.ts +7 -0
  34. package/dist/bundlers/vite/source-candidates/tailwind-v3-default-extractor.d.ts +1 -0
  35. package/dist/bundlers/vite/source-candidates.d.ts +8 -3
  36. package/dist/bundlers/vite/source-scan/css-entries.d.ts +20 -0
  37. package/dist/bundlers/vite/source-scan/dependencies.d.ts +2 -0
  38. package/dist/bundlers/vite/source-scan.d.ts +2 -12
  39. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/helpers.d.ts +48 -0
  40. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +1 -20
  41. package/dist/cli.js +69 -69
  42. package/dist/cli.mjs +69 -69
  43. package/dist/core.js +1 -1
  44. package/dist/core.mjs +1 -1
  45. package/dist/{defaults-BPUuNYcD.js → defaults-Boc26eel.js} +1 -0
  46. package/dist/{defaults-8xrgzxFY.mjs → defaults-DH0ZQRhy.mjs} +1 -0
  47. package/dist/defaults.js +1 -1
  48. package/dist/defaults.mjs +1 -1
  49. package/dist/{generator-AD-eX8Tr.js → generator-6yF8wjxR.js} +1 -1
  50. package/dist/{generator-DVWLNO0n.mjs → generator-BON6M1bL.mjs} +1 -1
  51. package/dist/generator.js +2 -2
  52. package/dist/generator.mjs +2 -2
  53. package/dist/gulp-_7p1Z2vc.js +473 -0
  54. package/dist/gulp-oE-Byqk6.mjs +463 -0
  55. package/dist/gulp.js +4 -414
  56. package/dist/gulp.mjs +1 -406
  57. package/dist/{incremental-runtime-class-set-vOetpdWs.js → hmr-timing-BKQNRxHr.js} +1257 -459
  58. package/dist/{incremental-runtime-class-set-xf49kky6.mjs → hmr-timing-BVTGf5ch.mjs} +1221 -477
  59. package/dist/index.js +5 -5
  60. package/dist/index.mjs +5 -5
  61. package/dist/{postcss-Cbi6RFpf.js → postcss-BTIunhWl.js} +7 -7
  62. package/dist/{postcss-hSUxK7oR.mjs → postcss-BtmrrZ31.mjs} +4 -4
  63. package/dist/postcss.js +1 -1
  64. package/dist/postcss.mjs +1 -1
  65. package/dist/{precheck-Bsn_LMmo.mjs → precheck-CZjr87m_.mjs} +19 -5
  66. package/dist/{precheck-b8Y8qZg0.js → precheck-fhIkzCSU.js} +19 -5
  67. package/dist/presets.js +2 -2
  68. package/dist/presets.mjs +2 -2
  69. package/dist/tailwindcss/source-scan/inline-source.d.ts +7 -0
  70. package/dist/tailwindcss/source-scan.d.ts +2 -7
  71. package/dist/tailwindcss/v3-engine/generator/cache-key.d.ts +3 -0
  72. package/dist/tailwindcss/v3-engine/generator/content.d.ts +10 -0
  73. package/dist/tailwindcss/v3-engine/generator/runtime-ready.d.ts +2 -0
  74. package/dist/tailwindcss/v4-engine/generator/css-compat.d.ts +2 -0
  75. package/dist/tailwindcss/v4-engine/generator/rpx-candidates.d.ts +6 -0
  76. package/dist/tailwindcss/v4-engine/generator/scan-sources.d.ts +2 -0
  77. package/dist/tailwindcss/v4-engine/types.d.ts +1 -1
  78. package/dist/{tailwindcss-AWaPVF2B.mjs → tailwindcss-bbQUg25J.mjs} +2 -2
  79. package/dist/{tailwindcss-CpQ6X4l6.js → tailwindcss-vswd1gc3.js} +2 -2
  80. package/dist/{transform-BkGtbxb1.js → transform-CReJxxh_.js} +11 -2
  81. package/dist/{transform-DumSZmTh.mjs → transform-DEsFlG9k.mjs} +11 -2
  82. package/dist/types/typedoc-tailwindcss-patch.d.ts +4 -2
  83. package/dist/types/user-defined-options/general.d.ts +5 -0
  84. package/dist/uni-app-x/component-local-style.d.ts +1 -0
  85. package/dist/uni-app-x/harmony.d.ts +1 -0
  86. package/dist/uni-app-x/style-asset/style-value.d.ts +16 -0
  87. package/dist/uni-app-x/style-asset.d.ts +20 -0
  88. package/dist/uni-app-x/transform.d.ts +1 -0
  89. package/dist/uni-app-x/vite.d.ts +1 -0
  90. package/dist/{v3-engine-CM0TRa8V.js → v3-engine-CEMXFegG.js} +714 -663
  91. package/dist/{v3-engine-Cczrkzqt.mjs → v3-engine-CdIwmHuc.mjs} +758 -707
  92. package/dist/{vite-CTuHPC91.js → vite-0jFbh9hx.js} +1797 -386
  93. package/dist/{vite-DLXDMHON.mjs → vite-C7BGAlCE.mjs} +1779 -369
  94. package/dist/vite.js +1 -1
  95. package/dist/vite.mjs +1 -1
  96. package/dist/weapp-tw-css-import-rewrite-loader.js +1169 -1002
  97. package/dist/{webpack-DJFw08SK.mjs → webpack-Dx6_eg5k.mjs} +96 -36
  98. package/dist/{webpack-BBHJYKqB.js → webpack-aEuDoYfQ.js} +105 -44
  99. package/dist/webpack.js +1 -1
  100. package/dist/webpack.mjs +1 -1
  101. package/package.json +6 -5
  102. package/dist/source-candidates-BsWYoIPN.mjs +0 -355
  103. package/dist/source-candidates-o2ZrKWzu.js +0 -374
@@ -1,13 +1,16 @@
1
- import { A as normalizeTailwindV3CssEntrySource, B as splitTailwindV4GeneratedCssBySourceOrder, E as hasTailwindSourceDirectives, F as createCssAppend, G as prependConfigDirective, H as stripTailwindBanner, I as hasTailwindGeneratedCss, L as hasTailwindGeneratedCssMarkers, M as removeTailwindSourceDirectives, N as resolveCssEntrySource, O as normalizeTailwindSourceDirectives, P as VITE_MARKER_RE, R as splitGeneratorPlaceholderCssBySourceOrder, S as resolveTailwindV4SourceOptionsFromPatcher, T as hasTailwindRootDirectives, U as stripTailwindBanners, V as stripGeneratorPlaceholderMarkers, W as normalizeConfigDirective, X as loadTailwindV4DesignSystem, Y as filterUnsupportedMiniProgramTailwindV4Candidates, gt as omitUndefined, h as resolveTailwindV4EntriesFromCss, j as parseImportRequest, l as getRuntimeClassSetSignature, lt as createDebug, n as resolveTailwindV3SourceFromPatcher, r as resolveTailwindV3SourceOptionsFromPatcher, rt as normalizeLegacyContentEntries, st as resolveTailwindV4CssSourceBase, t as resolveTailwindV3Source, w as hasTailwindApplyDirective, x as resolveTailwindV4SourceFromPatcher, y as resolveTailwindV4Source$1, z as splitTailwindGeneratedCssByBanner } from "./v3-engine-Cczrkzqt.mjs";
2
- import { i as normalizeWeappTailwindcssGeneratorOptions, t as createWeappTailwindcssGenerator } from "./generator-DVWLNO0n.mjs";
3
- import { p as replaceWxml, r as resolveStyleOptionsFromContext } from "./precheck-Bsn_LMmo.mjs";
4
- import { r as isUniAppXEnabled } from "./tailwindcss-AWaPVF2B.mjs";
5
- import { existsSync, readFileSync } from "node:fs";
1
+ import { A as normalizeTailwindV3CssEntrySource, B as splitTailwindV4GeneratedCssBySourceOrder, E as hasTailwindSourceDirectives, F as createCssAppend, G as prependConfigDirective, H as stripTailwindBanner, I as hasTailwindGeneratedCss, L as hasTailwindGeneratedCssMarkers, M as removeTailwindSourceDirectives, N as resolveCssEntrySource, O as normalizeTailwindSourceDirectives, P as VITE_MARKER_RE, Q as FULL_SOURCE_SCAN_EXTENSION_RE, R as splitGeneratorPlaceholderCssBySourceOrder, S as resolveTailwindV4SourceOptionsFromPatcher, T as hasTailwindRootDirectives, U as stripTailwindBanners, V as stripGeneratorPlaceholderMarkers, W as normalizeConfigDirective, X as loadTailwindV4DesignSystem, Y as filterUnsupportedMiniProgramTailwindV4Candidates, at as resolveSourceScanPath, g as resolveTailwindV4EntriesFromCss, j as parseImportRequest, l as getRuntimeClassSetSignature, lt as createDebug, n as resolveTailwindV3SourceFromPatcher, nt as normalizeLegacyContentEntries, ot as resolveTailwindV4CssSourceBase, r as resolveTailwindV3SourceOptionsFromPatcher, st as toPosixPath$1, t as resolveTailwindV3Source, tt as isFileMatchedByTailwindSourceEntries, w as hasTailwindApplyDirective, x as resolveTailwindV4SourceFromPatcher, y as resolveTailwindV4Source$1, yt as omitUndefined, z as splitTailwindGeneratedCssByBanner } from "./v3-engine-CdIwmHuc.mjs";
2
+ import { i as normalizeWeappTailwindcssGeneratorOptions, t as createWeappTailwindcssGenerator } from "./generator-BON6M1bL.mjs";
3
+ import { h as traverse, m as babelParse, p as replaceWxml, r as resolveStyleOptionsFromContext } from "./precheck-CZjr87m_.mjs";
4
+ import { r as isUniAppXEnabled } from "./tailwindcss-bbQUg25J.mjs";
5
+ import { createRequire } from "node:module";
6
6
  import postcss from "postcss";
7
- import { extractRawCandidatesWithPositions, extractSourceCandidates, extractValidCandidates, resolveValidTailwindV4Candidates } from "tailwindcss-patch";
7
+ import { extractRawCandidatesWithPositions, extractSourceCandidates, extractValidCandidates, resolveProjectSourceFiles, resolveValidTailwindV4Candidates, splitCandidateTokens } from "tailwindcss-patch";
8
8
  import process from "node:process";
9
+ import { existsSync, readFileSync } from "node:fs";
9
10
  import path from "node:path";
10
- import { finalizeMiniProgramCss, removeUnsupportedMiniProgramAtRules } from "@weapp-tailwindcss/postcss";
11
+ import { readFile } from "node:fs/promises";
12
+ import { finalizeMiniProgramCss, pruneMiniProgramGeneratedCss, removeUnsupportedMiniProgramAtRules } from "@weapp-tailwindcss/postcss";
13
+ import { MappingChars2String, unescape } from "@weapp-core/escape";
11
14
  //#region src/bundlers/shared/cache.ts
12
15
  async function processCachedTask({ cache, cacheKey, hashKey = cacheKey, rawSource, hash, readCache, applyResult, transform, onCacheHit }) {
13
16
  let cacheHit = false;
@@ -27,6 +30,199 @@ async function processCachedTask({ cache, cacheKey, hashKey = cacheKey, rawSourc
27
30
  if (!cacheHit) await applyResult(result, { cacheHit: false });
28
31
  }
29
32
  //#endregion
33
+ //#region src/bundlers/shared/css-source-trace.ts
34
+ const CSS_SOURCE_TRACE_COMMENT_RE = /^\s*tokens:\s/;
35
+ const TAILWIND_GENERATED_CONTAINER_TRACE_COMMENT_RE = /^\s*tokens:\s*container\s*<=\s*<tailwind generated>\s*$/i;
36
+ function normalizeSelectorTokenCandidate(candidate) {
37
+ return candidate.replace(/(?<!\\)\\:/g, ":").replace(/(?<!\\)\\\//g, "/");
38
+ }
39
+ function normalizeSourcePath(source, root) {
40
+ const resolvedRoot = path.resolve(root);
41
+ const resolvedSource = path.resolve(source);
42
+ const relative = path.relative(resolvedRoot, resolvedSource);
43
+ if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) return relative.split(path.sep).join("/");
44
+ return source.split(path.sep).join("/");
45
+ }
46
+ function getSourceTraceRoot(opts) {
47
+ const configured = opts.cssSourceTrace;
48
+ if (configured && typeof configured === "object" && configured.root) return configured.root;
49
+ return opts.tailwindcssBasedir ?? process.cwd();
50
+ }
51
+ function isCssSourceTraceEnabled(opts) {
52
+ return opts.cssSourceTrace === true || typeof opts.cssSourceTrace === "object" && opts.cssSourceTrace !== null;
53
+ }
54
+ function createCssTokenSourceMap(sourcesByToken, opts) {
55
+ const root = getSourceTraceRoot(opts);
56
+ const tokenSources = /* @__PURE__ */ new Map();
57
+ for (const [token, sources] of [...sourcesByToken.entries()].sort(([a], [b]) => a.localeCompare(b))) {
58
+ const source = {
59
+ token,
60
+ sources: [...sources].map((file) => normalizeSourcePath(file, root)).sort()
61
+ };
62
+ tokenSources.set(token, source);
63
+ const escaped = replaceWxml(token, { escapeMap: opts.escapeMap });
64
+ tokenSources.set(escaped, source);
65
+ tokenSources.set(escaped.replaceAll("\\", ""), source);
66
+ }
67
+ return tokenSources;
68
+ }
69
+ function createCssSourceTraceCacheSignature(tokenSources, opts) {
70
+ if (!isCssSourceTraceEnabled(opts)) return "css-source-trace:0";
71
+ if (!tokenSources?.size) return "css-source-trace:1:empty";
72
+ return `css-source-trace:1:${[...tokenSources.values()].map(({ token, sources }) => `${token}<=${sources.join(",")}`).sort().join("|")}`;
73
+ }
74
+ function getTokenSource(tokenSources, token) {
75
+ return tokenSources.get(token);
76
+ }
77
+ function collectRuleSourceTokens(rule, tokenSources) {
78
+ const tokens = /* @__PURE__ */ new Map();
79
+ for (const selector of rule.selectors) {
80
+ const classMatches = selector.matchAll(/\.((?:\\.|[^\s.#:[{>,])*)/g);
81
+ for (const match of classMatches) {
82
+ const rawCandidate = match[1];
83
+ if (!rawCandidate) continue;
84
+ const candidates = [normalizeSelectorTokenCandidate(rawCandidate), rawCandidate];
85
+ for (const candidate of candidates) {
86
+ const source = getTokenSource(tokenSources, candidate);
87
+ if (!source) continue;
88
+ tokens.set(source.token, source);
89
+ break;
90
+ }
91
+ }
92
+ }
93
+ return tokens;
94
+ }
95
+ function removeTracedTailwindGeneratedContainerRules(root) {
96
+ root.walkRules((rule) => {
97
+ if (!rule.selectors || rule.selectors.length !== 1 || rule.selectors[0] !== ".container") return;
98
+ const previous = rule.prev();
99
+ if (previous?.type !== "comment" || !TAILWIND_GENERATED_CONTAINER_TRACE_COMMENT_RE.test(previous.text)) return;
100
+ previous.remove();
101
+ rule.remove();
102
+ });
103
+ }
104
+ function annotateCssSourceTrace(css, options) {
105
+ if (!isCssSourceTraceEnabled(options.opts) || !options.tokenSources?.size) return css;
106
+ try {
107
+ const root = postcss.parse(css);
108
+ root.walkComments((comment) => {
109
+ if (CSS_SOURCE_TRACE_COMMENT_RE.test(comment.text)) comment.remove();
110
+ });
111
+ root.walkRules((rule) => {
112
+ const tokens = collectRuleSourceTokens(rule, options.tokenSources);
113
+ if (tokens.size === 0 || !rule.parent) return;
114
+ const lines = [...tokens.values()].map(({ token, sources }) => {
115
+ return `${token} <= ${sources.length > 0 ? sources.join(", ") : "<tailwind generated>"}`;
116
+ });
117
+ const comment = postcss.comment({ text: `tokens: ${lines.join(" | ")}` });
118
+ if (rule.raws.before !== void 0) comment.raws.before = rule.raws.before;
119
+ rule.raws.before = "\n";
120
+ rule.parent.insertBefore(rule, comment);
121
+ });
122
+ removeTracedTailwindGeneratedContainerRules(root);
123
+ return root.toString();
124
+ } catch {
125
+ return css;
126
+ }
127
+ }
128
+ //#endregion
129
+ //#region src/bundlers/shared/generator-css/generation-helpers.ts
130
+ function finalizeMiniProgramGeneratorCss(css, target, majorVersion, cssPreflight, options = {}) {
131
+ if (target !== "weapp") return css;
132
+ return finalizeMiniProgramCss(css, {
133
+ cssPreflight: majorVersion === 4 && options.injectPreflight !== false ? cssPreflight : void 0,
134
+ isTailwindcssV4: majorVersion === 4,
135
+ preservePseudoContentInit: majorVersion === 3
136
+ });
137
+ }
138
+ function shouldInjectMiniProgramPreflightForGeneratorCss(opts, options) {
139
+ if (options.cssHandlerOptions.uniAppX === true && options.cssHandlerOptions.uniAppXCssTarget === "uvue") return false;
140
+ if (!options.isolateCurrentCssCandidates) return true;
141
+ return isUniAppXEnabled(opts.uniAppX) && Boolean(options.localImports?.trim());
142
+ }
143
+ function mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtime, options) {
144
+ if (options.isolateCssSource && options.currentCssCandidates?.length) return new Set([...scopedRuntime, ...options.currentCssCandidates]);
145
+ if (runtime.size === 0 || !options.cssHandlerOptions.isMainChunk || options.matchedCssSourceFile || options.isolateCssSource && scopedRuntime.size === 0) return scopedRuntime;
146
+ return new Set([...scopedRuntime, ...runtime]);
147
+ }
148
+ function shouldIsolateScopedCssSource(source, sourceEntries) {
149
+ return Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile) || sourceEntries !== void 0 && sourceEntries.length > 0;
150
+ }
151
+ function shouldIsolateCurrentTailwindV4CssCandidates(majorVersion, cssHandlerOptions, options) {
152
+ return majorVersion === 4 && !cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(options.rawSource) && !hasTailwindRootDirectives(options.rawSource) && !options.hasGeneratedCss && !options.hasGeneratedMarkers;
153
+ }
154
+ function shouldScanTailwindV4Sources(majorVersion, target, generatorRuntime, isolateCssSource) {
155
+ if (majorVersion !== 4) return false;
156
+ if (target === "web") return true;
157
+ if (isolateCssSource) return false;
158
+ return generatorRuntime.size === 0;
159
+ }
160
+ function shouldAppendWebBundleCssFallback(target, options) {
161
+ return target === "web" && !options.hasMatchedCssSourceFile && !options.hasSourceDirectives;
162
+ }
163
+ function isEmptyCssSourceOrderParts(parts) {
164
+ return parts.before.trim().length === 0 && parts.after.trim().length === 0;
165
+ }
166
+ function resolveGeneratorStyleOptions(opts, cssHandlerOptions, generatorStyleOptions) {
167
+ const preflightStyleOptions = {
168
+ cssPreflight: opts.cssPreflight,
169
+ cssPreflightRange: opts.cssPreflightRange
170
+ };
171
+ return {
172
+ ...resolveStyleOptionsFromContext(opts),
173
+ atRules: opts.atRules,
174
+ uniAppXCssTarget: opts.uniAppXCssTarget,
175
+ uniAppXUnsupported: opts.uniAppXUnsupported,
176
+ ...cssHandlerOptions,
177
+ ...preflightStyleOptions,
178
+ ...generatorStyleOptions
179
+ };
180
+ }
181
+ function createCssSourceOrderAppend$1(base, extra) {
182
+ if (!base) return extra;
183
+ if (!extra) return base;
184
+ if (/\s$/.test(base) || /^\s/.test(extra)) return `${base}${extra}`;
185
+ return `${base}\n${extra}`;
186
+ }
187
+ function shouldFinalizeMarkedUserLayerComponentsCss(file) {
188
+ return !/\.(?:vue|svelte|astro|scss|sass|less|styl)(?:[?#].*)?$/i.test(file);
189
+ }
190
+ function splitRawSourceByGeneratedCssOrder(rawSource, rawTailwindCss) {
191
+ const placeholderParts = splitGeneratorPlaceholderCssBySourceOrder(rawSource, rawTailwindCss);
192
+ if (placeholderParts) return placeholderParts;
193
+ const exactParts = splitTailwindV4GeneratedCssBySourceOrder(rawSource, rawTailwindCss);
194
+ if (exactParts) return exactParts;
195
+ return splitTailwindGeneratedCssByBanner(rawSource);
196
+ }
197
+ function shouldUseGeneratorForCurrentCss(majorVersion, cssHandlerOptions, options) {
198
+ const hasApplyDirectives = hasTailwindApplyDirective(options.rawSource);
199
+ return options.hasGeneratedCss || options.hasGeneratedMarkers || options.hasSourceDirectives || majorVersion === 4 && hasApplyDirectives || cssHandlerOptions.isMainChunk;
200
+ }
201
+ function createRuntimeWithCurrentCssCandidates(runtime, currentCssCandidates, isolateCurrentCssCandidates) {
202
+ return isolateCurrentCssCandidates ? new Set(currentCssCandidates) : currentCssCandidates.length > 0 ? new Set([...runtime, ...currentCssCandidates]) : runtime;
203
+ }
204
+ function mergeGeneratorResults(generatedResults) {
205
+ const firstGenerated = generatedResults[0];
206
+ if (!firstGenerated) return;
207
+ if (generatedResults.length === 1) return firstGenerated;
208
+ const incrementalCssResults = generatedResults.map((item) => item.incrementalCss).filter((css) => typeof css === "string");
209
+ const incrementalRawCssResults = generatedResults.map((item) => item.incrementalRawCss).filter((css) => typeof css === "string");
210
+ return {
211
+ ...firstGenerated,
212
+ css: generatedResults.map((item) => item.css).join("\n"),
213
+ rawCss: generatedResults.map((item) => item.rawCss).join("\n"),
214
+ incrementalCss: incrementalCssResults.length === generatedResults.length ? incrementalCssResults.filter(Boolean).join("\n") : void 0,
215
+ incrementalRawCss: incrementalRawCssResults.length === generatedResults.length ? incrementalRawCssResults.filter(Boolean).join("\n") : void 0,
216
+ classSet: new Set(generatedResults.flatMap((item) => [...item.classSet])),
217
+ dependencies: [...new Set(generatedResults.flatMap((item) => item.dependencies))],
218
+ sources: generatedResults.flatMap((item) => item.sources)
219
+ };
220
+ }
221
+ const SUPPORTED_GENERATOR_MAJOR_VERSIONS$1 = new Set([3, 4]);
222
+ function isSupportedGeneratorMajorVersion(majorVersion) {
223
+ return SUPPORTED_GENERATOR_MAJOR_VERSIONS$1.has(majorVersion ?? 0);
224
+ }
225
+ //#endregion
30
226
  //#region src/bundlers/shared/generator-css/legacy-selectors.ts
31
227
  const CLASS_SELECTOR_RE = /(?:^|[^\w-])\.[_a-z\u00A0-\uFFFF\\-]/i;
32
228
  const MINI_PROGRAM_THEME_SCOPE_SELECTORS = new Set([
@@ -263,13 +459,6 @@ function isPathWithinRoot$1(file, root) {
263
459
  const relative = path.relative(root, file);
264
460
  return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
265
461
  }
266
- function countCommonSuffixSegments(a, b) {
267
- const aSegments = a.split("/").filter(Boolean);
268
- const bSegments = b.split("/").filter(Boolean);
269
- let count = 0;
270
- while (count < aSegments.length && count < bSegments.length && aSegments[aSegments.length - 1 - count] === bSegments[bSegments.length - 1 - count]) count++;
271
- return count;
272
- }
273
462
  function collectOutputMatchBases(file, sourceOptions) {
274
463
  const normalizedFile = file.replace(/[?#].*$/, "");
275
464
  const roots = [
@@ -304,7 +493,7 @@ function isMatchingSourceStyleFile(file, sourceFile, sourceOptions) {
304
493
  const normalizedRoot = path.resolve(root);
305
494
  if (isPathWithinRoot$1(normalizedSourceFile, normalizedRoot)) addSourceBase(path.relative(normalizedRoot, normalizedSourceFile));
306
495
  }
307
- for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase || outputBase.endsWith(`/${sourceBase}`) || sourceBase.endsWith(`/${outputBase}`) || countCommonSuffixSegments(outputBase, sourceBase) >= 2) return true;
496
+ for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase || outputBase.endsWith(`/${sourceBase}`) || sourceBase.endsWith(`/${outputBase}`)) return true;
308
497
  return false;
309
498
  }
310
499
  function scoreMatchingSourceStyleFile(file, sourceFile, sourceOptions) {
@@ -322,13 +511,9 @@ function scoreMatchingSourceStyleFile(file, sourceFile, sourceOptions) {
322
511
  if (isPathWithinRoot$1(normalizedSourceFile, normalizedRoot)) addSourceBase(path.relative(normalizedRoot, normalizedSourceFile));
323
512
  }
324
513
  let bestScore = 0;
325
- for (const outputBase of outputBases) for (const sourceBase of sourceBases) {
326
- const commonSuffixSegments = countCommonSuffixSegments(outputBase, sourceBase);
327
- if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
328
- else if (outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
329
- else if (sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
330
- else if (commonSuffixSegments >= 2) bestScore = Math.max(bestScore, 100 + commonSuffixSegments);
331
- }
514
+ for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
515
+ else if (outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
516
+ else if (sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
332
517
  return bestScore;
333
518
  }
334
519
  function collectMatchedConfiguredSourceFiles(file, sourceOptions) {
@@ -487,7 +672,7 @@ function canResolveSourceSideCssEntry(file, cssHandlerOptions, sourceOptions) {
487
672
  return true;
488
673
  }
489
674
  function shouldResolveSourceSideCssEntry(rawSource) {
490
- return rawSource.includes("@apply") || hasTailwindGeneratedCss(rawSource) || hasTailwindGeneratedCssMarkers(rawSource);
675
+ return rawSource.includes("@apply") || hasTailwindRootDirectives(rawSource, { importFallback: true }) || hasTailwindSourceDirectives(rawSource, { importFallback: true }) || hasTailwindGeneratedCss(rawSource) || hasTailwindGeneratedCssMarkers(rawSource);
491
676
  }
492
677
  function shouldPreferTailwindV3SourceSideEntry(rawSource, sourceSideEntrySource) {
493
678
  return Boolean(sourceSideEntrySource) && !hasTailwindSourceDirectives(rawSource, { importFallback: true });
@@ -532,17 +717,6 @@ function collectCssSourceMatchBases(file, roots) {
532
717
  } else for (const root of resolvedRoots) addBase(path.resolve(root, normalizedFile));
533
718
  return bases;
534
719
  }
535
- function hasMatchingCssSourceBase(outputBases, sourceBases) {
536
- for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase || outputBase.endsWith(`/${sourceBase}`) || sourceBase.endsWith(`/${outputBase}`)) return true;
537
- return false;
538
- }
539
- function isMatchingTailwindV4CssSourceFile(file, cssSourceFile, sourceOptions) {
540
- return hasMatchingCssSourceBase(collectCssSourceMatchBases(file, [
541
- sourceOptions.outputRoot,
542
- sourceOptions.projectRoot,
543
- sourceOptions.cwd
544
- ]), collectCssSourceMatchBases(cssSourceFile, [sourceOptions.projectRoot, sourceOptions.cwd]));
545
- }
546
720
  function scoreTailwindV4CssSourceFileMatch(file, cssSourceFile, sourceOptions) {
547
721
  const outputBases = collectCssSourceMatchBases(file, [
548
722
  sourceOptions.outputRoot,
@@ -629,12 +803,29 @@ async function resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOpt
629
803
  if (!cssSources?.length) return;
630
804
  const normalizedRawSource = normalizeCssSourceForCompare(rawSource);
631
805
  const sourceFile = resolvePostcssSourceFile(cssHandlerOptions);
632
- const matchingSource = cssSources.find((cssSource) => {
633
- if (typeof cssSource.css !== "string" || cssSource.css.length === 0) return false;
634
- if (sourceFile && typeof cssSource.file === "string" && path.resolve(sourceFile) === path.resolve(cssSource.file)) return true;
635
- if (typeof cssSource.file === "string" && isMatchingTailwindV4CssSourceFile(file, cssSource.file, sourceOptions)) return true;
636
- return normalizeCssSourceForCompare(cssSource.css) === normalizedRawSource;
637
- });
806
+ const matches = cssSources.map((cssSource, index) => {
807
+ if (typeof cssSource.css !== "string" || cssSource.css.length === 0) return;
808
+ if (sourceFile && typeof cssSource.file === "string" && path.resolve(sourceFile) === path.resolve(cssSource.file)) return {
809
+ cssSource,
810
+ index,
811
+ score: 1e6
812
+ };
813
+ if (typeof cssSource.file === "string") {
814
+ const pathScore = scoreTailwindV4CssSourceFileMatch(file, cssSource.file, sourceOptions);
815
+ if (pathScore > 0) return {
816
+ cssSource,
817
+ index,
818
+ score: pathScore
819
+ };
820
+ }
821
+ if (normalizeCssSourceForCompare(cssSource.css) === normalizedRawSource) return {
822
+ cssSource,
823
+ index,
824
+ score: 1
825
+ };
826
+ }).filter((match) => Boolean(match)).sort((a, b) => b.score - a.score || a.index - b.index);
827
+ const bestScore = matches[0]?.score;
828
+ const matchingSource = bestScore && matches.filter((match) => match.score === bestScore).length === 1 ? matches[0]?.cssSource : void 0;
638
829
  if (!matchingSource) return;
639
830
  return resolveSingleTailwindV4CssSource(matchingSource, sourceOptions, { matched: true });
640
831
  }
@@ -706,7 +897,10 @@ function createTailwindV4CssSourceResolver(sourceOptions, generatorOptions) {
706
897
  async function resolveTailwindV4SourceSideEntrySource(resolvedEntrySource, sourceOptions, generatorOptions, file) {
707
898
  if (!resolvedEntrySource) return;
708
899
  const resolvedSourceOptions = omitUndefined(sourceOptions);
709
- const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, resolvedSourceOptions);
900
+ const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, {
901
+ ...resolvedSourceOptions,
902
+ sourceFile: resolvedEntrySource.file
903
+ });
710
904
  const css = createTailwindV4ApplyReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), resolvedSourceOptions);
711
905
  return withMatchedSourceSideMetadata(await resolveTailwindV4Source$1(createSingleTailwindV4SourceOptions(resolvedSourceOptions, {
712
906
  base: resolvedEntrySource.base,
@@ -737,7 +931,25 @@ function withMatchedSourceSideMetadata(source, resolvedEntrySource) {
737
931
  }
738
932
  function createTailwindV4ApplyReferenceSource(css, sourceOptions) {
739
933
  if (!hasTailwindApplyDirective(css) || hasTailwindRootDirectives(css)) return css;
740
- return `@import "${sourceOptions.packageName ?? "tailwindcss"}" source(none);\n${css}`;
934
+ const utilities = collectTailwindApplyUtilities(css);
935
+ return [
936
+ `@import "${sourceOptions.packageName ?? "tailwindcss"}" source(none);`,
937
+ utilities.length > 0 ? `@source inline(${JSON.stringify(utilities.join(" "))});` : void 0,
938
+ css
939
+ ].filter(Boolean).join("\n");
940
+ }
941
+ function collectTailwindApplyUtilities(css) {
942
+ let root;
943
+ try {
944
+ root = postcss.parse(css);
945
+ } catch {
946
+ return [];
947
+ }
948
+ const utilities = /* @__PURE__ */ new Set();
949
+ root.walkAtRules("apply", (rule) => {
950
+ for (const utility of splitCandidateTokens(rule.params)) utilities.add(utility);
951
+ });
952
+ return [...utilities].sort();
741
953
  }
742
954
  async function resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions) {
743
955
  const base = resolveCssSourceBase(file, cssHandlerOptions);
@@ -850,11 +1062,15 @@ async function resolveGeneratorSources(majorVersion, runtimeState, rawSource, fi
850
1062
  return resolved ? [resolved] : [];
851
1063
  }
852
1064
  const matchedCssEntrySource = sourceOptions ? await resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) : void 0;
1065
+ if (matchedCssEntrySource) return [generatorOptions?.config ? {
1066
+ ...matchedCssEntrySource,
1067
+ css: prependConfigDirective(matchedCssEntrySource.css, generatorOptions.config)
1068
+ } : matchedCssEntrySource];
1069
+ const sourceSideCssSource = await resolveTailwindV4SourceSideEntrySource((shouldResolveSourceSideCssEntry(rawSource) || Boolean(cssEntrySource?.css.includes("weapp-tailwindcss generator-placeholder")) && (sourceOptions.cssEntries?.length ?? 0) <= 1) && canResolveSourceSideCssEntry(file, cssHandlerOptions, sourceOptions) ? resolveSourceSideCssEntrySource(file, sourceOptions, { removeConfig: false }) : void 0, sourceOptions, generatorOptions, file);
1070
+ if (sourceSideCssSource) return [sourceSideCssSource];
853
1071
  const matchedCssSource = await resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, sourceOptions);
854
1072
  const candidateMatchedCssSource = await resolveCandidateMatchedTailwindV4CssSource(rawSource, cssHandlerOptions, sourceOptions, selectionOptions);
855
- const sourceSideCssSource = await resolveTailwindV4SourceSideEntrySource((shouldResolveSourceSideCssEntry(rawSource) || Boolean(cssEntrySource?.css.includes("weapp-tailwindcss generator-placeholder")) && (sourceOptions.cssEntries?.length ?? 0) <= 1) && canResolveSourceSideCssEntry(file, cssHandlerOptions, sourceOptions) ? resolveSourceSideCssEntrySource(file, sourceOptions, { removeConfig: false }) : void 0, sourceOptions, generatorOptions, file);
856
1073
  const preferredCssEntrySource = matchedCssEntrySource ?? matchedCssSource ?? candidateMatchedCssSource;
857
- if (sourceSideCssSource) return [sourceSideCssSource];
858
1074
  if (preferredCssEntrySource) return [generatorOptions?.config ? {
859
1075
  ...preferredCssEntrySource,
860
1076
  css: prependConfigDirective(preferredCssEntrySource.css, generatorOptions.config)
@@ -1032,6 +1248,27 @@ function resolveLegacyCompatCssSource(rawSource) {
1032
1248
  setLimitedCacheValue(legacyCompatSourceCache, rawSource, resolved);
1033
1249
  return resolved;
1034
1250
  }
1251
+ function removeMiniProgramContainerCompatCss(css) {
1252
+ try {
1253
+ const root = postcss.parse(css);
1254
+ let removed = false;
1255
+ root.walkRules((rule) => {
1256
+ if (rule.selectors?.length === 1 && rule.selectors[0] === ".container") {
1257
+ rule.remove();
1258
+ removed = true;
1259
+ }
1260
+ });
1261
+ root.walkAtRules((atRule) => {
1262
+ if (atRule.nodes && atRule.nodes.length === 0) {
1263
+ atRule.remove();
1264
+ removed = true;
1265
+ }
1266
+ });
1267
+ return removed ? root.toString() : css;
1268
+ } catch {
1269
+ return css;
1270
+ }
1271
+ }
1035
1272
  function hasContainerConfigToken(rawSource) {
1036
1273
  return rawSource.includes("@config") && /\bcontainer\b/.test(rawSource);
1037
1274
  }
@@ -1060,7 +1297,8 @@ function hasConfiguredContainerCompatSources(sources) {
1060
1297
  return sources.some((source) => hasConfiguredContainerCompatSource(source));
1061
1298
  }
1062
1299
  async function appendLegacyCompatCss(css, rawSource, generatorTarget, styleHandler, cssHandlerOptions, generatorStyleOptions) {
1063
- const compatSource = removeGeneratedSelectorCompatCss(resolveLegacyCompatCssSource(rawSource), css);
1300
+ const resolvedCompatSource = resolveLegacyCompatCssSource(rawSource);
1301
+ const compatSource = removeGeneratedSelectorCompatCss(generatorTarget === "weapp" ? removeMiniProgramContainerCompatCss(resolvedCompatSource) : resolvedCompatSource, css);
1064
1302
  if (compatSource.trim().length === 0) return css;
1065
1303
  if (generatorTarget !== "weapp") return createCssAppend(css, compatSource);
1066
1304
  const styleOptions = {
@@ -1078,6 +1316,7 @@ async function appendLegacyCompatCss(css, rawSource, generatorTarget, styleHandl
1078
1316
  return createCssAppend(css, cleanedCompatCss);
1079
1317
  }
1080
1318
  async function appendLegacyContainerCompatCss(css, rawSource, file, runtime, configuredContainerCompat, generatorTarget, styleHandler, cssHandlerOptions, generatorStyleOptions) {
1319
+ if (generatorTarget === "weapp") return css;
1081
1320
  const compatSource = resolveLegacyCompatCssSource(rawSource);
1082
1321
  const shouldAppendContainer = runtime.has("container") || hasConfiguredContainerCompat(rawSource, file, cssHandlerOptions) || configuredContainerCompat || collectGeneratedSelectors(compatSource).has(".container");
1083
1322
  if (generatorTarget !== "weapp" || !shouldAppendContainer || collectGeneratedSelectors(css).has(".container")) return css;
@@ -1140,152 +1379,106 @@ function inheritLegacyUnitConvertedDeclarations(css, legacyCss) {
1140
1379
  }
1141
1380
  }
1142
1381
  //#endregion
1143
- //#region src/bundlers/shared/generator-css/user-layer-order.ts
1144
- const USER_LAYER_COMPONENTS_START = "/*! weapp-tailwindcss layer components start */";
1145
- const USER_LAYER_COMPONENTS_END = "/*! weapp-tailwindcss layer components end */";
1146
- const UTILITY_LAYER_INSERTION_RES = [
1147
- /(^|\n)\.(?:fixed|absolute|relative|sticky|static)\s*\{/,
1148
- /(^|\n)\.(?:block|inline-block|inline|flex|inline-flex|grid|hidden)\s*\{/,
1149
- /(^|\n)\.(?:m|mx|my|mt|mr|mb|ml|p|px|py|pt|pr|pb|pl)-/,
1150
- /(^|\n)\.(?:w|h|min-w|min-h|max-w|max-h)-/,
1151
- /(^|\n)\.(?:bg|text|border|rounded|shadow|opacity|transition|transform|translate|scale|rotate|gap|items|justify|content)-/
1152
- ];
1153
- function appendCss(base, extra) {
1382
+ //#region src/bundlers/shared/generator-css/local-imports.ts
1383
+ const REMOTE_IMPORT_RE = /^(?:https?:)?\/\//i;
1384
+ function createCssSourceOrderAppend(base, extra) {
1154
1385
  if (!base) return extra;
1155
1386
  if (!extra) return base;
1156
1387
  if (/\s$/.test(base) || /^\s/.test(extra)) return `${base}${extra}`;
1157
1388
  return `${base}\n${extra}`;
1158
1389
  }
1159
- function removeFirstCssOccurrence(css, chunk) {
1160
- const trimmed = chunk.trim();
1161
- if (!trimmed) return css;
1162
- const index = css.indexOf(trimmed);
1163
- if (index === -1) return css;
1164
- return appendCss(css.slice(0, index).trimEnd(), css.slice(index + trimmed.length).trimStart());
1390
+ function isLocalImportRequest(request) {
1391
+ return request.length > 0 && !request.startsWith("#") && !request.startsWith("tailwindcss") && !request.startsWith("weapp-tailwindcss") && !request.startsWith("data:") && !REMOTE_IMPORT_RE.test(request);
1165
1392
  }
1166
- function collectSelectorsFromCss(css) {
1167
- const selectors = /* @__PURE__ */ new Set();
1393
+ function isPureLocalCssImportWrapper(css) {
1394
+ let hasImport = false;
1168
1395
  try {
1169
- postcss.parse(css).walkRules((rule) => {
1170
- for (const selector of rule.selectors ?? [rule.selector]) {
1171
- const normalized = selector.trim();
1172
- if (normalized) selectors.add(normalized);
1173
- }
1174
- });
1175
- } catch {}
1176
- return selectors;
1396
+ const root = postcss.parse(css);
1397
+ for (const node of root.nodes) {
1398
+ if (node.type === "comment") continue;
1399
+ if (node.type !== "atrule" || node.name !== "import") return false;
1400
+ const request = parseImportRequest(node.params);
1401
+ if (!request || !isLocalImportRequest(request)) return false;
1402
+ hasImport = true;
1403
+ }
1404
+ } catch {
1405
+ return false;
1406
+ }
1407
+ return hasImport;
1177
1408
  }
1178
- function matchesLayerSelector(selector, layerSelector) {
1179
- if (selector === layerSelector) return true;
1180
- if (!selector.startsWith(layerSelector)) return false;
1181
- const next = selector[layerSelector.length];
1182
- return next === ":" || next === "[";
1409
+ function cleanLocalCssImportWrapperTailwindDirectives(css) {
1410
+ let hasLocalImport = false;
1411
+ let hasTailwindDirective = false;
1412
+ try {
1413
+ const root = postcss.parse(css);
1414
+ for (const node of root.nodes) {
1415
+ if (node.type === "comment") continue;
1416
+ if (node.type === "atrule" && node.name === "import") {
1417
+ const request = parseImportRequest(node.params);
1418
+ if (!request || !isLocalImportRequest(request)) return;
1419
+ hasLocalImport = true;
1420
+ continue;
1421
+ }
1422
+ if (node.type === "atrule" && node.name === "source") {
1423
+ hasTailwindDirective = true;
1424
+ continue;
1425
+ }
1426
+ return;
1427
+ }
1428
+ } catch {
1429
+ return;
1430
+ }
1431
+ return hasLocalImport && hasTailwindDirective ? prefixLocalCssImportsWithWebpackIgnore(removeTailwindSourceDirectives(css)) : void 0;
1183
1432
  }
1184
- function removeCssRulesForSelectors(css, layerCss) {
1185
- const selectors = [...collectSelectorsFromCss(layerCss)];
1186
- if (selectors.length === 0) return css;
1433
+ function prefixLocalCssImportsWithWebpackIgnore(css) {
1187
1434
  try {
1188
1435
  const root = postcss.parse(css);
1189
- root.walkRules((rule) => {
1190
- if ((rule.selectors ?? [rule.selector]).some((selector) => selectors.some((layerSelector) => matchesLayerSelector(selector.trim(), layerSelector)))) rule.remove();
1436
+ root.walkAtRules("import", (atRule) => {
1437
+ const request = parseImportRequest(atRule.params);
1438
+ if (request && isLocalImportRequest(request)) atRule.raws.before = `${atRule.raws.before ?? ""}/* webpackIgnore: true */\n`;
1191
1439
  });
1192
1440
  return root.toString();
1193
1441
  } catch {
1194
- return removeFirstCssOccurrence(css, layerCss);
1442
+ return css;
1195
1443
  }
1196
1444
  }
1197
- function wrapUserLayerComponentsCss(css) {
1198
- return css.trim().length > 0 ? `${USER_LAYER_COMPONENTS_START}\n${css}\n${USER_LAYER_COMPONENTS_END}` : css;
1199
- }
1200
- function extractMarkedUserLayerComponentsCss(css) {
1201
- const layers = [];
1202
- let rest = "";
1203
- let cursor = 0;
1204
- while (cursor < css.length) {
1205
- const startIndex = css.indexOf(USER_LAYER_COMPONENTS_START, cursor);
1206
- if (startIndex === -1) {
1207
- rest += css.slice(cursor);
1208
- break;
1445
+ function splitLocalCssImports(source) {
1446
+ try {
1447
+ const root = postcss.parse(source);
1448
+ const importRoot = postcss.root();
1449
+ let changed = false;
1450
+ for (const node of [...root.nodes]) {
1451
+ if (node.type !== "atrule" || node.name !== "import") continue;
1452
+ const request = parseImportRequest(node.params);
1453
+ if (!request || !isLocalImportRequest(request)) continue;
1454
+ importRoot.append(node.clone());
1455
+ node.remove();
1456
+ changed = true;
1209
1457
  }
1210
- rest += css.slice(cursor, startIndex);
1211
- const contentStart = startIndex + 47;
1212
- const endIndex = css.indexOf(USER_LAYER_COMPONENTS_END, contentStart);
1213
- if (endIndex === -1) {
1214
- rest += css.slice(startIndex);
1215
- break;
1216
- }
1217
- const layerCss = css.slice(contentStart, endIndex).trim();
1218
- if (layerCss) layers.push(layerCss);
1219
- cursor = endIndex + 45;
1220
- }
1221
- return {
1222
- layers,
1223
- rest
1224
- };
1225
- }
1226
- function findUtilityLayerInsertionIndex(css) {
1227
- let index = -1;
1228
- for (const pattern of UTILITY_LAYER_INSERTION_RES) {
1229
- const match = pattern.exec(css);
1230
- if (!match) continue;
1231
- const nextIndex = match.index + (match[1]?.length ?? 0);
1232
- index = index === -1 ? nextIndex : Math.min(index, nextIndex);
1458
+ const imports = importRoot.nodes.filter((node) => node.type === "atrule" && node.name === "import").map((node) => `@import ${node.params};`).join("\n");
1459
+ return changed ? {
1460
+ imports,
1461
+ source: root.toString()
1462
+ } : void 0;
1463
+ } catch {
1464
+ return;
1233
1465
  }
1234
- return index;
1235
- }
1236
- function reorderMarkedUserLayerComponentsCss(css) {
1237
- if (!css.includes(USER_LAYER_COMPONENTS_START)) return css;
1238
- const { layers, rest } = extractMarkedUserLayerComponentsCss(css);
1239
- if (layers.length === 0) return rest;
1240
- const layerCss = layers.join("\n");
1241
- const insertionIndex = findUtilityLayerInsertionIndex(rest);
1242
- if (insertionIndex === -1) return appendCss(rest, layerCss);
1243
- return appendCss(appendCss(rest.slice(0, insertionIndex), layerCss), rest.slice(insertionIndex));
1244
1466
  }
1245
- function mergeMarkedUserLayerComponentsCss(baseCss, markedCss) {
1246
- if (!markedCss.includes(USER_LAYER_COMPONENTS_START)) return {
1247
- css: baseCss,
1248
- merged: false
1249
- };
1250
- const { layers } = extractMarkedUserLayerComponentsCss(markedCss);
1251
- if (layers.length === 0) return {
1252
- css: baseCss,
1253
- merged: false
1254
- };
1255
- const layerCss = layers.join("\n");
1256
- return {
1257
- css: reorderMarkedUserLayerComponentsCss(appendCss(removeCssRulesForSelectors(baseCss, layerCss), wrapUserLayerComponentsCss(layerCss))),
1258
- merged: true
1259
- };
1467
+ function restoreLocalCssImports(css, imports) {
1468
+ if (!imports?.trim()) return css;
1469
+ return createCssSourceOrderAppend(imports, css);
1260
1470
  }
1261
1471
  //#endregion
1262
- //#region src/bundlers/shared/generator-css.ts
1263
- const SUPPORTED_GENERATOR_MAJOR_VERSIONS = new Set([3, 4]);
1264
- const REMOTE_IMPORT_RE = /^(?:https?:)?\/\//i;
1265
- function finalizeMiniProgramGeneratorCss(css, target, majorVersion, cssPreflight, options = {}) {
1266
- if (target !== "weapp") return css;
1267
- return finalizeMiniProgramCss(css, {
1268
- cssPreflight: majorVersion === 4 && options.injectPreflight !== false ? cssPreflight : void 0,
1269
- isTailwindcssV4: majorVersion === 4,
1270
- preservePseudoContentInit: majorVersion === 3
1271
- });
1272
- }
1273
- function shouldInjectMiniProgramPreflightForGeneratorCss(opts, options) {
1274
- if (options.cssHandlerOptions.uniAppX === true && options.cssHandlerOptions.uniAppXCssTarget === "uvue") return false;
1275
- if (!options.isolateCurrentCssCandidates) return true;
1276
- return isUniAppXEnabled(opts.uniAppX) && Boolean(options.localImports?.trim());
1277
- }
1278
- function mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtime, options) {
1279
- if (options.isolateCssSource && options.currentCssCandidates?.length) return new Set([...scopedRuntime, ...options.currentCssCandidates]);
1280
- if (runtime.size === 0 || !options.cssHandlerOptions.isMainChunk || options.matchedCssSourceFile || options.isolateCssSource && scopedRuntime.size === 0) return scopedRuntime;
1281
- return new Set([...scopedRuntime, ...runtime]);
1282
- }
1283
- function shouldIsolateScopedCssSource(source, sourceEntries) {
1284
- return Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile) || sourceEntries !== void 0 && sourceEntries.length > 0;
1285
- }
1286
- function shouldIsolateCurrentTailwindV4CssCandidates(majorVersion, cssHandlerOptions, options) {
1287
- return majorVersion === 4 && !cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(options.rawSource) && !hasTailwindRootDirectives(options.rawSource) && !options.hasGeneratedCss && !options.hasGeneratedMarkers;
1288
- }
1472
+ //#region src/bundlers/shared/generator-css/user-css.ts
1473
+ const TAILWIND_V4_GENERATOR_AT_RULES = new Set([
1474
+ "config",
1475
+ "custom-variant",
1476
+ "plugin",
1477
+ "source",
1478
+ "theme",
1479
+ "utility",
1480
+ "variant"
1481
+ ]);
1289
1482
  function removeTailwindApplyAtRules(source) {
1290
1483
  if (!source.includes("@apply")) return source;
1291
1484
  try {
@@ -1303,33 +1496,25 @@ function removeTailwindApplyAtRules(source) {
1303
1496
  return source;
1304
1497
  }
1305
1498
  }
1306
- function shouldScanTailwindV4Sources(majorVersion, target, generatorRuntime, isolateCssSource) {
1307
- if (majorVersion !== 4 || isolateCssSource) return false;
1308
- return target === "web" || generatorRuntime.size === 0;
1309
- }
1310
- function shouldAppendWebBundleCssFallback(target, options) {
1311
- return target === "web" && !options.hasMatchedCssSourceFile && !options.hasSourceDirectives;
1312
- }
1313
- function isEmptyCssSourceOrderParts(parts) {
1314
- return parts.before.trim().length === 0 && parts.after.trim().length === 0;
1315
- }
1316
- function resolveGeneratorStyleOptions(opts, cssHandlerOptions, generatorStyleOptions) {
1317
- const preflightStyleOptions = {
1318
- cssPreflight: opts.cssPreflight,
1319
- cssPreflightRange: opts.cssPreflightRange
1320
- };
1321
- return {
1322
- ...resolveStyleOptionsFromContext(opts),
1323
- atRules: opts.atRules,
1324
- uniAppXCssTarget: opts.uniAppXCssTarget,
1325
- uniAppXUnsupported: opts.uniAppXUnsupported,
1326
- ...cssHandlerOptions,
1327
- ...preflightStyleOptions,
1328
- ...generatorStyleOptions
1329
- };
1330
- }
1331
- function isLocalImportRequest(request) {
1332
- return request.length > 0 && !request.startsWith("#") && !request.startsWith("tailwindcss") && !request.startsWith("weapp-tailwindcss") && !request.startsWith("data:") && !REMOTE_IMPORT_RE.test(request);
1499
+ function removeTailwindV4GeneratorAtRules(source) {
1500
+ try {
1501
+ const root = postcss.parse(source);
1502
+ let changed = false;
1503
+ root.walkAtRules((rule) => {
1504
+ if (!TAILWIND_V4_GENERATOR_AT_RULES.has(rule.name)) return;
1505
+ rule.remove();
1506
+ changed = true;
1507
+ });
1508
+ root.walk((node) => {
1509
+ if ("nodes" in node && node.nodes?.length === 0) {
1510
+ node.remove();
1511
+ changed = true;
1512
+ }
1513
+ });
1514
+ return changed ? root.toString() : source;
1515
+ } catch {
1516
+ return source;
1517
+ }
1333
1518
  }
1334
1519
  function isCommentOnlyCss(source) {
1335
1520
  try {
@@ -1340,7 +1525,19 @@ function isCommentOnlyCss(source) {
1340
1525
  }
1341
1526
  }
1342
1527
  function stripTailwindSourceMediaFragments(source) {
1343
- return source.replace(/^\s*@media\s+source\([^)]*\)\s*\{\s*$/gm, "").replace(/^\s*\}\s*(?=@(?:source|theme|config|plugin|utility|variant|custom-variant)\b)/gm, "").replace(/^\s*\}\s*\/\*\s*source\([^)]*\)\s*\*\/\s*$/gm, "");
1528
+ let removedSourceMediaStart = false;
1529
+ return source.split(/\r?\n/).filter((line) => {
1530
+ if (/^\s*@media\s+source\([^)]*\)\s*\{\s*$/.test(line)) {
1531
+ removedSourceMediaStart = true;
1532
+ return false;
1533
+ }
1534
+ if (/^\s*\}\s*\/\*\s*source\([^)]*\)\s*\*\/\s*$/.test(line)) return false;
1535
+ if (removedSourceMediaStart && /^\s*\}\s*$/.test(line)) {
1536
+ removedSourceMediaStart = false;
1537
+ return false;
1538
+ }
1539
+ return true;
1540
+ }).join("\n").replace(/\}[^\S\r\n]*(?=@(?:config|source)\b)/g, "");
1344
1541
  }
1345
1542
  function stripLeadingTailwindSourceMediaCloseFragment(source) {
1346
1543
  return source.replace(/^\s*\}\s*(?:\n|$)/, "");
@@ -1353,22 +1550,6 @@ function stripUnmatchedTailwindSourceMediaCloseFragments(source) {
1353
1550
  return stripLeadingTailwindSourceMediaCloseFragment(source).replace(/\s*\}\s*$/, "");
1354
1551
  }
1355
1552
  }
1356
- function createCssSourceOrderAppend(base, extra) {
1357
- if (!base) return extra;
1358
- if (!extra) return base;
1359
- if (/\s$/.test(base) || /^\s/.test(extra)) return `${base}${extra}`;
1360
- return `${base}\n${extra}`;
1361
- }
1362
- function shouldFinalizeMarkedUserLayerComponentsCss(file) {
1363
- return !/\.(?:vue|svelte|astro|scss|sass|less|styl)(?:[?#].*)?$/i.test(file);
1364
- }
1365
- function splitRawSourceByGeneratedCssOrder(rawSource, rawTailwindCss) {
1366
- const placeholderParts = splitGeneratorPlaceholderCssBySourceOrder(rawSource, rawTailwindCss);
1367
- if (placeholderParts) return placeholderParts;
1368
- const exactParts = splitTailwindV4GeneratedCssBySourceOrder(rawSource, rawTailwindCss);
1369
- if (exactParts) return exactParts;
1370
- return splitTailwindGeneratedCssByBanner(rawSource);
1371
- }
1372
1553
  function splitUserCssLayerBlocks(source) {
1373
1554
  if (!source.includes("@layer")) return {
1374
1555
  layer: "",
@@ -1508,7 +1689,7 @@ function shouldFilterApplyOnlyGeneratedCss(majorVersion, target, source, options
1508
1689
  }
1509
1690
  async function transformGeneratorUserCss(source, options) {
1510
1691
  if (source.trim().length === 0) return "";
1511
- const cleanedSource = removeTailwindSourceDirectives(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(source)), { importFallback: options.importFallback });
1692
+ const cleanedSource = removeTailwindSourceDirectives(removeTailwindV4GeneratorAtRules(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(source))), { importFallback: options.importFallback });
1512
1693
  if (cleanedSource.trim().length === 0) return "";
1513
1694
  const userSource = stripUnmatchedTailwindSourceMediaCloseFragments(removeTailwindApplyAtRules(removeTailwindSourceDirectives(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(options.generatorTarget === "weapp" ? removeUnsupportedMiniProgramAtRules(cleanedSource) : cleanedSource)), { importFallback: options.importFallback })));
1514
1695
  if (userSource.trim().length === 0) return "";
@@ -1520,84 +1701,157 @@ async function transformGeneratorUserCss(source, options) {
1520
1701
  });
1521
1702
  return removeUnsupportedMiniProgramAtRules(css);
1522
1703
  }
1523
- function isPureLocalCssImportWrapper(css) {
1524
- let hasImport = false;
1525
- try {
1526
- const root = postcss.parse(css);
1527
- for (const node of root.nodes) {
1528
- if (node.type === "comment") continue;
1529
- if (node.type !== "atrule" || node.name !== "import") return false;
1530
- const request = parseImportRequest(node.params);
1531
- if (!request || !isLocalImportRequest(request)) return false;
1532
- hasImport = true;
1533
- }
1534
- } catch {
1535
- return false;
1536
- }
1537
- return hasImport;
1704
+ //#endregion
1705
+ //#region src/bundlers/shared/generator-css/user-layer-order.ts
1706
+ const USER_LAYER_COMPONENTS_START = "/*! weapp-tailwindcss layer components start */";
1707
+ const USER_LAYER_COMPONENTS_END = "/*! weapp-tailwindcss layer components end */";
1708
+ const UTILITY_LAYER_INSERTION_RES = [
1709
+ /(^|\n)\.(?:fixed|absolute|relative|sticky|static)\s*\{/,
1710
+ /(^|\n)\.(?:block|inline-block|inline|flex|inline-flex|grid|hidden)\s*\{/,
1711
+ /(^|\n)\.(?:m|mx|my|mt|mr|mb|ml|p|px|py|pt|pr|pb|pl)-/,
1712
+ /(^|\n)\.(?:w|h|min-w|min-h|max-w|max-h)-/,
1713
+ /(^|\n)\.(?:bg|text|border|rounded|shadow|opacity|transition|transform|translate|scale|rotate|gap|items|justify|content)-/
1714
+ ];
1715
+ function appendCss(base, extra) {
1716
+ if (!base) return extra;
1717
+ if (!extra) return base;
1718
+ if (/\s$/.test(base) || /^\s/.test(extra)) return `${base}${extra}`;
1719
+ return `${base}\n${extra}`;
1538
1720
  }
1539
- function cleanLocalCssImportWrapperTailwindDirectives(css) {
1540
- let hasLocalImport = false;
1541
- let hasTailwindDirective = false;
1721
+ function removeFirstCssOccurrence(css, chunk) {
1722
+ const trimmed = chunk.trim();
1723
+ if (!trimmed) return css;
1724
+ const index = css.indexOf(trimmed);
1725
+ if (index === -1) return css;
1726
+ return appendCss(css.slice(0, index).trimEnd(), css.slice(index + trimmed.length).trimStart());
1727
+ }
1728
+ function collectSelectorsFromCss(css) {
1729
+ const selectors = /* @__PURE__ */ new Set();
1542
1730
  try {
1543
- const root = postcss.parse(css);
1544
- for (const node of root.nodes) {
1545
- if (node.type === "comment") continue;
1546
- if (node.type === "atrule" && node.name === "import") {
1547
- const request = parseImportRequest(node.params);
1548
- if (!request || !isLocalImportRequest(request)) return;
1549
- hasLocalImport = true;
1550
- continue;
1551
- }
1552
- if (node.type === "atrule" && node.name === "source") {
1553
- hasTailwindDirective = true;
1554
- continue;
1731
+ postcss.parse(css).walkRules((rule) => {
1732
+ for (const selector of rule.selectors ?? [rule.selector]) {
1733
+ const normalized = selector.trim();
1734
+ if (normalized) selectors.add(normalized);
1555
1735
  }
1556
- return;
1557
- }
1558
- } catch {
1559
- return;
1560
- }
1561
- return hasLocalImport && hasTailwindDirective ? prefixLocalCssImportsWithWebpackIgnore(removeTailwindSourceDirectives(css)) : void 0;
1736
+ });
1737
+ } catch {}
1738
+ return selectors;
1562
1739
  }
1563
- function prefixLocalCssImportsWithWebpackIgnore(css) {
1740
+ function matchesLayerSelector(selector, layerSelector) {
1741
+ if (selector === layerSelector) return true;
1742
+ if (!selector.startsWith(layerSelector)) return false;
1743
+ const next = selector[layerSelector.length];
1744
+ return next === ":" || next === "[";
1745
+ }
1746
+ function removeCssRulesForSelectors(css, layerCss) {
1747
+ const selectors = [...collectSelectorsFromCss(layerCss)];
1748
+ if (selectors.length === 0) return css;
1564
1749
  try {
1565
1750
  const root = postcss.parse(css);
1566
- root.walkAtRules("import", (atRule) => {
1567
- const request = parseImportRequest(atRule.params);
1568
- if (request && isLocalImportRequest(request)) atRule.raws.before = `${atRule.raws.before ?? ""}/* webpackIgnore: true */\n`;
1751
+ root.walkRules((rule) => {
1752
+ if ((rule.selectors ?? [rule.selector]).some((selector) => selectors.some((layerSelector) => matchesLayerSelector(selector.trim(), layerSelector)))) rule.remove();
1569
1753
  });
1570
1754
  return root.toString();
1571
1755
  } catch {
1572
- return css;
1756
+ return removeFirstCssOccurrence(css, layerCss);
1573
1757
  }
1574
1758
  }
1575
- function splitLocalCssImports(source) {
1576
- try {
1577
- const root = postcss.parse(source);
1578
- const importRoot = postcss.root();
1579
- let changed = false;
1580
- for (const node of [...root.nodes]) {
1581
- if (node.type !== "atrule" || node.name !== "import") continue;
1582
- const request = parseImportRequest(node.params);
1583
- if (!request || !isLocalImportRequest(request)) continue;
1584
- importRoot.append(node.clone());
1585
- node.remove();
1586
- changed = true;
1759
+ function wrapUserLayerComponentsCss(css) {
1760
+ return css.trim().length > 0 ? `${USER_LAYER_COMPONENTS_START}\n${css}\n${USER_LAYER_COMPONENTS_END}` : css;
1761
+ }
1762
+ function extractMarkedUserLayerComponentsCss(css) {
1763
+ const layers = [];
1764
+ let rest = "";
1765
+ let cursor = 0;
1766
+ while (cursor < css.length) {
1767
+ const startIndex = css.indexOf(USER_LAYER_COMPONENTS_START, cursor);
1768
+ if (startIndex === -1) {
1769
+ rest += css.slice(cursor);
1770
+ break;
1587
1771
  }
1588
- const imports = importRoot.nodes.filter((node) => node.type === "atrule" && node.name === "import").map((node) => `@import ${node.params};`).join("\n");
1589
- return changed ? {
1590
- imports,
1591
- source: root.toString()
1592
- } : void 0;
1593
- } catch {
1594
- return;
1772
+ rest += css.slice(cursor, startIndex);
1773
+ const contentStart = startIndex + 47;
1774
+ const endIndex = css.indexOf(USER_LAYER_COMPONENTS_END, contentStart);
1775
+ if (endIndex === -1) {
1776
+ rest += css.slice(startIndex);
1777
+ break;
1778
+ }
1779
+ const layerCss = css.slice(contentStart, endIndex).trim();
1780
+ if (layerCss) layers.push(layerCss);
1781
+ cursor = endIndex + 45;
1595
1782
  }
1783
+ return {
1784
+ layers,
1785
+ rest
1786
+ };
1596
1787
  }
1597
- function restoreLocalCssImports(css, imports) {
1598
- if (!imports?.trim()) return css;
1599
- return createCssSourceOrderAppend(imports, css);
1788
+ function findUtilityLayerInsertionIndex(css) {
1789
+ let index = -1;
1790
+ for (const pattern of UTILITY_LAYER_INSERTION_RES) {
1791
+ const match = pattern.exec(css);
1792
+ if (!match) continue;
1793
+ const nextIndex = match.index + (match[1]?.length ?? 0);
1794
+ index = index === -1 ? nextIndex : Math.min(index, nextIndex);
1795
+ }
1796
+ return index;
1600
1797
  }
1798
+ function reorderMarkedUserLayerComponentsCss(css) {
1799
+ if (!css.includes(USER_LAYER_COMPONENTS_START)) return css;
1800
+ const { layers, rest } = extractMarkedUserLayerComponentsCss(css);
1801
+ if (layers.length === 0) return rest;
1802
+ const layerCss = layers.join("\n");
1803
+ const insertionIndex = findUtilityLayerInsertionIndex(rest);
1804
+ if (insertionIndex === -1) return appendCss(rest, layerCss);
1805
+ return appendCss(appendCss(rest.slice(0, insertionIndex), layerCss), rest.slice(insertionIndex));
1806
+ }
1807
+ function mergeMarkedUserLayerComponentsCss(baseCss, markedCss) {
1808
+ if (!markedCss.includes(USER_LAYER_COMPONENTS_START)) return {
1809
+ css: baseCss,
1810
+ merged: false
1811
+ };
1812
+ const { layers } = extractMarkedUserLayerComponentsCss(markedCss);
1813
+ if (layers.length === 0) return {
1814
+ css: baseCss,
1815
+ merged: false
1816
+ };
1817
+ const layerCss = layers.join("\n");
1818
+ return {
1819
+ css: reorderMarkedUserLayerComponentsCss(appendCss(removeCssRulesForSelectors(baseCss, layerCss), wrapUserLayerComponentsCss(layerCss))),
1820
+ merged: true
1821
+ };
1822
+ }
1823
+ //#endregion
1824
+ //#region src/bundlers/shared/generator-css/validate.ts
1825
+ const SUPPORTED_GENERATOR_MAJOR_VERSIONS = new Set([3, 4]);
1826
+ async function validateCandidatesByGenerator(options) {
1827
+ const { candidates, cssHandlerOptions, debug, file, opts, rawSource, runtimeState } = options;
1828
+ const majorVersion = runtimeState.twPatcher.majorVersion;
1829
+ if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || candidates.size === 0) return /* @__PURE__ */ new Set();
1830
+ const generatorOptions = {
1831
+ ...normalizeWeappTailwindcssGeneratorOptions(opts.generator),
1832
+ bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues
1833
+ };
1834
+ const sources = await resolveGeneratorSources(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, {
1835
+ cssEntries: opts.cssEntries,
1836
+ runtime: candidates
1837
+ });
1838
+ const classSets = await Promise.all(sources.map(async (source) => {
1839
+ const generator = createWeappTailwindcssGenerator(source);
1840
+ if (generatorOptions.bareArbitraryValues === void 0 || generatorOptions.bareArbitraryValues === false) {
1841
+ if (typeof generator.validateCandidates === "function") return generator.validateCandidates(candidates);
1842
+ }
1843
+ return (await generator.generate({
1844
+ bareArbitraryValues: generatorOptions.bareArbitraryValues,
1845
+ candidates,
1846
+ target: "tailwind"
1847
+ })).classSet;
1848
+ }));
1849
+ const classSet = new Set(classSets.flatMap((item) => [...item]));
1850
+ debug("tailwind generator validated candidates: %s candidates=%d classSet=%d", file, candidates.size, classSet.size);
1851
+ return classSet;
1852
+ }
1853
+ //#endregion
1854
+ //#region src/bundlers/shared/generator-css.ts
1601
1855
  async function generateCssByGenerator(options) {
1602
1856
  const { opts, runtimeState, runtime, rawSource, file, cssHandlerOptions, cssUserHandlerOptions, getSourceCandidatesForEntries, styleHandler, debug } = options;
1603
1857
  const generatorOptions = {
@@ -1608,6 +1862,7 @@ async function generateCssByGenerator(options) {
1608
1862
  const effectiveRawSource = stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(normalizeTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })));
1609
1863
  const localImportParts = splitLocalCssImports(effectiveRawSource);
1610
1864
  const generatorRawSource = localImportParts?.source ?? effectiveRawSource;
1865
+ const userCssRawSource = majorVersion === 4 ? removeTailwindV4GeneratorAtRules(generatorRawSource) : generatorRawSource;
1611
1866
  const cleanedLocalImportWrapper = cleanLocalCssImportWrapperTailwindDirectives(effectiveRawSource);
1612
1867
  if (cleanedLocalImportWrapper !== void 0) return {
1613
1868
  css: generatorOptions.target === "weapp" ? removeUnsupportedMiniProgramAtRules(cleanedLocalImportWrapper) : cleanedLocalImportWrapper,
@@ -1619,8 +1874,13 @@ async function generateCssByGenerator(options) {
1619
1874
  const hasGeneratedCss = hasTailwindGeneratedCss(generatorRawSource);
1620
1875
  const hasSourceDirectives = hasTailwindSourceDirectives(generatorRawSource, { importFallback: generatorOptions.importFallback });
1621
1876
  const hasGeneratedMarkers = hasTailwindGeneratedCssMarkers(generatorRawSource);
1622
- const shouldGenerateCurrentCss = hasGeneratedCss || hasGeneratedMarkers || hasSourceDirectives || cssHandlerOptions.isMainChunk;
1623
- if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || !shouldGenerateCurrentCss || majorVersion === 3 && !hasSourceDirectives && !hasGeneratedCss && !hasGeneratedMarkers) return;
1877
+ const shouldGenerateCurrentCss = shouldUseGeneratorForCurrentCss(majorVersion, cssHandlerOptions, {
1878
+ hasGeneratedCss,
1879
+ hasGeneratedMarkers,
1880
+ hasSourceDirectives,
1881
+ rawSource: generatorRawSource
1882
+ });
1883
+ if (!isSupportedGeneratorMajorVersion(majorVersion) || !shouldGenerateCurrentCss || majorVersion === 3 && !hasSourceDirectives && !hasGeneratedCss && !hasGeneratedMarkers) return;
1624
1884
  try {
1625
1885
  await runtimeState.readyPromise;
1626
1886
  const currentCssCandidates = majorVersion === 4 ? await extractSourceCandidates(generatorRawSource, "css", { ...generatorOptions.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: generatorOptions.bareArbitraryValues } }) : [];
@@ -1629,7 +1889,7 @@ async function generateCssByGenerator(options) {
1629
1889
  hasGeneratedMarkers,
1630
1890
  rawSource: generatorRawSource
1631
1891
  });
1632
- const runtimeWithCurrentCss = isolateCurrentCssCandidates ? new Set(currentCssCandidates) : currentCssCandidates.length > 0 ? new Set([...runtime, ...currentCssCandidates]) : runtime;
1892
+ const runtimeWithCurrentCss = createRuntimeWithCurrentCssCandidates(runtime, currentCssCandidates, isolateCurrentCssCandidates);
1633
1893
  const sources = await resolveGeneratorSources(majorVersion, runtimeState, generatorRawSource, file, cssHandlerOptions, generatorOptions, {
1634
1894
  cssEntries: opts.cssEntries,
1635
1895
  getSourceCandidatesForEntries,
@@ -1637,12 +1897,13 @@ async function generateCssByGenerator(options) {
1637
1897
  });
1638
1898
  const generatorStyleOptions = resolveGeneratorStyleOptions(opts, cssHandlerOptions, generatorOptions.styleOptions);
1639
1899
  const configuredContainerCompat = hasConfiguredContainerCompatSources(sources);
1640
- const generatedResults = (await Promise.all(sources.map(async (source) => {
1900
+ const generated = mergeGeneratorResults((await Promise.all(sources.map(async (source) => {
1641
1901
  const generator = createWeappTailwindcssGenerator(source);
1642
1902
  const sourceEntries = getSourceCandidatesForEntries && (majorVersion === 3 || majorVersion === 4) ? await resolveGeneratorSourceEntries(source, runtimeState) : void 0;
1643
1903
  const scopedRuntime = sourceEntries ? getSourceCandidatesForEntries?.(sourceEntries) : void 0;
1644
1904
  const isolateCssSource = shouldIsolateScopedCssSource(source, sourceEntries);
1645
- const matchedCssSourceFile = Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile);
1905
+ const sourceMetadata = source.__weappTailwindcssMeta;
1906
+ const matchedCssSourceFile = Boolean(sourceMetadata?.matchedCssSourceFile);
1646
1907
  if (options.deferEmptyScopedCssSource && isolateCssSource && scopedRuntime?.size === 0 && currentCssCandidates.length === 0 && !cssHandlerOptions.isMainChunk) {
1647
1908
  debug("defer empty scoped css source generation: %s", file);
1648
1909
  return;
@@ -1664,21 +1925,8 @@ async function generateCssByGenerator(options) {
1664
1925
  tailwindcssV3Compatibility: generatorOptions.tailwindcssV3Compatibility,
1665
1926
  target: generatorOptions.target
1666
1927
  });
1667
- }))).filter((item) => Boolean(item));
1668
- const firstGenerated = generatedResults[0];
1669
- if (!firstGenerated) return;
1670
- const incrementalCssResults = generatedResults.map((item) => item.incrementalCss).filter((css) => typeof css === "string");
1671
- const incrementalRawCssResults = generatedResults.map((item) => item.incrementalRawCss).filter((css) => typeof css === "string");
1672
- const generated = generatedResults.length === 1 ? firstGenerated : {
1673
- ...firstGenerated,
1674
- css: generatedResults.map((item) => item.css).join("\n"),
1675
- rawCss: generatedResults.map((item) => item.rawCss).join("\n"),
1676
- incrementalCss: incrementalCssResults.length === generatedResults.length ? incrementalCssResults.filter(Boolean).join("\n") : void 0,
1677
- incrementalRawCss: incrementalRawCssResults.length === generatedResults.length ? incrementalRawCssResults.filter(Boolean).join("\n") : void 0,
1678
- classSet: new Set(generatedResults.flatMap((item) => [...item.classSet])),
1679
- dependencies: [...new Set(generatedResults.flatMap((item) => item.dependencies))],
1680
- sources: generatedResults.flatMap((item) => item.sources)
1681
- };
1928
+ }))).filter((item) => Boolean(item)));
1929
+ if (!generated) return;
1682
1930
  debug("tailwind generator result: %s rawBytes=%d cssBytes=%d candidates=%d", file, generated.rawCss.length, generated.css.length, generated.classSet.size);
1683
1931
  if ((generated.target !== "weapp" || !hasUserCssLayerBlocks(generatorRawSource)) && typeof options.previousCss === "string" && typeof generated.incrementalCss === "string") {
1684
1932
  const incrementalCss = stripTailwindBanner(generated.incrementalCss);
@@ -1696,7 +1944,7 @@ async function generateCssByGenerator(options) {
1696
1944
  });
1697
1945
  const generatedCss = shouldFilterApplyOnlyCss ? filterApplyOnlyGeneratedCss(stripTailwindBanner(generated.css), generatorRawSource) : stripTailwindBanner(generated.css);
1698
1946
  const hasMatchedCssSourceFile = sources.some((source) => source.__weappTailwindcssMeta?.matchedCssSourceFile);
1699
- const orderedExtraCss = hasMatchedCssSourceFile ? splitTailwindV4GeneratedCssBySourceOrder(generatorRawSource, generated.rawCss) : splitRawSourceByGeneratedCssOrder(generatorRawSource, generated.rawCss);
1947
+ const orderedExtraCss = hasMatchedCssSourceFile ? splitTailwindV4GeneratedCssBySourceOrder(userCssRawSource, generated.rawCss) : splitRawSourceByGeneratedCssOrder(userCssRawSource, generated.rawCss);
1700
1948
  const shouldAppendMatchedCssSourceCompat = !hasMatchedCssSourceFile || orderedExtraCss !== void 0;
1701
1949
  if (orderedExtraCss) {
1702
1950
  let css = generatedCss;
@@ -1715,19 +1963,19 @@ async function generateCssByGenerator(options) {
1715
1963
  const beforeUserCss = await transformGeneratorUserCss(orderedExtraCss.before, userCssOptions);
1716
1964
  const afterLayerUserCss = await transformGeneratorUserCss(afterLayerParts.layer, userCssOptions);
1717
1965
  const afterUserCss = await transformGeneratorUserCss(afterLayerParts.rest, userCssOptions);
1718
- css = createCssSourceOrderAppend(createCssSourceOrderAppend(createCssSourceOrderAppend(beforeUserCss, generated.target === "weapp" ? wrapUserLayerComponentsCss(afterLayerUserCss) : afterLayerUserCss), css), afterUserCss);
1966
+ css = createCssSourceOrderAppend$1(createCssSourceOrderAppend$1(createCssSourceOrderAppend$1(beforeUserCss, generated.target === "weapp" ? wrapUserLayerComponentsCss(afterLayerUserCss) : afterLayerUserCss), css), afterUserCss);
1719
1967
  if (isEmptyCssSourceOrderParts(orderedExtraCss) && shouldAppendWebBundleCssFallback(generated.target, {
1720
1968
  hasSourceDirectives,
1721
1969
  hasMatchedCssSourceFile
1722
1970
  })) {
1723
- const userCss = await transformGeneratorUserCss(generatorRawSource, userCssOptions);
1724
- css = createCssSourceOrderAppend(css, userCss);
1971
+ const userCss = await transformGeneratorUserCss(userCssRawSource, userCssOptions);
1972
+ css = createCssSourceOrderAppend$1(css, userCss);
1725
1973
  }
1726
1974
  if (generated.target === "weapp" && shouldAppendMatchedCssSourceCompat) {
1727
1975
  if (shouldFinalizeMarkedUserLayerComponentsCss(file)) css = reorderMarkedUserLayerComponentsCss(css);
1728
1976
  if (!shouldFilterApplyOnlyCss) {
1729
- css = await appendLegacyCompatCss(css, generatorRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1730
- if (!isolateCurrentCssCandidates) css = await appendLegacyContainerCompatCss(css, generatorRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1977
+ css = await appendLegacyCompatCss(css, userCssRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1978
+ if (!isolateCurrentCssCandidates) css = await appendLegacyContainerCompatCss(css, userCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1731
1979
  }
1732
1980
  } else if (generated.target === "weapp" && shouldFinalizeMarkedUserLayerComponentsCss(file)) css = reorderMarkedUserLayerComponentsCss(css);
1733
1981
  return {
@@ -1759,37 +2007,37 @@ async function generateCssByGenerator(options) {
1759
2007
  rest: css
1760
2008
  } : extractGeneratedCssForUserLayerSelectors(css, layerParts.layer);
1761
2009
  if (layerCss.layer.trim().length > 0) {
1762
- css = createCssSourceOrderAppend(wrapUserLayerComponentsCss(layerCss.layer), layerCss.rest);
2010
+ css = createCssSourceOrderAppend$1(wrapUserLayerComponentsCss(layerCss.layer), layerCss.rest);
1763
2011
  if (shouldFinalizeMarkedUserLayerComponentsCss(file)) css = reorderMarkedUserLayerComponentsCss(css);
1764
2012
  }
1765
2013
  }
1766
2014
  }
1767
2015
  if (hasMatchedCssSourceFile || generated.target === "web") {
1768
2016
  if (hasMatchedCssSourceFile && generated.target === "weapp" && !hasGeneratedCss && !hasGeneratedMarkers) {
1769
- const userCss = await transformGeneratorUserCss(generatorRawSource, {
2017
+ const userCss = await transformGeneratorUserCss(userCssRawSource, {
1770
2018
  generatorTarget: generated.target,
1771
2019
  generatorStyleOptions,
1772
2020
  cssUserHandlerOptions,
1773
2021
  styleHandler,
1774
2022
  importFallback: generatorOptions.importFallback
1775
2023
  });
1776
- css = createCssSourceOrderAppend(css, userCss);
2024
+ css = createCssSourceOrderAppend$1(css, userCss);
1777
2025
  }
1778
2026
  if (hasMatchedCssSourceFile && generated.target === "weapp") {
1779
- if (!isolateCurrentCssCandidates && !shouldFilterApplyOnlyCss) css = await appendLegacyContainerCompatCss(css, generatorRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2027
+ if (!isolateCurrentCssCandidates && !shouldFilterApplyOnlyCss) css = await appendLegacyContainerCompatCss(css, userCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1780
2028
  }
1781
2029
  if (shouldAppendWebBundleCssFallback(generated.target, {
1782
2030
  hasSourceDirectives,
1783
2031
  hasMatchedCssSourceFile
1784
2032
  })) {
1785
- const userCss = await transformGeneratorUserCss(generatorRawSource, {
2033
+ const userCss = await transformGeneratorUserCss(userCssRawSource, {
1786
2034
  generatorTarget: generated.target,
1787
2035
  generatorStyleOptions,
1788
2036
  cssUserHandlerOptions,
1789
2037
  styleHandler,
1790
2038
  importFallback: generatorOptions.importFallback
1791
2039
  });
1792
- css = createCssSourceOrderAppend(css, userCss);
2040
+ css = createCssSourceOrderAppend$1(css, userCss);
1793
2041
  }
1794
2042
  return {
1795
2043
  css: restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, { injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
@@ -1801,134 +2049,28 @@ async function generateCssByGenerator(options) {
1801
2049
  source: "generator",
1802
2050
  dependencies: generated.dependencies
1803
2051
  };
1804
- }
1805
- if (!shouldFilterApplyOnlyCss) {
1806
- css = await appendLegacyCompatCss(css, generatorRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1807
- css = await appendLegacyContainerCompatCss(css, generatorRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1808
- }
1809
- return {
1810
- css: restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, { injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
1811
- cssHandlerOptions,
1812
- isolateCurrentCssCandidates,
1813
- localImports: localImportParts?.imports
1814
- }) }), localImportParts?.imports),
1815
- target: generated.target,
1816
- source: "generator",
1817
- dependencies: generated.dependencies
1818
- };
1819
- } catch (error) {
1820
- debug("tailwind direct css generation failed: %s %O", file, error);
1821
- throw error;
1822
- }
1823
- }
1824
- async function validateCandidatesByGenerator(options) {
1825
- const { candidates, cssHandlerOptions, debug, file, opts, rawSource, runtimeState } = options;
1826
- const majorVersion = runtimeState.twPatcher.majorVersion;
1827
- if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || candidates.size === 0) return /* @__PURE__ */ new Set();
1828
- const generatorOptions = {
1829
- ...normalizeWeappTailwindcssGeneratorOptions(opts.generator),
1830
- bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues
1831
- };
1832
- const sources = await resolveGeneratorSources(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, {
1833
- cssEntries: opts.cssEntries,
1834
- runtime: candidates
1835
- });
1836
- const classSets = await Promise.all(sources.map(async (source) => {
1837
- const generator = createWeappTailwindcssGenerator(source);
1838
- if (generatorOptions.bareArbitraryValues === void 0 || generatorOptions.bareArbitraryValues === false) {
1839
- if (typeof generator.validateCandidates === "function") return generator.validateCandidates(candidates);
1840
- }
1841
- return (await generator.generate({
1842
- bareArbitraryValues: generatorOptions.bareArbitraryValues,
1843
- candidates,
1844
- target: "tailwind"
1845
- })).classSet;
1846
- }));
1847
- const classSet = new Set(classSets.flatMap((item) => [...item]));
1848
- debug("tailwind generator validated candidates: %s candidates=%d classSet=%d", file, candidates.size, classSet.size);
1849
- return classSet;
1850
- }
1851
- //#endregion
1852
- //#region src/bundlers/shared/hmr-timing.ts
1853
- function shouldEmitHmrTiming() {
1854
- return process.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || process.env["WEAPP_TW_HMR_TIMING"] === "1";
1855
- }
1856
- function shouldEmitHumanReadableTiming() {
1857
- return process.env["WEAPP_TW_HMR_TIMING"] === "1" && process.env["WEAPP_TW_HMR_TIMING_LOG"] !== "0";
1858
- }
1859
- function emitHmrTiming(bundler, phase, durationMs, details = {}) {
1860
- if (!shouldEmitHmrTiming()) return;
1861
- const serializableDetails = { ...details };
1862
- delete serializableDetails.emit;
1863
- const payload = {
1864
- bundler,
1865
- phase,
1866
- durationMs: Math.max(0, Math.round(durationMs)),
1867
- ...serializableDetails,
1868
- ...typeof details.wallMs === "number" ? { wallMs: Math.max(0, Math.round(details.wallMs)) } : {}
1869
- };
1870
- process.stdout.write(`[weapp-tailwindcss:hmr] ${JSON.stringify(payload)}\n`);
1871
- if (shouldEmitHumanReadableTiming()) {
1872
- const fileSuffix = details.file ? ` file=${details.file}` : "";
1873
- if (details.metric === "total") {
1874
- const hooks = details.hooks ? Object.entries(details.hooks).map(([hook, summary]) => `${hook}=${Math.max(0, Math.round(summary.durationMs))}ms/${summary.count}`).join(", ") : "";
1875
- const hookSuffix = hooks ? ` (${hooks})` : "";
1876
- const wallSuffix = typeof payload.wallMs === "number" ? ` wall=${payload.wallMs}ms` : "";
1877
- process.stdout.write(`[weapp-tailwindcss] ${bundler}:weapp-tailwindcss 总耗时 ${payload.durationMs}ms${wallSuffix}${hookSuffix}\n`);
1878
- return;
1879
- }
1880
- process.stdout.write(`[weapp-tailwindcss] ${bundler}:${phase} 耗时 ${payload.durationMs}ms${fileSuffix}\n`);
1881
- }
1882
- }
1883
- function createHmrTimingRecorder(bundler) {
1884
- const session = {
1885
- hooks: {},
1886
- totalMs: 0
1887
- };
1888
- const record = (phase, durationMs, details = {}) => {
1889
- const roundedDuration = Math.max(0, Math.round(durationMs));
1890
- if (session.startedAt === void 0) session.startedAt = performance.now() - Math.max(0, durationMs);
1891
- session.totalMs += Math.max(0, durationMs);
1892
- const current = session.hooks[phase] ?? {
1893
- count: 0,
1894
- durationMs: 0,
1895
- maxMs: 0
1896
- };
1897
- current.count += 1;
1898
- current.durationMs += roundedDuration;
1899
- current.maxMs = Math.max(current.maxMs, roundedDuration);
1900
- session.hooks[phase] = current;
1901
- if (details.emit !== false) emitHmrTiming(bundler, phase, durationMs, details);
1902
- };
1903
- const measure = async (phase, task, details = {}) => {
1904
- const startedAt = performance.now();
1905
- try {
1906
- return await task();
1907
- } finally {
1908
- record(phase, performance.now() - startedAt, details);
1909
- }
1910
- };
1911
- const emitTotal = (phase = "total") => {
1912
- if (session.totalMs <= 0) return;
1913
- const wallMs = session.startedAt === void 0 ? session.totalMs : performance.now() - session.startedAt;
1914
- emitHmrTiming(bundler, phase, session.totalMs, {
1915
- hooks: session.hooks,
1916
- metric: "total",
1917
- wallMs
1918
- });
1919
- session.hooks = {};
1920
- delete session.startedAt;
1921
- session.totalMs = 0;
1922
- };
1923
- return {
1924
- emitTotal,
1925
- measure,
1926
- record
1927
- };
2052
+ }
2053
+ if (!shouldFilterApplyOnlyCss) {
2054
+ css = await appendLegacyCompatCss(css, userCssRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2055
+ css = await appendLegacyContainerCompatCss(css, userCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2056
+ }
2057
+ return {
2058
+ css: restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, { injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
2059
+ cssHandlerOptions,
2060
+ isolateCurrentCssCandidates,
2061
+ localImports: localImportParts?.imports
2062
+ }) }), localImportParts?.imports),
2063
+ target: generated.target,
2064
+ source: "generator",
2065
+ dependencies: generated.dependencies
2066
+ };
2067
+ } catch (error) {
2068
+ debug("tailwind direct css generation failed: %s %O", file, error);
2069
+ throw error;
2070
+ }
1928
2071
  }
1929
2072
  //#endregion
1930
- //#region src/bundlers/vite/incremental-runtime-class-set.ts
1931
- const debug = createDebug("[vite:runtime-set] ");
2073
+ //#region src/bundlers/vite/incremental-runtime-class-set/entries.ts
1932
2074
  const EXTENSION_DOT_PREFIX_RE = /^\./;
1933
2075
  const VENDOR_CHUNK_BASENAME_RE = /^(?:vendor|vendors|chunk-vendors|common_vendor)(?:[.-]|$)/i;
1934
2076
  const COMMON_VENDOR_CHUNK_RE = /^(?:common|static|assets|chunks?)\/(?:vendor|vendors|chunk-vendors|common_vendor|runtime)(?:[.-]|$)/i;
@@ -1963,17 +2105,6 @@ function isRuntimeCandidateEntry(entry) {
1963
2105
  if (entry.output.facadeModuleId && !isDependencyModuleId(entry.output.facadeModuleId)) return true;
1964
2106
  return collectChunkModuleIds(entry).some((id) => !isDependencyModuleId(id));
1965
2107
  }
1966
- function createExtractOptions(context, source, bareArbitraryValues) {
1967
- return {
1968
- cwd: context.projectRoot,
1969
- base: context.base,
1970
- baseFallbacks: context.baseFallbacks,
1971
- css: context.css,
1972
- content: source,
1973
- extension: "html",
1974
- bareArbitraryValues
1975
- };
1976
- }
1977
2108
  function createRuntimeEntries(snapshot) {
1978
2109
  return snapshot.entries.filter(isRuntimeCandidateEntry);
1979
2110
  }
@@ -1986,37 +2117,54 @@ function resolveEntryExtension(entry) {
1986
2117
  if (ext.length > 0) return ext;
1987
2118
  return "js";
1988
2119
  }
1989
- function createCandidateValidationSource(candidates) {
1990
- return [...new Set(candidates)].sort().join("\n");
1991
- }
1992
- function removeCandidateSet(candidateCountByClass, candidates) {
1993
- for (const className of candidates) {
1994
- const count = candidateCountByClass.get(className);
1995
- if (count == null) continue;
1996
- if (count <= 1) {
1997
- candidateCountByClass.delete(className);
2120
+ //#endregion
2121
+ //#region src/bundlers/vite/incremental-runtime-class-set/escaped-candidates.ts
2122
+ const ESCAPED_CLASS_TOKEN_RE = /[\w-]+_[A-Z][\w-]*/gi;
2123
+ const TAILWIND_RESTORED_CANDIDATE_SIGNAL_RE = /[[\]:/#!.]/;
2124
+ const MAX_RESTORED_CANDIDATE_VARIANTS = 512;
2125
+ function createEscapeFragments(escapeMap) {
2126
+ return [...new Set(Object.values(escapeMap).filter(Boolean))].sort((a, b) => b.length - a.length);
2127
+ }
2128
+ function hasEscapeFragment(token, escapeFragments) {
2129
+ return escapeFragments.some((fragment) => token.includes(fragment));
2130
+ }
2131
+ function createAmbiguousRestoredRuntimeCandidates(token, escapeMap, escapeFragments) {
2132
+ if (!hasEscapeFragment(token, escapeFragments)) return [];
2133
+ const unescapedByFragment = new Map(Object.entries(escapeMap).map(([char, fragment]) => [fragment, char]));
2134
+ let variants = [""];
2135
+ let index = 0;
2136
+ while (index < token.length) {
2137
+ const fragment = escapeFragments.find((item) => token.startsWith(item, index));
2138
+ if (!fragment) {
2139
+ variants = variants.map((item) => item + token[index]);
2140
+ index += 1;
1998
2141
  continue;
1999
2142
  }
2000
- candidateCountByClass.set(className, count - 1);
2143
+ const nextVariants = [];
2144
+ const unescaped = unescapedByFragment.get(fragment);
2145
+ for (const variant of variants) {
2146
+ nextVariants.push(variant + fragment);
2147
+ if (unescaped) nextVariants.push(variant + unescaped);
2148
+ if (nextVariants.length >= MAX_RESTORED_CANDIDATE_VARIANTS) break;
2149
+ }
2150
+ variants = nextVariants;
2151
+ index += fragment.length;
2001
2152
  }
2153
+ variants.push(unescape(token, { map: escapeMap }));
2154
+ return [...new Set(variants)].filter((restored) => restored !== token && TAILWIND_RESTORED_CANDIDATE_SIGNAL_RE.test(restored) && !/\s/.test(restored));
2002
2155
  }
2003
- function addCandidateSet(candidateCountByClass, candidates) {
2004
- for (const className of candidates) {
2005
- const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
2006
- candidateCountByClass.set(className, nextCount);
2156
+ function collectEscapedRuntimeCandidates(source, escapeMap, escapeFragments) {
2157
+ const candidates = /* @__PURE__ */ new Set();
2158
+ ESCAPED_CLASS_TOKEN_RE.lastIndex = 0;
2159
+ let match = ESCAPED_CLASS_TOKEN_RE.exec(source);
2160
+ while (match) {
2161
+ for (const restored of createAmbiguousRestoredRuntimeCandidates(match[0], escapeMap, escapeFragments)) candidates.add(restored);
2162
+ match = ESCAPED_CLASS_TOKEN_RE.exec(source);
2007
2163
  }
2164
+ return candidates;
2008
2165
  }
2009
- function createRuntimeClassSet(baseClassSet, candidateCountByClass) {
2010
- return new Set([...baseClassSet, ...candidateCountByClass.keys()]);
2011
- }
2012
- function createNonSourceBaseClassSet(baseClassSet, candidateCountByClass) {
2013
- const nextBaseClassSet = new Set(baseClassSet);
2014
- for (const candidate of candidateCountByClass.keys()) nextBaseClassSet.delete(candidate);
2015
- return nextBaseClassSet;
2016
- }
2017
- function isUrlLikeCandidate(candidate) {
2018
- return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
2019
- }
2166
+ //#endregion
2167
+ //#region src/bundlers/vite/incremental-runtime-class-set/v3-candidates.ts
2020
2168
  const TAILWIND_V3_ARBITRARY_UTILITY_PREFIXES = new Set([
2021
2169
  "accent",
2022
2170
  "animate",
@@ -2095,6 +2243,9 @@ const TAILWIND_V3_ARBITRARY_UTILITY_PREFIXES = new Set([
2095
2243
  "w",
2096
2244
  "z"
2097
2245
  ]);
2246
+ function isUrlLikeCandidate(candidate) {
2247
+ return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
2248
+ }
2098
2249
  function getBaseUtilityCandidate(candidate) {
2099
2250
  let bracketDepth = 0;
2100
2251
  let lastVariantSeparator = -1;
@@ -2189,10 +2340,54 @@ function isRawCandidateInRanges(start, ranges) {
2189
2340
  function isRawCandidateAllowedForV3(source, candidate, start, extension, knownSourceCandidates, highConfidenceLiteralRanges = []) {
2190
2341
  return isHighConfidenceV3Candidate(candidate) || knownSourceCandidates?.has(candidate) === true || isRawCandidateInClassContext(source, start, extension) || isRawCandidateInRanges(start, highConfidenceLiteralRanges);
2191
2342
  }
2343
+ //#endregion
2344
+ //#region src/bundlers/vite/incremental-runtime-class-set.ts
2345
+ const debug = createDebug("[vite:runtime-set] ");
2346
+ function createExtractOptions(context, source, bareArbitraryValues) {
2347
+ return {
2348
+ cwd: context.projectRoot,
2349
+ base: context.base,
2350
+ baseFallbacks: context.baseFallbacks,
2351
+ css: context.css,
2352
+ content: source,
2353
+ extension: "html",
2354
+ ...bareArbitraryValues === void 0 ? {} : { bareArbitraryValues }
2355
+ };
2356
+ }
2357
+ function createCandidateValidationSource(candidates) {
2358
+ return [...new Set(candidates)].sort().join("\n");
2359
+ }
2360
+ function removeCandidateSet$1(candidateCountByClass, candidates) {
2361
+ for (const className of candidates) {
2362
+ const count = candidateCountByClass.get(className);
2363
+ if (count == null) continue;
2364
+ if (count <= 1) {
2365
+ candidateCountByClass.delete(className);
2366
+ continue;
2367
+ }
2368
+ candidateCountByClass.set(className, count - 1);
2369
+ }
2370
+ }
2371
+ function addCandidateSet$1(candidateCountByClass, candidates) {
2372
+ for (const className of candidates) {
2373
+ const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
2374
+ candidateCountByClass.set(className, nextCount);
2375
+ }
2376
+ }
2377
+ function createRuntimeClassSet(baseClassSet, candidateCountByClass) {
2378
+ return new Set([...baseClassSet, ...candidateCountByClass.keys()]);
2379
+ }
2380
+ function createNonSourceBaseClassSet(baseClassSet, candidateCountByClass) {
2381
+ const nextBaseClassSet = new Set(baseClassSet);
2382
+ for (const candidate of candidateCountByClass.keys()) nextBaseClassSet.delete(candidate);
2383
+ return nextBaseClassSet;
2384
+ }
2192
2385
  function createBundleRuntimeClassSetManager(options = {}) {
2193
2386
  const customExtractCandidates = options.extractCandidates;
2194
2387
  const extractCandidates = customExtractCandidates ?? extractValidCandidates;
2195
2388
  const extractRawCandidates = options.extractRawCandidates ?? extractRawCandidatesWithPositions;
2389
+ const escapeMap = options.escapeMap ?? MappingChars2String;
2390
+ const escapeFragments = createEscapeFragments(escapeMap);
2196
2391
  let baseClassSet = /* @__PURE__ */ new Set();
2197
2392
  const candidateCountByClass = /* @__PURE__ */ new Map();
2198
2393
  const candidatesByFile = /* @__PURE__ */ new Map();
@@ -2218,7 +2413,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2218
2413
  return designSystemPromise;
2219
2414
  }
2220
2415
  function populateCandidateValidityCacheFromDesignSystem(designSystem, unknownCandidates) {
2221
- const validCandidates = resolveValidTailwindV4Candidates(designSystem, unknownCandidates, { bareArbitraryValues: options.bareArbitraryValues });
2416
+ const validCandidates = resolveValidTailwindV4Candidates(designSystem, unknownCandidates, { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } });
2222
2417
  for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
2223
2418
  }
2224
2419
  async function validateUnknownCandidates(patcher, unknownCandidates) {
@@ -2252,6 +2447,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2252
2447
  candidates.add(candidate);
2253
2448
  }
2254
2449
  }
2450
+ if (patcher.majorVersion === 4) for (const candidate of collectEscapedRuntimeCandidates(entry.source, escapeMap, escapeFragments)) candidates.add(candidate);
2255
2451
  return candidates;
2256
2452
  }
2257
2453
  async function sync(patcher, snapshot, options = {}) {
@@ -2270,7 +2466,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2270
2466
  const canUseBaseWithoutInitialFullScan = Boolean(fullRebuild && !hadTrackedRuntimeFiles && options.skipInitialFullScanWithBase === true && nextBaseClassSet && nextBaseClassSet.size > 0);
2271
2467
  for (const [file, previousCandidates] of candidatesByFile) {
2272
2468
  if (currentRuntimeFiles.has(file) || snapshot.hasOmittedKnownFiles) continue;
2273
- removeCandidateSet(candidateCountByClass, previousCandidates);
2469
+ removeCandidateSet$1(candidateCountByClass, previousCandidates);
2274
2470
  candidatesByFile.delete(file);
2275
2471
  }
2276
2472
  const changedRuntimeFiles = canUseBaseWithoutInitialFullScan ? [...collectChangedRuntimeFiles(snapshot)] : fullRebuild ? [...runtimeEntriesByFile.keys()] : [...collectChangedRuntimeFiles(snapshot)];
@@ -2292,7 +2488,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2292
2488
  for (const file of changedRuntimeFiles) {
2293
2489
  const nextRawCandidates = rawCandidatesByFile.get(file);
2294
2490
  const previousCandidates = candidatesByFile.get(file);
2295
- if (previousCandidates) removeCandidateSet(candidateCountByClass, previousCandidates);
2491
+ if (previousCandidates) removeCandidateSet$1(candidateCountByClass, previousCandidates);
2296
2492
  if (!nextRawCandidates || nextRawCandidates.size === 0) {
2297
2493
  candidatesByFile.delete(file);
2298
2494
  continue;
@@ -2303,7 +2499,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2303
2499
  candidatesByFile.delete(file);
2304
2500
  continue;
2305
2501
  }
2306
- addCandidateSet(candidateCountByClass, nextCandidates);
2502
+ addCandidateSet$1(candidateCountByClass, nextCandidates);
2307
2503
  candidatesByFile.set(file, nextCandidates);
2308
2504
  }
2309
2505
  if (nextBaseClassSet) baseClassSet = canUseBaseWithoutInitialFullScan ? new Set(nextBaseClassSet) : createNonSourceBaseClassSet(nextBaseClassSet, candidateCountByClass);
@@ -2317,4 +2513,552 @@ function createBundleRuntimeClassSetManager(options = {}) {
2317
2513
  };
2318
2514
  }
2319
2515
  //#endregion
2320
- export { validateCandidatesByGenerator as a, generateCssByGenerator as i, createHmrTimingRecorder as n, mergeMarkedUserLayerComponentsCss as o, emitHmrTiming as r, processCachedTask as s, createBundleRuntimeClassSetManager as t };
2516
+ //#region src/bundlers/vite/source-candidates/scan-root.ts
2517
+ const TAILWIND_V4_IGNORED_CONTENT_DIRS = [
2518
+ ".git",
2519
+ ".hg",
2520
+ ".jj",
2521
+ ".next",
2522
+ ".parcel-cache",
2523
+ ".pnpm-store",
2524
+ ".svelte-kit",
2525
+ ".svn",
2526
+ ".turbo",
2527
+ ".venv",
2528
+ ".vercel",
2529
+ ".yarn",
2530
+ "__pycache__",
2531
+ "node_modules",
2532
+ "venv"
2533
+ ];
2534
+ const TAILWIND_V4_IGNORED_EXTENSIONS = [
2535
+ "css",
2536
+ "less",
2537
+ "postcss",
2538
+ "pcss",
2539
+ "lock",
2540
+ "sass",
2541
+ "scss",
2542
+ "styl",
2543
+ "stylus",
2544
+ "log",
2545
+ "wxss",
2546
+ "acss",
2547
+ "jxss",
2548
+ "ttss",
2549
+ "qss",
2550
+ "tyss"
2551
+ ];
2552
+ const TAILWIND_V4_IGNORED_FILES = [
2553
+ "package-lock.json",
2554
+ "pnpm-lock.yaml",
2555
+ "bun.lockb",
2556
+ ".gitignore",
2557
+ ".env",
2558
+ ".env.*"
2559
+ ];
2560
+ function resolveOutDirIgnorePattern(root, outDir) {
2561
+ if (!outDir) return;
2562
+ const relative = path.relative(root, path.resolve(root, outDir));
2563
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return;
2564
+ return `${toPosixPath$1(relative)}/**`;
2565
+ }
2566
+ function normalizeScanEntries(root, entries, outDirIgnore) {
2567
+ const hasPositiveEntry = entries?.some((entry) => !entry.negated) === true;
2568
+ const scanEntries = entries?.length ? hasPositiveEntry ? entries : [{
2569
+ base: root,
2570
+ pattern: "**/*",
2571
+ negated: false
2572
+ }, ...entries] : void 0;
2573
+ if (!outDirIgnore) return scanEntries;
2574
+ return [...scanEntries ?? [{
2575
+ base: root,
2576
+ pattern: "**/*",
2577
+ negated: false
2578
+ }], {
2579
+ base: root,
2580
+ pattern: outDirIgnore,
2581
+ negated: true
2582
+ }];
2583
+ }
2584
+ function shouldApplyDefaultIgnoredSources(entries) {
2585
+ return entries?.length === void 0 ? false : entries.length > 0 && entries.every((entry) => entry.negated);
2586
+ }
2587
+ function createDefaultIgnoredSources(root, outDirIgnore, entries, explicit) {
2588
+ return [...!explicit || shouldApplyDefaultIgnoredSources(entries) ? [
2589
+ ...TAILWIND_V4_IGNORED_CONTENT_DIRS.map((pattern) => ({
2590
+ base: root,
2591
+ pattern: `**/${pattern}/**`,
2592
+ negated: true
2593
+ })),
2594
+ ...TAILWIND_V4_IGNORED_EXTENSIONS.map((extension) => ({
2595
+ base: root,
2596
+ pattern: `**/*.${extension}`,
2597
+ negated: true
2598
+ })),
2599
+ ...TAILWIND_V4_IGNORED_FILES.map((pattern) => ({
2600
+ base: root,
2601
+ pattern: `**/${pattern}`,
2602
+ negated: true
2603
+ }))
2604
+ ] : [], ...outDirIgnore ? [{
2605
+ base: root,
2606
+ pattern: outDirIgnore,
2607
+ negated: true
2608
+ }] : []];
2609
+ }
2610
+ function resolveSourceCandidateScanFiles(options) {
2611
+ const resolvedRoot = path.resolve(options.root);
2612
+ const outDirIgnore = resolveOutDirIgnorePattern(resolvedRoot, options.outDir);
2613
+ const scanEntries = normalizeScanEntries(resolvedRoot, options.entries, outDirIgnore);
2614
+ const ignoredSources = createDefaultIgnoredSources(resolvedRoot, outDirIgnore, options.entries, options.explicit);
2615
+ return resolveProjectSourceFiles({
2616
+ cwd: resolvedRoot,
2617
+ ...scanEntries === void 0 ? {} : { sources: scanEntries },
2618
+ ...ignoredSources.length > 0 ? { ignoredSources } : {},
2619
+ filter: options.filter
2620
+ });
2621
+ }
2622
+ //#endregion
2623
+ //#region src/bundlers/vite/source-candidates/script.ts
2624
+ const SCRIPT_SOURCE_CANDIDATE_EXTENSIONS = new Set([
2625
+ "js",
2626
+ "jsx",
2627
+ "mjs",
2628
+ "cjs",
2629
+ "ts",
2630
+ "tsx",
2631
+ "mts",
2632
+ "cts"
2633
+ ]);
2634
+ const CLASS_LIKE_NAME_RE = /class/i;
2635
+ function getPropertyName(node) {
2636
+ if (!node) return;
2637
+ if (node.type === "Identifier") return node.name;
2638
+ if (node.type === "StringLiteral") return node.value;
2639
+ }
2640
+ function isClassLikeStringPath(path) {
2641
+ const parent = path.parentPath;
2642
+ if (!parent) return false;
2643
+ if (parent.isVariableDeclarator?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.id) ?? "");
2644
+ if (parent.isObjectProperty?.() || parent.isObjectMethod?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.key) ?? "");
2645
+ if (parent.isAssignmentExpression?.()) {
2646
+ const left = parent.node.left;
2647
+ if (left?.type === "Identifier") return CLASS_LIKE_NAME_RE.test(left.name);
2648
+ if (left?.type === "MemberExpression") return CLASS_LIKE_NAME_RE.test(getPropertyName(left.property) ?? "");
2649
+ }
2650
+ if (parent.isJSXAttribute?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.name) ?? "");
2651
+ return false;
2652
+ }
2653
+ function isTemplateElementInClassLikePath(path) {
2654
+ const templateLiteralPath = path.parentPath;
2655
+ if (!templateLiteralPath?.isTemplateLiteral?.()) return false;
2656
+ const parent = templateLiteralPath.parentPath;
2657
+ if (!parent) return false;
2658
+ if (parent.isVariableDeclarator?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.id) ?? "");
2659
+ if (parent.isObjectProperty?.() || parent.isObjectMethod?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.key) ?? "");
2660
+ if (parent.isAssignmentExpression?.()) {
2661
+ const left = parent.node.left;
2662
+ if (left?.type === "Identifier") return CLASS_LIKE_NAME_RE.test(left.name);
2663
+ if (left?.type === "MemberExpression") return CLASS_LIKE_NAME_RE.test(getPropertyName(left.property) ?? "");
2664
+ }
2665
+ return false;
2666
+ }
2667
+ async function extractScriptStringCandidates(source, extension, options) {
2668
+ if (!SCRIPT_SOURCE_CANDIDATE_EXTENSIONS.has(extension)) return [];
2669
+ const values = /* @__PURE__ */ new Set();
2670
+ try {
2671
+ traverse(babelParse(source, {
2672
+ cache: true,
2673
+ cacheKey: `vite-source-candidates:${extension}`,
2674
+ plugins: ["jsx", "typescript"],
2675
+ sourceType: "unambiguous"
2676
+ }), {
2677
+ noScope: true,
2678
+ StringLiteral(path) {
2679
+ if (isClassLikeStringPath(path)) values.add(path.node.value);
2680
+ },
2681
+ TemplateElement(path) {
2682
+ if (isTemplateElementInClassLikePath(path)) values.add(path.node.value.raw);
2683
+ }
2684
+ });
2685
+ } catch {
2686
+ return [];
2687
+ }
2688
+ const candidates = /* @__PURE__ */ new Set();
2689
+ for (const value of values) {
2690
+ const extractedCandidates = options.extractor ? await options.extractor(value, "html") : await extractSourceCandidates(value, "html", { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } });
2691
+ for (const candidate of extractedCandidates) candidates.add(candidate);
2692
+ }
2693
+ return candidates;
2694
+ }
2695
+ //#endregion
2696
+ //#region src/bundlers/vite/source-candidates/tailwind-v3-default-extractor.ts
2697
+ const require = createRequire(import.meta.url);
2698
+ const TAILWIND_V3_HTML_TOKEN_CANDIDATES = new Set([
2699
+ "/block",
2700
+ "/div",
2701
+ "/span",
2702
+ "/template",
2703
+ "/text",
2704
+ "/view",
2705
+ "class",
2706
+ "className",
2707
+ "div",
2708
+ "hover-class",
2709
+ "span",
2710
+ "template",
2711
+ "text",
2712
+ "view"
2713
+ ]);
2714
+ function createTailwindV3DefaultExtractor() {
2715
+ try {
2716
+ const defaultExtractorModule = require("tailwindcss/lib/lib/defaultExtractor");
2717
+ const resolveConfigModule = require("tailwindcss/resolveConfig");
2718
+ const resolveConfig = resolveConfigModule.default ?? resolveConfigModule;
2719
+ const extractor = (defaultExtractorModule.defaultExtractor ?? defaultExtractorModule.default ?? defaultExtractorModule)({ tailwindConfig: resolveConfig({ content: [] }) });
2720
+ return (source) => new Set(extractor(source).filter((candidate) => !TAILWIND_V3_HTML_TOKEN_CANDIDATES.has(candidate)));
2721
+ } catch {
2722
+ return;
2723
+ }
2724
+ }
2725
+ //#endregion
2726
+ //#region src/bundlers/vite/source-candidates.ts
2727
+ const CLEAN_URL_RE = /[?#].*$/;
2728
+ const sourceCandidateContentCache = /* @__PURE__ */ new Map();
2729
+ function cleanUrl(id) {
2730
+ return resolveSourceScanPath(id.replace(CLEAN_URL_RE, ""));
2731
+ }
2732
+ function resolveSourceCandidateExtension(id) {
2733
+ const normalized = cleanUrl(id);
2734
+ return /\.([^.\\/]+)$/.exec(normalized)?.[1] ?? "html";
2735
+ }
2736
+ function createSourceCandidateContentCacheKey(extension, source, bareArbitraryValues, extractor) {
2737
+ return `${extension}\0${JSON.stringify(bareArbitraryValues ?? false)}\0${extractor ? "custom" : "default"}\0${source}`;
2738
+ }
2739
+ async function extractCandidates(source, extension, options) {
2740
+ const candidates = options.extractor ? new Set(await options.extractor(source, extension)) : new Set(await extractSourceCandidates(source, extension, { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } }));
2741
+ const scriptCandidates = await extractScriptStringCandidates(source, extension, options);
2742
+ for (const candidate of scriptCandidates) candidates.add(candidate);
2743
+ return candidates;
2744
+ }
2745
+ function isSourceCandidateRequest(id) {
2746
+ return FULL_SOURCE_SCAN_EXTENSION_RE.test(cleanUrl(id));
2747
+ }
2748
+ function removeCandidateSet(candidateCount, candidates) {
2749
+ for (const candidate of candidates) {
2750
+ const count = candidateCount.get(candidate);
2751
+ if (count == null) continue;
2752
+ if (count <= 1) {
2753
+ candidateCount.delete(candidate);
2754
+ continue;
2755
+ }
2756
+ candidateCount.set(candidate, count - 1);
2757
+ }
2758
+ }
2759
+ function addCandidateSet(candidateCount, candidates) {
2760
+ for (const candidate of candidates) candidateCount.set(candidate, (candidateCount.get(candidate) ?? 0) + 1);
2761
+ }
2762
+ function createSourceCandidateCollector(options = {}) {
2763
+ const candidatesById = /* @__PURE__ */ new Map();
2764
+ const scanCandidatesById = /* @__PURE__ */ new Map();
2765
+ const transformCandidatesById = /* @__PURE__ */ new Map();
2766
+ const cssCandidatesById = /* @__PURE__ */ new Map();
2767
+ const sourceById = /* @__PURE__ */ new Map();
2768
+ const candidateCount = /* @__PURE__ */ new Map();
2769
+ let inlineIncludedCandidates = /* @__PURE__ */ new Set();
2770
+ let inlineExcludedCandidates = /* @__PURE__ */ new Set();
2771
+ async function sync(id, source) {
2772
+ const normalizedId = cleanUrl(id);
2773
+ sourceById.set(normalizedId, source);
2774
+ const extension = resolveSourceCandidateExtension(normalizedId);
2775
+ const contentCacheKey = createSourceCandidateContentCacheKey(extension, source, options.bareArbitraryValues, options.extractor);
2776
+ const cachedCandidates = sourceCandidateContentCache.get(contentCacheKey);
2777
+ if (cachedCandidates) {
2778
+ replaceScanLayer(normalizedId, new Set(cachedCandidates));
2779
+ return;
2780
+ }
2781
+ const nextCandidates = await extractCandidates(source, extension, options);
2782
+ sourceCandidateContentCache.set(contentCacheKey, [...nextCandidates]);
2783
+ replaceScanLayer(normalizedId, nextCandidates);
2784
+ }
2785
+ async function syncCss(id, source) {
2786
+ const normalizedId = cleanUrl(id);
2787
+ const contentCacheKey = createSourceCandidateContentCacheKey("css", source, options.bareArbitraryValues, options.extractor);
2788
+ const cachedCandidates = sourceCandidateContentCache.get(contentCacheKey);
2789
+ if (cachedCandidates) {
2790
+ replaceCssLayer(normalizedId, new Set(cachedCandidates));
2791
+ return;
2792
+ }
2793
+ const nextCandidates = await extractCandidates(source, "css", options);
2794
+ sourceCandidateContentCache.set(contentCacheKey, [...nextCandidates]);
2795
+ replaceCssLayer(normalizedId, nextCandidates);
2796
+ }
2797
+ async function merge(id, source) {
2798
+ const normalizedId = cleanUrl(id);
2799
+ const extension = resolveSourceCandidateExtension(normalizedId);
2800
+ const contentCacheKey = createSourceCandidateContentCacheKey(extension, source, options.bareArbitraryValues, options.extractor);
2801
+ const cachedCandidates = sourceCandidateContentCache.get(contentCacheKey);
2802
+ const extractedCandidates = cachedCandidates ? new Set(cachedCandidates) : await extractCandidates(source, extension, options);
2803
+ if (!cachedCandidates) sourceCandidateContentCache.set(contentCacheKey, [...extractedCandidates]);
2804
+ replaceTransformLayer(normalizedId, extractedCandidates);
2805
+ }
2806
+ async function syncFile(id) {
2807
+ const normalizedId = cleanUrl(id);
2808
+ await sync(normalizedId, await readFile(normalizedId, "utf8"));
2809
+ }
2810
+ async function syncCurrentFile(id) {
2811
+ const normalizedId = cleanUrl(id);
2812
+ transformCandidatesById.delete(normalizedId);
2813
+ await syncFile(normalizedId);
2814
+ }
2815
+ async function scanRoot({ entries, explicit, root, outDir }) {
2816
+ const files = await resolveSourceCandidateScanFiles({
2817
+ entries,
2818
+ explicit,
2819
+ filter: isSourceCandidateRequest,
2820
+ outDir,
2821
+ root
2822
+ });
2823
+ await Promise.all(files.map((file) => syncFile(resolveSourceScanPath(file))));
2824
+ }
2825
+ function replaceFinal(id, nextCandidates) {
2826
+ const normalizedId = cleanUrl(id);
2827
+ const previousCandidates = candidatesById.get(normalizedId);
2828
+ if (previousCandidates) {
2829
+ removeCandidateSet(candidateCount, previousCandidates);
2830
+ candidatesById.delete(normalizedId);
2831
+ }
2832
+ if (nextCandidates.size === 0) return;
2833
+ candidatesById.set(normalizedId, nextCandidates);
2834
+ addCandidateSet(candidateCount, nextCandidates);
2835
+ }
2836
+ function replaceScanLayer(id, nextCandidates) {
2837
+ const normalizedId = cleanUrl(id);
2838
+ if (nextCandidates.size === 0) scanCandidatesById.delete(normalizedId);
2839
+ else scanCandidatesById.set(normalizedId, nextCandidates);
2840
+ recompute(normalizedId);
2841
+ }
2842
+ function replaceTransformLayer(id, nextCandidates) {
2843
+ const normalizedId = cleanUrl(id);
2844
+ if (nextCandidates.size === 0) transformCandidatesById.delete(normalizedId);
2845
+ else transformCandidatesById.set(normalizedId, nextCandidates);
2846
+ recompute(normalizedId);
2847
+ }
2848
+ function replaceCssLayer(id, nextCandidates) {
2849
+ const normalizedId = cleanUrl(id);
2850
+ if (nextCandidates.size === 0) cssCandidatesById.delete(normalizedId);
2851
+ else cssCandidatesById.set(normalizedId, nextCandidates);
2852
+ recompute(normalizedId);
2853
+ }
2854
+ function recompute(id) {
2855
+ const normalizedId = cleanUrl(id);
2856
+ replaceFinal(normalizedId, new Set([
2857
+ ...scanCandidatesById.get(normalizedId) ?? [],
2858
+ ...transformCandidatesById.get(normalizedId) ?? [],
2859
+ ...cssCandidatesById.get(normalizedId) ?? []
2860
+ ]));
2861
+ }
2862
+ function syncInline(inlineCandidates) {
2863
+ inlineIncludedCandidates = new Set(inlineCandidates?.included ?? []);
2864
+ inlineExcludedCandidates = new Set(inlineCandidates?.excluded ?? []);
2865
+ }
2866
+ function remove(id) {
2867
+ const normalizedId = cleanUrl(id);
2868
+ scanCandidatesById.delete(normalizedId);
2869
+ transformCandidatesById.delete(normalizedId);
2870
+ cssCandidatesById.delete(normalizedId);
2871
+ sourceById.delete(normalizedId);
2872
+ const previousCandidates = candidatesById.get(normalizedId);
2873
+ if (!previousCandidates) return;
2874
+ removeCandidateSet(candidateCount, previousCandidates);
2875
+ candidatesById.delete(normalizedId);
2876
+ }
2877
+ function source(id) {
2878
+ return sourceById.get(cleanUrl(id));
2879
+ }
2880
+ function values() {
2881
+ const values = new Set([...candidateCount.keys(), ...inlineIncludedCandidates]);
2882
+ for (const candidate of inlineExcludedCandidates) values.delete(candidate);
2883
+ return values;
2884
+ }
2885
+ function valuesForEntries(entries, options = {}) {
2886
+ if (entries === void 0) {
2887
+ if (!options.excludeEntries?.length) return values();
2888
+ }
2889
+ const filtered = /* @__PURE__ */ new Set();
2890
+ for (const [id, candidates] of candidatesById) {
2891
+ if (entries !== void 0 && !isFileMatchedByTailwindSourceEntries(id, entries)) continue;
2892
+ if (options.excludeEntries?.length && isFileMatchedByTailwindSourceEntries(id, options.excludeEntries)) continue;
2893
+ for (const candidate of candidates) filtered.add(candidate);
2894
+ }
2895
+ for (const candidate of inlineIncludedCandidates) filtered.add(candidate);
2896
+ for (const candidate of inlineExcludedCandidates) filtered.delete(candidate);
2897
+ return filtered;
2898
+ }
2899
+ function sourcesForEntries(entries, options = {}) {
2900
+ const sources = /* @__PURE__ */ new Map();
2901
+ const addCandidateSource = (candidate, id) => {
2902
+ let candidateSources = sources.get(candidate);
2903
+ if (!candidateSources) {
2904
+ candidateSources = /* @__PURE__ */ new Set();
2905
+ sources.set(candidate, candidateSources);
2906
+ }
2907
+ if (id) candidateSources.add(id);
2908
+ };
2909
+ for (const [id, candidates] of candidatesById) {
2910
+ if (entries !== void 0 && !isFileMatchedByTailwindSourceEntries(id, entries)) continue;
2911
+ if (options.excludeEntries?.length && isFileMatchedByTailwindSourceEntries(id, options.excludeEntries)) continue;
2912
+ for (const candidate of candidates) addCandidateSource(candidate, id);
2913
+ }
2914
+ for (const candidate of inlineIncludedCandidates) addCandidateSource(candidate, void 0);
2915
+ for (const candidate of inlineExcludedCandidates) sources.delete(candidate);
2916
+ return sources;
2917
+ }
2918
+ function clear() {
2919
+ candidatesById.clear();
2920
+ scanCandidatesById.clear();
2921
+ transformCandidatesById.clear();
2922
+ cssCandidatesById.clear();
2923
+ sourceById.clear();
2924
+ candidateCount.clear();
2925
+ inlineIncludedCandidates.clear();
2926
+ inlineExcludedCandidates.clear();
2927
+ }
2928
+ function snapshot() {
2929
+ return {
2930
+ candidatesById: [...candidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
2931
+ cssCandidatesById: [...cssCandidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
2932
+ scanCandidatesById: [...scanCandidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
2933
+ sourceById: [...sourceById.entries()],
2934
+ transformCandidatesById: [...transformCandidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
2935
+ inlineExcludedCandidates: [...inlineExcludedCandidates],
2936
+ inlineIncludedCandidates: [...inlineIncludedCandidates]
2937
+ };
2938
+ }
2939
+ function restore(snapshot) {
2940
+ clear();
2941
+ inlineExcludedCandidates = new Set(snapshot.inlineExcludedCandidates);
2942
+ inlineIncludedCandidates = new Set(snapshot.inlineIncludedCandidates);
2943
+ const scanEntries = snapshot.scanCandidatesById ?? snapshot.candidatesById;
2944
+ for (const [id, candidates] of scanEntries) {
2945
+ const candidateSet = new Set(candidates);
2946
+ if (candidateSet.size === 0) continue;
2947
+ scanCandidatesById.set(id, candidateSet);
2948
+ }
2949
+ for (const [id, candidates] of snapshot.transformCandidatesById ?? []) {
2950
+ const candidateSet = new Set(candidates);
2951
+ if (candidateSet.size === 0) continue;
2952
+ transformCandidatesById.set(id, candidateSet);
2953
+ }
2954
+ for (const [id, candidates] of snapshot.cssCandidatesById ?? []) {
2955
+ const candidateSet = new Set(candidates);
2956
+ if (candidateSet.size === 0) continue;
2957
+ cssCandidatesById.set(id, candidateSet);
2958
+ }
2959
+ for (const [id, candidates] of snapshot.candidatesById) {
2960
+ const candidateSet = new Set(candidates);
2961
+ if (candidateSet.size === 0) continue;
2962
+ candidatesById.set(id, candidateSet);
2963
+ addCandidateSet(candidateCount, candidateSet);
2964
+ }
2965
+ for (const [id, source] of snapshot.sourceById ?? []) sourceById.set(id, source);
2966
+ }
2967
+ return {
2968
+ sync,
2969
+ syncCss,
2970
+ merge,
2971
+ syncFile,
2972
+ syncCurrentFile,
2973
+ scanRoot,
2974
+ syncInline,
2975
+ remove,
2976
+ source,
2977
+ values,
2978
+ valuesForEntries,
2979
+ sourcesForEntries,
2980
+ snapshot,
2981
+ restore,
2982
+ clear
2983
+ };
2984
+ }
2985
+ //#endregion
2986
+ //#region src/bundlers/shared/hmr-timing.ts
2987
+ function shouldEmitHmrTiming() {
2988
+ return process.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || process.env["WEAPP_TW_HMR_TIMING"] === "1";
2989
+ }
2990
+ function shouldEmitHumanReadableTiming() {
2991
+ return process.env["WEAPP_TW_HMR_TIMING"] === "1" && process.env["WEAPP_TW_HMR_TIMING_LOG"] !== "0";
2992
+ }
2993
+ function emitHmrTiming(bundler, phase, durationMs, details = {}) {
2994
+ if (!shouldEmitHmrTiming()) return;
2995
+ const serializableDetails = { ...details };
2996
+ delete serializableDetails.emit;
2997
+ const payload = {
2998
+ bundler,
2999
+ phase,
3000
+ durationMs: Math.max(0, Math.round(durationMs)),
3001
+ ...serializableDetails,
3002
+ ...typeof details.wallMs === "number" ? { wallMs: Math.max(0, Math.round(details.wallMs)) } : {}
3003
+ };
3004
+ process.stdout.write(`[weapp-tailwindcss:hmr] ${JSON.stringify(payload)}\n`);
3005
+ if (shouldEmitHumanReadableTiming()) {
3006
+ const fileSuffix = details.file ? ` file=${details.file}` : "";
3007
+ if (details.metric === "total") {
3008
+ const hooks = details.hooks ? Object.entries(details.hooks).map(([hook, summary]) => `${hook}=${Math.max(0, Math.round(summary.durationMs))}ms/${summary.count}`).join(", ") : "";
3009
+ const hookSuffix = hooks ? ` (${hooks})` : "";
3010
+ const wallSuffix = typeof payload.wallMs === "number" ? ` wall=${payload.wallMs}ms` : "";
3011
+ process.stdout.write(`[weapp-tailwindcss] ${bundler}:weapp-tailwindcss 总耗时 ${payload.durationMs}ms${wallSuffix}${hookSuffix}\n`);
3012
+ return;
3013
+ }
3014
+ process.stdout.write(`[weapp-tailwindcss] ${bundler}:${phase} 耗时 ${payload.durationMs}ms${fileSuffix}\n`);
3015
+ }
3016
+ }
3017
+ function createHmrTimingRecorder(bundler) {
3018
+ const session = {
3019
+ hooks: {},
3020
+ totalMs: 0
3021
+ };
3022
+ const record = (phase, durationMs, details = {}) => {
3023
+ const roundedDuration = Math.max(0, Math.round(durationMs));
3024
+ if (session.startedAt === void 0) session.startedAt = performance.now() - Math.max(0, durationMs);
3025
+ session.totalMs += Math.max(0, durationMs);
3026
+ const current = session.hooks[phase] ?? {
3027
+ count: 0,
3028
+ durationMs: 0,
3029
+ maxMs: 0
3030
+ };
3031
+ current.count += 1;
3032
+ current.durationMs += roundedDuration;
3033
+ current.maxMs = Math.max(current.maxMs, roundedDuration);
3034
+ session.hooks[phase] = current;
3035
+ if (details.emit !== false) emitHmrTiming(bundler, phase, durationMs, details);
3036
+ };
3037
+ const measure = async (phase, task, details = {}) => {
3038
+ const startedAt = performance.now();
3039
+ try {
3040
+ return await task();
3041
+ } finally {
3042
+ record(phase, performance.now() - startedAt, details);
3043
+ }
3044
+ };
3045
+ const emitTotal = (phase = "total") => {
3046
+ if (session.totalMs <= 0) return;
3047
+ const wallMs = session.startedAt === void 0 ? session.totalMs : performance.now() - session.startedAt;
3048
+ emitHmrTiming(bundler, phase, session.totalMs, {
3049
+ hooks: session.hooks,
3050
+ metric: "total",
3051
+ wallMs
3052
+ });
3053
+ session.hooks = {};
3054
+ delete session.startedAt;
3055
+ session.totalMs = 0;
3056
+ };
3057
+ return {
3058
+ emitTotal,
3059
+ measure,
3060
+ record
3061
+ };
3062
+ }
3063
+ //#endregion
3064
+ export { isCssSourceTraceEnabled as _, createTailwindV3DefaultExtractor as a, validateCandidatesByGenerator as c, isPureLocalCssImportWrapper as d, finalizeMiniProgramCss as f, createCssTokenSourceMap as g, createCssSourceTraceCacheSignature as h, isSourceCandidateRequest as i, extractMarkedUserLayerComponentsCss as l, annotateCssSourceTrace as m, emitHmrTiming as n, createBundleRuntimeClassSetManager as o, pruneMiniProgramGeneratedCss as p, createSourceCandidateCollector as r, generateCssByGenerator as s, createHmrTimingRecorder as t, mergeMarkedUserLayerComponentsCss as u, processCachedTask as v };