weapp-tailwindcss 5.0.0-next.5 → 5.0.0-next.8

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 (131) hide show
  1. package/dist/bundlers/shared/css-cleanup/at-rules.d.ts +2 -0
  2. package/dist/bundlers/shared/css-cleanup/color-gamut.d.ts +3 -0
  3. package/dist/bundlers/shared/css-cleanup/root-cleanups.d.ts +4 -0
  4. package/dist/bundlers/shared/css-cleanup/selectors.d.ts +8 -0
  5. package/dist/bundlers/shared/css-cleanup.d.ts +1 -2
  6. package/dist/bundlers/shared/generator-css/config-directive.d.ts +2 -0
  7. package/dist/bundlers/shared/generator-css/directives.d.ts +12 -0
  8. package/dist/bundlers/shared/generator-css/legacy-compat.d.ts +7 -0
  9. package/dist/bundlers/shared/generator-css/legacy-selectors.d.ts +5 -0
  10. package/dist/bundlers/shared/generator-css/legacy-units.d.ts +1 -0
  11. package/dist/bundlers/shared/generator-css/markers.d.ts +16 -0
  12. package/dist/bundlers/shared/generator-css/source-files.d.ts +11 -0
  13. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +10 -0
  14. package/dist/bundlers/shared/generator-css.d.ts +10 -23
  15. package/dist/bundlers/vite/css-finalizer.d.ts +1 -1
  16. package/dist/bundlers/vite/generate-bundle/candidates.d.ts +2 -0
  17. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +20 -0
  18. package/dist/bundlers/vite/generate-bundle/css-share-scope.d.ts +3 -0
  19. package/dist/bundlers/vite/generate-bundle/dirty-state.d.ts +1 -0
  20. package/dist/bundlers/vite/generate-bundle/js-entries.d.ts +2 -0
  21. package/dist/bundlers/vite/generate-bundle/js-handler-options.d.ts +8 -0
  22. package/dist/bundlers/vite/generate-bundle/js-linking.d.ts +13 -0
  23. package/dist/bundlers/vite/generate-bundle/metrics.d.ts +17 -0
  24. package/dist/bundlers/vite/generate-bundle/process-plan.d.ts +9 -0
  25. package/dist/bundlers/vite/generate-bundle/rollup-assets.d.ts +7 -0
  26. package/dist/bundlers/vite/generate-bundle/signatures.d.ts +8 -0
  27. package/dist/bundlers/vite/generate-bundle.d.ts +1 -1
  28. package/dist/bundlers/vite/official-tailwind-plugins.d.ts +5 -0
  29. package/dist/bundlers/vite/postcss-config.d.ts +6 -0
  30. package/dist/bundlers/vite/rewrite-css-imports.d.ts +1 -0
  31. package/dist/bundlers/vite/runtime-class-set.d.ts +22 -0
  32. package/dist/bundlers/vite/tailwind-basedir.d.ts +1 -0
  33. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +1 -0
  34. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +1 -1
  35. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +2 -0
  36. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +1 -0
  37. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +2 -0
  38. package/dist/cache-BVAiJV3J.js +502 -0
  39. package/dist/cache-CHs4DXui.mjs +434 -0
  40. package/dist/cli/helpers.d.ts +1 -2
  41. package/dist/cli/mount-options.d.ts +2 -2
  42. package/dist/cli/types.d.ts +0 -2
  43. package/dist/cli.js +107 -603
  44. package/dist/cli.mjs +118 -613
  45. package/dist/constants.d.ts +0 -1
  46. package/dist/context/tailwindcss.d.ts +1 -1
  47. package/dist/core.js +13 -20
  48. package/dist/core.mjs +8 -14
  49. package/dist/css-macro/postcss.js +1 -1
  50. package/dist/css-macro/postcss.mjs +1 -1
  51. package/dist/css-macro.js +2 -2
  52. package/dist/css-macro.mjs +2 -2
  53. package/dist/defaults.d.ts +15 -1
  54. package/dist/defaults.js +28 -7
  55. package/dist/defaults.mjs +25 -8
  56. package/dist/{generator-9UEp8OoQ.js → generator-DKkhJbOg.js} +24 -7
  57. package/dist/{generator-Dpp-5s8z.mjs → generator-UBmfduYg.mjs} +20 -3
  58. package/dist/{generator-css-MyjZhF0z.mjs → generator-css-BIapP56i.mjs} +691 -606
  59. package/dist/{generator-css-CGueCYbX.js → generator-css-Mksw8PgB.js} +703 -606
  60. package/dist/generator.js +1 -1
  61. package/dist/generator.mjs +1 -1
  62. package/dist/gulp.js +33 -21
  63. package/dist/gulp.mjs +29 -17
  64. package/dist/index.js +5 -5
  65. package/dist/index.mjs +4 -4
  66. package/dist/logger-BRy6XPQ2.js +1 -0
  67. package/dist/logger-Bub1jggA.mjs +2 -0
  68. package/dist/postcss/config-directive.d.ts +1 -0
  69. package/dist/postcss/context.d.ts +9 -0
  70. package/dist/postcss/source-files.d.ts +8 -0
  71. package/dist/postcss/tailwind-version.d.ts +3 -0
  72. package/dist/postcss-QIXwT40c.js +298 -0
  73. package/dist/postcss-w48mGIhe.mjs +288 -0
  74. package/dist/postcss.js +3 -285
  75. package/dist/postcss.mjs +1 -278
  76. package/dist/{recorder-D4BKt75Q.js → precheck-B32p-gLI.js} +139 -274
  77. package/dist/{recorder-BIW3Kuke.mjs → precheck-B4RH6ZNN.mjs} +105 -239
  78. package/dist/presets.js +6 -4
  79. package/dist/presets.mjs +4 -2
  80. package/dist/runtime-patch-CwN5ya72.mjs +71 -0
  81. package/dist/runtime-patch-D6mBo_KB.js +85 -0
  82. package/dist/tailwindcss/runtime-patch.d.ts +5 -0
  83. package/dist/tailwindcss/runtime.d.ts +2 -3
  84. package/dist/tailwindcss/targets.d.ts +1 -5
  85. package/dist/tailwindcss/v4/css-sources.d.ts +5 -0
  86. package/dist/tailwindcss/v4/patcher.d.ts +1 -1
  87. package/dist/{logger-D9clu_3f.js → tailwindcss-Bu-RWIHx.js} +70 -413
  88. package/dist/{logger-1gx9UllH.mjs → tailwindcss-C5IgPlQ0.mjs} +56 -382
  89. package/dist/types/index.d.ts +1 -6
  90. package/dist/uni-app-x/vite.d.ts +1 -1
  91. package/dist/{vite-fDM-UQpR.mjs → vite-BwgRVgxH.mjs} +677 -525
  92. package/dist/{vite-BkMGwDeH.js → vite-DyZuiyap.js} +704 -552
  93. package/dist/vite.js +1 -1
  94. package/dist/vite.mjs +1 -1
  95. package/dist/weapp-tw-css-import-rewrite-loader.js +10 -1
  96. package/dist/{webpack-CICGEKT9.js → webpack-CNV2dx3Q.js} +72 -37
  97. package/dist/{webpack-D2Wdk28V.mjs → webpack-CT6EEENx.mjs} +58 -23
  98. package/dist/webpack.js +1 -1
  99. package/dist/webpack.mjs +1 -1
  100. package/package.json +6 -9
  101. package/dist/bundlers/shared/generator-candidates.d.ts +0 -5
  102. package/dist/bundlers/webpack/shared/css-imports.d.ts +0 -6
  103. package/dist/cli/config.d.ts +0 -5
  104. package/dist/cli/helpers/patch-cwd.d.ts +0 -1
  105. package/dist/cli/mount-options/patch-status.d.ts +0 -2
  106. package/dist/cli/patch-options.d.ts +0 -6
  107. package/dist/cli/tokens.d.ts +0 -4
  108. package/dist/cli/workspace/package-dirs.d.ts +0 -3
  109. package/dist/cli/workspace/patch-package.d.ts +0 -3
  110. package/dist/cli/workspace/patch-utils.d.ts +0 -3
  111. package/dist/cli/workspace/types.d.ts +0 -11
  112. package/dist/cli/workspace/workspace-globs.d.ts +0 -2
  113. package/dist/cli/workspace/workspace-io.d.ts +0 -1
  114. package/dist/cli/workspace/workspace-lock.d.ts +0 -1
  115. package/dist/cli/workspace.d.ts +0 -2
  116. package/dist/js/syntax.d.ts +0 -10
  117. package/dist/patcher-options-DnqazL9E.js +0 -34
  118. package/dist/patcher-options-GuOwX0-k.mjs +0 -17
  119. package/dist/tailwindcss/recorder.d.ts +0 -13
  120. package/dist/tailwindcss/targets/paths.d.ts +0 -13
  121. package/dist/tailwindcss/targets/record-io.d.ts +0 -5
  122. package/dist/tailwindcss/targets/recorder.d.ts +0 -3
  123. package/dist/tailwindcss/targets/types.d.ts +0 -35
  124. package/dist/version-CWBxRFPB.js +0 -56
  125. package/dist/version-WNz3MwRv.mjs +0 -49
  126. /package/dist/{constants-p1dyh1x1.js → constants-BoB_6lFw.js} +0 -0
  127. /package/dist/{constants-B-_T5UnW.mjs → constants-E_loJC49.mjs} +0 -0
  128. /package/dist/{run-tasks-Cq5A5nVD.js → run-tasks-B50A3pxt.js} +0 -0
  129. /package/dist/{run-tasks-DUVrDJGl.mjs → run-tasks-DdNi-hkk.mjs} +0 -0
  130. /package/dist/{utils-DmC9_In3.js → utils-BiShvil9.js} +0 -0
  131. /package/dist/{utils-7DUGTFED.mjs → utils-Btw1iOVV.mjs} +0 -0
@@ -1,22 +1,24 @@
1
1
  const require_chunk = require("./chunk-8l464Juk.js");
2
- const require_generator = require("./generator-9UEp8OoQ.js");
3
- const require_patcher_options = require("./patcher-options-DnqazL9E.js");
4
- const require_recorder = require("./recorder-D4BKt75Q.js");
5
- const require_utils = require("./utils-DmC9_In3.js");
6
- const require_logger = require("./logger-D9clu_3f.js");
7
- const require_generator_css = require("./generator-css-CGueCYbX.js");
8
- const require_run_tasks = require("./run-tasks-Cq5A5nVD.js");
2
+ const require_cache = require("./cache-BVAiJV3J.js");
3
+ const require_runtime_patch = require("./runtime-patch-D6mBo_KB.js");
4
+ const require_generator = require("./generator-DKkhJbOg.js");
5
+ const require_generator_css = require("./generator-css-Mksw8PgB.js");
6
+ const require_precheck = require("./precheck-B32p-gLI.js");
7
+ const require_utils = require("./utils-BiShvil9.js");
8
+ const require_tailwindcss = require("./tailwindcss-Bu-RWIHx.js");
9
+ const require_run_tasks = require("./run-tasks-B50A3pxt.js");
10
+ require("./logger-BRy6XPQ2.js");
9
11
  let node_path = require("node:path");
10
12
  node_path = require_chunk.__toESM(node_path);
11
13
  let node_process = require("node:process");
12
14
  node_process = require_chunk.__toESM(node_process);
15
+ let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
16
+ let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
13
17
  let tailwindcss_patch = require("tailwindcss-patch");
14
- let node_buffer = require("node:buffer");
15
18
  let node_fs = require("node:fs");
16
19
  node_fs = require_chunk.__toESM(node_fs);
20
+ let node_buffer = require("node:buffer");
17
21
  let node_fs_promises = require("node:fs/promises");
18
- let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
19
- let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
20
22
  let magic_string = require("magic-string");
21
23
  magic_string = require_chunk.__toESM(magic_string);
22
24
  let _weapp_tailwindcss_shared_extractors = require("@weapp-tailwindcss/shared/extractors");
@@ -25,11 +27,11 @@ let fast_glob = require("fast-glob");
25
27
  fast_glob = require_chunk.__toESM(fast_glob);
26
28
  let _weapp_tailwindcss_postcss_html_transform = require("@weapp-tailwindcss/postcss/html-transform");
27
29
  _weapp_tailwindcss_postcss_html_transform = require_chunk.__toESM(_weapp_tailwindcss_postcss_html_transform);
28
- let postcss_load_config = require("postcss-load-config");
29
- postcss_load_config = require_chunk.__toESM(postcss_load_config);
30
30
  let _vue_compiler_dom = require("@vue/compiler-dom");
31
31
  let _vue_compiler_sfc = require("@vue/compiler-sfc");
32
32
  let comment_json = require("comment-json");
33
+ let postcss_load_config = require("postcss-load-config");
34
+ postcss_load_config = require_chunk.__toESM(postcss_load_config);
33
35
  //#region src/uni-app-x/component-local-style.ts
34
36
  const EXPRESSION_WRAPPER_PREFIX = "(\n";
35
37
  const EXPRESSION_WRAPPER_SUFFIX = "\n)";
@@ -60,7 +62,7 @@ function createAlias(fileId, utility, index) {
60
62
  }
61
63
  function isRuntimeCandidate(candidate, runtimeSet) {
62
64
  if (!runtimeSet || runtimeSet.size === 0) return false;
63
- return runtimeSet.has(candidate) || runtimeSet.has(require_recorder.replaceWxml(candidate));
65
+ return runtimeSet.has(candidate) || runtimeSet.has(require_precheck.replaceWxml(candidate));
64
66
  }
65
67
  function shouldEnableComponentLocalStyle(id) {
66
68
  return COMPONENT_RE.test(id);
@@ -69,8 +71,8 @@ var UniAppXComponentLocalStyleCollector = class {
69
71
  constructor(fileId, runtimeSet) {
70
72
  this.fileId = fileId;
71
73
  this.runtimeSet = runtimeSet;
72
- this.aliasByUtility = /* @__PURE__ */ new Map();
73
- this.aliasByLookup = /* @__PURE__ */ new Map();
74
+ require_precheck._defineProperty(this, "aliasByUtility", /* @__PURE__ */ new Map());
75
+ require_precheck._defineProperty(this, "aliasByLookup", /* @__PURE__ */ new Map());
74
76
  }
75
77
  ensureAlias(utility) {
76
78
  const cached = this.aliasByUtility.get(utility);
@@ -78,7 +80,7 @@ var UniAppXComponentLocalStyleCollector = class {
78
80
  const alias = createAlias(this.fileId, utility, this.aliasByUtility.size);
79
81
  this.aliasByUtility.set(utility, alias);
80
82
  this.aliasByLookup.set(utility, alias);
81
- this.aliasByLookup.set(require_recorder.replaceWxml(utility), alias);
83
+ this.aliasByLookup.set(require_precheck.replaceWxml(utility), alias);
82
84
  return alias;
83
85
  }
84
86
  rewriteLiteral(literal, shouldInclude) {
@@ -97,14 +99,14 @@ var UniAppXComponentLocalStyleCollector = class {
97
99
  collectRuntimeClasses(rawSource, options = {}) {
98
100
  const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
99
101
  try {
100
- const analysis = require_recorder.analyzeSource(require_recorder.babelParse(wrapped, {
102
+ const analysis = require_precheck.analyzeSource(require_precheck.babelParse(wrapped, {
101
103
  plugins: ["typescript"],
102
104
  sourceType: options.wrapExpression ? "module" : "unambiguous"
103
105
  }), {}, void 0, false);
104
106
  for (const path of analysis.targetPaths) {
105
107
  const { literal, allowDoubleQuotes } = extractLiteralValue(path);
106
108
  const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
107
- const classContext = options.wrapExpression || require_recorder.isClassContextLiteralPath(path);
109
+ const classContext = options.wrapExpression || require_precheck.isClassContextLiteralPath(path);
108
110
  for (const candidate of candidates) {
109
111
  if (!candidate || !classContext && !isRuntimeCandidate(candidate, this.runtimeSet)) continue;
110
112
  if (isRuntimeCandidate(candidate, this.runtimeSet)) this.ensureAlias(candidate);
@@ -116,12 +118,12 @@ var UniAppXComponentLocalStyleCollector = class {
116
118
  if (this.aliasByLookup.size === 0) return rawSource;
117
119
  const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
118
120
  try {
119
- const analysis = require_recorder.analyzeSource(require_recorder.babelParse(wrapped, {
121
+ const analysis = require_precheck.analyzeSource(require_precheck.babelParse(wrapped, {
120
122
  plugins: ["typescript"],
121
123
  sourceType: options.wrapExpression ? "module" : "unambiguous"
122
124
  }), {}, void 0, false);
123
125
  if (analysis.targetPaths.length === 0) return rawSource;
124
- const updater = new require_recorder.JsTokenUpdater();
126
+ const updater = new require_precheck.JsTokenUpdater();
125
127
  for (const path of analysis.targetPaths) {
126
128
  const { literal, allowDoubleQuotes, offset } = extractLiteralValue(path);
127
129
  const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
@@ -184,7 +186,7 @@ function updateStaticAttribute(ms, prop, content = prop.value?.content) {
184
186
  if (!prop.value) return;
185
187
  const start = prop.value.loc.start.offset + 1;
186
188
  const end = prop.value.loc.end.offset - 1;
187
- if (start < end) ms.update(start, end, require_recorder.replaceWxml(content ?? ""));
189
+ if (start < end) ms.update(start, end, require_precheck.replaceWxml(content ?? ""));
188
190
  }
189
191
  function updateStaticAttributeWithLocalStyle(ms, prop, collector, content = prop.value?.content) {
190
192
  if (!prop.value) return;
@@ -198,7 +200,7 @@ function updateDirectiveExpression(ms, prop, jsHandler, runtimeSet) {
198
200
  const start = prop.exp.loc.start.offset;
199
201
  const end = prop.exp.loc.end.offset;
200
202
  if (start >= end) return;
201
- const generated = require_recorder.generateCode(expression, {
203
+ const generated = require_precheck.generateCode(expression, {
202
204
  jsHandler,
203
205
  runtimeSet,
204
206
  wrapExpression: true
@@ -212,7 +214,7 @@ function updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, collector,
212
214
  const end = prop.exp.loc.end.offset;
213
215
  if (start >= end) return;
214
216
  collector.collectRuntimeClasses(expression, { wrapExpression: true });
215
- const generated = require_recorder.generateCode(expression, {
217
+ const generated = require_precheck.generateCode(expression, {
216
218
  jsHandler,
217
219
  runtimeSet,
218
220
  wrapExpression: true
@@ -234,7 +236,7 @@ const UVUE_NVUE_RE$1 = /\.(?:uvue|nvue)(?:\?.*)?$/;
234
236
  function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
235
237
  if (!UVUE_NVUE_RE$1.test(id)) return;
236
238
  const { customAttributesEntities, disabledDefaultTemplateHandler = false } = options;
237
- const matchCustomAttribute = require_recorder.createAttributeMatcher(customAttributesEntities);
239
+ const matchCustomAttribute = require_precheck.createAttributeMatcher(customAttributesEntities);
238
240
  const ms = new magic_string.default(code);
239
241
  const { descriptor, errors } = (0, _vue_compiler_sfc.parse)(code);
240
242
  const localStyleCollector = options.enableComponentLocalStyle && shouldEnableComponentLocalStyle(id) ? new UniAppXComponentLocalStyleCollector(id, runtimeSet) : void 0;
@@ -371,11 +373,11 @@ function resolveUniAppXCssTarget(id) {
371
373
  return UVUE_NVUE_RE.test((0, _weapp_tailwindcss_shared.cleanUrl)(id)) ? "uvue" : void 0;
372
374
  }
373
375
  function resolveUniAppXJsTransformEnabled$1(uniAppX) {
374
- return uniAppX === void 0 ? true : require_logger.isUniAppXEnabled(uniAppX);
376
+ return uniAppX === void 0 ? true : require_tailwindcss.isUniAppXEnabled(uniAppX);
375
377
  }
376
378
  function createUniAppXPlugins(options) {
377
379
  const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, jsHandler, ensureRuntimeClassSet, getResolvedConfig, uniAppX } = options;
378
- const resolvedUniAppXOptions = require_logger.resolveUniAppXOptions(uniAppX);
380
+ const resolvedUniAppXOptions = require_tailwindcss.resolveUniAppXOptions(uniAppX);
379
381
  const isIosPlatform = providedIosPlatform ?? require_utils.resolveUniUtsPlatform().isAppIos;
380
382
  const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
381
383
  let componentLocalStyleEnabled;
@@ -427,14 +429,14 @@ function createUniAppXPlugins(options) {
427
429
  const cssPlugins = [{
428
430
  name: "weapp-tailwindcss:uni-app-x:css",
429
431
  async transform(code, id) {
430
- await runtimeState.patchPromise;
432
+ await runtimeState.readyPromise;
431
433
  return transformStyle(code, id);
432
434
  }
433
435
  }, {
434
436
  name: "weapp-tailwindcss:uni-app-x:css:pre",
435
437
  enforce: "pre",
436
438
  async transform(code, id) {
437
- await runtimeState.patchPromise;
439
+ await runtimeState.readyPromise;
438
440
  const { query } = parseVueRequest(id);
439
441
  const lang = query.lang;
440
442
  if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
@@ -552,7 +554,7 @@ function createViteCssFinalizerOutputPlugin(context) {
552
554
  if (getResolvedConfig()?.command !== "build") return;
553
555
  const entries = Object.entries(bundle).filter(([, output]) => output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName)));
554
556
  if (entries.length === 0) return;
555
- await runtimeState.patchPromise;
557
+ await runtimeState.readyPromise;
556
558
  await waitForSourceCandidateSyncs?.();
557
559
  const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
558
560
  const runtime = getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet();
@@ -671,14 +673,14 @@ function createHtmlRuntimeAffectingSignature(source) {
671
673
  }
672
674
  function createJsRuntimeAffectingSignature(source) {
673
675
  try {
674
- const ast = require_recorder.babelParse(source, {
676
+ const ast = require_precheck.babelParse(source, {
675
677
  cache: true,
676
678
  cacheKey: "vite-runtime-affecting:unambiguous",
677
679
  plugins: ["jsx", "typescript"],
678
680
  sourceType: "unambiguous"
679
681
  });
680
682
  const parts = [];
681
- require_recorder.traverse(ast, {
683
+ require_precheck.traverse(ast, {
682
684
  noScope: true,
683
685
  StringLiteral(path) {
684
686
  parts.push(`s:${path.node.value}`);
@@ -843,7 +845,160 @@ function updateBundleBuildState(state, snapshot, linkedByEntry, options = {}) {
843
845
  state.dependentsByLinkedFile = invertLinkedByEntry(state.linkedByEntry);
844
846
  }
845
847
  //#endregion
846
- //#region src/bundlers/vite/generate-bundle.ts
848
+ //#region src/bundlers/vite/generate-bundle/candidates.ts
849
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
850
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
851
+ function isArbitraryValueCandidate(candidate) {
852
+ return candidate.includes("[") && candidate.includes("]");
853
+ }
854
+ function collectUnescapedDynamicCandidates(source) {
855
+ const matches = /* @__PURE__ */ new Set();
856
+ for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
857
+ QUOTED_LITERAL_RE.lastIndex = 0;
858
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
859
+ while (quoted !== null) {
860
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
861
+ for (const candidate of (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, true)) {
862
+ const normalized = candidate.trim();
863
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
864
+ matches.add(normalized);
865
+ }
866
+ quoted = QUOTED_LITERAL_RE.exec(expression);
867
+ }
868
+ }
869
+ return [...matches];
870
+ }
871
+ function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
872
+ if (candidates.has("container")) return candidates;
873
+ if (!sourceCandidates.has("container")) return candidates;
874
+ return new Set([...candidates, "container"]);
875
+ }
876
+ //#endregion
877
+ //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
878
+ function createCssHandlerOptionsCache(options) {
879
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
880
+ const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
881
+ const getCssHandlerOptions = (file) => {
882
+ const majorVersion = options.getMajorVersion();
883
+ const isMainChunk = options.mainCssChunkMatcher(file, options.appType);
884
+ const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
885
+ const cached = cssHandlerOptionsCache.get(cacheKey);
886
+ if (cached) return cached;
887
+ const created = {
888
+ isMainChunk,
889
+ postcssOptions: { options: { from: file } },
890
+ majorVersion
891
+ };
892
+ cssHandlerOptionsCache.set(cacheKey, created);
893
+ return created;
894
+ };
895
+ const getCssUserHandlerOptions = (file) => {
896
+ const cacheKey = `${options.getMajorVersion() ?? "unknown"}:${file}`;
897
+ const cached = cssUserHandlerOptionsCache.get(cacheKey);
898
+ if (cached) return cached;
899
+ const created = {
900
+ ...getCssHandlerOptions(file),
901
+ isMainChunk: false
902
+ };
903
+ cssUserHandlerOptionsCache.set(cacheKey, created);
904
+ return created;
905
+ };
906
+ return {
907
+ getCssHandlerOptions,
908
+ getCssUserHandlerOptions
909
+ };
910
+ }
911
+ //#endregion
912
+ //#region src/bundlers/vite/generate-bundle/css-share-scope.ts
913
+ const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
914
+ const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
915
+ const CSS_IMPORT_RE = /@import\b/i;
916
+ function isPathIndependentCssUrl(value) {
917
+ const normalized = value.trim();
918
+ return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
919
+ }
920
+ function hasPathDependentCssUrl(rawSource) {
921
+ CSS_URL_FUNCTION_RE.lastIndex = 0;
922
+ let match = CSS_URL_FUNCTION_RE.exec(rawSource);
923
+ while (match !== null) {
924
+ if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
925
+ match = CSS_URL_FUNCTION_RE.exec(rawSource);
926
+ }
927
+ return false;
928
+ }
929
+ function createCssTransformShareScope(file, rawSource) {
930
+ if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${require_run_tasks.normalizeOutputPathKey(node_path.default.dirname(file))}`;
931
+ return "global";
932
+ }
933
+ function createCssTransformShareScopeKey(opts, file, rawSource) {
934
+ if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${require_run_tasks.normalizeOutputPathKey(file)}`;
935
+ return createCssTransformShareScope(file, rawSource);
936
+ }
937
+ function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
938
+ return `${runtimeSignature}:${generatorCandidateSignature}`;
939
+ }
940
+ //#endregion
941
+ //#region src/bundlers/vite/generate-bundle/dirty-state.ts
942
+ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
943
+ const currentFileSet = new Set(currentBundleFiles);
944
+ for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
945
+ return false;
946
+ }
947
+ //#endregion
948
+ //#region src/bundlers/vite/generate-bundle/js-entries.ts
949
+ function createJsEntryResolver(jsEntries) {
950
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
951
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(require_run_tasks.normalizeOutputPathKey(id), entry);
952
+ return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(require_run_tasks.normalizeOutputPathKey(id));
953
+ }
954
+ //#endregion
955
+ //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
956
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
957
+ return uniAppX === void 0 ? true : require_tailwindcss.isUniAppXEnabled(uniAppX);
958
+ }
959
+ function createJsHandlerOptionsFactory(options) {
960
+ return (absoluteFilename, extra) => ({
961
+ ...extra,
962
+ filename: absoluteFilename,
963
+ tailwindcssMajorVersion: options.getMajorVersion(),
964
+ moduleGraph: options.moduleGraph,
965
+ babelParserOptions: {
966
+ ...extra?.babelParserOptions ?? {},
967
+ sourceFilename: absoluteFilename
968
+ }
969
+ });
970
+ }
971
+ //#endregion
972
+ //#region src/bundlers/vite/generate-bundle/js-linking.ts
973
+ function createLinkedUpdateHelpers(options) {
974
+ const pendingLinkedUpdates = [];
975
+ const handleLinkedUpdate = (fileName, previous, next) => {
976
+ options.onUpdate(fileName, previous, next);
977
+ options.debug("js linked handle: %s", fileName);
978
+ };
979
+ const scheduleLinkedApply = (entry, code) => {
980
+ pendingLinkedUpdates.push(() => {
981
+ if (entry.output.type === "chunk") entry.output.code = code;
982
+ else entry.output.source = code;
983
+ });
984
+ };
985
+ const applyLinkedUpdates = (linked) => {
986
+ applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
987
+ };
988
+ return {
989
+ applyLinkedUpdates,
990
+ pendingLinkedUpdates
991
+ };
992
+ }
993
+ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
994
+ if (!linked || !linkedSet) return;
995
+ for (const id of Object.keys(linked)) {
996
+ const linkedEntry = getJsEntry(id);
997
+ if (linkedEntry) linkedSet.add(linkedEntry.fileName);
998
+ }
999
+ }
1000
+ //#endregion
1001
+ //#region src/bundlers/vite/generate-bundle/metrics.ts
847
1002
  function formatDebugFileList(files, limit = 8) {
848
1003
  if (files.size === 0) return "-";
849
1004
  const sorted = [...files].sort();
@@ -869,9 +1024,6 @@ function createEmptyMetrics() {
869
1024
  function measureElapsed(start) {
870
1025
  return performance.now() - start;
871
1026
  }
872
- function resolveUniAppXJsTransformEnabled(uniAppX) {
873
- return uniAppX === void 0 ? true : require_logger.isUniAppXEnabled(uniAppX);
874
- }
875
1027
  function formatCacheHitRate(metric) {
876
1028
  if (metric.total === 0) return "0.00%";
877
1029
  return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
@@ -879,6 +1031,50 @@ function formatCacheHitRate(metric) {
879
1031
  function formatMs(value) {
880
1032
  return value.toFixed(2);
881
1033
  }
1034
+ //#endregion
1035
+ //#region src/bundlers/vite/generate-bundle/process-plan.ts
1036
+ function logBundleProcessPlan(options) {
1037
+ const { debug, snapshot, useIncrementalMode, iteration } = options;
1038
+ const { processFiles } = snapshot;
1039
+ if (useIncrementalMode) {
1040
+ debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", iteration, snapshot.changedByType.html.size, formatDebugFileList(snapshot.changedByType.html), snapshot.changedByType.js.size, formatDebugFileList(snapshot.changedByType.js), snapshot.changedByType.css.size, formatDebugFileList(snapshot.changedByType.css), snapshot.changedByType.other.size, formatDebugFileList(snapshot.changedByType.other));
1041
+ debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", iteration, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
1042
+ return;
1043
+ }
1044
+ debug("build mode full process html=%d[%s] js=%d[%s] css=%d[%s]", processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
1045
+ }
1046
+ //#endregion
1047
+ //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
1048
+ function createReplayCssAsset(fileName, source) {
1049
+ return {
1050
+ type: "asset",
1051
+ fileName,
1052
+ name: void 0,
1053
+ source,
1054
+ needsCodeReference: false,
1055
+ names: [],
1056
+ originalFileName: null,
1057
+ originalFileNames: []
1058
+ };
1059
+ }
1060
+ function isAddWatchFileInvalidRollupPhaseError(error) {
1061
+ const candidate = error;
1062
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
1063
+ }
1064
+ function registerGeneratorDependencies(ctx, dependencies) {
1065
+ if (typeof ctx.addWatchFile !== "function") return;
1066
+ for (const dependency of dependencies ?? []) try {
1067
+ ctx.addWatchFile(dependency);
1068
+ } catch (error) {
1069
+ if (isAddWatchFileInvalidRollupPhaseError(error)) {
1070
+ _weapp_tailwindcss_logger.logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
1071
+ continue;
1072
+ }
1073
+ throw error;
1074
+ }
1075
+ }
1076
+ //#endregion
1077
+ //#region src/bundlers/vite/generate-bundle/signatures.ts
882
1078
  function summarizeStringDiff(previous, next) {
883
1079
  if (previous === next) return "same";
884
1080
  const previousLength = previous.length;
@@ -925,128 +1121,22 @@ function getSnapshotHash(snapshotMap, file, fallback) {
925
1121
  function hasRuntimeAffectingSourceChanges(changedByType) {
926
1122
  return changedByType.html.size > 0 || changedByType.js.size > 0;
927
1123
  }
928
- const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
929
- const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
930
- const CSS_IMPORT_RE = /@import\b/i;
931
- function isPathIndependentCssUrl(value) {
932
- const normalized = value.trim();
933
- return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
934
- }
935
- function hasPathDependentCssUrl(rawSource) {
936
- CSS_URL_FUNCTION_RE.lastIndex = 0;
937
- let match = CSS_URL_FUNCTION_RE.exec(rawSource);
938
- while (match !== null) {
939
- if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
940
- match = CSS_URL_FUNCTION_RE.exec(rawSource);
941
- }
942
- return false;
943
- }
944
- function createCssTransformShareScope(file, rawSource) {
945
- if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${require_run_tasks.normalizeOutputPathKey(node_path.default.dirname(file))}`;
946
- return "global";
947
- }
948
- function createCssTransformShareScopeKey(opts, file, rawSource) {
949
- if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${require_run_tasks.normalizeOutputPathKey(file)}`;
950
- return createCssTransformShareScope(file, rawSource);
951
- }
952
- function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
953
- return `${runtimeSignature}:${generatorCandidateSignature}`;
954
- }
955
- function createReplayCssAsset(fileName, source) {
956
- return {
957
- type: "asset",
958
- fileName,
959
- name: void 0,
960
- source,
961
- needsCodeReference: false,
962
- names: [],
963
- originalFileName: null,
964
- originalFileNames: []
965
- };
966
- }
967
- function isAddWatchFileInvalidRollupPhaseError(error) {
968
- const candidate = error;
969
- return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
970
- }
971
- function registerGeneratorDependencies(ctx, dependencies) {
972
- if (typeof ctx.addWatchFile !== "function") return;
973
- for (const dependency of dependencies ?? []) try {
974
- ctx.addWatchFile(dependency);
975
- } catch (error) {
976
- if (isAddWatchFileInvalidRollupPhaseError(error)) {
977
- _weapp_tailwindcss_logger.logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
978
- continue;
979
- }
980
- throw error;
981
- }
982
- }
983
- function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
984
- const currentFileSet = new Set(currentBundleFiles);
985
- for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
986
- return false;
987
- }
988
- const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
989
- const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
990
- function isArbitraryValueCandidate(candidate) {
991
- return candidate.includes("[") && candidate.includes("]");
992
- }
993
- function collectUnescapedDynamicCandidates(source) {
994
- const matches = /* @__PURE__ */ new Set();
995
- for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
996
- QUOTED_LITERAL_RE.lastIndex = 0;
997
- let quoted = QUOTED_LITERAL_RE.exec(expression);
998
- while (quoted !== null) {
999
- const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
1000
- for (const candidate of (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, true)) {
1001
- const normalized = candidate.trim();
1002
- if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
1003
- matches.add(normalized);
1004
- }
1005
- quoted = QUOTED_LITERAL_RE.exec(expression);
1006
- }
1007
- }
1008
- return [...matches];
1009
- }
1010
- function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
1011
- if (candidates.has("container")) return candidates;
1012
- if (!sourceCandidates.has("container")) return candidates;
1013
- return new Set([...candidates, "container"]);
1014
- }
1124
+ //#endregion
1125
+ //#region src/bundlers/vite/generate-bundle.ts
1015
1126
  function createGenerateBundleHook(context) {
1016
1127
  const state = createBundleBuildState();
1017
- const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
1018
- const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
1128
+ const cssHandlerOptions = createCssHandlerOptionsCache({
1129
+ appType: context.opts.appType,
1130
+ mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
1131
+ getMajorVersion: () => context.runtimeState.twPatcher.majorVersion
1132
+ });
1019
1133
  return async function generateBundle(_opt, bundle) {
1020
1134
  const addWatchFile = (id) => this.addWatchFile?.(id);
1021
1135
  const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates } = context;
1022
- const { appType, cache, mainCssChunkMatcher, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
1136
+ const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
1023
1137
  const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
1024
- const getCssHandlerOptions = (file) => {
1025
- const majorVersion = runtimeState.twPatcher.majorVersion;
1026
- const isMainChunk = mainCssChunkMatcher(file, appType);
1027
- const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
1028
- const cached = cssHandlerOptionsCache.get(cacheKey);
1029
- if (cached) return cached;
1030
- const created = {
1031
- isMainChunk,
1032
- postcssOptions: { options: { from: file } },
1033
- majorVersion
1034
- };
1035
- cssHandlerOptionsCache.set(cacheKey, created);
1036
- return created;
1037
- };
1038
- const getCssUserHandlerOptions = (file) => {
1039
- const cacheKey = `${runtimeState.twPatcher.majorVersion ?? "unknown"}:${file}`;
1040
- const cached = cssUserHandlerOptionsCache.get(cacheKey);
1041
- if (cached) return cached;
1042
- const created = {
1043
- ...getCssHandlerOptions(file),
1044
- isMainChunk: false
1045
- };
1046
- cssUserHandlerOptionsCache.set(cacheKey, created);
1047
- return created;
1048
- };
1049
- await runtimeState.patchPromise;
1138
+ const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
1139
+ await runtimeState.readyPromise;
1050
1140
  debug("start");
1051
1141
  onStart();
1052
1142
  const metrics = createEmptyMetrics();
@@ -1063,52 +1153,56 @@ function createGenerateBundleHook(context) {
1063
1153
  const useBundleRuntimeClassSet = useIncrementalMode || runtimeState.twPatcher.majorVersion === 4;
1064
1154
  const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1065
1155
  const processFiles = snapshot.processFiles;
1066
- if (useIncrementalMode) {
1067
- debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", state.iteration + 1, snapshot.changedByType.html.size, formatDebugFileList(snapshot.changedByType.html), snapshot.changedByType.js.size, formatDebugFileList(snapshot.changedByType.js), snapshot.changedByType.css.size, formatDebugFileList(snapshot.changedByType.css), snapshot.changedByType.other.size, formatDebugFileList(snapshot.changedByType.other));
1068
- debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", state.iteration + 1, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
1069
- } else debug("build mode full process html=%d[%s] js=%d[%s] css=%d[%s]", processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
1156
+ logBundleProcessPlan({
1157
+ debug,
1158
+ snapshot,
1159
+ useIncrementalMode,
1160
+ iteration: state.iteration + 1
1161
+ });
1070
1162
  const jsEntries = snapshot.jsEntries;
1071
- const normalizedJsEntries = /* @__PURE__ */ new Map();
1072
- for (const [id, entry] of jsEntries) normalizedJsEntries.set(require_run_tasks.normalizeOutputPathKey(id), entry);
1073
- const getJsEntry = (id) => jsEntries.get(id) ?? normalizedJsEntries.get(require_run_tasks.normalizeOutputPathKey(id));
1163
+ const getJsEntry = createJsEntryResolver(jsEntries);
1074
1164
  const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
1075
1165
  const runtimeStart = performance.now();
1076
1166
  const runtime = useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1077
1167
  const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
1078
1168
  await waitForSourceCandidateSyncs?.();
1079
1169
  const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
1080
- const collectedGeneratorCandidates = new Set(sourceCandidates);
1170
+ const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
1081
1171
  const generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? require_generator.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
1082
1172
  const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
1083
1173
  recordGeneratorCandidates?.(generatorRuntime);
1084
- const defaultTemplateHandlerOptions = { runtimeSet: runtime };
1174
+ let transformRuntime = runtime;
1175
+ if (runtimeState.twPatcher.majorVersion === 3 && generatorRuntime.size > 0) {
1176
+ const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
1177
+ const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
1178
+ if (mainCssEntry) {
1179
+ const validatedRuntime = await require_generator_css.validateCandidatesByGenerator({
1180
+ opts,
1181
+ runtimeState,
1182
+ candidates: generatorRuntime,
1183
+ rawSource: mainCssEntry.source,
1184
+ file: mainCssEntry.file,
1185
+ cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
1186
+ cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
1187
+ styleHandler,
1188
+ debug
1189
+ });
1190
+ if (validatedRuntime.size > 0) transformRuntime = new Set([...runtime, ...validatedRuntime]);
1191
+ }
1192
+ }
1193
+ const defaultTemplateHandlerOptions = { runtimeSet: transformRuntime };
1085
1194
  metrics.runtimeSet = measureElapsed(runtimeStart);
1086
1195
  if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
1087
- debug("get runtimeSet, class count: %d", runtime.size);
1088
- const runtimeSignature = require_logger.getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1089
- const handleLinkedUpdate = (fileName, previous, next) => {
1090
- onUpdate(fileName, previous, next);
1091
- debug("js linked handle: %s", fileName);
1092
- };
1093
- const pendingLinkedUpdates = [];
1094
- const scheduleLinkedApply = (entry, code) => {
1095
- pendingLinkedUpdates.push(() => {
1096
- if (entry.output.type === "chunk") entry.output.code = code;
1097
- else entry.output.source = code;
1098
- });
1099
- };
1100
- const applyLinkedUpdates = (linked) => {
1101
- applyLinkedResults(linked, jsEntries, handleLinkedUpdate, scheduleLinkedApply);
1102
- };
1103
- const createHandlerOptions = (absoluteFilename, extra) => ({
1104
- ...extra,
1105
- filename: absoluteFilename,
1106
- tailwindcssMajorVersion: runtimeState.twPatcher.majorVersion,
1107
- moduleGraph: moduleGraphOptions,
1108
- babelParserOptions: {
1109
- ...extra?.babelParserOptions ?? {},
1110
- sourceFilename: absoluteFilename
1111
- }
1196
+ debug("get runtimeSet, class count: %d, transform class count: %d", runtime.size, transformRuntime.size);
1197
+ const runtimeSignature = require_cache.getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1198
+ const { applyLinkedUpdates, pendingLinkedUpdates } = createLinkedUpdateHelpers({
1199
+ jsEntries,
1200
+ onUpdate,
1201
+ debug
1202
+ });
1203
+ const createHandlerOptions = createJsHandlerOptionsFactory({
1204
+ getMajorVersion: () => runtimeState.twPatcher.majorVersion,
1205
+ moduleGraph: moduleGraphOptions
1112
1206
  });
1113
1207
  const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
1114
1208
  const sharedCssResultCache = /* @__PURE__ */ new Map();
@@ -1186,7 +1280,7 @@ function createGenerateBundleHook(context) {
1186
1280
  }
1187
1281
  const runTransform = async () => {
1188
1282
  const start = performance.now();
1189
- await runtimeState.patchPromise;
1283
+ await runtimeState.readyPromise;
1190
1284
  const generated = await require_generator_css.generateCssByGenerator({
1191
1285
  opts,
1192
1286
  runtimeState,
@@ -1252,20 +1346,17 @@ function createGenerateBundleHook(context) {
1252
1346
  const rawSource = originalSource.code;
1253
1347
  if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1254
1348
  const handlerOptions = createHandlerOptions(absoluteFile);
1255
- if (!disableJsPrecheck && require_recorder.shouldSkipJsTransform(rawSource, handlerOptions)) {
1349
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(rawSource, handlerOptions)) {
1256
1350
  metrics.js.elapsed += measureElapsed(start);
1257
1351
  metrics.js.transformed++;
1258
1352
  return { result: rawSource };
1259
1353
  }
1260
- const { code, linked } = await jsHandler(rawSource, runtime, handlerOptions);
1354
+ const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
1261
1355
  metrics.js.elapsed += measureElapsed(start);
1262
1356
  metrics.js.transformed++;
1263
1357
  onUpdate(file, rawSource, code);
1264
1358
  debug("js handle: %s", file);
1265
- if (linked) for (const id of Object.keys(linked)) {
1266
- const linkedEntry = getJsEntry(id);
1267
- if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1268
- }
1359
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1269
1360
  applyLinkedUpdates(linked);
1270
1361
  return { result: code };
1271
1362
  }
@@ -1276,10 +1367,7 @@ function createGenerateBundleHook(context) {
1276
1367
  if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1277
1368
  const baseApplyLinkedUpdates = applyLinkedUpdates;
1278
1369
  const wrappedApplyLinkedUpdates = (linked) => {
1279
- if (linked) for (const id of Object.keys(linked)) {
1280
- const linkedEntry = getJsEntry(id);
1281
- if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1282
- }
1370
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1283
1371
  baseApplyLinkedUpdates(linked);
1284
1372
  };
1285
1373
  const factory = createUniAppXAssetTask(file, originalSource, outDir, {
@@ -1290,7 +1378,7 @@ function createGenerateBundleHook(context) {
1290
1378
  debug,
1291
1379
  jsHandler,
1292
1380
  onUpdate,
1293
- runtimeSet: runtime,
1381
+ runtimeSet: transformRuntime,
1294
1382
  applyLinkedResults: wrappedApplyLinkedUpdates,
1295
1383
  uniAppX
1296
1384
  });
@@ -1311,7 +1399,7 @@ function createGenerateBundleHook(context) {
1311
1399
  sourceType: "unambiguous"
1312
1400
  }
1313
1401
  });
1314
- if (!disableJsPrecheck && require_recorder.shouldSkipJsTransform(currentSource, precheckOptions)) {
1402
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(currentSource, precheckOptions)) {
1315
1403
  metrics.js.elapsed += measureElapsed(start);
1316
1404
  metrics.js.transformed++;
1317
1405
  return;
@@ -1370,13 +1458,241 @@ function createGenerateBundleHook(context) {
1370
1458
  };
1371
1459
  }
1372
1460
  //#endregion
1373
- //#region src/bundlers/vite/incremental-runtime-class-set.ts
1374
- const debug$1 = require_recorder.createDebug("[vite:runtime-set] ");
1375
- const EXTENSION_DOT_PREFIX_RE = /^\./;
1376
- function createExtractOptions(context, source) {
1377
- return {
1378
- cwd: context.projectRoot,
1379
- base: context.base,
1461
+ //#region src/bundlers/vite/official-tailwind-plugins.ts
1462
+ const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1463
+ function getPostcssPluginName(plugin) {
1464
+ if (!plugin) return;
1465
+ if (typeof plugin === "function" && "postcss" in plugin) try {
1466
+ return getPostcssPluginName(plugin());
1467
+ } catch {
1468
+ return;
1469
+ }
1470
+ if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1471
+ const { postcssPlugin } = plugin;
1472
+ return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1473
+ }
1474
+ function isTailwindPostcssPlugin(plugin) {
1475
+ const name = getPostcssPluginName(plugin);
1476
+ return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1477
+ }
1478
+ function removeTailwindPostcssPlugins(plugins) {
1479
+ let removed = 0;
1480
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1481
+ plugins.splice(i, 1);
1482
+ removed++;
1483
+ }
1484
+ return removed;
1485
+ }
1486
+ function isTailwindVitePlugin(plugin) {
1487
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1488
+ const { name } = plugin;
1489
+ return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1490
+ }
1491
+ function removeTailwindVitePlugins(plugins) {
1492
+ let removed = 0;
1493
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1494
+ plugins.splice(i, 1);
1495
+ removed++;
1496
+ }
1497
+ return removed;
1498
+ }
1499
+ function disableTailwindVitePlugin(plugin) {
1500
+ if (!isTailwindVitePlugin(plugin)) return false;
1501
+ const mutablePlugin = plugin;
1502
+ for (const hook of [
1503
+ "configResolved",
1504
+ "configureServer",
1505
+ "transform",
1506
+ "hotUpdate",
1507
+ "handleHotUpdate"
1508
+ ]) delete mutablePlugin[hook];
1509
+ return true;
1510
+ }
1511
+ function disableAndRemoveTailwindVitePlugins(plugins) {
1512
+ let removed = 0;
1513
+ for (let i = plugins.length - 1; i >= 0; i--) {
1514
+ const plugin = plugins[i];
1515
+ if (Array.isArray(plugin)) {
1516
+ removed += disableAndRemoveTailwindVitePlugins(plugin);
1517
+ if (plugin.length === 0) plugins.splice(i, 1);
1518
+ continue;
1519
+ }
1520
+ if (disableTailwindVitePlugin(plugin)) {
1521
+ plugins.splice(i, 1);
1522
+ removed++;
1523
+ }
1524
+ }
1525
+ return removed;
1526
+ }
1527
+ //#endregion
1528
+ //#region src/bundlers/vite/postcss-config.ts
1529
+ async function resolveFilteredPostcssConfig(root) {
1530
+ try {
1531
+ const loaded = await (0, postcss_load_config.default)({}, root);
1532
+ const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1533
+ const removed = removeTailwindPostcssPlugins(plugins);
1534
+ if (removed === 0) return;
1535
+ return {
1536
+ options: loaded.options,
1537
+ plugins,
1538
+ removed
1539
+ };
1540
+ } catch (error) {
1541
+ if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1542
+ throw error;
1543
+ }
1544
+ }
1545
+ //#endregion
1546
+ //#region src/bundlers/vite/resolve-app-type.ts
1547
+ const PACKAGE_JSON_FILE$1 = "package.json";
1548
+ const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
1549
+ const TARO_SCRIPT_RE = /\btaro\b/u;
1550
+ const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
1551
+ function resolveDependencyNames(pkg) {
1552
+ return new Set([
1553
+ ...Object.keys(pkg.dependencies ?? {}),
1554
+ ...Object.keys(pkg.devDependencies ?? {}),
1555
+ ...Object.keys(pkg.peerDependencies ?? {}),
1556
+ ...Object.keys(pkg.optionalDependencies ?? {})
1557
+ ]);
1558
+ }
1559
+ function hasScriptMatch(pkg, pattern) {
1560
+ return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
1561
+ }
1562
+ function resolveAppTypeFromPackageJson(pkg) {
1563
+ const dependencyNames = resolveDependencyNames(pkg);
1564
+ if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
1565
+ if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
1566
+ if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
1567
+ if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
1568
+ if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
1569
+ }
1570
+ function tryReadUniAppManifest(root) {
1571
+ const manifestPath = node_path.default.join(root, "manifest.json");
1572
+ if (!(0, node_fs.existsSync)(manifestPath)) return;
1573
+ try {
1574
+ return JSON.parse((0, node_fs.readFileSync)(manifestPath, "utf8"));
1575
+ } catch {}
1576
+ }
1577
+ function tryReadPackageJson(root) {
1578
+ const packageJsonPath = node_path.default.join(root, PACKAGE_JSON_FILE$1);
1579
+ if (!(0, node_fs.existsSync)(packageJsonPath)) return;
1580
+ try {
1581
+ return JSON.parse((0, node_fs.readFileSync)(packageJsonPath, "utf8"));
1582
+ } catch {}
1583
+ }
1584
+ function resolveAppTypeFromMarkers(root) {
1585
+ for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if ((0, node_fs.existsSync)(node_path.default.join(root, relativePath))) return appType;
1586
+ }
1587
+ function resolveImplicitAppTypeFromViteRoot(root) {
1588
+ const resolvedRoot = node_path.default.resolve(root);
1589
+ if (!(0, node_fs.existsSync)(resolvedRoot)) return;
1590
+ const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
1591
+ if (markerDetected) return markerDetected;
1592
+ let current = resolvedRoot;
1593
+ while (true) {
1594
+ const manifest = tryReadUniAppManifest(current);
1595
+ if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
1596
+ const pkg = tryReadPackageJson(current);
1597
+ if (pkg) {
1598
+ const detected = resolveAppTypeFromPackageJson(pkg);
1599
+ if (detected) return detected;
1600
+ }
1601
+ const parent = node_path.default.dirname(current);
1602
+ if (parent === current) break;
1603
+ current = parent;
1604
+ }
1605
+ }
1606
+ //#endregion
1607
+ //#region src/bundlers/shared/css-imports.ts
1608
+ const tailwindcssImportRE = /^tailwindcss(?:\/.*)?$/;
1609
+ const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])(tailwindcss(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
1610
+ function normalizeTailwindcssSpecifier(specifier) {
1611
+ if (specifier === "tailwindcss$") return "tailwindcss";
1612
+ return specifier;
1613
+ }
1614
+ function getTailwindcssSubpath(specifier) {
1615
+ if (specifier === "tailwindcss") return "index.css";
1616
+ return specifier.slice(12);
1617
+ }
1618
+ function resolveTailwindcssImport(specifier, pkgDir, options) {
1619
+ const normalized = normalizeTailwindcssSpecifier(specifier);
1620
+ if (!tailwindcssImportRE.test(normalized)) return null;
1621
+ if (normalized === "tailwindcss") return options?.rootImport ?? "weapp-tailwindcss/index.css";
1622
+ return (options?.join ?? node_path.default.join)(pkgDir, getTailwindcssSubpath(normalized));
1623
+ }
1624
+ function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
1625
+ let hasReplacements = false;
1626
+ const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
1627
+ const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
1628
+ if (!replacement) return full;
1629
+ hasReplacements = true;
1630
+ return `${prefix}${quote}${replacement}${suffix}`;
1631
+ });
1632
+ return hasReplacements ? rewritten : void 0;
1633
+ }
1634
+ //#endregion
1635
+ //#region src/bundlers/vite/rewrite-css-imports.ts
1636
+ function joinPosixPath(base, subpath) {
1637
+ if (base.endsWith("/")) return `${base}${subpath}`;
1638
+ return `${base}/${subpath}`;
1639
+ }
1640
+ function isCssLikeImporter(importer) {
1641
+ if (!importer) return false;
1642
+ const normalized = (0, _weapp_tailwindcss_shared.cleanUrl)(importer);
1643
+ return isCSSRequest(normalized) || normalized.endsWith("/*");
1644
+ }
1645
+ function stripTailwindConfigDirectives(code) {
1646
+ return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
1647
+ }
1648
+ function createRewriteCssImportsPlugins(options) {
1649
+ if (!options.shouldRewrite) return [];
1650
+ const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
1651
+ const resolveAppType = () => getAppType?.() ?? appType;
1652
+ return [{
1653
+ name: `${require_precheck.vitePluginName}:rewrite-css-imports`,
1654
+ enforce: "pre",
1655
+ resolveId: {
1656
+ order: "pre",
1657
+ handler(id, importer) {
1658
+ const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1659
+ join: joinPosixPath,
1660
+ appType: resolveAppType(),
1661
+ rootImport
1662
+ });
1663
+ if (!replacement) return null;
1664
+ if (importer && !isCssLikeImporter(importer)) return null;
1665
+ return replacement;
1666
+ }
1667
+ },
1668
+ transform: {
1669
+ order: "pre",
1670
+ async handler(code, id) {
1671
+ if (!isCSSRequest(id)) return null;
1672
+ if (require_generator_css.hasTailwindRootDirectives(code)) await options.onTailwindRootCss?.(id, code);
1673
+ const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1674
+ join: joinPosixPath,
1675
+ appType: resolveAppType(),
1676
+ rootImport
1677
+ });
1678
+ const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? code) : rewritten;
1679
+ if (!nextCode || nextCode === code) return null;
1680
+ return {
1681
+ code: nextCode,
1682
+ map: null
1683
+ };
1684
+ }
1685
+ }
1686
+ }];
1687
+ }
1688
+ //#endregion
1689
+ //#region src/bundlers/vite/incremental-runtime-class-set.ts
1690
+ const debug$1 = require_runtime_patch.createDebug("[vite:runtime-set] ");
1691
+ const EXTENSION_DOT_PREFIX_RE = /^\./;
1692
+ function createExtractOptions(context, source) {
1693
+ return {
1694
+ cwd: context.projectRoot,
1695
+ base: context.base,
1380
1696
  baseFallbacks: context.baseFallbacks,
1381
1697
  css: context.css,
1382
1698
  content: source,
@@ -1480,7 +1796,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
1480
1796
  return candidates;
1481
1797
  }
1482
1798
  async function sync(patcher, snapshot) {
1483
- const nextSignature = require_logger.getRuntimeClassSetSignature(patcher) ?? "runtime:missing";
1799
+ const nextSignature = require_cache.getRuntimeClassSetSignature(patcher) ?? "runtime:missing";
1484
1800
  const runtimeEntries = createRuntimeEntries(snapshot);
1485
1801
  const runtimeEntriesByFile = new Map(runtimeEntries.map((entry) => [entry.file, entry]));
1486
1802
  const currentRuntimeFiles = new Set(runtimeEntriesByFile.keys());
@@ -1534,146 +1850,111 @@ function createBundleRuntimeClassSetManager(options = {}) {
1534
1850
  };
1535
1851
  }
1536
1852
  //#endregion
1537
- //#region src/bundlers/vite/resolve-app-type.ts
1538
- const PACKAGE_JSON_FILE$1 = "package.json";
1539
- const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
1540
- const TARO_SCRIPT_RE = /\btaro\b/u;
1541
- const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
1542
- function resolveDependencyNames(pkg) {
1543
- return new Set([
1544
- ...Object.keys(pkg.dependencies ?? {}),
1545
- ...Object.keys(pkg.devDependencies ?? {}),
1546
- ...Object.keys(pkg.peerDependencies ?? {}),
1547
- ...Object.keys(pkg.optionalDependencies ?? {})
1548
- ]);
1549
- }
1550
- function hasScriptMatch(pkg, pattern) {
1551
- return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
1552
- }
1553
- function resolveAppTypeFromPackageJson(pkg) {
1554
- const dependencyNames = resolveDependencyNames(pkg);
1555
- if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
1556
- if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
1557
- if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
1558
- if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
1559
- if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
1560
- }
1561
- function tryReadUniAppManifest(root) {
1562
- const manifestPath = node_path.default.join(root, "manifest.json");
1563
- if (!(0, node_fs.existsSync)(manifestPath)) return;
1564
- try {
1565
- return JSON.parse((0, node_fs.readFileSync)(manifestPath, "utf8"));
1566
- } catch {}
1567
- }
1568
- function tryReadPackageJson(root) {
1569
- const packageJsonPath = node_path.default.join(root, PACKAGE_JSON_FILE$1);
1570
- if (!(0, node_fs.existsSync)(packageJsonPath)) return;
1571
- try {
1572
- return JSON.parse((0, node_fs.readFileSync)(packageJsonPath, "utf8"));
1573
- } catch {}
1574
- }
1575
- function resolveAppTypeFromMarkers(root) {
1576
- for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if ((0, node_fs.existsSync)(node_path.default.join(root, relativePath))) return appType;
1577
- }
1578
- function resolveImplicitAppTypeFromViteRoot(root) {
1579
- const resolvedRoot = node_path.default.resolve(root);
1580
- if (!(0, node_fs.existsSync)(resolvedRoot)) return;
1581
- const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
1582
- if (markerDetected) return markerDetected;
1583
- let current = resolvedRoot;
1584
- while (true) {
1585
- const manifest = tryReadUniAppManifest(current);
1586
- if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
1587
- const pkg = tryReadPackageJson(current);
1588
- if (pkg) {
1589
- const detected = resolveAppTypeFromPackageJson(pkg);
1590
- if (detected) return detected;
1853
+ //#region src/bundlers/vite/runtime-class-set.ts
1854
+ function createViteRuntimeClassSet(options) {
1855
+ const { opts, initialTwPatcher, refreshTailwindcssPatcher, uniAppXEnabled, customAttributesEntities, disabledDefaultTemplateHandler, debug } = options;
1856
+ const runtimeState = {
1857
+ twPatcher: initialTwPatcher,
1858
+ readyPromise: require_precheck.createTailwindRuntimeReadyPromise(initialTwPatcher),
1859
+ refreshTailwindcssPatcher
1860
+ };
1861
+ const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1862
+ let runtimeSet;
1863
+ let runtimeSetPromise;
1864
+ let runtimeRefreshSignature;
1865
+ let runtimeRefreshOptionsKey;
1866
+ function resolveRuntimeRefreshOptions() {
1867
+ const configPath = require_cache.resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1868
+ const signature = require_cache.getRuntimeClassSetSignature(runtimeState.twPatcher);
1869
+ const optionsKey = JSON.stringify({
1870
+ appType: opts.appType,
1871
+ uniAppX: uniAppXEnabled,
1872
+ customAttributesEntities,
1873
+ disabledDefaultTemplateHandler,
1874
+ configPath
1875
+ });
1876
+ const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1877
+ runtimeRefreshSignature = signature;
1878
+ runtimeRefreshOptionsKey = optionsKey;
1879
+ return {
1880
+ changed,
1881
+ signature,
1882
+ optionsKey
1883
+ };
1884
+ }
1885
+ async function refreshRuntimeState(force) {
1886
+ const invalidation = resolveRuntimeRefreshOptions();
1887
+ const refreshed = await require_precheck.refreshTailwindRuntimeState(runtimeState, {
1888
+ force: force || invalidation.changed,
1889
+ clearCache: force || invalidation.changed
1890
+ });
1891
+ if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
1892
+ if (refreshed) {
1893
+ runtimeSet = void 0;
1894
+ runtimeSetPromise = void 0;
1591
1895
  }
1592
- const parent = node_path.default.dirname(current);
1593
- if (parent === current) break;
1594
- current = parent;
1595
1896
  }
1596
- }
1597
- //#endregion
1598
- //#region src/bundlers/shared/css-imports.ts
1599
- const tailwindcssImportRE = /^tailwindcss(?:\/.*)?$/;
1600
- const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])(tailwindcss(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
1601
- function normalizeTailwindcssSpecifier(specifier) {
1602
- if (specifier === "tailwindcss$") return "tailwindcss";
1603
- return specifier;
1604
- }
1605
- function getTailwindcssSubpath(specifier) {
1606
- if (specifier === "tailwindcss") return "index.css";
1607
- return specifier.slice(12);
1608
- }
1609
- function resolveTailwindcssImport(specifier, pkgDir, options) {
1610
- const normalized = normalizeTailwindcssSpecifier(specifier);
1611
- if (!tailwindcssImportRE.test(normalized)) return null;
1612
- if (normalized === "tailwindcss") return options?.rootImport ?? "weapp-tailwindcss/index.css";
1613
- return (options?.join ?? node_path.default.join)(pkgDir, getTailwindcssSubpath(normalized));
1614
- }
1615
- function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
1616
- let hasReplacements = false;
1617
- const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
1618
- const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
1619
- if (!replacement) return full;
1620
- hasReplacements = true;
1621
- return `${prefix}${quote}${replacement}${suffix}`;
1622
- });
1623
- return hasReplacements ? rewritten : void 0;
1624
- }
1625
- //#endregion
1626
- //#region src/bundlers/vite/rewrite-css-imports.ts
1627
- function joinPosixPath(base, subpath) {
1628
- if (base.endsWith("/")) return `${base}${subpath}`;
1629
- return `${base}/${subpath}`;
1630
- }
1631
- function isCssLikeImporter(importer) {
1632
- if (!importer) return false;
1633
- const normalized = (0, _weapp_tailwindcss_shared.cleanUrl)(importer);
1634
- return isCSSRequest(normalized) || normalized.endsWith("/*");
1635
- }
1636
- function stripTailwindConfigDirectives(code) {
1637
- return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
1638
- }
1639
- function createRewriteCssImportsPlugins(options) {
1640
- if (!options.shouldRewrite) return [];
1641
- const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
1642
- const resolveAppType = () => getAppType?.() ?? appType;
1643
- return [{
1644
- name: `${require_recorder.vitePluginName}:rewrite-css-imports`,
1645
- enforce: "pre",
1646
- resolveId: {
1647
- order: "pre",
1648
- handler(id, importer) {
1649
- const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1650
- join: joinPosixPath,
1651
- appType: resolveAppType(),
1652
- rootImport
1653
- });
1654
- if (!replacement) return null;
1655
- if (importer && !isCssLikeImporter(importer)) return null;
1656
- return replacement;
1657
- }
1658
- },
1659
- transform: {
1660
- order: "pre",
1661
- handler(code, id) {
1662
- if (!isCSSRequest(id)) return null;
1663
- const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1664
- join: joinPosixPath,
1665
- appType: resolveAppType(),
1666
- rootImport
1667
- });
1668
- const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? code) : rewritten;
1669
- if (!nextCode || nextCode === code) return null;
1670
- return {
1671
- code: nextCode,
1672
- map: null
1673
- };
1674
- }
1897
+ async function ensureRuntimeClassSet(force = false) {
1898
+ const forceRuntimeRefresh = force || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1899
+ await refreshRuntimeState(force);
1900
+ await runtimeState.readyPromise;
1901
+ if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
1902
+ if (forceRuntimeRefresh || !runtimeSetPromise) {
1903
+ const invalidation = resolveRuntimeRefreshOptions();
1904
+ runtimeSetPromise = require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
1905
+ force: forceRuntimeRefresh || invalidation.changed,
1906
+ skipRefresh: forceRuntimeRefresh,
1907
+ clearCache: forceRuntimeRefresh || invalidation.changed
1908
+ });
1675
1909
  }
1676
- }];
1910
+ const task = runtimeSetPromise;
1911
+ try {
1912
+ runtimeSet = await task;
1913
+ return runtimeSet;
1914
+ } finally {
1915
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1916
+ }
1917
+ }
1918
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
1919
+ const forceRuntimeRefresh = forceRefresh || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1920
+ const invalidation = resolveRuntimeRefreshOptions();
1921
+ const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
1922
+ const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
1923
+ await refreshRuntimeState(shouldRefreshPatcher);
1924
+ await runtimeState.readyPromise;
1925
+ if (shouldRefreshPatcher) {
1926
+ runtimeSet = void 0;
1927
+ runtimeSetPromise = void 0;
1928
+ await bundleRuntimeClassSetManager.reset();
1929
+ }
1930
+ if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
1931
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
1932
+ runtimeSet = nextRuntimeSet;
1933
+ return nextRuntimeSet;
1934
+ } catch (error) {
1935
+ debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1936
+ await bundleRuntimeClassSetManager.reset();
1937
+ }
1938
+ if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
1939
+ const task = require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
1940
+ force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
1941
+ skipRefresh: forceRuntimeRefresh,
1942
+ clearCache: forceRuntimeRefresh || invalidation.changed
1943
+ });
1944
+ runtimeSetPromise = task;
1945
+ try {
1946
+ runtimeSet = await task;
1947
+ return runtimeSet;
1948
+ } finally {
1949
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1950
+ }
1951
+ }
1952
+ return {
1953
+ runtimeState,
1954
+ refreshRuntimeState,
1955
+ ensureRuntimeClassSet,
1956
+ ensureBundleRuntimeClassSet
1957
+ };
1677
1958
  }
1678
1959
  //#endregion
1679
1960
  //#region src/bundlers/vite/source-candidates.ts
@@ -1828,92 +2109,8 @@ function createSourceCandidateCollector() {
1828
2109
  };
1829
2110
  }
1830
2111
  //#endregion
1831
- //#region src/bundlers/vite/index.ts
1832
- const debug = require_recorder.createDebug();
1833
- const weappTailwindcssPackageDir = require_run_tasks.resolvePackageDir("weapp-tailwindcss");
1834
- const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
2112
+ //#region src/bundlers/vite/tailwind-basedir.ts
1835
2113
  const PACKAGE_JSON_FILE = "package.json";
1836
- const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1837
- function getPostcssPluginName(plugin) {
1838
- if (!plugin) return;
1839
- if (typeof plugin === "function" && "postcss" in plugin) try {
1840
- return getPostcssPluginName(plugin());
1841
- } catch {
1842
- return;
1843
- }
1844
- if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1845
- const { postcssPlugin } = plugin;
1846
- return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1847
- }
1848
- function isTailwindPostcssPlugin(plugin) {
1849
- const name = getPostcssPluginName(plugin);
1850
- return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1851
- }
1852
- function removeTailwindPostcssPlugins(plugins) {
1853
- let removed = 0;
1854
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1855
- plugins.splice(i, 1);
1856
- removed++;
1857
- }
1858
- return removed;
1859
- }
1860
- async function resolveFilteredPostcssConfig(root) {
1861
- try {
1862
- const loaded = await (0, postcss_load_config.default)({}, root);
1863
- const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1864
- const removed = removeTailwindPostcssPlugins(plugins);
1865
- if (removed === 0) return;
1866
- return {
1867
- options: loaded.options,
1868
- plugins,
1869
- removed
1870
- };
1871
- } catch (error) {
1872
- if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1873
- throw error;
1874
- }
1875
- }
1876
- function isTailwindVitePlugin(plugin) {
1877
- if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1878
- const { name } = plugin;
1879
- return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1880
- }
1881
- function removeTailwindVitePlugins(plugins) {
1882
- let removed = 0;
1883
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1884
- plugins.splice(i, 1);
1885
- removed++;
1886
- }
1887
- return removed;
1888
- }
1889
- function disableTailwindVitePlugin(plugin) {
1890
- if (!isTailwindVitePlugin(plugin)) return false;
1891
- const mutablePlugin = plugin;
1892
- for (const hook of [
1893
- "configResolved",
1894
- "configureServer",
1895
- "transform",
1896
- "hotUpdate",
1897
- "handleHotUpdate"
1898
- ]) delete mutablePlugin[hook];
1899
- return true;
1900
- }
1901
- function disableAndRemoveTailwindVitePlugins(plugins) {
1902
- let removed = 0;
1903
- for (let i = plugins.length - 1; i >= 0; i--) {
1904
- const plugin = plugins[i];
1905
- if (Array.isArray(plugin)) {
1906
- removed += disableAndRemoveTailwindVitePlugins(plugin);
1907
- if (plugin.length === 0) plugins.splice(i, 1);
1908
- continue;
1909
- }
1910
- if (disableTailwindVitePlugin(plugin)) {
1911
- plugins.splice(i, 1);
1912
- removed++;
1913
- }
1914
- }
1915
- return removed;
1916
- }
1917
2114
  function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1918
2115
  const resolvedRoot = node_path.default.resolve(root);
1919
2116
  if (!(0, node_fs.existsSync)(resolvedRoot)) return resolvedRoot;
@@ -1925,12 +2122,17 @@ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1925
2122
  if (parent === current) break;
1926
2123
  current = parent;
1927
2124
  }
1928
- const tailwindConfigPath = require_logger.findTailwindConfig(searchRoots);
2125
+ const tailwindConfigPath = require_cache.findTailwindConfig(searchRoots);
1929
2126
  if (tailwindConfigPath) return node_path.default.dirname(tailwindConfigPath);
1930
- const packageRoot = require_logger.findNearestPackageRoot(resolvedRoot);
2127
+ const packageRoot = require_cache.findNearestPackageRoot(resolvedRoot);
1931
2128
  if (packageRoot && (0, node_fs.existsSync)(node_path.default.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1932
2129
  return resolvedRoot;
1933
2130
  }
2131
+ //#endregion
2132
+ //#region src/bundlers/vite/index.ts
2133
+ const debug = require_runtime_patch.createDebug();
2134
+ const weappTailwindcssPackageDir = require_run_tasks.resolvePackageDir("weapp-tailwindcss");
2135
+ const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1934
2136
  /**
1935
2137
  * @name WeappTailwindcss
1936
2138
  * @description uni-app vite / uni-app-x 版本插件
@@ -1939,131 +2141,68 @@ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1939
2141
  function WeappTailwindcss(options = {}) {
1940
2142
  const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
1941
2143
  const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1942
- const opts = require_recorder.getCompilerContext(options);
2144
+ const opts = require_precheck.getCompilerContext({
2145
+ ...options,
2146
+ __internalDeferMissingCssEntriesWarning: true
2147
+ });
1943
2148
  const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
1944
- const uniAppXEnabled = require_logger.isUniAppXEnabled(uniAppX);
2149
+ const uniAppXEnabled = require_tailwindcss.isUniAppXEnabled(uniAppX);
1945
2150
  const disabledOptions = require_run_tasks.resolvePluginDisabledState(disabled);
1946
2151
  const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1947
2152
  const shouldOwnTailwindGeneration = !disabledOptions.plugin;
1948
2153
  const shouldRewriteCssImports = tailwindcssMajorVersion >= 4;
2154
+ const hasInitialTailwindCssRoots = require_tailwindcss.hasConfiguredTailwindV4CssRoots({
2155
+ ...options,
2156
+ cssEntries: opts.cssEntries ?? options.cssEntries
2157
+ });
2158
+ const autoCssSourceContent = /* @__PURE__ */ new Map();
2159
+ let refreshRuntimeStateForAutoCssSources;
2160
+ let autoCssSourcesRefresh;
2161
+ const registerAutoCssSource = async (id, css) => {
2162
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots) return;
2163
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2164
+ if (!node_path.default.isAbsolute(file)) return;
2165
+ const sourceFile = node_path.default.normalize(file);
2166
+ if (autoCssSourceContent.get(sourceFile) === css) return;
2167
+ autoCssSourceContent.set(sourceFile, css);
2168
+ require_tailwindcss.upsertTailwindV4CssSource(opts, {
2169
+ file: sourceFile,
2170
+ css
2171
+ });
2172
+ debug("detected tailwindcss v4 css source from vite css module: %s", sourceFile);
2173
+ autoCssSourcesRefresh = (autoCssSourcesRefresh ?? Promise.resolve()).then(async () => {
2174
+ await refreshRuntimeStateForAutoCssSources?.(true);
2175
+ });
2176
+ await autoCssSourcesRefresh;
2177
+ };
1949
2178
  const rewritePlugins = createRewriteCssImportsPlugins({
1950
2179
  getAppType: () => opts.appType,
1951
2180
  rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
2181
+ onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
1952
2182
  shouldOwnTailwindGeneration,
1953
2183
  shouldRewrite: shouldRewriteCssImports,
1954
2184
  weappTailwindcssDirPosix
1955
2185
  });
1956
2186
  if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
1957
- const customAttributesEntities = require_recorder.toCustomAttributesEntities(customAttributes);
1958
- const patchRecorderState = require_recorder.setupPatchRecorder(initialTwPatcher, opts.tailwindcssBasedir, {
1959
- source: "runtime",
1960
- cwd: opts.tailwindcssBasedir ?? node_process.default.cwd()
1961
- });
1962
- const runtimeState = {
1963
- twPatcher: initialTwPatcher,
1964
- patchPromise: patchRecorderState.patchPromise,
1965
- refreshTailwindcssPatcher,
1966
- onPatchCompleted: patchRecorderState.onPatchCompleted
1967
- };
1968
- let runtimeSet;
1969
- let runtimeSetPromise;
2187
+ const customAttributesEntities = require_precheck.toCustomAttributesEntities(customAttributes);
1970
2188
  let resolvedConfig;
1971
- let runtimeRefreshSignature;
1972
- let runtimeRefreshOptionsKey;
1973
2189
  let recordedGeneratorCandidates;
1974
- const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1975
2190
  const sourceCandidateCollector = createSourceCandidateCollector();
1976
2191
  const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
1977
2192
  const processedCssAssets = /* @__PURE__ */ new WeakSet();
1978
2193
  const processedCssAssetFiles = /* @__PURE__ */ new Set();
1979
2194
  const rememberedMainCssSources = /* @__PURE__ */ new Map();
1980
2195
  const rememberedMainCssSignatureByFile = /* @__PURE__ */ new Map();
1981
- function resolveRuntimeRefreshOptions() {
1982
- const configPath = require_patcher_options.resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1983
- const signature = require_logger.getRuntimeClassSetSignature(runtimeState.twPatcher);
1984
- const optionsKey = JSON.stringify({
1985
- appType: opts.appType,
1986
- uniAppX: uniAppXEnabled,
1987
- customAttributesEntities,
1988
- disabledDefaultTemplateHandler,
1989
- configPath
1990
- });
1991
- const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1992
- runtimeRefreshSignature = signature;
1993
- runtimeRefreshOptionsKey = optionsKey;
1994
- return {
1995
- changed,
1996
- signature,
1997
- optionsKey
1998
- };
1999
- }
2000
- async function refreshRuntimeState(force) {
2001
- const invalidation = resolveRuntimeRefreshOptions();
2002
- const refreshed = await require_recorder.refreshTailwindRuntimeState(runtimeState, {
2003
- force: force || invalidation.changed,
2004
- clearCache: force || invalidation.changed
2005
- });
2006
- if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
2007
- if (refreshed) {
2008
- runtimeSet = void 0;
2009
- runtimeSetPromise = void 0;
2010
- }
2011
- }
2012
- async function ensureRuntimeClassSet(force = false) {
2013
- const forceRuntimeRefresh = force || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
2014
- await refreshRuntimeState(force);
2015
- await runtimeState.patchPromise;
2016
- if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
2017
- if (forceRuntimeRefresh || !runtimeSetPromise) {
2018
- const invalidation = resolveRuntimeRefreshOptions();
2019
- runtimeSetPromise = require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
2020
- force: forceRuntimeRefresh || invalidation.changed,
2021
- skipRefresh: forceRuntimeRefresh,
2022
- clearCache: forceRuntimeRefresh || invalidation.changed
2023
- });
2024
- }
2025
- const task = runtimeSetPromise;
2026
- try {
2027
- runtimeSet = await task;
2028
- return runtimeSet;
2029
- } finally {
2030
- if (runtimeSetPromise === task) runtimeSetPromise = void 0;
2031
- }
2032
- }
2033
- async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
2034
- const forceRuntimeRefresh = forceRefresh || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
2035
- const invalidation = resolveRuntimeRefreshOptions();
2036
- const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
2037
- const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
2038
- await refreshRuntimeState(shouldRefreshPatcher);
2039
- await runtimeState.patchPromise;
2040
- if (shouldRefreshPatcher) {
2041
- runtimeSet = void 0;
2042
- runtimeSetPromise = void 0;
2043
- await bundleRuntimeClassSetManager.reset();
2044
- }
2045
- if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
2046
- const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
2047
- runtimeSet = nextRuntimeSet;
2048
- return nextRuntimeSet;
2049
- } catch (error) {
2050
- debug("incremental runtime set sync failed, fallback to full collect: %O", error);
2051
- await bundleRuntimeClassSetManager.reset();
2052
- }
2053
- if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
2054
- const task = require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
2055
- force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
2056
- skipRefresh: forceRuntimeRefresh,
2057
- clearCache: forceRuntimeRefresh || invalidation.changed
2058
- });
2059
- runtimeSetPromise = task;
2060
- try {
2061
- runtimeSet = await task;
2062
- return runtimeSet;
2063
- } finally {
2064
- if (runtimeSetPromise === task) runtimeSetPromise = void 0;
2065
- }
2066
- }
2196
+ const { runtimeState, refreshRuntimeState, ensureRuntimeClassSet, ensureBundleRuntimeClassSet } = createViteRuntimeClassSet({
2197
+ opts,
2198
+ initialTwPatcher,
2199
+ refreshTailwindcssPatcher,
2200
+ uniAppXEnabled,
2201
+ customAttributesEntities,
2202
+ disabledDefaultTemplateHandler,
2203
+ debug
2204
+ });
2205
+ refreshRuntimeStateForAutoCssSources = refreshRuntimeState;
2067
2206
  onLoad();
2068
2207
  const getResolvedConfig = () => resolvedConfig;
2069
2208
  const markCssAssetProcessed = (asset, file) => {
@@ -2101,6 +2240,22 @@ function WeappTailwindcss(options = {}) {
2101
2240
  const setRememberedMainCssSignature = (file, cssRuntimeSignature) => {
2102
2241
  rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2103
2242
  };
2243
+ const generateBundleHook = createGenerateBundleHook({
2244
+ opts,
2245
+ runtimeState,
2246
+ ensureRuntimeClassSet,
2247
+ ensureBundleRuntimeClassSet,
2248
+ debug,
2249
+ getResolvedConfig,
2250
+ markCssAssetProcessed,
2251
+ getSourceCandidates,
2252
+ waitForSourceCandidateSyncs,
2253
+ rememberMainCssSource,
2254
+ getRememberedMainCssSources,
2255
+ getRememberedMainCssSignature,
2256
+ setRememberedMainCssSignature,
2257
+ recordGeneratorCandidates
2258
+ });
2104
2259
  const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
2105
2260
  opts,
2106
2261
  runtimeState,
@@ -2131,7 +2286,7 @@ function WeappTailwindcss(options = {}) {
2131
2286
  const plugins = [
2132
2287
  ...rewritePlugins,
2133
2288
  {
2134
- name: `${require_recorder.vitePluginName}:source-candidates`,
2289
+ name: `${require_precheck.vitePluginName}:source-candidates`,
2135
2290
  enforce: "pre",
2136
2291
  async transform(code, id) {
2137
2292
  if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return;
@@ -2156,10 +2311,22 @@ function WeappTailwindcss(options = {}) {
2156
2311
  root,
2157
2312
  outDir
2158
2313
  });
2314
+ const basedir = opts.tailwindcssBasedir ? node_path.default.resolve(opts.tailwindcssBasedir) : void 0;
2315
+ if (basedir && basedir !== node_path.default.resolve(root)) await sourceCandidateCollector.scanRoot({
2316
+ root: basedir,
2317
+ outDir
2318
+ });
2319
+ for (const cssEntry of opts.tailwindcss?.cssEntries ?? []) {
2320
+ const cssEntryRoot = node_path.default.dirname(node_path.default.resolve(cssEntry));
2321
+ if (cssEntryRoot !== node_path.default.resolve(root) && cssEntryRoot !== basedir) await sourceCandidateCollector.scanRoot({
2322
+ root: cssEntryRoot,
2323
+ outDir
2324
+ });
2325
+ }
2159
2326
  }
2160
2327
  },
2161
2328
  {
2162
- name: `${require_recorder.vitePluginName}:post`,
2329
+ name: `${require_precheck.vitePluginName}:post`,
2163
2330
  enforce: "post",
2164
2331
  config(config) {
2165
2332
  if (!shouldOwnTailwindGeneration) return;
@@ -2228,22 +2395,7 @@ function WeappTailwindcss(options = {}) {
2228
2395
  },
2229
2396
  generateBundle: {
2230
2397
  order: "post",
2231
- handler: createGenerateBundleHook({
2232
- opts,
2233
- runtimeState,
2234
- ensureRuntimeClassSet,
2235
- ensureBundleRuntimeClassSet,
2236
- debug,
2237
- getResolvedConfig,
2238
- markCssAssetProcessed,
2239
- getSourceCandidates,
2240
- waitForSourceCandidateSyncs,
2241
- rememberMainCssSource,
2242
- getRememberedMainCssSources,
2243
- getRememberedMainCssSignature,
2244
- setRememberedMainCssSignature,
2245
- recordGeneratorCandidates
2246
- })
2398
+ handler: generateBundleHook
2247
2399
  },
2248
2400
  outputOptions(options) {
2249
2401
  const plugins = options.plugins;